This case study shows how I architected a modular platform with a deterministic pricing engine, 146 automated tests, and domain-driven boundaries — built for the Moroccan medical transport market.
5 pain points identified before writing a single line of code
Medical transport operators in Morocco manage scheduling, pricing, and invoicing through disconnected spreadsheets and manual processes
No unified system exists for ambulance dispatch, nursing visits, and home care coordination
Pricing involves complex rules: urgency levels, staff types, distance zones, time-of-day modifiers, and holidays
Invoice generation and payment tracking are manual — reconciliation is error-prone
No audit trail or role-based access control for sensitive patient and financial data
Real cost — not hypothetical risk
Pricing errors due to manual calculation of complex modifier stacks (night, weekend, holiday)
Lost revenue from untracked services and inconsistent invoicing
No visibility into business performance — revenue, collection rates, service distribution
Compliance risk from missing audit trails on sensitive medical operations
Operator burnout from repetitive admin tasks that could be automated
7 deliberate trade-offs
Modular DDD-style architecture: each module follows schema → types → repository → service → actions
Server Actions for all mutations — no REST API routes for CRUD operations
Deterministic pricing engine with 7 explicit steps and immutable snapshot persistence
Vitest test suite from Phase 0 — pricing engine at 100% coverage before any UI was built
RBAC with admin/assistant roles enforced at every server action boundary
Professional PDF invoice engine with @react-pdf/renderer (11 modular components)
Layered security: middleware → requireSession → requireAdmin → Zod validation → audit log
The blueprint that holds everything together
8 business modules (clients, patients, services, invoices, payments, pricing, users, dashboard) each with clear boundaries
Pricing engine resolves in 7 steps: catalog lookup → base price → distance fees → modifiers → manual override → VAT → snapshot
All pricing snapshots are immutable — past invoices always reflect the rules active at service time
Custom Design System with 10+ reusable components, consistent tokens, and layout system
PostgreSQL with Prisma ORM — 11 tables, relational integrity, and selective queries to prevent over-fetching
5 measurable improvements
146 automated tests across 9 test files — pricing engine at 100% coverage
128+ source files organized across 8 business modules with clean boundaries
10 development phases completed with full documentation at each stage
Dashboard loads 15 queries concurrently via Promise.all — bundle reduced 96% with dynamic imports
Professional invoice PDFs with itemized lines, pricing breakdown, and status badges
How the pricing engine, security model, and module architecture are designed — from schema to deployment.
Business or individual client with contact info and billing details
Patient record linked to client — name, condition, transport needs
Scheduled transport or care visit with pricing snapshot
Catalog-based pricing rules with urgency and staff type modifiers
Immutable point-in-time capture of pricing calculation
Generated from completed services with itemized lines and PDF export
Multi-method payment record with auto-reconciliation
Admin or assistant with RBAC and session hardening
Automatic logging of all critical operations
Same inputs always produce the same price. Every calculation step is logged and snapshot-persisted.
JWT with 8h maxAge, isActive re-validation on refresh, middleware protection on all dashboard routes.
PricingSnapshots are never modified. Rule changes don't retroactively alter past service prices.
Invoice status auto-updates based on payment totals: Unpaid → Partial → Paid. No manual status management.
Every create, delete, and cancel operation is logged with userId, role, entity, entityId, and timestamp.
RBAC checked at every server action — not just at the UI level. Assistant users cannot access admin mutations.
1. matchRule(serviceType, urgency, staffType)2. basePrice = rule.price3. distanceFee = getZoneRate(zone) × distance4. modifiers = applyNight() + applyWeekend() + applyHoliday()5. override? = admin.fixedPrice ?? calculated6. vat = finalAmount × vatRate7. snapshot = persist({ steps, total, timestamp })schema.ts → Zod validation (input/output shapes)types.ts → TypeScript interfaces & enumsrepository → Prisma queries (select, create, update)service.ts → Business logic + cross-module coordinationactions.ts → Server Actions (auth + validate + service + audit)middleware.ts → redirect if no session cookierequireSession() → JWT decode + isActive checkrequireAdmin() → role === 'admin' guardzodSchema.parse() → input validationauditLog() → { userId, role, action, entity, entityId }Past invoices always reflect the rules active at service time — rule changes never corrupt history
Simpler mutation layer with built-in type safety — no API versioning or endpoint management needed
Pricing engine was 100% tested before any UI existed — caught 12 edge cases during development
Each module can evolve independently — adding fleet management won't touch pricing or invoicing code
This is not a tutorial project. It is a production-grade SaaS being built with the same rigor I would apply to a team codebase.