Official Engineering & Security Architecture (13 Chapters)
← Visual Functional Manual

Technical
Architecture.

Inspect every engineering layer of CapAssysta: per-tenant ACID MariaDB isolation, HMAC-SHA256 + 2FA TOTP Edge security, SHA-256 dead-zone offline QR sync, Haversine GPS dispatch, 1-click CD92 + SEPA pain.008 closing, AI OCR, and < 2s zero-downtime releases.

Runtime & UI
Next.js 16 • React 19 • TS Strict
App Router + Server Actions
Database Engine
MariaDB 11 InnoDB ACID
1 Agency = 1 Dedicated DB
ORM & Routing
Dual Prisma (master + tenant)
Dynamic Connection Pool
Edge Security
HMAC-SHA256 + RFC 6238 2FA
Constant-Time Verification
Offline Mobility
PWA SW v2 + IndexedDB
WebCrypto SHA-256 Seal
Cloud Continuity
Atomic Staging Swap (< 2s)
Zero-Downtime Releases
SPECIFICATION 01 / 12

Isolated Multi-Tenant & Zero-Downtime Core

cap_master + tenant_<uuid>MariaDB 11 ACID.next_staging -> .next (< 2s)/api/health Zero-Leak

CapAssysta runs on a physically isolated Multi-Tenant SaaS architecture where each organization receives its own dedicated ACID relational database (tenant_<uuid>) routed dynamically via a dual-schema Prisma layer.

Physical Database Isolation & Dual-Prisma Routing

  • →Dedicated Tenant Schematenant_<companyId>

    Every agency operates inside its own MariaDB database, eliminating cross-tenant SQL joins or row-level leakage by design.

  • →Smart Prisma Pool CachinggetDb() / getTenantPrisma()

    Resolves the authenticated session's companyId with timeout protection and routes queries to the isolated tenant pool.

  • →Idempotent Multi-DB Migrations

    Schema upgrades apply atomically and idempotently across cap_master and all tenant_* databases prior to build swap.

Zero-Downtime Atomic Deployment Pipeline

  • →Isolated Staging Compilation.next_staging

    Production builds compile inside a separate directory on a pre-equipped Alpine container while live traffic continues uninterrupted.

  • →Sub-2-Second Atomic Swap & Health ProbeGET /api/health -> 200 OK

    Directory swap and container restart complete in under 2–5 seconds, verified against a hardened /api/health endpoint that exposes zero internal server metadata.

SPECIFICATION 02 / 12

Edge Cryptography, 2FA TOTP & Granular RBAC

HMAC-SHA256timingSafeEqualRFC 6238 TOTP5-Try Rate Limit

Every HTTP request and Server Action passes through constant-time cryptographic cookie verification, role-based access guards, and RFC 6238 two-factor authentication.

Signed Session Architecture & Logout Hygiene

  • →Constant-Time Edge Signature CheckHMAC-SHA256

    Session cookies (user_id, session_sig, access_token, sa_token) are verified at the Edge before reaching application routes.

  • →Role-Specific Login Routing & Clean Logout/dashboard | /portal

    Beneficiary accounts (CLIENT / linked USER) route directly to /portal, and logout deterministically clears all tenant and superadmin session tokens.

Enforced 2FA TOTP & Anti-Bruteforce Shield

  • →RFC 6238 Authenticator CompatibilityOTPAuth TOTP (6 digits / 30s)

    Compatible with Google Authenticator, Authy, and 1Password; re-generating a QR secret preserves active 2FA enforcement until verified.

  • →Brute-Force Rate Limiting5 attempts / 5 min lockout

    Protects TOTP challenge verification against automated guessing attacks while enforcing requireRole(['ADMIN', 'PLANNER']) on sensitive mutations.

SPECIFICATION 03 / 12

Live Operations Control Tower & Haversine Dispatch

> 15 min Delay RadarHaversine GPS SortBlacklist & Leave Filter2-Click Reassign

Real-time operational command center mounted above the fold for coordinators, combining live attendance telemetry with GPS-ranked express staff replacement.

Real-Time Telemetry & Incident Detection

  • →4 Live Operational Buckets

    Continuously computes Active (checked-in), Late > 15 min / Unassigned, Upcoming Today, and Completed shifts.

  • →Role-Adapted Workspace Hubs

    Coordinators get the Live Control Tower, field staff get a mobile Field Hub (QR Scanner, Schedule, Leave, HR Vault), and families get a dedicated Portal Hub.

Geodesic Candidate Ranking Engine

  • →Conflict, Leave & Blacklist FilteringUnwantedEmployee + Absence

    Excludes staff on approved leave, overlapping shifts, or beneficiary incompatibility blacklists automatically.

  • →Haversine Distance & Reset Statestatus: 'ASSIGNED'

    Ranks conflict-free caregivers by exact GPS distance and estimated travel minutes, resetting shift status cleanly upon reassignment.

SPECIFICATION 04 / 12

360° Beneficiary Schema, GIR & SocialAid Engine

11-Tab Client ModelGender BOTH (Mr. & Mrs.)GIR 1–6selectActiveSocialAid()

11-tab clinical and administrative data model handling individuals, couples, encrypted access logistics, GIR 1–6 dependency grids, and multi-funder social aid plans.

Clinical Dossier & Couple Civility Engine

  • →Structured Access & Safety Metadata

    Stores building, floor, door/keybox codes, emergency contacts, legal guardians, and GIR 1–6 autonomy evaluations.

  • →Native Couple CivilityGender.BOTH -> Mme et M. / Mr. & Mrs.

    Propagates couple titles cleanly across client dossiers, quotes, contracts, invoices, and annual tax certificates.

Date-Bounded SocialAid Resolution

  • →Active Plan & Ceiling NormalizationselectActiveSocialAid() + resolveSocialAidRates()

    Validates plan start/end windows (inclusive of end-of-day timestamps), monthly hour caps, funder hourly rates, and beneficiary co-pay percentages.

SPECIFICATION 05 / 12

SIRH, CR80 ISO/IEC 7810 Cards & Live QR Verification

CR80 85.6×54mm4:5 Canvas Crop/verify/employee/[id]J-30 Watchdog

End-to-end workforce compliance combining 30-day document expiry watchdogs, studio photo cropping, PVC CR80 badge generation, and live public verification.

Verifiable Staff Credentials

  • →CR80 Badge Studio & Photo Pipeline

    Captures or uploads staff portraits with 4:5 aspect cropping, generating print-ready PVC CR80 cards and bulk photo ZIP exports.

  • →Public Real-Time Authorization EndpointGET /verify/employee/[id]

    Allows families or inspectors to scan an employee's badge QR and confirm active employment status in real time across isolated tenant databases.

  • →Proactive J-30 Compliance Alerts

    Flags expiring ID cards, residence permits, driving licenses, and medical certificates 30 days ahead.

SPECIFICATION 06 / 12

Multi-View Scheduling & International Regionalization

Grid / Gantt / MapMinute-Accurate SplitFR EUR 5.5% VATQA QAR 0% VAT / WPS

High-density scheduling engine supporting multi-week recurrence, minute-level surcharge splitting, and multi-country legal/tax profiles (France EUR & Qatar QAR).

Recurrence & Surcharge Calculation

  • →Selective Series Propagation

    Applies schedule edits to a single shift or future occurrences while checking rest periods and shift overlaps.

  • →Holiday, Night & Rest-Day Splitter

    Automatically splits shift durations across regular hours, Sundays/Fridays, night hours, and statutory or Islamic public holidays.

Native Multi-Country Profiles

  • →France SAP & Qatar / International Enginesregional-profiles.ts + country-legal-packs.ts

    Adapts currency (EUR / QAR), VAT (5.5% / 0%), workweek (Mon–Sun / Sun–Thu), QID & WPS IBAN validation, and 1-click legal contract packs.

SPECIFICATION 07 / 12

Dead-Zone Offline QR Protocol (IndexedDB + SHA-256)

IndexedDB QueueWebCrypto SHA-256Service Worker v2Chronological Backfill

Offline-first mobile clock-in pipeline engineered so basements and zero-signal buildings never lose or distort a caregiver's arrival or departure timestamp.

Tamper-Evident Local Storage & Sync Replay

  • →Cryptographic Timestamp Sealingoffline-scan-db.ts (SHA-256)

    When offline, the scan payload (client QR, exact timestamp, GPS coordinates, touch signature) is sealed with a SHA-256 digest in IndexedDB.

  • →Bounded Timestamp & Backfill ReconciliationisBackfillCompletedStart

    Upon 4G/Wi-Fi reconnection, queued scans replay chronologically, honoring the authentic basement timestamp within bounded anti-spoof windows and purging permanent invalid scans.

  • →Hardened PWA Service Worker v2public/sw.js

    Caches scanner assets for zero-network boot while explicitly bypassing /login and redirected responses so authenticated sessions never stale.

SPECIFICATION 08 / 12

1-Click Month-End Closing, CD92 ZIP & SEPA pain.008

runMonthPreBillingAudit()APAP•AMPAP•AMPHP•PCHAD•PCHEDISO 20022 pain.008.001.02bulkInvoiceEmailEnabled = false

Deterministic 4-step billing pipeline combining pre-billing anomaly detection, split beneficiary/funder invoicing, Departmental Council ZIP archives, and ISO 20022 SEPA XML.

Pre-Audit & Consolidated Departmental Pack

  • →Pre-Closing Diagnostic Engine

    Scans the selected month for unclosed shifts, absent/cancelled comments, expired APA/PCH plans, missing rates, and incomplete SEPA mandates.

  • →5-Stream Official CD92 ZIP ArchivegenerateCd92MonthlyPackZip()

    Generates /ECH 30J summary PDFs and semicolon-delimited reconciliation CSVs across APAP, AMPAP, AMPHP, PCHAD, and PCHED in a single ZIP download.

SEPA Direct Debit XML & Outbound Email Lock

  • →ISO 20022 Bank Remittancepain.008.001.02 (FRST / RCUR)

    Builds bank-compliant XML batches strictly from validated non-draft invoices (DRAFT and CANCELLED excluded) with creditor ICS/IBAN/BIC validation.

  • →Strict Default 'Network Silence' LockbulkInvoiceEmailEnabled === false

    Outbound bulk invoice and reminder emails are disabled by default at the code and settings level—nothing leaves until an administrator explicitly toggles the switch.

SPECIFICATION 09 / 12

Isolated Family Portal, 50% Tax PDFs & Anti-Fraud Ledger

/portal 24/7Art. 199 sexdecies 50%Immutable Credit NotesFEC / Sage / Silae

Self-service beneficiary portal paired with immutable VAT-compliant invoicing, cryptographic credit notes, multi-method payment reconciliation, and FEC/Payroll exports.

Beneficiary Portal & Fiscal Attestations

  • →Non-Draft Portal Isolationstatus: { notIn: ['DRAFT', 'CANCELLED'] }

    Families view live schedules, active APA/PCH hour meters, finalized invoices with real agency IBAN/BIC, and download annual 50% tax credit PDFs in one click.

  • →Anti-Fraud Credit Notes & Multi-Channel Treasury

    Tracks SEPA, CESU, wire, check, cash, and card settlements, balance regularizations, sequentially chained credit notes, and FEC / Quadra / Silae exports.

SPECIFICATION 10 / 12

Physical DMS Vault, AI OCR & Visual eIDAS Signatures

Isolated FilesystemPOST /api/ocrpdf-lib SHA-256 Seal/sign/[token] + /session-live

Per-company isolated filesystem storage integrated with optical AI data extraction, batch PDF/ZIP generation, live room kiosks, and sealed eIDAS PDF signatures.

Document Intelligence & Cryptographic Signing

  • →Visual PDF Tagging & Live Group Signingpdf-signature.ts

    Supports remote single-signer links (/sign/[token]) and live multi-employee QR room sessions (/session-live/[id]), embedding signature graphics, IP, timestamp, and hash into the PDF.

  • →AI Optical Character Recognition & Batch Engine/api/ocr + batch-zip

    Extracts structured fields from IDs and social aid notifications while protecting historical imported files in read-only archival mode.

SPECIFICATION 11 / 12

Telephony, WhatsApp, Spotlight UX, Migration & Backups

Calls & Team ChatWhatsApp WebhookSpotlight Tour Engine.sql.gz Per-Tenant Backup

Operational communications, role-segmented onboarding/help, relational Excel migration, cron automations, and sovereign .sql.gz per-tenant snapshots.

Unified Communications & Guided UX

  • →Call Logs, Internal Chat & WhatsApp Dispatch

    Centralizes family/staff call traceability (/dashboard/calls), team chat (/dashboard/chat), and WhatsApp schedule sharing (/api/webhook/whatsapp).

  • →Role-Scoped Contextual Help & Spotlight Tourscontextual-help-registry.ts

    Delivers bilingual step-by-step interactive data-tour spotlights tailored separately for back-office coordinators and mobile field workers.

Data Reversibility & Automated Operations

  • →Relational XLSX/CSV Importer & Encrypted Snapshots/dashboard/import + /dashboard/backups

    Imports legacy clients, staff, and funding plans cleanly, and exports on-demand compressed .sql.gz backups of the agency's isolated database.

SPECIFICATION 12 / 12

Multi-Agent AI Architecture & Anti-Regression Gates

RBAC RAG CopilotBilingual Concierge4 Supervised Daemonstsc --noEmit Gate

Tenant-scoped RBAC Copilot, 24/7 bilingual public Concierge, and 4 supervised autonomous daemons locked behind deterministic validation gates.

Scoped Intelligence & Deterministic Safety

  • →Strict Tenant & Role Isolation/api/chat + /chat-api

    Internal Copilot queries execute strictly within the authenticated user's RBAC permissions and isolated tenant database.

  • →4 Supervised Agents with Rollback

    Treasury, Billing, Security Scanner, and Developer agents are guarded by syntax/delimiter validators, full tsc --noEmit verification, and automatic rollback.

SPECIFICATION 13 / 12

Factur-X EN 16931, Pre-Payroll Engine, Bank CSV & Care Liaison

Factur-X EN 16931Silae / WPS CSVBank CSV Auto-MatchJSON-LD + /statut

Hybrid PDF/XML electronic invoicing (UN/CEFACT CII), automated Silae/Sage/WPS pre-payroll computation, heuristic CSV bank reconciliation, and field-to-family liaison telemetry.

Electronic Invoicing, Payroll & Care Continuity

  • →Factur-X 1.0 Hybrid PDF/XML Attachmentlib/factur-x.ts + pdf-lib

    Generates a compliant UN/CEFACT Cross-Industry Invoice (urn:cen.eu:en16931:2017) and attaches factur-x.xml inside rendered invoices via AFRelationship.Alternative.

  • →Pre-Payroll & CSV Bank Reconciliation/dashboard/payroll + BankReconciliationModal

    Computes regular, rest-day, holiday, night (21:00–06:00) hours & Haversine GPS mileage for Silae/WPS exports, and reconciles bank CSV credits & SEPA rejections in 1 click.

  • →Digital Care Liaison, 1-Click PWA & Public Telemetrycare_liaison_notes + /demo + /statut

    Connects post-scan caregiver tags to coordinator alerts and /portal/liaison, backed by Schema.org JSON-LD, dynamic sitemap.ts, and live /api/health latency probes.

Deploy Your Isolated Instance in 60 Seconds

Every trial workspace provisions its own dedicated ACID MariaDB database with full access to all 12 engineering modules above.