charges.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. const express = require('express');
  2. const path = require('path');
  3. const fs = require('fs');
  4. const multer = require('multer');
  5. const PDFDocument = require('pdfkit');
  6. const { PDFDocument: LibPDFDocument, rgb, StandardFonts } = require('pdf-lib');
  7. const db = require('../db');
  8. const { authMiddleware } = require('../auth');
  9. const router = express.Router();
  10. router.use(authMiddleware);
  11. // Configure multer for invoice uploads
  12. const uploadDir = path.join(__dirname, '../../uploads');
  13. if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
  14. const storage = multer.diskStorage({
  15. destination: (req, file, cb) => cb(null, uploadDir),
  16. filename: (req, file, cb) => {
  17. const ext = path.extname(file.originalname);
  18. cb(null, `charge_${Date.now()}_${Math.random().toString(36).slice(2)}${ext}`);
  19. }
  20. });
  21. const upload = multer({
  22. storage,
  23. limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
  24. fileFilter: (req, file, cb) => {
  25. const allowed = ['.pdf', '.jpg', '.jpeg', '.png', '.webp'];
  26. if (allowed.includes(path.extname(file.originalname).toLowerCase())) cb(null, true);
  27. else cb(new Error('Fichier non autorisé (PDF, JPG, PNG)'));
  28. }
  29. });
  30. // List charges (filter by property_id, year)
  31. router.get('/', (req, res) => {
  32. const { property_id, year } = req.query;
  33. let query = `
  34. SELECT c.*, p.name as property_name
  35. FROM charges c
  36. JOIN properties p ON c.property_id = p.id
  37. WHERE c.user_id = ?
  38. `;
  39. const params = [req.userId];
  40. if (property_id) { query += ' AND c.property_id = ?'; params.push(property_id); }
  41. if (year) { query += ' AND c.year = ?'; params.push(year); }
  42. query += ' ORDER BY c.date DESC';
  43. res.json(db.prepare(query).all(...params));
  44. });
  45. // Create charge (with optional invoice file)
  46. router.post('/', upload.single('invoice'), (req, res) => {
  47. const { property_id, category, label, amount, date, year, notes, recoverable } = req.body;
  48. if (!property_id || !category || !label || !amount || !date || !year)
  49. return res.status(400).json({ error: 'Champs requis manquants' });
  50. const prop = db.prepare('SELECT id FROM properties WHERE id = ? AND user_id = ?').get(property_id, req.userId);
  51. if (!prop) return res.status(403).json({ error: 'Bien non autorisé' });
  52. const invoice_path = req.file ? req.file.filename : null;
  53. const invoice_name = req.file ? req.file.originalname : null;
  54. const result = db.prepare(`
  55. INSERT INTO charges (user_id, property_id, category, label, amount, date, year, invoice_path, invoice_name, notes, recoverable)
  56. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  57. `).run(req.userId, property_id, category, label, parseFloat(amount), date, parseInt(year), invoice_path, invoice_name, notes || null, recoverable === 'false' || recoverable === '0' ? 0 : 1);
  58. res.status(201).json({ id: result.lastInsertRowid });
  59. });
  60. // Update charge (with optional new invoice)
  61. router.put('/:id', upload.single('invoice'), (req, res) => {
  62. const charge = db.prepare('SELECT * FROM charges WHERE id = ? AND user_id = ?').get(req.params.id, req.userId);
  63. if (!charge) return res.status(404).json({ error: 'Charge non trouvée' });
  64. const { category, label, amount, date, year, notes, recoverable } = req.body;
  65. let invoice_path = charge.invoice_path;
  66. let invoice_name = charge.invoice_name;
  67. if (req.file) {
  68. // Delete old file
  69. if (charge.invoice_path) {
  70. const oldPath = path.join(uploadDir, charge.invoice_path);
  71. if (fs.existsSync(oldPath)) fs.unlinkSync(oldPath);
  72. }
  73. invoice_path = req.file.filename;
  74. invoice_name = req.file.originalname;
  75. }
  76. db.prepare(`
  77. UPDATE charges SET category=?, label=?, amount=?, date=?, year=?, invoice_path=?, invoice_name=?, notes=?, recoverable=?
  78. WHERE id=?
  79. `).run(category, label, parseFloat(amount), date, parseInt(year), invoice_path, invoice_name, notes || null, recoverable === 'false' || recoverable === '0' ? 0 : 1, req.params.id);
  80. res.json({ success: true });
  81. });
  82. // Delete charge
  83. router.delete('/:id', (req, res) => {
  84. const charge = db.prepare('SELECT * FROM charges WHERE id = ? AND user_id = ?').get(req.params.id, req.userId);
  85. if (!charge) return res.status(404).json({ error: 'Charge non trouvée' });
  86. if (charge.invoice_path) {
  87. const filePath = path.join(uploadDir, charge.invoice_path);
  88. if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
  89. }
  90. db.prepare('DELETE FROM charges WHERE id = ?').run(req.params.id);
  91. res.json({ success: true });
  92. });
  93. // Download invoice
  94. router.get('/:id/invoice', (req, res) => {
  95. const charge = db.prepare('SELECT * FROM charges WHERE id = ? AND user_id = ?').get(req.params.id, req.userId);
  96. if (!charge || !charge.invoice_path) return res.status(404).json({ error: 'Facture non trouvée' });
  97. const filePath = path.join(uploadDir, charge.invoice_path);
  98. if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'Fichier introuvable' });
  99. res.setHeader('Content-Disposition', `attachment; filename="${charge.invoice_name}"`);
  100. res.sendFile(filePath);
  101. });
  102. // Annual bilan for a property
  103. router.get('/bilan/:property_id/:year', (req, res) => {
  104. const { property_id, year } = req.params;
  105. // Verify property ownership
  106. const prop = db.prepare('SELECT * FROM properties WHERE id = ? AND user_id = ?').get(property_id, req.userId);
  107. if (!prop) return res.status(403).json({ error: 'Bien non autorisé' });
  108. // Total recoverable charges for this property/year (for tenant billing)
  109. const totalChargesRow = db.prepare(`
  110. SELECT SUM(amount) as total, COUNT(*) as count
  111. FROM charges WHERE property_id = ? AND year = ? AND user_id = ? AND recoverable = 1
  112. `).get(property_id, year, req.userId);
  113. // Total non-recoverable (landlord's own charges, for info)
  114. const totalNonRecovRow = db.prepare(`
  115. SELECT SUM(amount) as total, COUNT(*) as count
  116. FROM charges WHERE property_id = ? AND year = ? AND user_id = ? AND recoverable = 0
  117. `).get(property_id, year, req.userId);
  118. const totalChargesReelles = totalChargesRow?.total || 0;
  119. const totalNonRecoverable = totalNonRecovRow?.total || 0;
  120. // Charges by category (recoverable only)
  121. const chargesByCategory = db.prepare(`
  122. SELECT category, SUM(amount) as total
  123. FROM charges WHERE property_id = ? AND year = ? AND user_id = ? AND recoverable = 1
  124. GROUP BY category ORDER BY total DESC
  125. `).all(property_id, year, req.userId);
  126. // Non-recoverable by category (for info)
  127. const chargesNonRecovByCategory = db.prepare(`
  128. SELECT category, SUM(amount) as total
  129. FROM charges WHERE property_id = ? AND year = ? AND user_id = ? AND recoverable = 0
  130. GROUP BY category ORDER BY total DESC
  131. `).all(property_id, year, req.userId);
  132. // All leases on this property (active or that were active during the year)
  133. const leases = db.prepare(`
  134. SELECT l.*, t.first_name, t.last_name, t.email
  135. FROM leases l
  136. JOIN tenants t ON l.tenant_id = t.id
  137. WHERE l.property_id = ? AND l.user_id = ?
  138. AND (l.start_date <= ? AND (l.end_date IS NULL OR l.end_date >= ?))
  139. `).all(property_id, req.userId, `${year}-12-31`, `${year}-01-01`);
  140. // For each lease, get provisions perçues for the year
  141. const leaseBilans = leases.map(lease => {
  142. const provisions = db.prepare(`
  143. SELECT SUM(charges_paid) as total
  144. FROM payments
  145. WHERE lease_id = ? AND period_year = ?
  146. `).get(lease.id, year);
  147. return {
  148. lease_id: lease.id,
  149. tenant_name: `${lease.first_name} ${lease.last_name}`,
  150. tenant_email: lease.email,
  151. monthly_provision: lease.charges_amount,
  152. provisions_percues: provisions?.total || 0
  153. };
  154. });
  155. // Calculate total provisions across all tenants for proportional split
  156. const totalProvisions = leaseBilans.reduce((s, l) => s + l.provisions_percues, 0);
  157. // Compute each tenant's share
  158. const bilans = leaseBilans.map(l => {
  159. const ratio = totalProvisions > 0 ? l.provisions_percues / totalProvisions : (leaseBilans.length > 0 ? 1 / leaseBilans.length : 0);
  160. const quote_part_charges = totalChargesReelles * ratio;
  161. const trop_percu = l.provisions_percues - quote_part_charges;
  162. return {
  163. ...l,
  164. ratio_percent: Math.round(ratio * 100 * 100) / 100,
  165. quote_part_charges: Math.round(quote_part_charges * 100) / 100,
  166. trop_percu: Math.round(trop_percu * 100) / 100
  167. };
  168. });
  169. res.json({
  170. property: prop,
  171. year: parseInt(year),
  172. total_charges_reelles: Math.round(totalChargesReelles * 100) / 100,
  173. total_non_recoverable: Math.round(totalNonRecoverable * 100) / 100,
  174. charges_count: totalChargesRow?.count || 0,
  175. charges_by_category: chargesByCategory,
  176. charges_non_recov_by_category: chargesNonRecovByCategory,
  177. total_provisions_percues: Math.round(totalProvisions * 100) / 100,
  178. bilans
  179. });
  180. });
  181. // Export PDF bilan + invoices
  182. router.get('/bilan/:property_id/:year/pdf', async (req, res) => {
  183. const { property_id, year } = req.params;
  184. const prop = db.prepare('SELECT * FROM properties WHERE id = ? AND user_id = ?').get(property_id, req.userId);
  185. if (!prop) return res.status(403).json({ error: 'Bien non autorisé' });
  186. const owner = db.prepare('SELECT name, first_name, last_name, email, address, phone FROM users WHERE id = ?').get(req.userId);
  187. const ownerFullName = (owner.first_name && owner.last_name) ? `${owner.first_name} ${owner.last_name}` : owner.name;
  188. const totalChargesRow = db.prepare(`
  189. SELECT SUM(amount) as total, COUNT(*) as count FROM charges
  190. WHERE property_id = ? AND year = ? AND user_id = ? AND recoverable = 1
  191. `).get(property_id, year, req.userId);
  192. const totalChargesReelles = totalChargesRow?.total || 0;
  193. const chargesList = db.prepare(`
  194. SELECT * FROM charges WHERE property_id = ? AND year = ? AND user_id = ?
  195. ORDER BY date ASC
  196. `).all(property_id, year, req.userId);
  197. const chargesByCategory = db.prepare(`
  198. SELECT category, SUM(amount) as total FROM charges
  199. WHERE property_id = ? AND year = ? AND user_id = ? AND recoverable = 1
  200. GROUP BY category ORDER BY total DESC
  201. `).all(property_id, year, req.userId);
  202. const leases = db.prepare(`
  203. SELECT l.*, t.first_name, t.last_name, t.email FROM leases l
  204. JOIN tenants t ON l.tenant_id = t.id
  205. WHERE l.property_id = ? AND l.user_id = ?
  206. AND (l.start_date <= ? AND (l.end_date IS NULL OR l.end_date >= ?))
  207. `).all(property_id, req.userId, `${year}-12-31`, `${year}-01-01`);
  208. const leaseBilans = leases.map(lease => {
  209. const provisions = db.prepare(`SELECT SUM(charges_paid) as total FROM payments WHERE lease_id = ? AND period_year = ?`).get(lease.id, year);
  210. return {
  211. lease_id: lease.id,
  212. tenant_name: `${lease.first_name} ${lease.last_name}`,
  213. tenant_email: lease.email,
  214. provisions_percues: provisions?.total || 0
  215. };
  216. });
  217. const totalProvisions = leaseBilans.reduce((s, l) => s + l.provisions_percues, 0);
  218. const bilans = leaseBilans.map(l => {
  219. const ratio = totalProvisions > 0 ? l.provisions_percues / totalProvisions : (leaseBilans.length > 0 ? 1 / leaseBilans.length : 0);
  220. const quote_part = totalChargesReelles * ratio;
  221. const trop_percu = l.provisions_percues - quote_part;
  222. return { ...l, ratio_percent: Math.round(ratio * 100 * 100) / 100, quote_part_charges: Math.round(quote_part * 100) / 100, trop_percu: Math.round(trop_percu * 100) / 100 };
  223. });
  224. const catLabels = { eau: 'Eau', gaz: 'Gaz', electricite: 'Électricité', entretien: 'Entretien / Réparations', ascenseur: 'Ascenseur', ordures: 'Ordures ménagères', assurance: 'Assurance', autre: 'Autre' };
  225. const fmtEur = v => `${Number(v).toFixed(2)} EUR`;
  226. const fmtDate = d => d ? new Date(d + 'T00:00:00').toLocaleDateString('fr-FR') : '—';
  227. const solde = totalProvisions - totalChargesReelles;
  228. try {
  229. // --- Step 1: Generate bilan PDF with pdfkit ---
  230. const bilanBuf = await new Promise((resolve, reject) => {
  231. const doc = new PDFDocument({ margin: 50, size: 'A4' });
  232. const chunks = [];
  233. doc.on('data', c => chunks.push(c));
  234. doc.on('end', () => resolve(Buffer.concat(chunks)));
  235. doc.on('error', reject);
  236. const W = doc.page.width - 100;
  237. const blue = '#2563eb'; const red = '#dc2626'; const green = '#15803d'; const orange = '#c2410c'; const gray = '#6b7280';
  238. // Header
  239. doc.fontSize(20).fillColor('#111827').text(`Bilan annuel de charges ${year}`, { align: 'left' });
  240. doc.fontSize(11).fillColor(gray).text(`${prop.name} — ${prop.address || ''}`, { align: 'left' });
  241. doc.moveDown(0.5);
  242. doc.fontSize(10).fillColor(gray).text(`Document généré le ${new Date().toLocaleDateString('fr-FR')}`, { align: 'right' });
  243. doc.moveDown(0.8);
  244. // Bailleur info
  245. doc.moveTo(50, doc.y).lineTo(50 + W, doc.y).strokeColor('#e5e7eb').lineWidth(1).stroke();
  246. doc.moveDown(0.5);
  247. doc.fontSize(9).fillColor(gray).text('BAILLEUR', { continued: false });
  248. doc.fontSize(10).fillColor('#111827').font('Helvetica-Bold').text(ownerFullName);
  249. doc.font('Helvetica');
  250. if (owner.address) doc.fontSize(10).fillColor('#374151').text(owner.address);
  251. doc.fontSize(10).fillColor('#374151').text(owner.email || '');
  252. if (owner.phone) doc.fontSize(10).fillColor('#374151').text(owner.phone);
  253. doc.moveDown(0.5);
  254. doc.moveTo(50, doc.y).lineTo(50 + W, doc.y).strokeColor('#e5e7eb').lineWidth(1).stroke();
  255. doc.moveDown(1);
  256. // Summary boxes
  257. doc.fontSize(11).fillColor('#111827').text('Synthèse', { underline: true });
  258. doc.moveDown(0.5);
  259. const bx = 50; const bw = (W - 20) / 3;
  260. [[`Charges réelles`, fmtEur(totalChargesReelles), `${totalChargesRow?.count || 0} facture(s)`, red],
  261. [`Provisions perçues`, fmtEur(totalProvisions), 'de tous les locataires', blue],
  262. [solde >= 0 ? 'Trop-perçu global' : 'Solde insuffisant', `${solde >= 0 ? '+' : '-'}${fmtEur(Math.abs(solde))}`, solde >= 0 ? 'à restituer' : 'à appeler', solde >= 0 ? green : orange]
  263. ].forEach(([label, val, note, color], i) => {
  264. const x = bx + i * (bw + 10); const y = doc.y;
  265. doc.rect(x, y, bw, 60).stroke('#e5e7eb');
  266. doc.fontSize(9).fillColor(gray).text(label, x + 8, y + 8, { width: bw - 16 });
  267. doc.fontSize(14).fillColor(color).text(val, x + 8, y + 22, { width: bw - 16 });
  268. doc.fontSize(8).fillColor(gray).text(note, x + 8, y + 42, { width: bw - 16 });
  269. });
  270. doc.moveDown(4.5);
  271. // Charges by category
  272. if (chargesByCategory.length > 0) {
  273. doc.fontSize(11).fillColor('#111827').text('Répartition par catégorie', { underline: true });
  274. doc.moveDown(0.5);
  275. const colWidths = [220, 100, 80];
  276. const headers = ['Catégorie', 'Montant', '%'];
  277. let tx = 50; let ty = doc.y;
  278. doc.fontSize(9).fillColor(gray);
  279. headers.forEach((h, i) => { doc.text(h, tx, ty, { width: colWidths[i] }); tx += colWidths[i]; });
  280. doc.moveDown(0.3);
  281. doc.moveTo(50, doc.y).lineTo(50 + W, doc.y).strokeColor('#e5e7eb').stroke();
  282. doc.moveDown(0.3);
  283. chargesByCategory.forEach(c => {
  284. const pct = totalChargesReelles > 0 ? (c.total / totalChargesReelles * 100).toFixed(1) : '0.0';
  285. tx = 50; ty = doc.y;
  286. doc.fontSize(9).fillColor('#111827');
  287. [catLabels[c.category] || c.category, fmtEur(c.total), `${pct}%`].forEach((v, i) => { doc.text(v, tx, ty, { width: colWidths[i] }); tx += colWidths[i]; });
  288. doc.moveDown(0.4);
  289. });
  290. tx = 50; ty = doc.y;
  291. doc.fontSize(9).fillColor('#111827').font('Helvetica-Bold');
  292. ['Total', fmtEur(totalChargesReelles), ''].forEach((v, i) => { doc.text(v, tx, ty, { width: colWidths[i] }); tx += colWidths[i]; });
  293. doc.font('Helvetica');
  294. doc.moveDown(1.5);
  295. }
  296. // Per tenant bilan
  297. if (bilans.length > 0) {
  298. doc.fontSize(11).fillColor('#111827').text('Décompte par locataire', { underline: true });
  299. doc.moveDown(0.5);
  300. bilans.forEach(b => {
  301. const isPos = b.trop_percu >= 0;
  302. const color = isPos ? green : orange;
  303. const bY = doc.y;
  304. doc.rect(50, bY, W, 90).stroke('#e5e7eb');
  305. doc.fontSize(11).fillColor('#111827').font('Helvetica-Bold').text(b.tenant_name, 62, bY + 10, { width: W - 24 });
  306. doc.font('Helvetica');
  307. if (b.tenant_email) doc.fontSize(9).fillColor(gray).text(b.tenant_email, 62, bY + 24);
  308. const badge = isPos ? 'Remboursement' : 'Appel de fonds';
  309. doc.fontSize(9).fillColor(color).text(badge, 62, bY + 38);
  310. const cols = [['Provisions perçues', fmtEur(b.provisions_percues)], [`Quote-part (${b.ratio_percent}%)`, fmtEur(b.quote_part_charges)], [isPos ? 'Trop-perçu' : 'Solde dû', fmtEur(Math.abs(b.trop_percu))]];
  311. const cw = (W - 24) / 3;
  312. cols.forEach(([lbl, val], i) => {
  313. const cx = 62 + i * (cw + 8);
  314. doc.fontSize(8).fillColor(gray).text(lbl, cx, bY + 54, { width: cw });
  315. doc.fontSize(10).fillColor(i === 2 ? color : '#111827').font('Helvetica-Bold').text(val, cx, bY + 66, { width: cw });
  316. doc.font('Helvetica');
  317. });
  318. doc.y = bY + 100;
  319. doc.moveDown(0.3);
  320. });
  321. }
  322. // Charges list
  323. if (chargesList.length > 0) {
  324. doc.addPage();
  325. doc.fontSize(13).fillColor('#111827').text(`Détail des charges ${year}`, { underline: true });
  326. doc.moveDown(0.5);
  327. const hdrs = ['Date', 'Catégorie', 'Libellé', 'Montant', 'Facture'];
  328. const cws2 = [70, 100, 180, 80, 100];
  329. let hx = 50; const hy = doc.y;
  330. doc.fontSize(9).fillColor(gray);
  331. hdrs.forEach((h, i) => { doc.text(h, hx, hy, { width: cws2[i] }); hx += cws2[i]; });
  332. doc.moveDown(0.3);
  333. doc.moveTo(50, doc.y).lineTo(50 + W, doc.y).strokeColor('#e5e7eb').stroke();
  334. doc.moveDown(0.3);
  335. chargesList.forEach(c => {
  336. if (doc.y > doc.page.height - 80) { doc.addPage(); }
  337. hx = 50; const row = doc.y;
  338. doc.fontSize(9).fillColor('#111827');
  339. [fmtDate(c.date), catLabels[c.category] || c.category, c.label, fmtEur(c.amount), c.invoice_name ? `📎 Voir annexe` : '—'].forEach((v, i) => {
  340. doc.text(v, hx, row, { width: cws2[i] }); hx += cws2[i];
  341. });
  342. doc.moveDown(0.5);
  343. });
  344. }
  345. doc.end();
  346. });
  347. // --- Step 2: Merge bilan + invoice files with pdf-lib ---
  348. const mergedPdf = await LibPDFDocument.create();
  349. // Copy bilan pages
  350. const bilanPdf = await LibPDFDocument.load(bilanBuf);
  351. const bilanPages = await mergedPdf.copyPages(bilanPdf, bilanPdf.getPageIndices());
  352. bilanPages.forEach(p => mergedPdf.addPage(p));
  353. // Append each invoice
  354. for (const charge of chargesList) {
  355. if (!charge.invoice_path) continue;
  356. const filePath = path.join(uploadDir, charge.invoice_path);
  357. if (!fs.existsSync(filePath)) continue;
  358. const ext = path.extname(charge.invoice_path).toLowerCase();
  359. const fileBytes = fs.readFileSync(filePath);
  360. if (ext === '.pdf') {
  361. try {
  362. const invPdf = await LibPDFDocument.load(fileBytes, { ignoreEncryption: true });
  363. const invPages = await mergedPdf.copyPages(invPdf, invPdf.getPageIndices());
  364. invPages.forEach(p => mergedPdf.addPage(p));
  365. } catch { /* skip unreadable PDFs */ }
  366. } else if (['.jpg', '.jpeg'].includes(ext)) {
  367. try {
  368. const img = await mergedPdf.embedJpg(fileBytes);
  369. const page = mergedPdf.addPage([img.width, img.height]);
  370. page.drawImage(img, { x: 0, y: 0, width: img.width, height: img.height });
  371. } catch { /* skip unreadable images */ }
  372. } else if (ext === '.png') {
  373. try {
  374. const img = await mergedPdf.embedPng(fileBytes);
  375. const page = mergedPdf.addPage([img.width, img.height]);
  376. page.drawImage(img, { x: 0, y: 0, width: img.width, height: img.height });
  377. } catch { /* skip unreadable images */ }
  378. }
  379. // webp not supported by pdf-lib natively — skipped
  380. }
  381. const pdfBytes = await mergedPdf.save();
  382. const filename = `bilan_charges_${year}_${prop.name.replace(/[^a-z0-9]/gi, '_')}.pdf`;
  383. res.setHeader('Content-Type', 'application/pdf');
  384. res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
  385. res.send(Buffer.from(pdfBytes));
  386. } catch (err) {
  387. console.error('PDF generation error:', err);
  388. res.status(500).json({ error: 'Erreur génération PDF' });
  389. }
  390. });
  391. module.exports = router;