ProdyPanda Factures Knowledge & Architecture Wiki

🌐 Language: English | Français | العربية

Level 5 — Expert / System Administration, Security, OCR, Schema & REST API#

Level 5 is the complete technical handbook for administrators, IT operators, and developers deploying, securing, customizing, or integrating with ProdyPanda Factures.

For Print Studio, stock, production and the N1–N8 API/workflows, see the Agency operations guide.


1. Multi-Company Profiles & A4 Templates#

A. Multi-Company / Brand Profiles#

If you operate multiple Tunisian entities, sister brands, or freelance + SARL identities from one installation:

  1. Open Paramètres & Taxes → Profils Sociétés, Style de Modèle A4 & Portail Client.
  2. Click + Ajouter un profil société to define an additional issuer profile (Display Name, Legal Name, Address, Phone, Code TVA / MF, City, RIB, Bank Name, Footer Address, Website, Email, Signature Label, Logo Text/Tagline).
  3. Inside Studio Facture (A4), choose the active emitter in Profil société émettrice (#doc-company-profile). The invoice header, tax ID, RIB footer, branded email template, and legal signatures all switch dynamically per document!

B. A4 Invoice Templates, Logos, Stamps & Verification QR#

Every document supports three official layout styles (set globally as defaultTemplateStyle or overridden per document):

Template IDUI LabelBest Use Case
classicClassique ProdyPanda OfficielExact pixel-accurate match to ProdyPanda. Sarl's official Tunisian invoice (Facture 20260300001).
modernModerne ÉpuréClean contemporary typography with crisp accent lines for international / creative clients.
compactCompact (Multi-lignes)Tighter vertical spacing optimized for long itemized bills to fit comfortably on fewer pages.
  • Logo & Stamp Controls: Upload custom PNG/SVG images (companyLogoDataUrl, companyStampDataUrl) or revert anytime with Logo ProdyPanda par défaut and Cachet vectoriel (a crisp procedural SVG corporate stamp generated automatically from your company name, city, and Code TVA).
  • Verification QR Code (showQrCode): Renders a clean inline SVG QR code on the bottom of the invoice encoding key document verification metadata (number, date, issuer MF, and net total).
  • Document Numbering Tokens (numberingPatterns): Customize per document type (FACTURE, DEVIS, PROFORMA, AVOIR, BON_LIVRAISON, BON_COMMANDE) using:
    • {YYYY} (4-digit year), {YY} (2-digit year), {MM} (2-digit month), {SEQ:N} (zero-padded sequence of width N).
    • Default pattern: {YYYY}{MM}{SEQ:5} → produces 20260300001.

2. Security & Role-Based Access Control (RBAC)#

Authentication and authorization are implemented in src/auth.js with zero external crypto dependencies (pure Node.js node:crypto).

The 3 Security Modes#

ModeConfiguration (settings)How Requests AuthenticateBest For
1. Open Local Mode (default)multiUserEnabled: false, passwordEnabled: falseAutomatic Local Admin (ADMIN role) — zero login frictionSingle-user personal workstation
2. PIN LockmultiUserEnabled: false, passwordEnabled: true, passwordPin setPOST /api/auth/unlock sets signed HttpOnly cookie pp_pin_session (12 hours), including downloads and all seven /print* routesShared office PC needing quick privacy lock
3. Multi-User RBACmultiUserEnabled: trueLogin issues HttpOnly cookie pp_session (7-day session); integrations can use Authorization: Bearer <token> or x-session-tokenTeams and external accountant read access

Cryptographic & Session Safeguards#

  • Password Hashing: crypto.scryptSync(password, salt, 64) with a 16-byte random hex salt stored as <saltHex>:<derivedKeyHex> and verified using constant-time crypto.timingSafeEqual.
  • Default Bootstrap Admin: When the users table is empty, seedDefaultAdminIfEmpty() creates username admin with password admin123 (ADMIN role). Change this password immediately before enabling multiUserEnabled on a LAN or server!
  • Last-Admin Lockout Protection: The system refuses to delete, deactivate, or demote the last active ADMIN user. Deactivating a user immediately revokes all their active rows in sessions.
  • Public Portal Secret Stripping: Unauthenticated routes (/portal/:token*) use getPublicSafeSettings(), blanking geminiApiKey, passwordPin, and smtp before rendering.
  • PIN & Login Hardening: Constant-time PIN checks and rate-limited login/unlock attempts; lock/logout revoke browser access. Never put a PIN or session token in a URL. Prefer cookies or a Bearer header for integrations.

RBAC Permission Matrix (checkRolePolicy & requireRole)#

Capability / API ScopeADMINCOMMERCIALCOMPTABLE
View Documents, Expenses, Suppliers, Treasury, Reports & Exports✅✅✅
Download PDFs, Executive Report, Accountant ZIP, CSVs, Preview PDF (POST /api/preview/pdf)✅✅✅
Create & Edit Clients, Quotes, Invoices, Payments, Expenses, Suppliers, POs, Print Dossiers✅✅❌ (403)
Treasury writes, stock allocation, print catalogs, budgets, tax assumptions, automation settings/dispatch✅❌ (403)❌ (403)
Send document/entity emails✅✅ (no internal-cost workshop sharing)❌ (403)
Stateless print calculation, workshop PDF, WhatsApp preview (sends nothing)✅✅✅
DELETE operations (Documents, Payments, Expenses, Clients, Suppliers, etc.)✅❌ (403)❌ (403)
Modify Settings (PUT /api/settings, SMTP test) & Manage Backups / Restore✅❌ (403)❌ (403)
Manage Users & Roles (/api/users*)✅❌ (403)❌ (403)

3. Deep SMTP Configuration & Troubleshooting#

Configure email delivery under Paramètres & Taxes → Configuration Serveur SMTP & Modèles d'E-mails.

Built-In Provider Presets#

Preset ButtonHost (smtp.host)Portsecure (SSL/TLS)Authentication Notes
OVH / ProdyPandassl0.ovh.net465true (Direct TLS)Full email address (admin@prodypanda.com) + mailbox password
Gmailsmtp.gmail.com587false (STARTTLS)Requires 2-Step Verification enabled + a 16-character Google App Password (not your normal Gmail login password!)
Outlook / M365smtp.office365.com587false (STARTTLS)Ensure Authenticated SMTP is enabled in Microsoft 365 Admin Center (or use App Password if MFA is enforced)
Brevosmtp-relay.brevo.com587false (STARTTLS)Use your Brevo account login email + SMTP Key generated under Brevo SMTP & API

Email Template Placeholders (src/mailer.js)#

Customize your facture, devis, and reminder subjects/bodies using any of these dynamic tokens: {DOC_TYPE}, {DOC_NUMBER}, {CLIENT_NAME}, {ISSUE_DATE}, {DUE_DATE}, {TOTAL_HT}, {TVA_AMOUNT}, {NET_A_PAYER}, {COMPANY_NAME}, {COMPANY_PHONE}, {RIB}, {BANK_NAME}, {WEBSITE}.

Every outgoing document and Purchase Order email embeds the ProdyPanda logo inline (cid:prodypanda-logo), includes a clean HTML financial recap card with your RIB, and attaches the Chromium-generated vector PDF (Facture_....pdf or BC_....pdf, plus optional Client RS Certificate PDF).

Testing & TLS Troubleshooting#

  1. Enter a test recipient address and click Tester la connexion SMTP (POST /api/settings/test-smtp, runs transporter.verify() + optional test mail).
  2. self-signed certificate in certificate chain / Antivirus SSL interception: Enable the ignoreTlsErrors checkbox (tls: { rejectUnauthorized: false }) if a local corporate firewall or antivirus inspects outbound SMTP TLS traffic.
  3. Timeout on port 465 / 587: Check whether your Tunisian ISP or Windows Firewall blocks port 465; switching to port 587 (secure: false, STARTTLS) resolves most ISP restrictions.

4. Smart Bill Auto-Fill & OCR Architecture (src/ocrHelper.js)#

When a user attaches a receipt in Nouvelle Dépense / Facture Fournisseur and clicks Analyser la facture (Auto-remplir) (POST /api/expenses/parse-receipt), ProdyPanda runs a 3-stage hybrid pipeline:

MERMAID DIAGRAM
flowchart TD
    In["Input: Uploaded PDF, Image,<br/>or Pasted Raw Text"] --> Check{"Input Type?"}
    Check -->|"Raw Text"| S2["Stage 2: Pure-Node Regex &<br/>Tunisian / Cloud Vendor Engine"]
    Check -->|"Digital PDF"| S1["Stage 1: Pure-Node PDF Parser<br/>(zlib FlateDecode + ToUnicode CMap<br/>+ Tj/TJ Operators)"]
    S1 --> S2
    Check -->|"Photo / Scan"| S2
    S2 --> Gem{"geminiApiKey set AND<br/>(Image OR Scanned PDF < 80 chars)?"}
    Gem -->|"No"| Out["Return Extracted Fields +<br/>HT/TVA Reconciliation + Notes"]
    Gem -->|"Yes"| S3["Stage 3: Gemini 2.5 Flash Vision API<br/>(20s timeout, structured JSON,<br/>graceful local fallback)"]
    S3 --> Out

Stage 1 — Pure-Node PDF Text Extraction (Zero External Dependencies)#

  • Decompresses PDF FlateDecode binary streams via Node's native node:zlib.
  • Parses ToUnicode CMap tables (beginbfchar / beginbfrange), UTF-16BE, and Latin-1/WinAnsi hex & literal strings inside Tj / TJ content operators.
  • Works 100% offline on native digital PDFs (STEG e-bills, SONEDE, Topnet, OVHcloud, AWS, Stripe).

Stage 2 — Built-In Tunisian & Cloud/SaaS Matchers#

Automatically identifies:

  • Tunisian Utilities & Telecom: STEG (UTILITY, 19%), SONEDE (UTILITY), Topnet, Ooredoo Tunisie, Orange Tunisie, Tunisie Telecom, GlobalNet, Hexabyte, CNSS (0%).
  • Cloud & SaaS Providers: OVHcloud, AWS, Google Cloud, DigitalOcean, Cloudflare, Hetzner, Vercel, Netlify, Hostinger, Adobe, OpenAI, Figma, GitHub, Stripe, Meta, Slack, Notion, Canva, JetBrains, Zoom.
  • Smart Field Extraction: Detects currency (DT/EUR/USD, normalizing TND to DT), supplier tax ID (excluding the configured buyer ID in settings.companyTvaCode), reference, contract, dates, timbre and TVA. SONEDE defaults to 7%; categories come from live settings. Always review extraction before saving.

Stage 3 — Optional Gemini 2.5 Flash Vision API (For Phone Photos & Paper Scans)#

Digital PDFs work completely offline with zero API key. To enable visual OCR on smartphone photos of paper receipts or scanned image PDFs:

  1. Obtain a Gemini API key from Google AI Studio.
  2. Open Paramètres & Taxes → Catégories, Étiquettes, Devises & OCR IA, paste your key into Clé API Gemini (#set-gemini-api-key), and click Enregistrer toute la configuration.
  3. When you upload a JPG/PNG photo (or paste a screenshot with Ctrl+V) and click Analyser la facture (Auto-remplir), ProdyPanda sends the image to gemini-2.5-flash (temperature: 0.1, JSON schema prompt, 20-second timeout) and auto-populates all 16 expense fields! If offline or rate-limited, it falls back cleanly to local extraction without blocking you.

5. Backups, Atomic Restore & Environment Variables#

Automated 30-Day Rotating Backups (src/backupService.js)#

  • Daily Schedule: startDailyBackupSchedule() runs automatically on server startup and every 24 hours, saving formatted JSON snapshots into <DATA_DIR>/backups/prodypanda_backup_YYYY-MM-DD_HHmmss.json.
  • 30-Snapshot Retention: pruneOldBackups(30) automatically deletes snapshots beyond the newest 30 (MAX_BACKUPS = 30).
  • Instant Manual Backup & Download: In Paramètres & Taxes → Sauvegarde de Base de Données & Sécurité Locale, click Créer une sauvegarde instantanée (POST /api/backups/run-now) or export a full snapshot file via GET /api/backup/export.

Schema-4 Atomic JSON Restore (with Legacy Compatibility)#

  • Backup format version: '4.0.0' captures 21 row tables plus settings, including users/password hashes, print catalogs/jobs/offcuts, bank import fingerprints and email/audit history. Receipt bytes are included for portable restoration.
  • restoreBackupPayload() runs inside a single atomic BEGIN IMMEDIATE; ... COMMIT; SQLite transaction — deleting child tables in foreign-key-safe order and rolling back completely on any validation failure.
  • Backward Compatibility: Importing an older Phase 1 (9-table) JSON backup works seamlessly — missing Phase 2 tables (suppliers, recurring_expenses, purchase_orders, treasury_*, expense_budgets) default safely to empty arrays and re-seed the 3 default Tunisian treasury accounts!
  • Security Note: Users are included; active sessions are excluded and revoked on restore. Full snapshot list/download/export/create/restore require ADMIN. Backups contain secrets and personal data: protect them. Missing legacy user data preserves existing users; restoring settings removes stale keys atomically.

Environment Variables#

VariableDefaultPurpose
PORT3000HTTP listen port for Express (http://localhost:<PORT>).
PRODYPANDA_DATA_DIR<project>/dataDirectory for SQLite, receipts/ and backups/; use a separate directory for tests. Keep the active WAL database on local storage; copy finished backups to NAS/cloud rather than synchronizing an open database.
PUPPETEER_EXECUTABLE_PATHAuto-detectedExplicit absolute path to a Chrome, Edge, or Chromium binary for headless PDF generation.

Example PowerShell launch on an isolated port & data folder:

POWERSHELL
$env:PORT = "3050"
$env:PRODYPANDA_DATA_DIR = "D:\Backups\CompanyB_Data"
node server.js

6. System Architecture & SQLite Schema#

High-Level Architecture#

MERMAID DIAGRAM
flowchart TB
    subgraph Browser["Browser Client (public/)"]
      UI["index.html + styles.css<br/>(Dark/Light Theme, 12 Views, 15 Resizable Tables)"]
      CoreJS["app.js + features.js + phase2.js<br/>(SPA State, Screen Options, Modals, SVG Charts)"]
      Shared["calculator.js + invoiceRenderer.js<br/>(Isomorphic UMD: Runs in Browser & Node!)"]
    end

    subgraph Server["Node.js v24 + Express 5 Backend (server.js)"]
      Auth["src/auth.js<br/>(Open / PIN / RBAC scrypt + HttpOnly Cookie)"]
      PDF["src/pdfGenerator.js<br/>(puppeteer-core Local Chrome/Edge)"]
      Mail["src/mailer.js<br/>(Nodemailer SMTP + Inline Logo)"]
      OCR["src/ocrHelper.js<br/>(Pure-Node PDF + Optional Gemini Vision)"]
      Rep["src/reportRenderer.js + portalRenderer.js<br/>(PO, Supplier RS, Executive PDF, Public Portal)"]
      Zip["src/zipExport.js<br/>(Zero-Dep PKZIP + UTF-8 BOM CSV)"]
      Jobs["src/scheduler.js + backupService.js<br/>(Recurring Retainers + 30-Day Backups)"]
    end

    subgraph Storage["Local Persistence (DATA_DIR/)"]
      DB[("SQLite WAL<br/>prodypanda_billing.sqlite<br/>(23 Application Tables, 22 Backed Up)")]
      Bkp[("Rotating Snapshots<br/>backups/*.json (Max 30)")]
    end

    Browser <-->|"REST JSON + Print/PDF + Portal"| Server
    Shared -.->|"Reused identically"| Server
    Server <--> DB
    Jobs --> Bkp

Complete SQLite Schema Summary (src/db.js)#

Engine: Node.js native node:sqlite (DatabaseSync) with PRAGMA journal_mode = WAL; and PRAGMA foreign_keys = ON;. Schema upgrades use safe idempotent ALTER TABLE migrations on boot.

A. Original Business Tables (Included in JSON Backups)#

| # | Table | Purpose & Key Columns | | :-: | :--- | :--- | | 1 | settings | Key-value JSON store (key PK, value) for company identity, tax defaults, SMTP, profiles, exchange rates, custom lists, geminiApiKey. | | 2 | clients | Customer directory (name, address, contact, email, tvaCode, notes). | | 3 | catalog_items | Reusable services & loyalty discount templates (ref, category, title, bulletsJson, footerNote, unitPrice, isDiscount, discountMode, discountValue). | | 4 | documents | All 6 commercial doc types (docType, docNumber, status, itemsJson, customFeesJson, tvaEnabled/tvaRate/perLineTva, timbre*, totalHT, tvaAmount, netAPayer, paidAmount, locked, templateStyle, companyProfileId, depositParentId, publicToken, portalEnabled, clientSignatureDataUrl, exchangeRate, docLanguage). | | 5 | payments | Client payment installments (documentId FK, amount, paymentDate, method, reference, accountId). | | 6 | email_logs | Outgoing email audit trail (documentId FK, recipient, cc, subject, status, errorMessage, sentAt). | | 7 | audit_logs | Per-document action history (documentId FK, action, details, actor, createdAt). | | 8 | expenses | Full expense & client purchase ledger (supplier, supplierId, supplierTvaCode, category, expenseScope, clientId, linkedDocumentId, billable, rebilledDocId, markupPct, rebillPriceHT, billingPeriodStart/End, contractNumber, dueDate, status, attachmentsJson, rsApplicable/rsRate/rsAmount/netPaidToSupplier, currency/exchangeRate/original*/totalTnd*, accountId, tagsJson, recurringExpenseId, purchaseOrderId). | | 9 | recurring_profiles | Automated client subscription billing schedules (templateDocId FK, label, frequency, nextRunDate, autoSendEmail, active, lastRunAt). | | 10 | suppliers | Vendor directory (name, category, tvaCode, contractNumber, defaultTvaRate, defaultRsRate, phone, email, address, rib, bankName). | | 11 | recurring_expenses | Utility & fixed-bill schedules (label, supplierId, supplier, category, contractNumber, frequency, estimatedHT, tvaRate, timbreAmount, currency, accountId, nextDueDate, reminderDays, active). | | 12 | purchase_orders | Supplier Purchase Orders (poNumber, supplierId, supplierName, clientId, issueDate, expectedDate, status, currency, exchangeRate, itemsJson, tvaRate, totalHT, tvaAmount, totalTTC, convertedExpenseId). | | 13 | treasury_accounts | Bank, cash & check accounts (name, type [BANK/CASH/CHECKS], bankName, rib, openingBalance, currency, isDefault, active). | | 14 | treasury_transactions | Unified cash flow ledger (accountId, targetAccountId, type [CREDIT/DEBIT], amount, transactionDate, label, category, reference, sourceType [MANUAL/PAYMENT/EXPENSE/TRANSFER], sourceId, reconciled). | | 15 | expense_budgets | Monthly spend caps per category (category UNIQUE, monthlyCapTnd, alertThresholdPct, active). |

B. Users and Sessions (Users Included; Sessions Excluded and Revoked on Restore)#

| # | Table | Purpose & Key Columns | | :-: | :--- | :--- | | 16 | users | Multi-user RBAC accounts (username UNIQUE, displayName, role [ADMIN/COMMERCIAL/COMPTABLE], passwordHash [salted scrypt], active). | | 17 | sessions | Active login tokens (token PK, userId FK, expiresAt, createdAt). |

C. Print, Stock and Bank Import Tables (Included in JSON Backups)#

| # | Table | Purpose | | :-: | :--- | :--- | | 18 | print_materials | Print media, supplier prices and roll constraints | | 19 | print_boards | Raw sheet dimensions, material/thickness, supplier prices and charging defaults | | 20 | print_finishings | Finishing cost/sell rules and quantity modes | | 21 | print_jobs | Saved calculation configuration/result, links, stage, priority and deadline | | 22 | print_offcuts | AVAILABLE/USED stock, geometry and consumption job ID/number history | | 23 | bank_import_rows | Reconciliation fingerprints preventing repeated bank imports |

documents also stores comparative quote options/selection; email/audit logs support entityType/entityId. See Agency API reference for the added routes.


7. Complete REST API Reference (server.js)#

JSON request payload limit is 50 MB (supporting multi-file Base64 receipt attachments). All /api/* endpoints (except /api/auth/*) pass through authMiddleware.

Authentication & Users#

Method & PathDescription
GET /api/auth/statusReturns { passwordEnabled, multiUserEnabled, authenticated, user }
POST /api/auth/loginAuthenticates { username, password }, sets HttpOnly pp_session cookie
POST /api/auth/logoutDestroys active session token and clears cookie
POST /api/auth/unlock, POST /api/auth/lockUnlock sets signed PIN cookie; lock revokes it
GET / POST /api/users, PUT / DELETE /api/users/:idMulti-user RBAC CRUD (ADMIN only)

Documents, Conversions & Payments#

Method & PathDescription
GET /api/statsTop-level dashboard KPIs
GET /api/documents, GET /api/documents/next-numberList/filter documents; preview next sequential number
GET / POST /api/documents, PUT / DELETE /api/documents/:idDocument CRUD (GET /:id includes linkedExpenses)
POST /api/documents/batchBatch mark paid, lock, or delete multiple documents
PATCH /api/documents/:id/statusQuick status transition (with optional accountId Treasury sync)
POST /api/documents/:id/lockLock or unlock a document ({ locked: true|false })
GET /api/documents/:id/auditRetrieve document audit log history
POST /api/documents/:id/portalEnable/toggle Public Client Portal token
POST /api/documents/:id/deposit / /balanceGenerate Deposit (Facture d'Acompte) or Balance (Facture de Solde)
POST /api/documents/:id/convertConvert to FACTURE, PROFORMA, BON_LIVRAISON, BON_COMMANDE, or AVOIR
POST /api/documents/:id/duplicate / /next-monthDuplicate document or clone with next-month dates & fresh number
GET /api/documents/:id/email-preview, POST /api/documents/:id/emailPreview interpolated email; send document email with PDF attachment
POST /api/documents/:id/payments, POST /api/documents/:id/mark-paid, DELETE /api/payments/:paymentIdRecord partial/full payments (with automatic Treasury sync) or delete payment

Expenses, OCR, Rebilling & Recurring Fixed Bills#

Method & PathDescription
GET /api/expensesFiltered ledger (year, month, category, clientId, supplierId, status, unbilled, scope, rsOnly, tag, q) → { items, expenses, totals }
GET / POST /api/expenses, PUT / DELETE /api/expenses/:idExpense CRUD (auto-syncs Treasury when PAID)
POST /api/expenses/parse-receiptSmart Bill Auto-Fill / OCR ({ dataUrl, fileName, rawText })
POST /api/expenses/:id/rebill1-Click Rebill to existing or new client document ({ targetDocId, docType, customTitle, includeMarkup })
GET /api/expenses/rs-csvDownload UTF-8 BOM RS_Fournisseurs_Recette_Finances_*.csv (?year=&month=)
GET /api/expenses/:id/rs-pdf (alias /rs-certificate-pdf)Download A4 Supplier RS Certificate PDF
GET / POST /api/recurring-expenses, PUT / DELETE /api/recurring-expenses/:idFixed/utility bills schedule CRUD
GET /api/recurring-expenses/upcoming?days=15Fetch bills due within N days
POST /api/recurring-expenses/:id/logLog bill as Expense AND advance schedule nextDueDate

Suppliers & Purchase Orders#

Method & PathDescription
GET / POST /api/suppliers, GET / PUT / DELETE /api/suppliers/:idSupplier directory CRUD
POST /api/suppliers/seed-tunisiaIdempotently seed 6 Tunisian starter suppliers (STEG, SONEDE, Topnet, Orange, OVHcloud, CNSS)
GET /api/purchase-orders, GET /api/purchase-orders/next-numberList POs (?status=&supplierId=&clientId=&q=) & next BC-YYYY-NNNN
GET / POST /api/purchase-orders, PUT / DELETE /api/purchase-orders/:idPurchase Order CRUD
GET /api/purchase-orders/:id/pdfDownload branded A4 Purchase Order PDF
POST /api/purchase-orders/:id/send-emailEmail PO PDF to supplier via SMTP (advances DRAFT → SENT)
POST /api/purchase-orders/:id/convert-to-expenseConvert PO to Expense & mark CONVERTED

Treasury, Budgets, Alerts & Recurring Retainers#

Method & PathDescription
GET /api/treasury/summaryConsolidated & per-account Book + Reconciled balances
GET / POST /api/treasury/accounts, PUT /api/treasury/accounts/:idTreasury accounts & opening balances CRUD
GET / POST /api/treasury/transactions, PUT / DELETE /api/treasury/transactions/:idManual ledger entries/edit/delete; synchronized PAYMENT/EXPENSE entries are corrected through their source
POST /api/treasury/transferBalanced internal transfer between two accounts
POST /api/treasury/transactions/:id/reconcileToggle bank reconciliation checkmark (reconciled)
GET / PUT /api/budgets, DELETE /api/budgets/:idMonthly category budget caps & thresholds
GET /api/alertsUnified Alert Center feed (unbilled, bills, overdue, budgets, quotes)
GET / POST /api/recurring, PUT / DELETE /api/recurring/:id, POST /api/recurring/run-nowClient recurring retainers CRUD & manual scheduler trigger

Clients, Catalog, Settings, Reports, PDFs, Portal & Backups#

Method & PathDescription
GET / POST /api/clients, PUT / DELETE /api/clients/:idClients CRUD (GET enriched with linkedExpensesHT, unbilledExpensesHT, grossMarginHT, marginPct)
GET / POST /api/catalog, PUT / DELETE /api/catalog/:idService & discount catalog CRUD
GET / PUT /api/settings, POST /api/settings/test-smtpGlobal settings read/update & SMTP verification
GET /api/reports/fiscal, GET /api/reports/profitabilityExtended Fiscal/P&L/TVA/Donut/YoY data & per-client profitability
GET /api/reports/executive-pdf, GET /api/documents/:id/pdf, GET /api/documents/:id/rs-pdf, GET /api/clients/:id/statement-pdf, POST /api/preview/pdfServer-side Headless Chromium A4 PDF endpoints
GET /print/:id, /print-rs/:id, /print-statement/:clientId, /print-supplier-rs/:id, /print-po/:id, /print-executive-report, /print-job-sheet/:idSeven authenticated standalone HTML print views
GET /api/export/csv, GET /api/export/accountant-zip (alias /api/reports/accountant-zip)CSV ledger & full Accountant PKZIP export (PDFs/, Justificatifs_Depenses/, RS_Fournisseurs_Recette_Finances.csv)
GET /portal/:token, GET /portal/:token/pdf, POST /portal/:token/acceptUnauthenticated Public Client Portal & Canvas E-Signature
GET /api/backups/snapshots, POST /api/backups/run-now, GET /api/backups/snapshots/:filename, POST /api/backups/snapshots/:filename/restoreSnapshot management (all operations ADMIN-only)
GET /api/backup/export, POST /api/backup/importSchema-4 full JSON export & atomic restore (ADMIN-only)
GET /health, GET /wiki/Health readiness and the trilingual help library

8. Headless Chromium PDF Engine & Troubleshooting Playbook#

How src/pdfGenerator.js Works#

  • Zero Bundled 300 MB Browser Download: Uses puppeteer-core connected to your already-installed Google Chrome, Microsoft Edge, or Linux/macOS Chromium binary (auto-searched in standard OS paths or overridden via PUPPETEER_EXECUTABLE_PATH).
  • Shared Singleton Browser: Launches one headless browser instance lazily on the first PDF request, reuses it across tabs for sub-second exports, and auto-recovers on disconnected events.
  • Smart Single-Page vs Multi-Page Pagination:
    • Sets an exact A4 96-DPI viewport (794 × 1123 px), emulates print media, waits for document.fonts.ready, and measures document.body.scrollHeight.
    • If scrollHeight <= 1150 px (like Facture 20260300001): prints edge-to-edge 1 page with zero extra margins or page numbers.
    • If an invoice exceeds one page: repeating headers, unbroken totals/signatures, and Page X / Y pagination apply. Executive/PO/workshop reports retain their own 12mm margins; shutdown closes the shared browser.

Expert Troubleshooting Playbook#

Symptom / ErrorRoot CauseFix
Cannot find module 'node:sqlite'Node.js version is older than v22.5Upgrade to Node.js v24 LTS (or v22.13+) from nodejs.org and restart.
EADDRINUSE: address already in use :::3000Another ProdyPanda instance or service is already listening on port 3000Either open http://localhost:3000 directly (if already running) or launch on another port: $env:PORT=3001; node server.js.
Aucun navigateur Chromium/Edge/Chrome local trouvéChrome/Edge is installed in a non-standard directory (or headless Linux server)Install Chromium/Chrome/Edge, or set PUPPETEER_EXECUTABLE_PATH to the exact executable path.
HTTP 401 Accès verrouillé par mot de passePIN Lock (passwordEnabled) or Multi-User RBAC (multiUserEnabled) is activeLog in via UI (admin / admin123 for fresh RBAC) or pass header x-app-pin / Authorization: Bearer <token> in API scripts.
Gmail SMTP returns 535 Username and Password not acceptedUsing regular Google account password instead of an App PasswordEnable Google 2-Step Verification → create a 16-char App Password → paste it into Paramètres & Taxes → SMTP.
OCR on scanned image PDF returns empty fieldsScanned PDF has no embedded text layer and no geminiApiKey is configuredEither click Coller le texte d'une facture to paste text manually, or add a free/paid Gemini API Key in Paramètres & Taxes to activate Gemini 2.5 Flash Vision.
Large multi-attachment expense upload failsReverse proxy (Nginx/Caddy) defaults to 1 MB body limit even though Express allows 50 MBSet client_max_body_size 50M; in Nginx if reverse-proxying ProdyPanda.
Need to roll back an accidental bulk changeUser modified or deleted data before lockingGo to Paramètres & Taxes → Sauvegarde de Base de Données and restore the latest automated daily snapshot from data/backups/ in 1 click (atomic rollback!).

← Level 4 — Advanced | English Index | Trilingual Master Hub →

ProdyPanda Factures — Complete English Documentation Curriculum