From f6bd030b35f12c307a923b74b6354225e1ccaf74 Mon Sep 17 00:00:00 2001 From: Tony AVERTY Date: Tue, 6 Oct 2026 16:30:37 +0200 Subject: [PATCH] =?UTF-8?q?Facturation=20Stripe=20:=20abonnement,=20suspen?= =?UTF-8?q?sion=20pour=20impay=C3=A9,=20factures=20PDF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Lien Checkout d'abonnement 10 €/mois (carte ou SEPA) créé depuis l'admin et envoyé au contact du magasin - Webhook Stripe signé : suivi de l'abonnement, suspension automatique des magasins actifs en cas d'impayé, réactivation au paiement (uniquement si la suspension venait de la facturation) - Factures MEP-AAAA-NNNNNN à numérotation continue, PDF avec mentions légales (art. 293 B, pénalités, indemnité 40 €), envoyées par e-mail - Onglet Facturation dans l'admin, page /abonnement/merci/ sur le site - Migration SQL manuelle prisma/manual-migrations/2026-10-06-facturation.sql Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + admin/src/api.ts | 15 + admin/src/components/StoreForm.tsx | 2 +- admin/src/pages/BillingTab.tsx | 115 +++ admin/src/pages/StorePage.tsx | 6 +- backend/package-lock.json | 758 +++++++++++++++++- backend/package.json | 5 +- .../2026-10-06-facturation.sql | 12 + backend/prisma/schema.prisma | 7 + backend/src/app.module.ts | 2 + backend/src/billing/billing.controller.ts | 69 ++ backend/src/billing/billing.service.ts | 302 +++++++ backend/src/billing/invoice-pdf.ts | 123 +++ backend/src/config/configuration.ts | 13 + backend/src/mail/mail.service.ts | 14 + backend/src/main.ts | 3 +- site-src/build.js | 23 + site/abonnement/merci/index.html | 118 +++ 18 files changed, 1580 insertions(+), 10 deletions(-) create mode 100644 admin/src/pages/BillingTab.tsx create mode 100644 backend/prisma/manual-migrations/2026-10-06-facturation.sql create mode 100644 backend/src/billing/billing.controller.ts create mode 100644 backend/src/billing/billing.service.ts create mode 100644 backend/src/billing/invoice-pdf.ts create mode 100644 site/abonnement/merci/index.html diff --git a/.gitignore b/.gitignore index c68b03d..f103db5 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,6 @@ carte-test.pkpass *.rar *.7z *.tar.gz + +# Factures PDF générées (archive légale, sauvegardée côté serveur) +backend/storage/ diff --git a/admin/src/api.ts b/admin/src/api.ts index 377c6dd..ba2c6c6 100644 --- a/admin/src/api.ts +++ b/admin/src/api.ts @@ -107,6 +107,20 @@ async function request(method: string, path: string, body?: unknown, auth = t return (text ? JSON.parse(text) : null) as T; } +/** Téléchargement d'un fichier protégé (le jeton ne peut pas passer par un simple lien). */ +export async function downloadFile(path: string, filename: string) { + if (!accessToken) await refresh(); + let res = await fetch(`${BASE}${path}`, { headers: { Authorization: `Bearer ${accessToken}` } }); + if (res.status === 401 && (await refresh())) { + res = await fetch(`${BASE}${path}`, { headers: { Authorization: `Bearer ${accessToken}` } }); + } + if (!res.ok) throw new ApiError(res.status, 'Téléchargement impossible'); + const url = URL.createObjectURL(await res.blob()); + const a = Object.assign(document.createElement('a'), { href: url, download: filename }); + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 10_000); +} + export const api = { get: (path: string) => request('GET', path), post: (path: string, body?: unknown) => request('POST', path, body ?? {}), @@ -130,6 +144,7 @@ export interface Store { contactEmail: string; contactPhone: string; status: StoreStatus; + billingSuspended: boolean; maxAmountEuros: number; minScanIntervalMin: number; createdAt: string; diff --git a/admin/src/components/StoreForm.tsx b/admin/src/components/StoreForm.tsx index bcf3187..d8e802d 100644 --- a/admin/src/components/StoreForm.tsx +++ b/admin/src/components/StoreForm.tsx @@ -1,7 +1,7 @@ import { FormEvent, useState } from 'react'; import { Store } from '../api'; -export type StoreInput = Omit; +export type StoreInput = Omit; export const EMPTY_STORE: StoreInput = { name: '', diff --git a/admin/src/pages/BillingTab.tsx b/admin/src/pages/BillingTab.tsx new file mode 100644 index 0000000..c3c479f --- /dev/null +++ b/admin/src/pages/BillingTab.tsx @@ -0,0 +1,115 @@ +import { useCallback, useEffect, useState } from 'react'; +import { api, downloadFile, SubscriptionStatus } from '../api'; + +interface Billing { + testMode: boolean; + subscription: { status: SubscriptionStatus; currentPeriodEnd: string | null; hasCustomer: boolean } | null; + billingSuspended: boolean; + invoices: { id: string; number: string; amountCents: number; periodStart: string; periodEnd: string; issuedAt: string; paidAt: string | null }[]; +} + +const STATUS: Record = { + ACTIVE: ['Actif', 'ACTIVE'], + INCOMPLETE: ['En attente de paiement', 'DRAFT'], + PAST_DUE: ['Impayé', 'SUSPENDED'], + CANCELED: ['Résilié', 'CLOSED'], +}; + +const euros = (c: number) => (c / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR' }); +const day = (d: string) => new Date(d).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' }); + +export function BillingTab({ storeId, contactEmail, onChange }: { storeId: string; contactEmail: string; onChange: () => void }) { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [link, setLink] = useState<{ url: string; emailedTo: string | null } | null>(null); + const [busy, setBusy] = useState(false); + + const reload = useCallback(() => { + api.get(`/api/admin/stores/${storeId}/billing`).then(setData).catch((e) => setError(e.message)); + }, [storeId]); + useEffect(reload, [reload]); + + async function createLink(sendEmail: boolean) { + setBusy(true); + setError(null); + try { + setLink(await api.post(`/api/admin/stores/${storeId}/billing/checkout-link`, { sendEmail })); + reload(); + onChange(); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(false); + } + } + + if (!data) return error ?
{error}
:

Chargement…

; + const sub = data.subscription; + const active = sub?.status === 'ACTIVE'; + + return ( + <> + {data.testMode &&
Stripe est en mode test : aucun paiement réel n'est encaissé (carte de test 4242 4242 4242 4242).
} + {error &&
{error}
} + +
+
+
+

Abonnement

+

10 € par mois, sans engagement — carte bancaire ou prélèvement SEPA.

+
+ {sub ? STATUS[sub.status][0] : 'Aucun abonnement'} +
+ {sub?.currentPeriodEnd && active &&

Prochain prélèvement le {day(sub.currentPeriodEnd)}.

} + {data.billingSuspended && ( +
Magasin suspendu automatiquement pour impayé. Il sera réactivé dès que le paiement passera.
+ )} + {!active && ( +
+ + +
+ )} + {link && ( +
+ {link.emailedTo ? <>Lien envoyé à {link.emailedTo}. : null} + Valable 24 h :{' '} + {link.url} +
+ )} +
+ +
+
+ + + + + + + + + + + + {data.invoices.map((i) => ( + + + + + + + + ))} + +
FacturePériodeMontantStatutPDF
{i.number}{day(i.periodStart)} → {day(i.periodEnd)}{euros(i.amountCents)}{i.paidAt ? Payée le {day(i.paidAt)} : Impayée} + +
+
+ {data.invoices.length === 0 &&

Aucune facture pour l'instant. Elles sont créées automatiquement à chaque paiement.

} +
+ + ); +} diff --git a/admin/src/pages/StorePage.tsx b/admin/src/pages/StorePage.tsx index 0d2a708..0ef9600 100644 --- a/admin/src/pages/StorePage.tsx +++ b/admin/src/pages/StorePage.tsx @@ -5,11 +5,13 @@ import { StatusBadge } from '../components/Layout'; import { StoreForm } from '../components/StoreForm'; import { CardWizard } from './CardWizard'; import { StaffTab } from './StaffTab'; +import { BillingTab } from './BillingTab'; const TABS = [ ['infos', 'Infos'], ['carte', 'Carte de fidélité'], ['employes', 'Employés'], + ['facturation', 'Facturation'], ] as const; export function StorePage() { @@ -69,7 +71,8 @@ export function StorePage() { {store.status === 'SUSPENDED' && (
- Magasin suspendu : les scans et les nouvelles inscriptions sont refusés. + Magasin suspendu{store.billingSuspended ? ' pour impayé' : ''} : les scans et les nouvelles inscriptions sont refusés. + {store.billingSuspended && <> Voir l'onglet Facturation.}
)} {error &&
{error}
} @@ -101,6 +104,7 @@ export function StorePage() { /> } /> } /> + } /> ); diff --git a/backend/package-lock.json b/backend/package-lock.json index e4fa56f..973a803 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -28,9 +28,11 @@ "passkit-generator": "^3.6.1", "passport": "^0.7.0", "passport-jwt": "^4.0.1", + "pdfkit": "^0.15.2", "qrcode": "^1.5.4", "reflect-metadata": "^0.2.2", - "rxjs": "^7.8.1" + "rxjs": "^7.8.1", + "stripe": "^17.7.0" }, "devDependencies": { "@nestjs/cli": "^10.4.5", @@ -40,6 +42,7 @@ "@types/node": "^22.7.4", "@types/nodemailer": "^8.0.2", "@types/passport-jwt": "^4.0.1", + "@types/pdfkit": "^0.17.6", "@types/qrcode": "^1.5.6", "prisma": "^5.20.0", "ts-node": "^10.9.2", @@ -1331,6 +1334,15 @@ "integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==", "license": "BSD-3-Clause" }, + "node_modules/@swc/helpers": { + "version": "0.3.17", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.3.17.tgz", + "integrity": "sha512-tb7Iu+oZ+zWJZ3HJqwx8oNwSDIU440hmVMDPhpACWQWnrZHK99Bxs70gT1L2dnr5Hg50ZRWEFkQCAnOVVV0z1Q==", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@tokenizer/inflate": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.2.7.tgz", @@ -1565,6 +1577,16 @@ "@types/passport": "*" } }, + "node_modules/@types/pdfkit": { + "version": "0.17.6", + "resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.6.tgz", + "integrity": "sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/qrcode": { "version": "1.5.6", "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz", @@ -1996,6 +2018,22 @@ "dev": true, "license": "Python-2.0" }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/array-flatten": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", @@ -2009,6 +2047,21 @@ "dev": true, "license": "MIT" }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/await-to-js": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/await-to-js/-/await-to-js-3.0.0.tgz", @@ -2029,7 +2082,6 @@ "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "dev": true, "funding": [ { "type": "github", @@ -2138,6 +2190,24 @@ "node": ">=8" } }, + "node_modules/brotli": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz", + "integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.1.2" + } + }, + "node_modules/browserify-zlib": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", + "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", + "license": "MIT", + "dependencies": { + "pako": "~1.0.5" + } + }, "node_modules/browserslist": { "version": "4.29.3", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz", @@ -2233,7 +2303,6 @@ "version": "1.0.9", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", - "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -2643,6 +2712,13 @@ "node": ">= 8" } }, + "node_modules/crypto-js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==", + "deprecated": "Active development of CryptoJS has been discontinued. This library is no longer maintained.", + "license": "MIT" + }, "node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -2661,6 +2737,38 @@ "node": ">=0.10.0" } }, + "node_modules/deep-equal": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.3.tgz", + "integrity": "sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==", + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.0", + "call-bind": "^1.0.5", + "es-get-iterator": "^1.1.3", + "get-intrinsic": "^1.2.2", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.2", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.5.1", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/deepmerge": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", @@ -2688,7 +2796,6 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", - "dev": true, "license": "MIT", "dependencies": { "es-define-property": "^1.0.0", @@ -2702,6 +2809,23 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -2721,6 +2845,12 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/dfa": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz", + "integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==", + "license": "MIT" + }, "node_modules/diff": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", @@ -2864,6 +2994,26 @@ "node": ">= 0.4" } }, + "node_modules/es-get-iterator": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.3.tgz", + "integrity": "sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "has-symbols": "^1.0.3", + "is-arguments": "^1.1.1", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.7", + "isarray": "^2.0.5", + "stop-iteration-iterator": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -3182,6 +3332,47 @@ "node": ">=8" } }, + "node_modules/fontkit": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/fontkit/-/fontkit-1.9.0.tgz", + "integrity": "sha512-HkW/8Lrk8jl18kzQHvAw9aTHe1cqsyx5sDnxncx652+CIfhawokEPkeM3BoIC+z/Xv7a0yMr0f3pRRwhGH455g==", + "license": "MIT", + "dependencies": { + "@swc/helpers": "^0.3.13", + "brotli": "^1.3.2", + "clone": "^2.1.2", + "deep-equal": "^2.0.5", + "dfa": "^1.2.0", + "restructure": "^2.0.1", + "tiny-inflate": "^1.0.3", + "unicode-properties": "^1.3.1", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/fontkit/node_modules/clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/foreground-child": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", @@ -3291,6 +3482,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -3434,6 +3634,18 @@ "dev": true, "license": "ISC" }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -3457,7 +3669,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", - "dev": true, "license": "MIT", "dependencies": { "es-define-property": "^1.0.0" @@ -3478,6 +3689,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/hasown": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", @@ -3619,6 +3845,20 @@ "node": ">=12.0.0" } }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", @@ -3628,6 +3868,39 @@ "node": ">= 0.10" } }, + "node_modules/is-arguments": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.2.0.tgz", + "integrity": "sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", @@ -3635,6 +3908,21 @@ "dev": true, "license": "MIT" }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-binary-path": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", @@ -3648,6 +3936,50 @@ "node": ">=8" } }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -3690,6 +4022,18 @@ "node": ">=8" } }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -3700,6 +4044,100 @@ "node": ">=0.12.0" } }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-unicode-supported": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", @@ -3713,6 +4151,40 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -3836,6 +4308,13 @@ "url": "https://github.com/sponsors/panva" } }, + "node_modules/jpeg-exif": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/jpeg-exif/-/jpeg-exif-1.1.4.tgz", + "integrity": "sha512-a+bKEcCjtuW5WTdgeXFzswSrdqi0jk4XlEtZlx5A94wCoBpFjfFTbo/Tra5SpNCl/YFZPvcV1dJc+TAYeg6ROQ==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT" + }, "node_modules/jpeg-js": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/jpeg-js/-/jpeg-js-0.4.4.tgz", @@ -3974,6 +4453,25 @@ "integrity": "sha512-llihgCcx0BFLksecLP+x1J+6JDE1GsXS1RN/LoPF6qcwpeQcnjj0lcvZxY8AzbEpYwyZWPZW/nDuqkqzm3amiw==", "license": "MIT" }, + "node_modules/linebreak": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz", + "integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==", + "license": "MIT", + "dependencies": { + "base64-js": "0.0.8", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/linebreak/node_modules/base64-js": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz", + "integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", @@ -4405,6 +4903,51 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/object-is": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.6.tgz", + "integrity": "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/omggif": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/omggif/-/omggif-1.0.10.tgz", @@ -4693,6 +5236,19 @@ "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", "integrity": "sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg==" }, + "node_modules/pdfkit": { + "version": "0.15.2", + "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.15.2.tgz", + "integrity": "sha512-s3GjpdBFSCaeDSX/v73MI5UsPqH1kjKut2AXCgxQ5OH10lPVOu5q5vLAG0OCpz/EYqKsTSw1WHpENqMvp43RKg==", + "license": "MIT", + "dependencies": { + "crypto-js": "^4.2.0", + "fontkit": "^1.8.1", + "jpeg-exif": "^1.1.4", + "linebreak": "^1.0.2", + "png-js": "^1.0.0" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -4744,6 +5300,14 @@ "node": ">=4" } }, + "node_modules/png-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/png-js/-/png-js-1.1.0.tgz", + "integrity": "sha512-PM/uYGzGdNSzqeOgly68+6wKQDL1SY0a/N+OEa/+br6LnHWOAJB0Npiamnodfq3jd2LS/i2fMeOKSAILjA+m5Q==", + "dependencies": { + "browserify-zlib": "^0.2.0" + } + }, "node_modules/pngjs": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz", @@ -4753,6 +5317,15 @@ "node": ">=14.19.0" } }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/prisma": { "version": "5.22.0", "resolved": "https://registry.npmjs.org/prisma/-/prisma-5.22.0.tgz", @@ -4911,6 +5484,26 @@ "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", "license": "Apache-2.0" }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/repeat-string": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", @@ -4977,6 +5570,12 @@ "dev": true, "license": "ISC" }, + "node_modules/restructure": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/restructure/-/restructure-2.0.1.tgz", + "integrity": "sha512-e0dOpjm5DseomnXx2M5lpdZ5zoHqF1+bqdMJUohoYVVQa7cBdnk7fdmeI6byNWP/kiME72EeTiSypTCVnpLiDg==", + "license": "MIT" + }, "node_modules/run-async": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", @@ -5016,6 +5615,23 @@ ], "license": "MIT" }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -5151,7 +5767,6 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", - "dev": true, "license": "MIT", "dependencies": { "define-data-property": "^1.1.4", @@ -5165,6 +5780,21 @@ "node": ">= 0.4" } }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -5328,6 +5958,19 @@ "node": ">= 0.8" } }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/streamsearch": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", @@ -5411,6 +6054,19 @@ "node": ">=4" } }, + "node_modules/stripe": { + "version": "17.7.0", + "resolved": "https://registry.npmjs.org/stripe/-/stripe-17.7.0.tgz", + "integrity": "sha512-aT2BU9KkizY9SATf14WhhYVv2uOapBWX0OFWF4xvcj1mPaNotlSc2CsxpS4DS46ZueSppmCF5BX1sNYBtwBvfw==", + "license": "MIT", + "dependencies": { + "@types/node": ">=8.1.0", + "qs": "^6.11.0" + }, + "engines": { + "node": ">=12.*" + } + }, "node_modules/strtok3": { "version": "10.3.5", "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.5.tgz", @@ -5623,6 +6279,12 @@ "dev": true, "license": "MIT" }, + "node_modules/tiny-inflate": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "license": "MIT" + }, "node_modules/tinycolor2": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz", @@ -5855,6 +6517,32 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "license": "MIT" }, + "node_modules/unicode-properties": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz", + "integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.0", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/unicode-trie": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz", + "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==", + "license": "MIT", + "dependencies": { + "pako": "^0.2.5", + "tiny-inflate": "^1.0.0" + } + }, + "node_modules/unicode-trie/node_modules/pako": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", + "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==", + "license": "MIT" + }, "node_modules/universalify": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", @@ -6086,12 +6774,70 @@ "node": ">= 8" } }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/which-module": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", "license": "ISC" }, + "node_modules/which-typed-array": { + "version": "1.1.24", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.24.tgz", + "integrity": "sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/wrap-ansi": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", diff --git a/backend/package.json b/backend/package.json index 4f60a8d..9ff8947 100644 --- a/backend/package.json +++ b/backend/package.json @@ -36,9 +36,11 @@ "passkit-generator": "^3.6.1", "passport": "^0.7.0", "passport-jwt": "^4.0.1", + "pdfkit": "^0.15.2", "qrcode": "^1.5.4", "reflect-metadata": "^0.2.2", - "rxjs": "^7.8.1" + "rxjs": "^7.8.1", + "stripe": "^17.7.0" }, "devDependencies": { "@nestjs/cli": "^10.4.5", @@ -48,6 +50,7 @@ "@types/node": "^22.7.4", "@types/nodemailer": "^8.0.2", "@types/passport-jwt": "^4.0.1", + "@types/pdfkit": "^0.17.6", "@types/qrcode": "^1.5.6", "prisma": "^5.20.0", "ts-node": "^10.9.2", diff --git a/backend/prisma/manual-migrations/2026-10-06-facturation.sql b/backend/prisma/manual-migrations/2026-10-06-facturation.sql new file mode 100644 index 0000000..f806ceb --- /dev/null +++ b/backend/prisma/manual-migrations/2026-10-06-facturation.sql @@ -0,0 +1,12 @@ +-- Facturation Stripe (étape 6) — à exécuter UNE fois dans phpMyAdmin sur la base monespacepro, +-- AVANT de déployer le nouveau code. Table Invoice vide à ce stade : colonnes NOT NULL sans risque. + +-- AlterTable +ALTER TABLE `Store` ADD COLUMN `billingSuspended` BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable +ALTER TABLE `Invoice` ADD COLUMN `clientAddress` TEXT NOT NULL, + ADD COLUMN `clientEmail` VARCHAR(191) NOT NULL, + ADD COLUMN `clientName` VARCHAR(191) NOT NULL, + ADD COLUMN `clientSiret` VARCHAR(191) NOT NULL; + diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 8bb687d..dfbf343 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -41,6 +41,8 @@ model Store { contactEmail String contactPhone String status StoreStatus @default(DRAFT) + /// Suspendu automatiquement pour impayé (réactivé automatiquement au paiement). + billingSuspended Boolean @default(false) // Anti-triche : réglages par magasin maxAmountCents Int @default(50000) /// plafond d'un montant saisi @@ -224,6 +226,11 @@ model Invoice { store Store @relation(fields: [storeId], references: [id]) stripeInvoiceId String? @unique amountCents Int + /// Identité du client figée à l'émission (une facture ne change plus). + clientName String + clientAddress String @db.Text + clientSiret String + clientEmail String periodStart DateTime periodEnd DateTime issuedAt DateTime @default(now()) diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index b16889f..be46957 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -10,6 +10,7 @@ import { MailModule } from './mail/mail.service'; import { EnrollmentModule } from './enrollment/enrollment.module'; import { CounterModule } from './counter/counter.module'; import { ContactModule } from './contact/contact.controller'; +import { BillingModule } from './billing/billing.controller'; import { HealthController } from './health.controller'; @Module({ @@ -23,6 +24,7 @@ import { HealthController } from './health.controller'; EnrollmentModule, CounterModule, ContactModule, + BillingModule, ], controllers: [HealthController], providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], diff --git a/backend/src/billing/billing.controller.ts b/backend/src/billing/billing.controller.ts new file mode 100644 index 0000000..bc43311 --- /dev/null +++ b/backend/src/billing/billing.controller.ts @@ -0,0 +1,69 @@ +import { Body, Controller, Get, Headers, HttpCode, Logger, Module, Param, Post, Req, Res, UseGuards } from '@nestjs/common'; +import type { RawBodyRequest } from '@nestjs/common'; +import { SkipThrottle } from '@nestjs/throttler'; +import { IsBoolean, IsOptional } from 'class-validator'; +import type { Request, Response } from 'express'; +import { AdminGuard, JwtAuthGuard } from '../common/guards'; +import { BillingService } from './billing.service'; + +class CheckoutLinkDto { + /** Envoyer le lien par e-mail au contact du magasin. */ + @IsOptional() @IsBoolean() + sendEmail?: boolean; +} + +@Controller('admin') +@UseGuards(JwtAuthGuard, AdminGuard) +export class BillingAdminController { + constructor(private billing: BillingService) {} + + @Get('stores/:storeId/billing') + overview(@Param('storeId') storeId: string) { + return this.billing.overview(storeId); + } + + @Post('stores/:storeId/billing/checkout-link') + @HttpCode(200) + checkoutLink(@Param('storeId') storeId: string, @Body() dto: CheckoutLinkDto) { + return this.billing.checkoutLink(storeId, dto.sendEmail ?? true); + } + + @Get('invoices/:id/pdf') + async pdf(@Param('id') id: string, @Res() res: Response) { + const [pdf, number] = await Promise.all([this.billing.renderPdf(id), this.billing.invoiceNumber(id)]); + res + .type('application/pdf') + .setHeader('Content-Disposition', `attachment; filename="${number}.pdf"`) + .setHeader('Cache-Control', 'private, no-store') + .send(pdf); + } +} + +/** Notifications Stripe : signature vérifiée sur le corps brut. */ +@Controller('stripe') +@SkipThrottle() +export class StripeWebhookController { + private readonly logger = new Logger(StripeWebhookController.name); + + constructor(private billing: BillingService) {} + + @Post('webhook') + @HttpCode(200) + async webhook(@Req() req: RawBodyRequest, @Headers('stripe-signature') signature: string | undefined) { + const event = this.billing.verify(req.rawBody, signature); + try { + await this.billing.handle(event); + } catch (e) { + // Erreur → 500 : Stripe renverra l'événement plus tard. + this.logger.error(`Webhook ${event.type} (${event.id}) : ${(e as Error).message}`); + throw e; + } + return { received: true }; + } +} + +@Module({ + controllers: [BillingAdminController, StripeWebhookController], + providers: [BillingService], +}) +export class BillingModule {} diff --git a/backend/src/billing/billing.service.ts b/backend/src/billing/billing.service.ts new file mode 100644 index 0000000..3395640 --- /dev/null +++ b/backend/src/billing/billing.service.ts @@ -0,0 +1,302 @@ +import { BadRequestException, Injectable, Logger, NotFoundException, ServiceUnavailableException } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { Prisma, SubscriptionStatus } from '@prisma/client'; +import { mkdir, readFile, writeFile } from 'fs/promises'; +import { join } from 'path'; +import Stripe from 'stripe'; +import { PrismaService } from '../prisma/prisma.service'; +import { MailService } from '../mail/mail.service'; +import { escapeHtml } from '../enrollment/pages'; +import { renderInvoicePdf } from './invoice-pdf'; + +/** Factures PDF : hors des dossiers servis publiquement. */ +export const INVOICES_DIR = join(process.cwd(), 'storage', 'invoices'); + +const STATUS: Record = { + active: 'ACTIVE', + trialing: 'ACTIVE', + past_due: 'PAST_DUE', + unpaid: 'PAST_DUE', + canceled: 'CANCELED', + incomplete_expired: 'CANCELED', + incomplete: 'INCOMPLETE', + paused: 'PAST_DUE', +}; + +const euros = (cents: number) => (cents / 100).toLocaleString('fr-FR', { style: 'currency', currency: 'EUR' }); + +/** + * Abonnement Stripe (10 €/mois/magasin), suspension automatique en cas + * d'impayé, factures numérotées sans trou émises au nom de l'auto-entreprise. + */ +@Injectable() +export class BillingService { + private readonly logger = new Logger(BillingService.name); + private client: Stripe | null = null; + + constructor( + private prisma: PrismaService, + private config: ConfigService, + private mail: MailService, + ) {} + + get stripe(): Stripe { + const key: string = this.config.get('stripe.secretKey')!; + if (!key) throw new ServiceUnavailableException('Stripe n’est pas configuré'); + this.client ??= new Stripe(key); + return this.client; + } + + /** Résumé pour l'onglet Facturation de l'admin. */ + async overview(storeId: string) { + const store = await this.prisma.store.findUnique({ + where: { id: storeId }, + include: { subscription: true, invoices: { orderBy: { sequence: 'desc' } } }, + }); + if (!store) throw new NotFoundException('Magasin introuvable'); + return { + testMode: (this.config.get('stripe.secretKey') ?? '').startsWith('sk_test_'), + subscription: store.subscription && { + status: store.subscription.status, + currentPeriodEnd: store.subscription.currentPeriodEnd, + hasCustomer: !!store.subscription.stripeCustomerId, + }, + billingSuspended: store.billingSuspended, + invoices: store.invoices.map((i) => ({ + id: i.id, + number: i.number, + amountCents: i.amountCents, + periodStart: i.periodStart, + periodEnd: i.periodEnd, + issuedAt: i.issuedAt, + paidAt: i.paidAt, + })), + }; + } + + /** + * Crée (ou réutilise) le client Stripe du magasin et un lien Checkout + * d'abonnement ; l'envoie par e-mail au contact du magasin si demandé. + */ + async checkoutLink(storeId: string, sendEmail: boolean) { + const store = await this.prisma.store.findUnique({ where: { id: storeId }, include: { subscription: true } }); + if (!store) throw new NotFoundException('Magasin introuvable'); + if (store.subscription?.status === 'ACTIVE') throw new BadRequestException('Ce magasin a déjà un abonnement actif'); + + let customerId = store.subscription?.stripeCustomerId; + if (!customerId) { + const customer = await this.stripe.customers.create({ + name: store.name, + email: store.contactEmail, + phone: store.contactPhone, + address: { line1: store.addressLine, postal_code: store.postalCode, city: store.city, country: 'FR' }, + metadata: { storeId: store.id, siret: store.siret }, + preferred_locales: ['fr'], + }); + customerId = customer.id; + await this.prisma.subscription.upsert({ + where: { storeId }, + create: { storeId, stripeCustomerId: customerId }, + update: { stripeCustomerId: customerId }, + }); + } + + const price = (await this.stripe.prices.list({ lookup_keys: [this.config.get('stripe.priceLookupKey')!], limit: 1 })).data[0]; + if (!price) throw new ServiceUnavailableException('Prix Stripe introuvable'); + + const webUrl: string = this.config.get('webUrl')!; + const session = await this.stripe.checkout.sessions.create({ + mode: 'subscription', + customer: customerId, + line_items: [{ price: price.id, quantity: 1 }], + payment_method_types: ['card', 'sepa_debit'], + locale: 'fr', + client_reference_id: store.id, + subscription_data: { metadata: { storeId: store.id } }, + metadata: { storeId: store.id }, + success_url: `${webUrl}/abonnement/merci/`, + cancel_url: `${webUrl}/tarif/`, + expires_at: Math.floor(Date.now() / 1000) + 24 * 3600, // 24 h, maximum autorisé par Stripe + }); + + if (sendEmail) { + const text = `Bonjour ${store.contactName},\n\nVoici le lien pour activer l'abonnement MonEspacePro de ${store.name} (10 € par mois, sans engagement, carte bancaire ou prélèvement SEPA) :\n${session.url}\n\nCe lien est valable 24 heures.\n\nMonEspacePro`; + const html = `

Bonjour ${escapeHtml(store.contactName)},

Voici le lien pour activer l'abonnement MonEspacePro de ${escapeHtml(store.name)} : 10 € par mois, sans engagement, par carte bancaire ou prélèvement SEPA.

Activer mon abonnement

Ce lien est valable 24 heures.

MonEspacePro

`; + await this.mail.send(store.contactEmail, `Activez l'abonnement MonEspacePro de ${store.name}`, text, html); + } + return { url: session.url, expiresAt: new Date(session.expires_at * 1000), emailedTo: sendEmail ? store.contactEmail : null }; + } + + // ── Webhook ──────────────────────────────────────────────── + + verify(rawBody: Buffer | undefined, signature: string | undefined): Stripe.Event { + const secret: string = this.config.get('stripe.webhookSecret')!; + if (!rawBody || !signature || !secret) throw new BadRequestException('Signature Stripe manquante'); + try { + return this.stripe.webhooks.constructEvent(rawBody, signature, secret); + } catch { + throw new BadRequestException('Signature Stripe invalide'); + } + } + + async handle(event: Stripe.Event) { + switch (event.type) { + case 'checkout.session.completed': { + const s = event.data.object; + if (s.mode === 'subscription' && s.subscription) await this.syncSubscription(String(s.subscription)); + break; + } + case 'customer.subscription.created': + case 'customer.subscription.updated': + case 'customer.subscription.deleted': + await this.syncSubscription(event.data.object.id); + break; + case 'invoice.paid': + await this.onInvoicePaid(event.data.object); + break; + case 'invoice.payment_failed': + await this.onPaymentFailed(event.data.object); + break; + default: + break; + } + } + + /** Recopie l'état de l'abonnement Stripe et applique suspension / réactivation. */ + private async syncSubscription(subscriptionId: string) { + const sub = await this.stripe.subscriptions.retrieve(subscriptionId); + const storeId = sub.metadata.storeId; + if (!storeId) return; + const status = STATUS[sub.status] ?? 'INCOMPLETE'; + const periodEnd = sub.current_period_end; + await this.prisma.subscription.upsert({ + where: { storeId }, + create: { storeId, stripeCustomerId: String(sub.customer), stripeSubscriptionId: sub.id, status, currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null }, + update: { stripeCustomerId: String(sub.customer), stripeSubscriptionId: sub.id, status, currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null }, + }); + if (status === 'ACTIVE') await this.reactivate(storeId); + if (status === 'PAST_DUE' || status === 'CANCELED') await this.suspend(storeId, `abonnement ${sub.status}`); + } + + private async onPaymentFailed(invoice: Stripe.Invoice) { + const storeId = await this.storeIdForCustomer(String(invoice.customer)); + if (storeId) await this.suspend(storeId, `paiement de ${euros(invoice.amount_due)} refusé`); + } + + /** Seuls les magasins actifs sont suspendus ; un brouillon ou un magasin fermé reste tel quel. */ + private async suspend(storeId: string, reason: string) { + const { count } = await this.prisma.store.updateMany({ + where: { id: storeId, status: 'ACTIVE' }, + data: { status: 'SUSPENDED', billingSuspended: true }, + }); + if (count) this.logger.warn(`Magasin ${storeId} suspendu : ${reason}`); + } + + /** Ne réactive que ce que la facturation a suspendu (pas une suspension manuelle). */ + private async reactivate(storeId: string) { + const { count } = await this.prisma.store.updateMany({ + where: { id: storeId, status: 'SUSPENDED', billingSuspended: true }, + data: { status: 'ACTIVE', billingSuspended: false }, + }); + if (count) this.logger.log(`Magasin ${storeId} réactivé après paiement`); + } + + private async storeIdForCustomer(customerId: string) { + const sub = await this.prisma.subscription.findUnique({ where: { stripeCustomerId: customerId }, select: { storeId: true } }); + return sub?.storeId ?? null; + } + + /** Émet la facture MonEspacePro (numéro suivant, PDF, e-mail). Idempotent. */ + private async onInvoicePaid(si: Stripe.Invoice) { + if (!si.id || si.amount_paid <= 0) return; + const storeId = await this.storeIdForCustomer(String(si.customer)); + if (!storeId) { + this.logger.warn(`Facture Stripe ${si.id} : client ${si.customer} inconnu`); + return; + } + await this.reactivate(storeId); + if (await this.prisma.invoice.findUnique({ where: { stripeInvoiceId: si.id } })) return; + + const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId } }); + const period = si.lines.data[0]?.period; + const paidAt = si.status_transitions?.paid_at ? new Date(si.status_transitions.paid_at * 1000) : new Date(); + + // Numérotation continue : séquence globale, l'unicité en base empêche tout doublon. + let invoice: Prisma.InvoiceGetPayload | null = null; + for (let attempt = 0; attempt < 5 && !invoice; attempt++) { + try { + invoice = await this.prisma.$transaction(async (tx) => { + const last = await tx.invoice.aggregate({ _max: { sequence: true } }); + const sequence = (last._max.sequence ?? 0) + 1; + return tx.invoice.create({ + data: { + number: `MEP-${paidAt.getFullYear()}-${String(sequence).padStart(6, '0')}`, + sequence, + storeId, + stripeInvoiceId: si.id, + amountCents: si.amount_paid, + clientName: store.name, + clientAddress: `${store.addressLine}\n${store.postalCode} ${store.city}`, + clientSiret: store.siret.replace(/(\d{3})(\d{3})(\d{3})(\d{5})/, '$1 $2 $3 $4'), + clientEmail: store.contactEmail, + periodStart: period ? new Date(period.start * 1000) : paidAt, + periodEnd: period ? new Date(period.end * 1000) : paidAt, + paidAt, + }, + }); + }); + } catch (e) { + if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') { + // Même facture traitée en parallèle (webhook rejoué) : on s'arrête là. + if (await this.prisma.invoice.findUnique({ where: { stripeInvoiceId: si.id } })) return; + continue; // collision de numéro : on retente avec le suivant + } + throw e; + } + } + if (!invoice) throw new Error(`Numérotation impossible pour ${si.id}`); + + const pdf = await this.renderPdf(invoice.id); + const text = `Bonjour ${store.contactName},\n\nVeuillez trouver ci-joint la facture ${invoice.number} de ${euros(invoice.amountCents)} pour l'abonnement MonEspacePro de ${store.name}. Elle a été réglée le ${paidAt.toLocaleDateString('fr-FR')}.\n\nMerci de votre confiance,\nMonEspacePro`; + await this.mail + .sendWithAttachment(store.contactEmail, `Votre facture MonEspacePro ${invoice.number}`, text, `

${escapeHtml(text).replace(/\n/g, '
')}

`, { + filename: `${invoice.number}.pdf`, + content: pdf, + }) + .catch((e) => this.logger.error(`Facture ${invoice!.number} non envoyée : ${e.message}`)); + } + + /** PDF généré une fois puis conservé tel quel (archive légale de 10 ans). */ + async renderPdf(invoiceId: string): Promise { + const inv = await this.prisma.invoice.findUnique({ where: { id: invoiceId } }); + if (!inv) throw new NotFoundException('Facture introuvable'); + if (inv.pdfPath) { + try { + return await readFile(join(INVOICES_DIR, inv.pdfPath)); + } catch { + /* fichier absent : on le régénère depuis les données figées */ + } + } + const pdf = await renderInvoicePdf({ + number: inv.number, + issuedAt: inv.issuedAt, + paidAt: inv.paidAt, + periodStart: inv.periodStart, + periodEnd: inv.periodEnd, + amountCents: inv.amountCents, + issuer: this.config.get('issuer')!, + client: { name: inv.clientName, address: inv.clientAddress, siret: inv.clientSiret, email: inv.clientEmail }, + }); + await mkdir(INVOICES_DIR, { recursive: true }); + const file = `${inv.number}.pdf`; + await writeFile(join(INVOICES_DIR, file), pdf); + if (!inv.pdfPath) await this.prisma.invoice.update({ where: { id: inv.id }, data: { pdfPath: file } }); + return pdf; + } + + async invoiceNumber(invoiceId: string) { + const inv = await this.prisma.invoice.findUnique({ where: { id: invoiceId }, select: { number: true } }); + if (!inv) throw new NotFoundException('Facture introuvable'); + return inv.number; + } +} diff --git a/backend/src/billing/invoice-pdf.ts b/backend/src/billing/invoice-pdf.ts new file mode 100644 index 0000000..c74eb5c --- /dev/null +++ b/backend/src/billing/invoice-pdf.ts @@ -0,0 +1,123 @@ +import PDFDocument from 'pdfkit'; + +export interface InvoicePdfData { + number: string; + issuedAt: Date; + paidAt: Date | null; + periodStart: Date; + periodEnd: Date; + amountCents: number; + issuer: { name: string; tradeName: string; siret: string; address: string; email: string }; + client: { name: string; address: string; siret: string; email: string }; +} + +const GREEN = '#0E7A66'; +const INK = '#1C1C19'; +const MUTED = '#5F5E56'; + +const date = (d: Date) => d.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'Europe/Paris' }); +const euros = (cents: number) => + (cents / 100).toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).replace(/ | /g, ' ') + ' €'; +const month = (d: Date) => d.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric', timeZone: 'Europe/Paris' }); + +/** + * Facture A4 conforme aux mentions obligatoires (art. L441-9 du Code de + * commerce, art. 242 nonies A annexe II du CGI) pour une entreprise en + * franchise en base de TVA. + */ +export function renderInvoicePdf(d: InvoicePdfData): Promise { + return new Promise((resolve, reject) => { + const doc = new PDFDocument({ size: 'A4', margin: 56, info: { Title: `Facture ${d.number}`, Author: d.issuer.name } }); + const chunks: Buffer[] = []; + doc.on('data', (c: Buffer) => chunks.push(c)); + doc.on('end', () => resolve(Buffer.concat(chunks))); + doc.on('error', reject); + + const left = 56; + const right = doc.page.width - 56; + const width = right - left; + + // En-tête : symbole + émetteur + doc.save().translate(left, 50).scale(0.5); + doc.path('M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22').lineWidth(8).strokeColor(GREEN).stroke(); + doc.circle(51, 12, 6).fillColor('#F2B544').fill(); + doc.restore(); + doc.fillColor(INK).font('Helvetica-Bold').fontSize(16).text(d.issuer.tradeName, left + 40, 58); + doc.font('Helvetica').fontSize(9).fillColor(MUTED) + .text(d.issuer.name, left, 96) + .text(d.issuer.address) + .text(`SIRET ${d.issuer.siret}`) + .text(d.issuer.email); + + // Titre facture + doc.font('Helvetica-Bold').fontSize(22).fillColor(INK).text('FACTURE', left, 58, { width, align: 'right' }); + doc.font('Helvetica').fontSize(10).fillColor(MUTED) + .text(`N° ${d.number}`, left, 88, { width, align: 'right' }) + .text(`Date d'émission : ${date(d.issuedAt)}`, { width, align: 'right' }) + .text(`Date de la prestation : ${date(d.periodStart)} au ${date(d.periodEnd)}`, { width, align: 'right' }); + + // Client + const clientY = 180; + doc.roundedRect(left + width / 2, clientY, width / 2, 92, 8).fillColor('#F6F6F3').fill(); + doc.fillColor(MUTED).font('Helvetica-Bold').fontSize(8).text('FACTURÉ À', left + width / 2 + 14, clientY + 12); + doc.fillColor(INK).font('Helvetica-Bold').fontSize(11).text(d.client.name, left + width / 2 + 14, clientY + 26, { width: width / 2 - 28 }); + doc.font('Helvetica').fontSize(9).fillColor(INK) + .text(d.client.address, { width: width / 2 - 28 }) + .text(`SIRET ${d.client.siret}`) + .text(d.client.email); + + // Tableau + let y = 310; + doc.rect(left, y, width, 24).fillColor(GREEN).fill(); + doc.fillColor('#FFFFFF').font('Helvetica-Bold').fontSize(9) + .text('Désignation', left + 10, y + 8) + .text('Qté', left + width - 230, y + 8, { width: 40, align: 'right' }) + .text('Prix unitaire HT', left + width - 180, y + 8, { width: 90, align: 'right' }) + .text('Total HT', left + width - 90, y + 8, { width: 80, align: 'right' }); + y += 34; + doc.fillColor(INK).font('Helvetica').fontSize(10) + .text(`Abonnement MonEspacePro — carte de fidélité dématérialisée, 1 magasin\nPériode : ${month(d.periodStart)} (du ${date(d.periodStart)} au ${date(d.periodEnd)})`, left + 10, y, { width: width - 250 }) + .text('1', left + width - 230, y, { width: 40, align: 'right' }) + .text(euros(d.amountCents), left + width - 180, y, { width: 90, align: 'right' }) + .text(euros(d.amountCents), left + width - 90, y, { width: 80, align: 'right' }); + y += 44; + doc.moveTo(left, y).lineTo(right, y).lineWidth(0.5).strokeColor('#DEDDD6').stroke(); + + // Totaux + y += 14; + const line = (label: string, value: string, bold = false) => { + doc.font(bold ? 'Helvetica-Bold' : 'Helvetica').fontSize(bold ? 12 : 10).fillColor(INK) + .text(label, left + width - 260, y, { width: 160, align: 'right' }) + .text(value, left + width - 90, y, { width: 80, align: 'right' }); + y += bold ? 22 : 18; + }; + line('Total HT', euros(d.amountCents)); + line('TVA', '0,00 €'); + line('Total TTC', euros(d.amountCents), true); + doc.font('Helvetica-Oblique').fontSize(9).fillColor(MUTED).text('TVA non applicable, art. 293 B du CGI', left, y + 4, { width, align: 'right' }); + + // Règlement + y += 40; + doc.font('Helvetica-Bold').fontSize(10).fillColor(INK).text('Règlement', left, y); + doc.font('Helvetica').fontSize(9).fillColor(INK).text( + d.paidAt + ? `Payée le ${date(d.paidAt)} par prélèvement automatique (Stripe).` + : 'Paiement par prélèvement automatique à réception de la facture.', + left, y + 16, { width }, + ); + + // Mentions légales + const legalY = doc.page.height - 56 - 92; + doc.moveTo(left, legalY - 12).lineTo(right, legalY - 12).lineWidth(0.5).strokeColor('#DEDDD6').stroke(); + doc.font('Helvetica').fontSize(7.5).fillColor(MUTED).text( + [ + "Conditions de paiement : paiement à réception, par prélèvement automatique mensuel. Pas d'escompte en cas de paiement anticipé.", + "En cas de retard de paiement, des pénalités sont exigibles au taux d'intérêt appliqué par la Banque centrale européenne à son opération de refinancement la plus récente majoré de 10 points (art. L441-10 du Code de commerce), ainsi qu'une indemnité forfaitaire pour frais de recouvrement de 40 € (art. D441-5 du Code de commerce).", + `${d.issuer.name} — Entrepreneur individuel — SIRET ${d.issuer.siret} — TVA non applicable, art. 293 B du CGI.`, + ].join('\n'), + left, legalY, { width, lineGap: 2 }, + ); + + doc.end(); + }); +} diff --git a/backend/src/config/configuration.ts b/backend/src/config/configuration.ts index a161e34..a2019db 100644 --- a/backend/src/config/configuration.ts +++ b/backend/src/config/configuration.ts @@ -26,6 +26,19 @@ export default () => ({ /** Chemin vers la clé JSON du compte de service. */ serviceAccountFile: process.env.GOOGLE_WALLET_SA_FILE ?? '', }, + stripe: { + secretKey: process.env.STRIPE_SECRET_KEY ?? '', + webhookSecret: process.env.STRIPE_WEBHOOK_SECRET ?? '', + priceLookupKey: process.env.STRIPE_PRICE_LOOKUP_KEY || 'mep_magasin_mensuel', + }, + /** Émetteur des factures (mentions obligatoires). */ + issuer: { + name: process.env.ISSUER_NAME || 'EI Tony Averty', + tradeName: 'MonEspacePro', + siret: process.env.ISSUER_SIRET || '100 142 819 00018', + address: process.env.ISSUER_ADDRESS || '[ADRESSE DE L’ENTREPRISE]', + email: process.env.ISSUER_EMAIL || 'contact@monespacepro.eu', + }, mail: { host: process.env.SMTP_HOST ?? '', port: parseInt(process.env.SMTP_PORT ?? '587', 10), diff --git a/backend/src/mail/mail.service.ts b/backend/src/mail/mail.service.ts index de8512e..625e3b8 100644 --- a/backend/src/mail/mail.service.ts +++ b/backend/src/mail/mail.service.ts @@ -32,6 +32,20 @@ export class MailService { } await this.transport.sendMail({ from: this.from, to, subject, text, html, ...(replyTo && { replyTo }) }); } + + async sendWithAttachment( + to: string, + subject: string, + text: string, + html: string, + attachment: { filename: string; content: Buffer }, + ) { + if (!this.transport) { + this.logger.warn(`SMTP non configuré — e-mail à ${to} : « ${subject} » + pièce jointe ${attachment.filename}`); + return; + } + await this.transport.sendMail({ from: this.from, to, subject, text, html, attachments: [attachment] }); + } } @Global() diff --git a/backend/src/main.ts b/backend/src/main.ts index b9ed60f..c23dcb8 100644 --- a/backend/src/main.ts +++ b/backend/src/main.ts @@ -23,7 +23,8 @@ function verifierSecrets(config: ConfigService) { } async function bootstrap() { - const app = await NestFactory.create(AppModule); + // rawBody : la signature des webhooks Stripe porte sur les octets exacts du corps. + const app = await NestFactory.create(AppModule, { rawBody: true }); const config = app.get(ConfigService); verifierSecrets(config); diff --git a/site-src/build.js b/site-src/build.js index 8101490..c8fb99b 100644 --- a/site-src/build.js +++ b/site-src/build.js @@ -211,4 +211,27 @@ for (const file of Object.keys(PAGES)) { fs.writeFileSync(out, page(file, title, transform(file, extractBody(html)), cookie)); console.log('✓', PAGES[file].url); } +// Page de retour après paiement Stripe : gabarit de la 404, contenu propre. +{ + const html = read('Erreur404.dc.html'); + let body = transform('Erreur404.dc.html', extractBody(html)); + body = body.replace( + /
/, + `
+
+
+

Abonnement

+

Merci, votre abonnement est activé.

+

Vous allez recevoir la confirmation et votre première facture par e-mail. Votre carte de fidélité est prête à accueillir vos clients.

+ +
+
`, + ); + PAGES['Merci'] = { out: 'abonnement/merci/index.html', url: '/abonnement/merci/' }; + DESCRIPTIONS['Merci'] = 'Votre abonnement MonEspacePro est activé.'; + const out = path.join(OUT, PAGES['Merci'].out); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, page('Merci', 'Abonnement activé — MonEspacePro', body, cookie).replace('\n + + + + +Abonnement activé — MonEspacePro + + + + + + + + + + + + + + + + + + +
+ + + + + +
+ +
+
+ +
+
+
+

Abonnement

+

Merci, votre abonnement est activé.

+

Vous allez recevoir la confirmation et votre première facture par e-mail. Votre carte de fidélité est prête à accueillir vos clients.

+ +
+
+ +
+ + + + + + +
+ +