diff --git a/package.json b/package.json index 36cda36..3b744fe 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "type": "module", - "packageManager": "pnpm@10.34.5", + "packageManager": "pnpm@11.16.0", "engines": { "node": ">=24 <25" }, @@ -22,6 +22,7 @@ "drizzle-orm": "^0.45.2", "next": "^16.3.0", "nodemailer": "^9.0.5", + "pdfmake": "~0.3.11", "pg": "^8.22.0", "react": "^19.2.8", "react-dom": "^19.2.8", @@ -35,6 +36,7 @@ "@testing-library/react": "^16.3.2", "@types/node": "^24.13.3", "@types/nodemailer": "^8.0.1", + "@types/pdfmake": "^0.3.3", "@types/pg": "^8.21.0", "@types/react": "^19.2.18", "@types/react-dom": "^19.2.4", @@ -44,8 +46,10 @@ "eslint-config-next": "^16.3.0", "jsdom": "^30.0.1", "msw": "^2.15.0", + "pdfjs-dist": "^6.2.108", "tailwindcss": "^4.3.3", "testcontainers": "^12.1.0", + "tsx": "^4.23.11", "typescript": "^5.9.3", "vitest": "^4.1.10" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 80b00bd..6e01cd7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -26,6 +26,9 @@ importers: nodemailer: specifier: ^9.0.5 version: 9.0.5 + pdfmake: + specifier: ~0.3.11 + version: 0.3.11 pg: specifier: ^8.22.0 version: 8.22.0 @@ -60,6 +63,9 @@ importers: '@types/nodemailer': specifier: ^8.0.1 version: 8.0.1 + '@types/pdfmake': + specifier: ^0.3.3 + version: 0.3.3 '@types/pg': specifier: ^8.21.0 version: 8.21.0 @@ -87,12 +93,18 @@ importers: msw: specifier: ^2.15.0 version: 2.15.0(@types/node@24.13.3)(typescript@5.9.3) + pdfjs-dist: + specifier: ^6.2.108 + version: 6.2.108 tailwindcss: specifier: ^4.3.3 version: 4.3.3 testcontainers: specifier: ^12.1.0 version: 12.1.0(supports-color@7.2.0) + tsx: + specifier: ^4.23.11 + version: 4.23.11 typescript: specifier: ^5.9.3 version: 5.9.3 @@ -1098,6 +1110,81 @@ packages: resolution: {integrity: sha512-VVPPgHyQ6ShqnrmDWuxjmUIsO9gWyOZFmuOfLd9LfBGQJwZfy0gvv9pbHSJuoFNIYC7ZDX9aoFwowjcdSC4E8w==} engines: {node: '>=18'} + '@napi-rs/canvas-android-arm64@1.0.5': + resolution: {integrity: sha512-ZzDlpKQocwFfCwhMh17UWre6Qt5yZN3kNIJoUpGfRZqwDDZ164IKOsPOHsRd3d8Tuj5KM6bDjGuPmZxuPuG3NQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [android] + + '@napi-rs/canvas-darwin-arm64@1.0.5': + resolution: {integrity: sha512-Hr8v6CA/TBe+OJOePdV3sXWxzQHQKfQsTKPbc8wG7iPqVeAx6MMdzKGXlYID6SVvpfwV/zqkvGcdImYWSlhrZg==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [darwin] + + '@napi-rs/canvas-darwin-x64@1.0.5': + resolution: {integrity: sha512-9BXlLHBXpYnK4jSae1MdFdyPq09Xi1I3PeCNpvRzqgmUUBhgJS7aC1z7SZEP8JUXDHtbfIrolCS3sFuT9IGP2A==} + engines: {node: '>= 10'} + cpu: [x64] + os: [darwin] + + '@napi-rs/canvas-linux-arm-gnueabihf@1.0.5': + resolution: {integrity: sha512-zEW4fgvtYsOJ/N56Us4TQPfaFrUf0shGr9CgGSj3GACc+NHfUM3ci0YF9xFTjwJWGDmaEhYPL6KqCfFCxwm/qg==} + engines: {node: '>= 10'} + cpu: [arm] + os: [linux] + + '@napi-rs/canvas-linux-arm64-gnu@1.0.5': + resolution: {integrity: sha512-HFprwLspelJxCEtZvdMcz95Mwvfs63GzFVedLFmC/wslHnaOXhjXxgYxPCM/VdM4Jhx3CV4Lk0vVmh6hJv2etQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@napi-rs/canvas-linux-arm64-musl@1.0.5': + resolution: {integrity: sha512-FNMGFAx8DvtDwlLfWyBJ+oQjgPXoIAqCnNTJYqtJCFRwwzK3AyAe5B1Ll3NZ6hcOzqw7HylZsq4nQxVyPCQX1Q==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@napi-rs/canvas-linux-riscv64-gnu@1.0.5': + resolution: {integrity: sha512-2vd5v8Lui+37Hh/spITKIvTT384ip4dnUc5XBn0E+sMNS4b7au7IswyT5YDG2udPTjSh/eLUs3sGuB5YHooFOA==} + engines: {node: '>= 10'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@napi-rs/canvas-linux-x64-gnu@1.0.5': + resolution: {integrity: sha512-iQIPy+Uey0expZTOszLri5n8rY7x4WUpMaY82mcXNIgbil30iHvc01OsiizhZC1KQHTK90RFMFWSpwFU+ON3aA==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@napi-rs/canvas-linux-x64-musl@1.0.5': + resolution: {integrity: sha512-Npthji25t7FUqIAKsoEkFS0qY5CYVkHjvI3tuZjDTG92wX8g4dst+Lfb4hhubdqPazlDcIwalPzInsFCtf3FFg==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@napi-rs/canvas-win32-arm64-msvc@1.0.5': + resolution: {integrity: sha512-bi+JsdCdbfVJDoAQybTYmkLKwh1xpYpptg5j/BNr2BB56u4/R26jrVvtjqff+CxYMXV6Kz1/jeDVhZCuj6bDng==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [win32] + + '@napi-rs/canvas-win32-x64-msvc@1.0.5': + resolution: {integrity: sha512-KQQwG9/sBmcGxqaLFIQf+k2OefREGoyEaIBmRuTM8bUuFKOEE9Xk5pel90hE6pmBwk/vo4RB0OdX+FxobJGMFw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [win32] + + '@napi-rs/canvas@1.0.5': + resolution: {integrity: sha512-GaPlicMtnvgPr5SowFRprkEJicDSrV3qCq17U4jiF5u0kNORZo3IbdN2Bk4SfcZJAMYFHbMVJ81O3w21CYxazg==} + engines: {node: '>= 10'} + '@napi-rs/wasm-runtime@1.2.2': resolution: {integrity: sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==} engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} @@ -1163,10 +1250,18 @@ packages: cpu: [x64] os: [win32] + '@noble/ciphers@1.3.0': + resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==} + engines: {node: ^14.21.3 || >=16} + '@noble/ciphers@2.3.0': resolution: {integrity: sha512-Clu/xdfgVTf9o7ngLOURaxePwR0j8sjclKEtVij10/jGulwFsPWCvvRgG/XjUVf8Nei+jLG6uwyXzUTGY1DQrw==} engines: {node: '>= 20.19.0'} + '@noble/hashes@1.8.0': + resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} + engines: {node: ^14.21.3 || >=16} + '@noble/hashes@2.3.0': resolution: {integrity: sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==} engines: {node: '>= 20.19.0'} @@ -1495,6 +1590,12 @@ packages: '@types/nodemailer@8.0.1': resolution: {integrity: sha512-PxpaInm8V1JQDd4j0ds5HfvWQk8JupS1C0Picb96QJsrrRDjBH+DlK7L4ZdNSqNULhiZRQHc40nLVShaGxXAMw==} + '@types/pdfkit@0.17.6': + resolution: {integrity: sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==} + + '@types/pdfmake@0.3.3': + resolution: {integrity: sha512-ufbceB4Q3dKpmFUMKEbZvJcfLi8+C5b1+rTFVG6urtkS3FHwaTQH6NCh/iEEDINlApCxH/W3/rsq99pP5E9/JA==} + '@types/pg@8.21.0': resolution: {integrity: sha512-AYdtudzabjLZgVgRZmAnU8bAnVUXzuJX2IYHeSIiIHm68olD+LgQYCGWdtcNYnP0uq9c4S4NibVG3Ni7VbKW7Q==} @@ -1913,6 +2014,10 @@ packages: bare-url@2.5.1: resolution: {integrity: sha512-cD5ciQuKlx+eumTCfqbfiL+fhQm+dHbVNB/cX4+d+I/nx4JsVop9VoFEPAs5RJ6I84QR6bZIBjpd2kjDOYeWcg==} + base64-js@0.0.8: + resolution: {integrity: sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==} + engines: {node: '>= 0.4'} + base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} @@ -2014,6 +2119,12 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} + brotli@1.3.3: + resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==} + + browserify-zlib@0.2.0: + resolution: {integrity: sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==} + browserslist@4.28.7: resolution: {integrity: sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} @@ -2081,6 +2192,10 @@ packages: resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} engines: {node: '>=12'} + clone@2.1.2: + resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==} + engines: {node: '>=0.8'} + color-convert@2.0.1: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} @@ -2193,6 +2308,9 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + dfa@1.2.0: + resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==} + docker-compose@1.4.2: resolution: {integrity: sha512-rPHigTKGaEHpkUmfd69QgaOp+Os5vGJwG/Ry8lcr8W/382AmI+z/D7qoa9BybKIkqNppaIbs8RYeHSevdQjWww==} engines: {node: '>= 6.0.0'} @@ -2594,6 +2712,9 @@ packages: flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + fontkit@2.0.4: + resolution: {integrity: sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==} + for-each@0.3.5: resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} engines: {node: '>= 0.4'} @@ -2901,6 +3022,9 @@ packages: jose@6.2.8: resolution: {integrity: sha512-Bsdjwm3Qsd/P0jR+BHDe3LytDfY7WBq2HmCCLIwuVRHMuEC9ae7/R474GIUdF1NgCyZjzVo/A9DOiOBtXq8ZoQ==} + js-md5@0.8.3: + resolution: {integrity: sha512-qR0HB5uP6wCuRMrWPTrkMaev7MJZwJuuw4fnwAzRgP4J4/F8RwtodOKpGp4XpqsLBFzzgqIO42efFAyz2Et6KQ==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -3117,6 +3241,9 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} + linebreak@1.1.0: + resolution: {integrity: sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==} + locate-path@6.0.0: resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} engines: {node: '>=10'} @@ -3338,6 +3465,12 @@ packages: package-json-from-dist@1.0.1: resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + pako@0.2.9: + resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==} + + pako@1.0.11: + resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} + parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -3366,6 +3499,17 @@ packages: pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pdfjs-dist@6.2.108: + resolution: {integrity: sha512-YxFb+SQcodN2rnX9Tn3dHYlqfb7NjlzzfONPpJd+AKoKtUjEdevTfbC07d5TcczzOK6261auRkP/M8OBHs9vFQ==} + engines: {node: '>=22.13.0 || >=24'} + + pdfkit@0.19.1: + resolution: {integrity: sha512-6Gzk+wDwTs4VSxsR5rCMTnIl5nlmkye1oWB0l2hDB1EX6ZNSIBroKQEv+2+fPPn+stVjyqzmsqRJVDfB9fo5DA==} + + pdfmake@0.3.11: + resolution: {integrity: sha512-Uc49J9hUMyuqJk+U+PxlpBpPr96A4HOOfesGx609EPr2ue82+5/Smq/KTAkEqh0/jUGSi1fumvqZ5yAWijJTJg==} + engines: {node: '>=20'} + pg-cloudflare@1.4.0: resolution: {integrity: sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==} @@ -3411,6 +3555,9 @@ packages: resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} engines: {node: '>=12'} + png-js@1.1.0: + resolution: {integrity: sha512-PM/uYGzGdNSzqeOgly68+6wKQDL1SY0a/N+OEa/+br6LnHWOAJB0Npiamnodfq3jd2LS/i2fMeOKSAILjA+m5Q==} + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -3539,6 +3686,9 @@ packages: engines: {node: '>= 0.4'} hasBin: true + restructure@3.0.2: + resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==} + retry@0.12.0: resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==} engines: {node: '>= 4'} @@ -3582,6 +3732,10 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + sax@1.6.1: + resolution: {integrity: sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==} + engines: {node: '>=11.0.0'} + saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} @@ -3822,6 +3976,9 @@ packages: text-decoder@1.2.7: resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==} + tiny-inflate@1.0.3: + resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -3930,6 +4087,12 @@ packages: resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==} engines: {node: '>=22.19.0'} + unicode-properties@1.4.1: + resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==} + + unicode-trie@2.0.0: + resolution: {integrity: sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==} + unrs-resolver@1.12.2: resolution: {integrity: sha512-dmlRxBJJayXjqTwC+JtF1HhJmgf3ftQ3YejFcZrf4+KKtJv0qDsK1pjqaaVjG7wJ5NJ6UVP1OqRMQ71Z4C3rxQ==} @@ -4100,6 +4263,10 @@ packages: xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + xmldoc@2.0.3: + resolution: {integrity: sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==} + engines: {node: '>=12.0.0'} + xtend@4.0.2: resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} engines: {node: '>=0.4'} @@ -4879,6 +5046,54 @@ snapshots: outvariant: 1.4.3 strict-event-emitter: 0.5.1 + '@napi-rs/canvas-android-arm64@1.0.5': + optional: true + + '@napi-rs/canvas-darwin-arm64@1.0.5': + optional: true + + '@napi-rs/canvas-darwin-x64@1.0.5': + optional: true + + '@napi-rs/canvas-linux-arm-gnueabihf@1.0.5': + optional: true + + '@napi-rs/canvas-linux-arm64-gnu@1.0.5': + optional: true + + '@napi-rs/canvas-linux-arm64-musl@1.0.5': + optional: true + + '@napi-rs/canvas-linux-riscv64-gnu@1.0.5': + optional: true + + '@napi-rs/canvas-linux-x64-gnu@1.0.5': + optional: true + + '@napi-rs/canvas-linux-x64-musl@1.0.5': + optional: true + + '@napi-rs/canvas-win32-arm64-msvc@1.0.5': + optional: true + + '@napi-rs/canvas-win32-x64-msvc@1.0.5': + optional: true + + '@napi-rs/canvas@1.0.5': + optionalDependencies: + '@napi-rs/canvas-android-arm64': 1.0.5 + '@napi-rs/canvas-darwin-arm64': 1.0.5 + '@napi-rs/canvas-darwin-x64': 1.0.5 + '@napi-rs/canvas-linux-arm-gnueabihf': 1.0.5 + '@napi-rs/canvas-linux-arm64-gnu': 1.0.5 + '@napi-rs/canvas-linux-arm64-musl': 1.0.5 + '@napi-rs/canvas-linux-riscv64-gnu': 1.0.5 + '@napi-rs/canvas-linux-x64-gnu': 1.0.5 + '@napi-rs/canvas-linux-x64-musl': 1.0.5 + '@napi-rs/canvas-win32-arm64-msvc': 1.0.5 + '@napi-rs/canvas-win32-x64-msvc': 1.0.5 + optional: true + '@napi-rs/wasm-runtime@1.2.2(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': dependencies: '@emnapi/core': 1.10.0 @@ -4919,8 +5134,12 @@ snapshots: '@next/swc-win32-x64-msvc@16.3.0': optional: true + '@noble/ciphers@1.3.0': {} + '@noble/ciphers@2.3.0': {} + '@noble/hashes@1.8.0': {} + '@noble/hashes@2.3.0': {} '@nodelib/fs.scandir@2.1.5': @@ -5179,6 +5398,15 @@ snapshots: dependencies: '@types/node': 24.13.3 + '@types/pdfkit@0.17.6': + dependencies: + '@types/node': 24.13.3 + + '@types/pdfmake@0.3.3': + dependencies: + '@types/node': 24.13.3 + '@types/pdfkit': 0.17.6 + '@types/pg@8.21.0': dependencies: '@types/node': 24.13.3 @@ -5605,6 +5833,8 @@ snapshots: dependencies: bare-path: 3.1.1 + base64-js@0.0.8: {} + base64-js@1.5.1: {} baseline-browser-mapping@2.11.12: {} @@ -5680,6 +5910,14 @@ snapshots: dependencies: fill-range: 7.1.1 + brotli@1.3.3: + dependencies: + base64-js: 1.5.1 + + browserify-zlib@0.2.0: + dependencies: + pako: 1.0.11 + browserslist@4.28.7: dependencies: baseline-browser-mapping: 2.11.12 @@ -5747,6 +5985,8 @@ snapshots: strip-ansi: 6.0.1 wrap-ansi: 7.0.0 + clone@2.1.2: {} + color-convert@2.0.1: dependencies: color-name: 1.1.4 @@ -5858,6 +6098,8 @@ snapshots: detect-libc@2.1.2: {} + dfa@1.2.0: {} + docker-compose@1.4.2: dependencies: yaml: 2.9.0 @@ -6403,6 +6645,18 @@ snapshots: flatted@3.4.4: {} + fontkit@2.0.4: + dependencies: + '@swc/helpers': 0.5.15 + brotli: 1.3.3 + clone: 2.1.2 + dfa: 1.2.0 + fast-deep-equal: 3.1.3 + restructure: 3.0.2 + tiny-inflate: 1.0.3 + unicode-properties: 1.4.1 + unicode-trie: 2.0.0 + for-each@0.3.5: dependencies: is-callable: 1.2.7 @@ -6712,6 +6966,8 @@ snapshots: jose@6.2.8: {} + js-md5@0.8.3: {} + js-tokens@4.0.0: {} js-yaml@4.3.1: @@ -6886,6 +7142,11 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 + linebreak@1.1.0: + dependencies: + base64-js: 0.0.8 + unicode-trie: 2.0.0 + locate-path@6.0.0: dependencies: p-locate: 5.0.0 @@ -7107,6 +7368,10 @@ snapshots: package-json-from-dist@1.0.1: {} + pako@0.2.9: {} + + pako@1.0.11: {} + parent-module@1.0.1: dependencies: callsites: 3.1.0 @@ -7130,6 +7395,25 @@ snapshots: pathe@2.0.3: {} + pdfjs-dist@6.2.108: + optionalDependencies: + '@napi-rs/canvas': 1.0.5 + + pdfkit@0.19.1: + dependencies: + '@noble/ciphers': 1.3.0 + '@noble/hashes': 1.8.0 + fontkit: 2.0.4 + js-md5: 0.8.3 + linebreak: 1.1.0 + png-js: 1.1.0 + + pdfmake@0.3.11: + dependencies: + linebreak: 1.1.0 + pdfkit: 0.19.1 + xmldoc: 2.0.3 + pg-cloudflare@1.4.0: optional: true @@ -7171,6 +7455,10 @@ snapshots: picomatch@4.0.5: {} + png-js@1.1.0: + dependencies: + browserify-zlib: 0.2.0 + possible-typed-array-names@1.1.0: {} postcss@8.5.23: @@ -7330,6 +7618,8 @@ snapshots: path-parse: 1.0.7 supports-preserve-symlinks-flag: 1.0.0 + restructure@3.0.2: {} + retry@0.12.0: {} rettime@0.11.11: {} @@ -7387,6 +7677,8 @@ snapshots: safer-buffer@2.1.2: {} + sax@1.6.1: {} + saxes@6.0.0: dependencies: xmlchars: 2.2.0 @@ -7729,6 +8021,8 @@ snapshots: transitivePeerDependencies: - react-native-b4a + tiny-inflate@1.0.3: {} + tinybench@2.9.0: {} tinyexec@1.3.0: {} @@ -7848,6 +8142,16 @@ snapshots: undici@8.10.0: {} + unicode-properties@1.4.1: + dependencies: + base64-js: 1.5.1 + unicode-trie: 2.0.0 + + unicode-trie@2.0.0: + dependencies: + pako: 0.2.9 + tiny-inflate: 1.0.3 + unrs-resolver@1.12.2: dependencies: napi-postinstall: 0.3.4 @@ -8026,6 +8330,10 @@ snapshots: xmlchars@2.2.0: {} + xmldoc@2.0.3: + dependencies: + sax: 1.6.1 + xtend@4.0.2: {} y18n@5.0.8: {} diff --git a/scripts/render-pdf-fixture.ts b/scripts/render-pdf-fixture.ts new file mode 100644 index 0000000..fd69791 --- /dev/null +++ b/scripts/render-pdf-fixture.ts @@ -0,0 +1,218 @@ +#!/usr/bin/env tsx +/** + * Renders stress-test PDFs from BillingReportSnapshot fixtures into tmp/pdfs/. + * + * Covers: 1 row, 60 rows, long German company/address text, long + * filenames/purposes, umlauts (äöüß), and a 3-page case. + * + * Run: pnpm tsx scripts/render-pdf-fixture.ts + * + * PNG visual inspection (pdftoppm) is deferred to Task 15 — this script only + * generates the PDFs. When pdftoppm is available, run: + * pdftoppm -png tmp/pdfs/billing-stress.pdf tmp/pdfs/billing-stress + */ + +import { promises as fs } from "node:fs"; +import path from "node:path"; + +import type { BillingReportSnapshot } from "../src/modules/billing/types"; +import { renderBillingPdf } from "../src/modules/pdf/render"; + +const OUTPUT_DIR = path.join(process.cwd(), "tmp", "pdfs"); + +function baseAddress() { + return { + companyName: "Redaktion Beispiel GmbH", + contactName: "Anna Schmidt", + addressLine1: "Musterstraße 12", + addressLine2: null as string | null, + postalCode: "10115", + city: "Berlin", + countryCode: "DE", + }; +} + +function basePosition(priceCents = 6_000) { + return { + id: "pos-1", + assetId: "asset-1", + filename: "jubel-eroeffnung.jpg", + albumName: "Jubel", + purpose: "Print Nutzung", + reference: "REF-001" as string | null, + priceCents, + createdAt: new Date("2026-03-15T10:00:00.000Z"), + }; +} + +function baseRepeatDownload() { + return { + id: "rdl-1", + assetId: "asset-1", + usageId: "usage-1", + authorizedAt: new Date("2026-03-20T14:00:00.000Z"), + repeatDownloadNote: "Zweitverwendung im Web" as string | null, + }; +} + +function baseSnapshot(overrides: Partial = {}): BillingReportSnapshot { + return { + address: baseAddress(), + selectedPositions: [basePosition()], + repeatDownloads: [baseRepeatDownload()], + netTotalCents: 6_000, + reportNumber: 1, + invoiceNumber: "NN-2026-03-001", + period: { + fromUtc: new Date("2026-03-01T00:00:00.000Z"), + toUtcExclusive: new Date("2026-04-01T00:00:00.000Z"), + }, + documentId: "doc-00000000-0000-0000-0000-000000000001", + createdAt: new Date("2026-04-02T08:00:00.000Z"), + legalSeparationNotice: + "Dieser Nutzungsnachweis ist keine Rechnung im Sinne des Umsatzsteuerrechts.", + ...overrides, + }; +} + +// --- Fixture builders ------------------------------------------------------- + +function oneRowFixture(): BillingReportSnapshot { + return baseSnapshot(); +} + +function sixtyRowsFixture(): BillingReportSnapshot { + const positions = Array.from({ length: 60 }, (_, i) => ({ + ...basePosition(500), + id: `pos-${i + 1}`, + assetId: `asset-${i + 1}`, + filename: `bild-${String(i + 1).padStart(3, "0")}.jpg`, + reference: `REF-${String(i + 1).padStart(3, "0")}`, + })); + const netTotal = positions.reduce((sum, p) => sum + p.priceCents, 0); + return baseSnapshot({ + selectedPositions: positions, + repeatDownloads: [], + netTotalCents: netTotal, + invoiceNumber: "NN-2026-03-060", + }); +} + +function longAddressFixture(): BillingReportSnapshot { + return baseSnapshot({ + address: { + companyName: "Süddeutsche Verlagsgesellschaft mbH & Co. KG Herausgeber-Bevollmächtigte", + contactName: "Dr. Maximilian von und zu Müllendorf-Wiesenbach", + addressLine1: "Königsallee 42a, Hinterhof 3. Stock, Raum 312", + addressLine2: "Nebengebäude bei der alten Mühle", + postalCode: "80331", + city: "München", + countryCode: "DE", + }, + invoiceNumber: "NN-2026-03-LONG", + }); +} + +function longFieldsFixture(): BillingReportSnapshot { + return baseSnapshot({ + selectedPositions: [ + { + ...basePosition(12_500), + id: "pos-long-1", + filename: "jahreshauptversammlung-eroeffnungsrede-vorstandsvorsitzender-2026.jpg", + albumName: "Jahreshauptversammlung 2026 — Rückblick und Ausblick", + purpose: "Print-Nutzung in der Sonderbeilage zum Jahresrückblick der Zeitung", + reference: "REF-Sonderbeilage-2026-Q1-001", + }, + { + ...basePosition(8_750), + id: "pos-long-2", + filename: "pressekonferenz-ministerpräsident-bayern-klimaschutzgesetz.jpg", + albumName: "Pressekonferenz Klimaschutz", + purpose: "Online-Nutzung im Nachrichtenportal sowie Print-Ausgabe", + reference: "REF-PK-Klima-2026-03-15", + }, + ], + netTotalCents: 21_250, + invoiceNumber: "NN-2026-03-LONGFIELDS", + }); +} + +function umlautsFixture(): BillingReportSnapshot { + return baseSnapshot({ + selectedPositions: [ + { + ...basePosition(3_500), + id: "pos-umlaut-1", + filename: "münchen-strße-österreich.jpg", + albumName: "Münchner Straße Österreich", + purpose: "Äöüß Nutzung für Flüsse und Öfen", + reference: "REF-ÄÖÜß-001", + }, + ], + repeatDownloads: [ + { + ...baseRepeatDownload(), + id: "rdl-umlaut-1", + repeatDownloadNote: "Zweitverwendung für Grüße aus Übersee", + }, + ], + netTotalCents: 3_500, + invoiceNumber: "NN-2026-03-UMLAUT", + }); +} + +function threePageFixture(): BillingReportSnapshot { + const positions = Array.from({ length: 45 }, (_, i) => ({ + ...basePosition(300), + id: `pos-3p-${i + 1}`, + assetId: `asset-3p-${i + 1}`, + filename: `seite3-bild-${String(i + 1).padStart(3, "0")}.jpg`, + albumName: `Album ${i + 1}`, + purpose: `Nutzung ${i + 1}`, + reference: `REF-3P-${String(i + 1).padStart(3, "0")}`, + })); + const downloads = Array.from({ length: 30 }, (_, i) => ({ + ...baseRepeatDownload(), + id: `rdl-3p-${i + 1}`, + assetId: `asset-3p-${i + 1}`, + usageId: `usage-3p-${i + 1}`, + repeatDownloadNote: `Hinweis für Download ${i + 1}`, + })); + const netTotal = positions.reduce((sum, p) => sum + p.priceCents, 0); + return baseSnapshot({ + selectedPositions: positions, + repeatDownloads: downloads, + netTotalCents: netTotal, + invoiceNumber: "NN-2026-03-3PAGE", + }); +} + +// --- Main ------------------------------------------------------------------- + +async function main() { + await fs.mkdir(OUTPUT_DIR, { recursive: true }); + + const fixtures: Array<{ name: string; snapshot: BillingReportSnapshot }> = [ + { name: "billing-one-row.pdf", snapshot: oneRowFixture() }, + { name: "billing-60-rows.pdf", snapshot: sixtyRowsFixture() }, + { name: "billing-long-address.pdf", snapshot: longAddressFixture() }, + { name: "billing-long-fields.pdf", snapshot: longFieldsFixture() }, + { name: "billing-umlauts.pdf", snapshot: umlautsFixture() }, + { name: "billing-stress.pdf", snapshot: threePageFixture() }, + ]; + + for (const { name, snapshot } of fixtures) { + const result = await renderBillingPdf(snapshot); + const outPath = path.join(OUTPUT_DIR, name); + await fs.writeFile(outPath, result.bytes); + console.log(`${name} ${result.bytes.length} bytes sha256=${result.sha256.slice(0, 16)}…`); + } + + console.log(`\nDone. ${fixtures.length} PDFs written to ${OUTPUT_DIR}/`); +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); \ No newline at end of file diff --git a/src/modules/billing/types.ts b/src/modules/billing/types.ts new file mode 100644 index 0000000..b0a1f12 --- /dev/null +++ b/src/modules/billing/types.ts @@ -0,0 +1,75 @@ +import type { BillingPeriod } from "./period"; + +/** + * Recipient address for a billing report, mirroring the editable fields of + * `billingAddressVersions`. The address is snapshotted at report creation time + * so the PDF remains immutable even if the editorial account's address changes + * later. + */ +export type BillingReportAddress = { + companyName: string; + contactName: string; + addressLine1: string; + addressLine2: string | null; + postalCode: string; + city: string; + countryCode: string; +}; + +/** + * A billable usage position included in the report. Corresponds to a + * `BillingPosition` from the billing queries module but is duplicated here so + * the snapshot type does not pull in the database layer. + */ +export type BillingReportPosition = { + id: string; + assetId: string; + filename: string; + albumName: string; + purpose: string; + reference: string | null; + priceCents: number; + createdAt: Date; +}; + +/** + * A repeat-download position that was authorised during the period but not + * billed again. Corresponds to a `RepeatDownloadPosition` from the billing + * queries module. + */ +export type BillingReportRepeatDownload = { + id: string; + assetId: string; + usageId: string; + authorizedAt: Date; + repeatDownloadNote: string | null; +}; + +/** + * Immutable snapshot of everything the PDF renderer needs to produce a + * "Nutzungsnachweis" document. Task 12 builds this from database rows and + * passes it to `renderBillingPdf`. The renderer never reads the live database + * or Immich — it accepts only this self-contained value. + */ +export type BillingReportSnapshot = { + /** Recipient address block. */ + address: BillingReportAddress; + /** Selected, paid billing positions for the period. */ + selectedPositions: BillingReportPosition[]; + /** Repeat downloads authorised during the period (not re-billed). */ + repeatDownloads: BillingReportRepeatDownload[]; + /** Net total in integer Euro cents (sum of selected position prices). */ + netTotalCents: number; + /** Sequential report number. */ + reportNumber: number; + /** Human-readable invoice reference. */ + invoiceNumber: string; + /** Half-open UTC billing period. */ + period: BillingPeriod; + /** Unique document identifier (UUID). */ + documentId: string; + /** Moment the report was created (UTC). */ + createdAt: Date; + /** Legal notice clarifying that the report is not a VAT invoice. */ + legalSeparationNotice: string; +}; \ No newline at end of file diff --git a/src/modules/pdf/document.ts b/src/modules/pdf/document.ts new file mode 100644 index 0000000..13d0c0b --- /dev/null +++ b/src/modules/pdf/document.ts @@ -0,0 +1,385 @@ +import "server-only"; + +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { formatCents } from "@/modules/billing/format"; +import type { BillingReportSnapshot } from "@/modules/billing/types"; + +// --------------------------------------------------------------------------- +// Font: IBM Plex Mono (SIL Open Font License 1.1) +// TTF files are vendored under src/modules/pdf/fonts/ — see LICENSE.txt. +// --------------------------------------------------------------------------- + +export const FONT_NAME = "IBMPlexMono"; + +// --------------------------------------------------------------------------- +// Colors (monochrome palette) +// --------------------------------------------------------------------------- + +const BLACK = "#000000"; +const WHITE = "#FFFFFF"; +const LIGHT_GRAY = "#F2F2F2"; +const MEDIUM_GRAY = "#888888"; + +// --------------------------------------------------------------------------- +// Date formatting (Europe/Berlin, German format) +// --------------------------------------------------------------------------- + +function formatGermanDate(date: Date): string { + return new Intl.DateTimeFormat("de-DE", { + timeZone: "Europe/Berlin", + day: "2-digit", + month: "2-digit", + year: "numeric", + }).format(date); +} + +function formatPeriodRange(fromUtc: Date, toUtcExclusive: Date): string { + return `${formatGermanDate(fromUtc)} – ${formatGermanDate(toUtcExclusive)}`; +} + +// --------------------------------------------------------------------------- +// Logo (base64 data URL, read at build time from public/brand/logo-black.png) +// --------------------------------------------------------------------------- + +function logoDataUrl(): string { + const logoPath = path.join(process.cwd(), "public", "brand", "logo-black.png"); + const buffer = readFileSync(logoPath); + return `data:image/png;base64,${buffer.toString("base64")}`; +} + +// --------------------------------------------------------------------------- +// Table builders +// --------------------------------------------------------------------------- + +function paidPositionsTable(snapshot: BillingReportSnapshot) { + const headerRow = [ + { text: "Datei", style: "tableHeader" }, + { text: "Album", style: "tableHeader" }, + { text: "Zweck", style: "tableHeader" }, + { text: "Referenz", style: "tableHeader" }, + { text: "Datum", style: "tableHeader", alignment: "right" as const }, + { text: "Betrag", style: "tableHeader", alignment: "right" as const }, + ]; + + const body = [headerRow]; + + for (const pos of snapshot.selectedPositions) { + body.push([ + { text: pos.filename, style: "tableCell" }, + { text: pos.albumName, style: "tableCell" }, + { text: pos.purpose, style: "tableCell" }, + { text: pos.reference ?? "", style: "tableCell" }, + { text: formatGermanDate(pos.createdAt), style: "tableCell", alignment: "right" as const }, + { text: formatCents(pos.priceCents), style: "tableCell", alignment: "right" as const }, + ]); + } + + return { + table: { + headerRows: 1, + widths: ["*", "auto", "auto", "auto", "auto", "auto"], + body, + }, + layout: { + fillColor: (rowIndex: number) => { + if (rowIndex === 0) return BLACK; + return rowIndex % 2 === 0 ? LIGHT_GRAY : WHITE; + }, + hLineColor: () => MEDIUM_GRAY, + vLineColor: () => MEDIUM_GRAY, + hLineWidth: () => 0.5, + vLineWidth: () => 0.5, + }, + margin: [0, 0, 0, 16], + }; +} + +function repeatDownloadsTable(snapshot: BillingReportSnapshot) { + const headerRow = [ + { text: "Datei", style: "tableHeader" }, + { text: "Nutzung", style: "tableHeader" }, + { text: "Datum", style: "tableHeader", alignment: "right" as const }, + { text: "Hinweis", style: "tableHeader" }, + ]; + + const body = [headerRow]; + + for (const dl of snapshot.repeatDownloads) { + body.push([ + { text: dl.assetId, style: "tableCell" }, + { text: dl.usageId, style: "tableCell" }, + { text: formatGermanDate(dl.authorizedAt), style: "tableCell", alignment: "right" as const }, + { text: dl.repeatDownloadNote ?? "", style: "tableCell" }, + ]); + } + + return { + table: { + headerRows: 1, + widths: ["auto", "auto", "auto", "*"], + body, + }, + layout: { + fillColor: (rowIndex: number) => { + if (rowIndex === 0) return BLACK; + return rowIndex % 2 === 0 ? LIGHT_GRAY : WHITE; + }, + hLineColor: () => MEDIUM_GRAY, + vLineColor: () => MEDIUM_GRAY, + hLineWidth: () => 0.5, + vLineWidth: () => 0.5, + }, + margin: [0, 0, 0, 16], + }; +} + +// --------------------------------------------------------------------------- +// Document definition +// --------------------------------------------------------------------------- + +export function buildDocumentDefinition(snapshot: BillingReportSnapshot) { + const addr = snapshot.address; + const addressLines = [ + addr.companyName, + addr.contactName, + addr.addressLine1, + addr.addressLine2, + `${addr.postalCode} ${addr.city}`, + addr.countryCode, + ].filter((line): line is string => line !== null && line.length > 0); + + const doc = { + pageSize: "A4", + pageMargins: [40, 120, 40, 60], + defaultStyle: { + font: FONT_NAME, + fontSize: 9, + lineHeight: 1.3, + color: BLACK, + }, + styles: { + title: { + font: FONT_NAME, + fontSize: 20, + bold: true, + margin: [0, 20, 0, 12], + }, + sectionHeading: { + font: FONT_NAME, + fontSize: 11, + bold: true, + margin: [0, 16, 0, 8], + }, + tableHeader: { + font: FONT_NAME, + fontSize: 8, + bold: true, + color: WHITE, + }, + tableCell: { + font: FONT_NAME, + fontSize: 8, + }, + summaryLabel: { + font: FONT_NAME, + fontSize: 11, + bold: true, + color: WHITE, + }, + summaryValue: { + font: FONT_NAME, + fontSize: 16, + bold: true, + color: WHITE, + }, + small: { + font: FONT_NAME, + fontSize: 7, + color: MEDIUM_GRAY, + }, + sender: { + font: FONT_NAME, + fontSize: 7, + color: MEDIUM_GRAY, + }, + recipient: { + font: FONT_NAME, + fontSize: 9, + }, + legal: { + font: FONT_NAME, + fontSize: 8, + color: MEDIUM_GRAY, + }, + }, + images: { + logo: logoDataUrl(), + }, + header: (_currentPage: number, pageSize: { width: number; height: number }) => ({ + margin: [40, 30, 40, 10], + stack: [ + { + columns: [ + { + image: "logo", + width: 120, + }, + { + width: "*", + stack: [ + { text: "Redaktionsportal", style: "sender", alignment: "right" as const }, + { text: "Nutzungsnachweis-Service", style: "sender", alignment: "right" as const }, + ], + margin: [0, 4, 0, 0], + }, + ], + }, + { + canvas: [ + { + type: "line", + x1: 0, + y1: 10, + x2: pageSize.width - 80, + y2: 10, + lineWidth: 1, + lineColor: BLACK, + }, + ], + margin: [0, 8, 0, 0], + }, + ], + }), + footer: (currentPage: number, pageCount: number) => ({ + margin: [40, 20, 40, 0], + stack: [ + { + canvas: [ + { + type: "line", + x1: 0, + y1: 0, + x2: 515, + y2: 0, + lineWidth: 0.5, + lineColor: MEDIUM_GRAY, + }, + ], + }, + { + columns: [ + { text: `Dokument-ID: ${snapshot.documentId}`, style: "small" }, + { text: `Rechnung: ${snapshot.invoiceNumber}`, style: "small" }, + { + text: `Seite ${currentPage} / ${pageCount}`, + style: "small", + alignment: "right" as const, + }, + ], + margin: [0, 4, 0, 0], + }, + ], + }), + content: [ + // Recipient block + { + stack: addressLines.map((line) => ({ text: line, style: "recipient" })), + margin: [0, 0, 0, 20], + }, + + // Title + { text: "Nutzungsnachweis", style: "title" }, + + // Metadata block + { + columns: [ + { + width: "auto", + stack: [ + { text: "Berichtsnummer", style: "small" }, + { text: String(snapshot.reportNumber), style: "recipient", margin: [0, 0, 0, 6] }, + { text: "Abrechnungszeitraum", style: "small" }, + { + text: formatPeriodRange(snapshot.period.fromUtc, snapshot.period.toUtcExclusive), + style: "recipient", + margin: [0, 0, 0, 6], + }, + { text: "Erstellt am", style: "small" }, + { text: formatGermanDate(snapshot.createdAt), style: "recipient" }, + ], + }, + { + width: "*", + stack: [ + { text: "Rechnungsnummer", style: "small" }, + { text: snapshot.invoiceNumber, style: "recipient", margin: [0, 0, 0, 6] }, + { text: "Dokument-ID", style: "small" }, + { text: snapshot.documentId, style: "recipient" }, + ], + }, + ], + margin: [0, 0, 0, 16], + }, + + // Rounded black summary panel + { + canvas: [ + { + type: "rect", + x: 0, + y: 0, + w: 515, + h: 60, + r: 8, + lineColor: BLACK, + fillColor: BLACK, + }, + ], + margin: [0, 0, 0, 4], + }, + { + // Overlay text on the summary panel (absolute positioning via column trick) + margin: [16, -52, 16, 0], + columns: [ + { + width: "*", + text: "Gesamtbetrag (Netto)", + style: "summaryLabel", + margin: [0, 8, 0, 0], + }, + { + width: "auto", + text: formatCents(snapshot.netTotalCents), + style: "summaryValue", + margin: [0, 4, 0, 0], + }, + ], + }, + { text: "", margin: [0, 0, 0, 16] }, + + // Paid positions section + { text: "Berechnete Bildnutzungen", style: "sectionHeading" }, + paidPositionsTable(snapshot), + + // Repeat downloads section + { text: "Nicht erneut berechnete Downloads", style: "sectionHeading" }, + repeatDownloadsTable(snapshot), + + // Legal separation notice + { text: snapshot.legalSeparationNotice, style: "legal", margin: [0, 20, 0, 0] }, + ], + info: { + title: `Nutzungsnachweis ${snapshot.invoiceNumber}`, + author: "Redaktionsportal", + subject: `Nutzungsnachweis für den Zeitraum ${formatPeriodRange( + snapshot.period.fromUtc, + snapshot.period.toUtcExclusive, + )}`, + creationDate: snapshot.createdAt, + }, + }; + + return doc; +} \ No newline at end of file diff --git a/src/modules/pdf/fonts/IBMPlexMono-Bold.ttf b/src/modules/pdf/fonts/IBMPlexMono-Bold.ttf new file mode 100644 index 0000000..9a168d2 Binary files /dev/null and b/src/modules/pdf/fonts/IBMPlexMono-Bold.ttf differ diff --git a/src/modules/pdf/fonts/IBMPlexMono-Italic.ttf b/src/modules/pdf/fonts/IBMPlexMono-Italic.ttf new file mode 100644 index 0000000..950842a Binary files /dev/null and b/src/modules/pdf/fonts/IBMPlexMono-Italic.ttf differ diff --git a/src/modules/pdf/fonts/IBMPlexMono-Regular.ttf b/src/modules/pdf/fonts/IBMPlexMono-Regular.ttf new file mode 100644 index 0000000..4254c37 Binary files /dev/null and b/src/modules/pdf/fonts/IBMPlexMono-Regular.ttf differ diff --git a/src/modules/pdf/fonts/LICENSE.txt b/src/modules/pdf/fonts/LICENSE.txt new file mode 100644 index 0000000..f72f765 --- /dev/null +++ b/src/modules/pdf/fonts/LICENSE.txt @@ -0,0 +1,92 @@ +Copyright © 2017 IBM Corp. with Reserved Font Name "Plex" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/src/modules/pdf/render.test.ts b/src/modules/pdf/render.test.ts new file mode 100644 index 0000000..53dc262 --- /dev/null +++ b/src/modules/pdf/render.test.ts @@ -0,0 +1,54 @@ +import { createRequire } from "node:module"; + +import { expect, test } from "vitest"; + +import { reportFixture } from "../../../tests/fixtures/billing-report"; + +import { renderBillingPdf } from "./render"; + +const require = createRequire(import.meta.url); + +/** + * Extracts all text content from a PDF buffer using pdfjs-dist. Uses the + * legacy build which does not require browser APIs (DOMMatrix etc.) and + * loads the worker from the filesystem so it works in the Node test env. + */ +async function extractPdfText(bytes: Buffer): Promise { + const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs"); + const workerPath = require.resolve("pdfjs-dist/legacy/build/pdf.worker.mjs"); + pdfjs.GlobalWorkerOptions.workerSrc = workerPath; + const loadingTask = pdfjs.getDocument({ + data: new Uint8Array(bytes), + verbosity: 0, + useWorkerFetch: false, + }); + const pdf = await loadingTask.promise; + const parts: string[] = []; + for (let i = 1; i <= pdf.numPages; i++) { + const page = await pdf.getPage(i); + const content = await page.getTextContent(); + for (const item of content.items) { + if ("str" in item) { + parts.push(item.str); + } + } + } + await loadingTask.destroy(); + return parts.join(" ").replace(/\s+/g, " ").trim(); +} + +test("renders paid and free-repeat sections with the net total", async () => { + const result = await renderBillingPdf(reportFixture); + const text = await extractPdfText(result.bytes); + expect(text).toContain("Nutzungsnachweis"); + expect(text).toContain("Berechnete Bildnutzungen"); + expect(text).toContain("Nicht erneut berechnete Downloads"); + expect(text).toContain("60,00 EUR"); + expect(result.sha256).toMatch(/^[a-f0-9]{64}$/); +}); + +test("pdf buffer is non-empty and starts with the PDF magic header", async () => { + const result = await renderBillingPdf(reportFixture); + expect(result.bytes.length).toBeGreaterThan(1000); + expect(result.bytes.subarray(0, 5).toString("ascii")).toBe("%PDF-"); +}); \ No newline at end of file diff --git a/src/modules/pdf/render.ts b/src/modules/pdf/render.ts new file mode 100644 index 0000000..f19881c --- /dev/null +++ b/src/modules/pdf/render.ts @@ -0,0 +1,76 @@ +import "server-only"; + +import { createHash } from "node:crypto"; +import { createRequire } from "node:module"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import type { BillingReportSnapshot } from "@/modules/billing/types"; + +import { buildDocumentDefinition, FONT_NAME } from "./document"; + +// --------------------------------------------------------------------------- +// Font: IBM Plex Mono — SIL Open Font License 1.1 (see fonts/LICENSE.txt) +// The TTF files are vendored under src/modules/pdf/fonts/ and embedded into +// the PDF via pdfmake's virtual filesystem so the renderer never reads the +// real filesystem at render time. +// --------------------------------------------------------------------------- + +const FONTS_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "fonts"); + +interface PdfMakeInstance { + createPdf(docDefinition: unknown): { getBuffer(): Promise }; + setFonts(fonts: Record): void; + setLocalAccessPolicy(callback: (p: string) => boolean): void; + virtualfs: { + writeFileSync(filename: string, content: Buffer): void; + existsSync(filename: string): boolean; + }; +} + +// pdfmake exports a CommonJS singleton; use createRequire to preserve the +// `this` context that methods like setFonts rely on. +const require = createRequire(import.meta.url); +const pdfmake = require("pdfmake") as PdfMakeInstance; + +function readFont(filename: string): Buffer { + return readFileSync(path.join(FONTS_DIR, filename)); +} + +// Register fonts once at module load time. Writing to the VFS is idempotent — +// overwriting the same key with the same buffer is a no-op. +pdfmake.virtualfs.writeFileSync("IBMPlexMono-Regular.ttf", readFont("IBMPlexMono-Regular.ttf")); +pdfmake.virtualfs.writeFileSync("IBMPlexMono-Bold.ttf", readFont("IBMPlexMono-Bold.ttf")); +pdfmake.virtualfs.writeFileSync("IBMPlexMono-Italic.ttf", readFont("IBMPlexMono-Italic.ttf")); + +pdfmake.setFonts({ + [FONT_NAME]: { + normal: "IBMPlexMono-Regular.ttf", + bold: "IBMPlexMono-Bold.ttf", + italics: "IBMPlexMono-Italic.ttf", + bolditalics: "IBMPlexMono-Bold.ttf", + }, +}); + +// Allow pdfmake to read font files from the VFS and the logo from the real +// filesystem (the logo is loaded as a base64 data URL in document.ts, so no +// real file access is needed at render time). +pdfmake.setLocalAccessPolicy(() => true); + +// --------------------------------------------------------------------------- +// Renderer +// --------------------------------------------------------------------------- + +export type RenderedPdf = { + bytes: Buffer; + sha256: string; +}; + +export async function renderBillingPdf(snapshot: BillingReportSnapshot): Promise { + const docDefinition = buildDocumentDefinition(snapshot); + const pdf = pdfmake.createPdf(docDefinition); + const bytes = await pdf.getBuffer(); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + return { bytes, sha256 }; +} \ No newline at end of file diff --git a/tests/fixtures/billing-report.ts b/tests/fixtures/billing-report.ts new file mode 100644 index 0000000..d4ae5a1 --- /dev/null +++ b/tests/fixtures/billing-report.ts @@ -0,0 +1,49 @@ +import type { BillingReportSnapshot } from "@/modules/billing/types"; + +/** + * Minimal, deterministic snapshot used by the render test. The net total is + * 6000 cents so the PDF displays "60,00 EUR" (the value the test asserts on). + */ +export const reportFixture: BillingReportSnapshot = { + address: { + companyName: "Redaktion Beispiel GmbH", + contactName: "Anna Schmidt", + addressLine1: "Musterstraße 12", + addressLine2: null, + postalCode: "10115", + city: "Berlin", + countryCode: "DE", + }, + selectedPositions: [ + { + id: "pos-1", + assetId: "asset-1", + filename: "jubel-eroeffnung.jpg", + albumName: "Jubel", + purpose: "Print Nutzung", + reference: "REF-001", + priceCents: 6_000, + createdAt: new Date("2026-03-15T10:00:00.000Z"), + }, + ], + repeatDownloads: [ + { + id: "rdl-1", + assetId: "asset-1", + usageId: "usage-1", + authorizedAt: new Date("2026-03-20T14:00:00.000Z"), + repeatDownloadNote: "Zweitverwendung im Web", + }, + ], + netTotalCents: 6_000, + reportNumber: 1, + invoiceNumber: "NN-2026-03-001", + period: { + fromUtc: new Date("2026-03-01T00:00:00.000Z"), + toUtcExclusive: new Date("2026-04-01T00:00:00.000Z"), + }, + documentId: "doc-00000000-0000-0000-0000-000000000001", + createdAt: new Date("2026-04-02T08:00:00.000Z"), + legalSeparationNotice: + "Dieser Nutzungsnachweis ist keine Rechnung im Sinne des Umsatzsteuerrechts.", +}; \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index ea6d6f6..fa82ac0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -25,6 +25,9 @@ "paths": { "@/*": [ "./src/*" + ], + "server-only": [ + "./src/test/server-only.ts" ] } },