🌐 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:
- Open
Paramètres & Taxes→Profils Sociétés, Style de Modèle A4 & Portail Client. - 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). - 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 ID | UI Label | Best Use Case |
|---|---|---|
classic | Classique ProdyPanda Officiel | Exact pixel-accurate match to ProdyPanda. Sarl's official Tunisian invoice (Facture 20260300001). |
modern | Moderne Épuré | Clean contemporary typography with crisp accent lines for international / creative clients. |
compact | Compact (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 withLogo ProdyPanda par défautandCachet vectoriel(a crisp procedural SVG corporate stamp generated automatically from your company name, city, andCode 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 widthN).- Default pattern:
{YYYY}{MM}{SEQ:5}→ produces20260300001.
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#
| Mode | Configuration (settings) | How Requests Authenticate | Best For |
|---|---|---|---|
| 1. Open Local Mode (default) | multiUserEnabled: false, passwordEnabled: false | Automatic Local Admin (ADMIN role) — zero login friction | Single-user personal workstation |
| 2. PIN Lock | multiUserEnabled: false, passwordEnabled: true, passwordPin set | POST /api/auth/unlock sets signed HttpOnly cookie pp_pin_session (12 hours), including downloads and all seven /print* routes | Shared office PC needing quick privacy lock |
| 3. Multi-User RBAC | multiUserEnabled: true | Login issues HttpOnly cookie pp_session (7-day session); integrations can use Authorization: Bearer <token> or x-session-token | Teams and external accountant read access |
Cryptographic & Session Safeguards#
- Password Hashing:
crypto.scryptSync(password, salt, 64)with a16-byte random hex salt stored as<saltHex>:<derivedKeyHex>and verified using constant-timecrypto.timingSafeEqual. - Default Bootstrap Admin: When the
userstable is empty,seedDefaultAdminIfEmpty()creates usernameadminwith passwordadmin123(ADMINrole). Change this password immediately before enablingmultiUserEnabledon a LAN or server! - Last-Admin Lockout Protection: The system refuses to delete, deactivate, or demote the last active
ADMINuser. Deactivating a user immediately revokes all their active rows insessions. - Public Portal Secret Stripping: Unauthenticated routes (
/portal/:token*) usegetPublicSafeSettings(), blankinggeminiApiKey,passwordPin, andsmtpbefore 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 Scope | ADMIN | COMMERCIAL | COMPTABLE |
|---|---|---|---|
| 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 Button | Host (smtp.host) | Port | secure (SSL/TLS) | Authentication Notes |
|---|---|---|---|---|
OVH / ProdyPanda | ssl0.ovh.net | 465 | true (Direct TLS) | Full email address (admin@prodypanda.com) + mailbox password |
Gmail | smtp.gmail.com | 587 | false (STARTTLS) | Requires 2-Step Verification enabled + a 16-character Google App Password (not your normal Gmail login password!) |
Outlook / M365 | smtp.office365.com | 587 | false (STARTTLS) | Ensure Authenticated SMTP is enabled in Microsoft 365 Admin Center (or use App Password if MFA is enforced) |
Brevo | smtp-relay.brevo.com | 587 | false (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#
- Enter a test recipient address and click
Tester la connexion SMTP(POST /api/settings/test-smtp, runstransporter.verify()+ optional test mail). self-signed certificate in certificate chain/ Antivirus SSL interception: Enable theignoreTlsErrorscheckbox (tls: { rejectUnauthorized: false }) if a local corporate firewall or antivirus inspects outbound SMTP TLS traffic.- Timeout on port 465 / 587: Check whether your Tunisian ISP or Windows Firewall blocks port
465; switching to port587(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:
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 --> OutStage 1 — Pure-Node PDF Text Extraction (Zero External Dependencies)#
- Decompresses PDF
FlateDecodebinary streams via Node's nativenode:zlib. - Parses
ToUnicodeCMap tables (beginbfchar/beginbfrange), UTF-16BE, and Latin-1/WinAnsi hex & literal strings insideTj/TJcontent 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, normalizingTNDtoDT), supplier tax ID (excluding the configured buyer ID insettings.companyTvaCode), reference, contract, dates, timbre and TVA. SONEDE defaults to7%; 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:
- Obtain a Gemini API key from Google AI Studio.
- Open
Paramètres & Taxes→Catégories, Étiquettes, Devises & OCR IA, paste your key intoClé API Gemini(#set-gemini-api-key), and clickEnregistrer toute la configuration. - When you upload a JPG/PNG photo (or paste a screenshot with
Ctrl+V) and clickAnalyser la facture (Auto-remplir), ProdyPanda sends the image togemini-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 newest30(MAX_BACKUPS = 30). - Instant Manual Backup & Download: In
Paramètres & Taxes→Sauvegarde de Base de Données & Sécurité Locale, clickCréer une sauvegarde instantanée(POST /api/backups/run-now) or export a full snapshot file viaGET /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 atomicBEGIN 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
sessionsare 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#
| Variable | Default | Purpose |
|---|---|---|
PORT | 3000 | HTTP listen port for Express (http://localhost:<PORT>). |
PRODYPANDA_DATA_DIR | <project>/data | Directory 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_PATH | Auto-detected | Explicit absolute path to a Chrome, Edge, or Chromium binary for headless PDF generation. |
Example PowerShell launch on an isolated port & data folder:
$env:PORT = "3050"
$env:PRODYPANDA_DATA_DIR = "D:\Backups\CompanyB_Data"
node server.js6. System Architecture & SQLite Schema#
High-Level Architecture#
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 --> BkpComplete 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 & Path | Description |
|---|---|
GET /api/auth/status | Returns { passwordEnabled, multiUserEnabled, authenticated, user } |
POST /api/auth/login | Authenticates { username, password }, sets HttpOnly pp_session cookie |
POST /api/auth/logout | Destroys active session token and clears cookie |
POST /api/auth/unlock, POST /api/auth/lock | Unlock sets signed PIN cookie; lock revokes it |
GET / POST /api/users, PUT / DELETE /api/users/:id | Multi-user RBAC CRUD (ADMIN only) |
Documents, Conversions & Payments#
| Method & Path | Description |
|---|---|
GET /api/stats | Top-level dashboard KPIs |
GET /api/documents, GET /api/documents/next-number | List/filter documents; preview next sequential number |
GET / POST /api/documents, PUT / DELETE /api/documents/:id | Document CRUD (GET /:id includes linkedExpenses) |
POST /api/documents/batch | Batch mark paid, lock, or delete multiple documents |
PATCH /api/documents/:id/status | Quick status transition (with optional accountId Treasury sync) |
POST /api/documents/:id/lock | Lock or unlock a document ({ locked: true|false }) |
GET /api/documents/:id/audit | Retrieve document audit log history |
POST /api/documents/:id/portal | Enable/toggle Public Client Portal token |
POST /api/documents/:id/deposit / /balance | Generate Deposit (Facture d'Acompte) or Balance (Facture de Solde) |
POST /api/documents/:id/convert | Convert to FACTURE, PROFORMA, BON_LIVRAISON, BON_COMMANDE, or AVOIR |
POST /api/documents/:id/duplicate / /next-month | Duplicate document or clone with next-month dates & fresh number |
GET /api/documents/:id/email-preview, POST /api/documents/:id/email | Preview interpolated email; send document email with PDF attachment |
POST /api/documents/:id/payments, POST /api/documents/:id/mark-paid, DELETE /api/payments/:paymentId | Record partial/full payments (with automatic Treasury sync) or delete payment |
Expenses, OCR, Rebilling & Recurring Fixed Bills#
| Method & Path | Description |
|---|---|
GET /api/expenses | Filtered ledger (year, month, category, clientId, supplierId, status, unbilled, scope, rsOnly, tag, q) → { items, expenses, totals } |
GET / POST /api/expenses, PUT / DELETE /api/expenses/:id | Expense CRUD (auto-syncs Treasury when PAID) |
POST /api/expenses/parse-receipt | Smart Bill Auto-Fill / OCR ({ dataUrl, fileName, rawText }) |
POST /api/expenses/:id/rebill | 1-Click Rebill to existing or new client document ({ targetDocId, docType, customTitle, includeMarkup }) |
GET /api/expenses/rs-csv | Download 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/:id | Fixed/utility bills schedule CRUD |
GET /api/recurring-expenses/upcoming?days=15 | Fetch bills due within N days |
POST /api/recurring-expenses/:id/log | Log bill as Expense AND advance schedule nextDueDate |
Suppliers & Purchase Orders#
| Method & Path | Description |
|---|---|
GET / POST /api/suppliers, GET / PUT / DELETE /api/suppliers/:id | Supplier directory CRUD |
POST /api/suppliers/seed-tunisia | Idempotently seed 6 Tunisian starter suppliers (STEG, SONEDE, Topnet, Orange, OVHcloud, CNSS) |
GET /api/purchase-orders, GET /api/purchase-orders/next-number | List POs (?status=&supplierId=&clientId=&q=) & next BC-YYYY-NNNN |
GET / POST /api/purchase-orders, PUT / DELETE /api/purchase-orders/:id | Purchase Order CRUD |
GET /api/purchase-orders/:id/pdf | Download branded A4 Purchase Order PDF |
POST /api/purchase-orders/:id/send-email | Email PO PDF to supplier via SMTP (advances DRAFT → SENT) |
POST /api/purchase-orders/:id/convert-to-expense | Convert PO to Expense & mark CONVERTED |
Treasury, Budgets, Alerts & Recurring Retainers#
| Method & Path | Description |
|---|---|
GET /api/treasury/summary | Consolidated & per-account Book + Reconciled balances |
GET / POST /api/treasury/accounts, PUT /api/treasury/accounts/:id | Treasury accounts & opening balances CRUD |
GET / POST /api/treasury/transactions, PUT / DELETE /api/treasury/transactions/:id | Manual ledger entries/edit/delete; synchronized PAYMENT/EXPENSE entries are corrected through their source |
POST /api/treasury/transfer | Balanced internal transfer between two accounts |
POST /api/treasury/transactions/:id/reconcile | Toggle bank reconciliation checkmark (reconciled) |
GET / PUT /api/budgets, DELETE /api/budgets/:id | Monthly category budget caps & thresholds |
GET /api/alerts | Unified Alert Center feed (unbilled, bills, overdue, budgets, quotes) |
GET / POST /api/recurring, PUT / DELETE /api/recurring/:id, POST /api/recurring/run-now | Client recurring retainers CRUD & manual scheduler trigger |
Clients, Catalog, Settings, Reports, PDFs, Portal & Backups#
| Method & Path | Description |
|---|---|
GET / POST /api/clients, PUT / DELETE /api/clients/:id | Clients CRUD (GET enriched with linkedExpensesHT, unbilledExpensesHT, grossMarginHT, marginPct) |
GET / POST /api/catalog, PUT / DELETE /api/catalog/:id | Service & discount catalog CRUD |
GET / PUT /api/settings, POST /api/settings/test-smtp | Global settings read/update & SMTP verification |
GET /api/reports/fiscal, GET /api/reports/profitability | Extended 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/pdf | Server-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/:id | Seven 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/accept | Unauthenticated 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/restore | Snapshot management (all operations ADMIN-only) |
GET /api/backup/export, POST /api/backup/import | Schema-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-coreconnected to your already-installed Google Chrome, Microsoft Edge, or Linux/macOS Chromium binary (auto-searched in standard OS paths or overridden viaPUPPETEER_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
disconnectedevents. - Smart Single-Page vs Multi-Page Pagination:
- Sets an exact A4 96-DPI viewport (
794 × 1123 px), emulatesprintmedia, waits fordocument.fonts.ready, and measuresdocument.body.scrollHeight. - If
scrollHeight <= 1150 px(likeFacture 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 / Ypagination apply. Executive/PO/workshop reports retain their own 12mm margins; shutdown closes the shared browser.
- Sets an exact A4 96-DPI viewport (
Expert Troubleshooting Playbook#
| Symptom / Error | Root Cause | Fix |
|---|---|---|
Cannot find module 'node:sqlite' | Node.js version is older than v22.5 | Upgrade to Node.js v24 LTS (or v22.13+) from nodejs.org and restart. |
EADDRINUSE: address already in use :::3000 | Another ProdyPanda instance or service is already listening on port 3000 | Either 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 passe | PIN Lock (passwordEnabled) or Multi-User RBAC (multiUserEnabled) is active | Log 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 accepted | Using regular Google account password instead of an App Password | Enable Google 2-Step Verification → create a 16-char App Password → paste it into Paramètres & Taxes → SMTP. |
| OCR on scanned image PDF returns empty fields | Scanned PDF has no embedded text layer and no geminiApiKey is configured | Either 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 fails | Reverse proxy (Nginx/Caddy) defaults to 1 MB body limit even though Express allows 50 MB | Set client_max_body_size 50M; in Nginx if reverse-proxying ProdyPanda. |
| Need to roll back an accidental bulk change | User modified or deleted data before locking | Go 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!). |
🧭 Navigation#
← Level 4 — Advanced | English Index | Trilingual Master Hub →