# Master Architecture Report — TorbatYar SuperApp

| Field | Value |
| --- | --- |
| Document | Master Architecture Report |
| Version | 1.0 |
| Date | 2026-07-24 |
| Classification | Internal — Enterprise Planning |
| Status | Synthesis for review |
| Scope | Platform + Accounting + planned modules |
| Sources | Canonical docs under `docs/` (architecture, progress, roadmap, registries, frontend, deployment, phases, decisions, reference). Folder `docs/architecture-review/` did not previously contain intermediate review packs; this master report synthesizes the live documentation set. |

---

## Document Control

### Purpose

This report consolidates TorbatYar’s architecture, delivery maturity, platform services, business modules, risks, and enterprise roadmap into a single planning artifact. It is intended for long-term product and engineering decisions—not as a runbook and not as a substitute for phase checklists.

### Source-of-Truth Hierarchy (when docs conflict)

1. **Delivery status:** `docs/progress.md` (completed work) + `docs/next-steps.md` (immediate milestone) + `docs/roadmap.md` (future only)
2. **Module inventory:** `docs/module-registry.md`
3. **Architecture intent:** `docs/architecture/*` and ADRs
4. **Contracts / schema:** `docs/reference/*`
5. **Historical inventory review:** `docs/current-architecture-review.md` (dated 2026-07-22; some claims pre-date Accounting 5.x completion)

### Explicit Conflicts Called Out in This Report

| Topic | Side A | Side B | Preferred truth for this report |
| --- | --- | --- | --- |
| Accounting maturity | `database-architecture.md` still labels Accounting DB as “(future)” | `progress.md`, `module-registry.md`, Accounting phase area: Phases 5.1–5.11 complete, status Active | **Active / implemented** (registry + progress) |
| First business module | Product decision (Proposed): Restaurant after white-label | Accounting already delivered as Active business module | **Accounting shipped**; Restaurant remains preferred *next* go-to-market vertical after white-label polish (decision still Proposed) |
| Immediate next work | Older white-label narrative in some architecture notes | `next-steps.md`: Phase 5.12 AI readiness + production hardening | **next-steps.md** |
| Phase “3” meaning | External brief: onboarding as Phase 3 | Internal: Phase 3 = OTP/Tenant Mgmt; Phase 4 = Onboarding | **Internal numbering** (`decisions/technical/phase-numbering.md`) |
| White-label completion | Framed as incomplete / next | Progress: partial runtime exists (`tenant-site`, theme, SSL) | **Partial** — polish still near-term |
| Message bus | Architecture describes outbox path | Real broker still future | **Outbox/Celery today; bus later** |
| Stale doc inventory claims | `current-architecture-review.md` (Jul 22): Identity real, business modules placeholders, Accounting not yet a delivered module | Jul 24 progress/scoreboard: Accounting backend + FE largely complete | Prefer **Jul 24 progress/registry** for Accounting; keep review file for historical doc-drift lessons |

### Reading Guide

- Sections 1–3: executive and structural view
- Sections 4–11: capability deep dives (modules, APIs, data, FE/BE, security, infra)
- Sections 12–17: debt, refactoring, future platform map, scale, sequencing, recommendations, scorecard

---

# 1. Executive Summary

## 1.1 Current Project Maturity

TorbatYar is a **multi-tenant SuperApp SaaS** past foundation phases and into its first deep vertical: **Accounting**.

| Stage | Status (per docs) |
| --- | --- |
| Phase 1 — Core Platform | Complete |
| Phase 2 — Identity & Access + SSO | Complete |
| Phase 3 — OTP + Tenant Management | Complete |
| Phase 4 — Onboarding & Workspace Activation | Complete (with intentional gaps) |
| Phase D — Documentation consolidation | Complete |
| Accounting 5.1–5.11 | Complete (backend + enterprise FE baseline) |
| Accounting 5.12 AI | Blocked on AI Model Provider (Planned) |
| White-label runtime polish | Partial / near-term |
| Restaurant / CRM / commerce stack | Scaffolded or Planned |

**Maturity characterization:** Platform core is **production-shaped** (Nginx edge, TLS, Keycloak SSO, tenant SSL automation, entitlement, onboarding). Business depth is **strong in Accounting**, **thin elsewhere**. Shared horizontal services (notification, file storage, SMS panel, payment, message bus) remain **scaffolded/planned**.

## 1.2 Current Architecture (one paragraph)

The system is **service-oriented, API-first, database-per-service, row-level multi-tenant**. A Next.js frontend talks only to versioned HTTP APIs. Nginx terminates TLS and routes apex/API/identity/auth/tenant hosts. **Core Platform** owns tenants, plans, entitlements, onboarding, audit, and outbox. **Identity & Access** is the OIDC BFF to Keycloak and owns identity profiles. **Accounting** is an independent service (`accounting_db`, port 8002 documented) with a sole **Posting Engine** for financial entries. Cross-service coupling is restricted to REST, webhooks, async events, and Outbox/Inbox. Celery workers process outbox and tenant SSL expansion.

## 1.3 Technology Stack

| Layer | Technology (documented) |
| --- | --- |
| Frontend | Next.js 15.5.x, module routes, design system (`components/ds`), TanStack Query, Sonner, ColorMode |
| Backend services | Python services (Core, Identity, Accounting); layered API → Service → Repository → Model |
| Auth | Keycloak OIDC (RS256 JWT); Core OTP HS256 JWT; internal service tokens (hashed) |
| Data | PostgreSQL per service DB; Redis (entitlement cache, Celery broker usage implied by stack) |
| Workers | Celery worker + beat (outbox, SSL provision) |
| Edge | Nginx TLS, Let's Encrypt / Certbot, tenant SSL map + `provision_ssl.py` |
| Compose | postgres, redis, keycloak, core-service, identity-access-service, frontend, celery-worker, celery-beat |
| SMS | Payamak (Active) |
| Object storage / PSP / AI models | Planned |

## 1.4 Overall Readiness

| Dimension | Assessment |
| --- | --- |
| Multi-tenant SaaS foundation | Ready for early production tenants |
| Identity & workspace lifecycle | Ready (SSO + OTP + onboarding + JIT) |
| First enterprise vertical (Accounting) | Functionally broad; AI & some export/IAM depth remain |
| Horizontal platform services | Not ready (notification, files, payments, bus) |
| White-label / custom domain | Partial (subdomain SSL yes; DNS/TXT verify no) |
| 100 / 1,000 / 10,000 tenants | See Enterprise Readiness — 100 plausible with ops discipline; 1k+ needs bus, isolation hardening, observability, horizontal scale |

**Verdict:** Ready to **operate and deepen Accounting**, and to **finish platform polish** before proliferating many new business modules. Not yet ready as a full multi-vertical SuperApp marketplace.

## 1.5 Strengths

1. Clear **ADR set** (database-per-service, FE/BE split, tenancy, SSO, OTP, outbox, dual memberships, white-label, nginx SSL, posting engine).
2. **Entitlement + membership** dual-axis authorization model.
3. **Tenant resolution** order documented and operationally wired (headers → host → current tenant).
4. **Accounting Posting Engine ownership** prevents fragmented journals (ADR-010).
5. **Documentation-as-software** decision and consolidated `docs/` tree after Phase D.
6. Production topology documented (app host + nginx edge + named public hosts).
7. Accounting FE scoreboard shows high completion across core financial screens (mostly 85–98%).
8. Shared-lib boundaries for JWT/events without owning domain workflows.

## 1.6 Weaknesses

1. **Horizontal services delayed** — notification, file storage, payment, real message bus.
2. **White-label unfinished** relative to product ambition for Restaurant guest sites.
3. **Dual `tenant_memberships`** increases cognitive and sync risk (ADR-007 accepted tradeoff).
4. **Doc drift** still present (e.g., Accounting marked future in database-architecture).
5. **Advanced RBAC / invites** not delivered.
6. **Custom domain verification** pending.
7. **Observability** is checklist-level (health endpoints + suggested alerts), not a full SRE stack in docs.
8. **AI provider** not Active → Accounting AI UI blocked at 0%.
9. Product decision for “first business module” **out of sync** with Accounting already shipping.

## 1.7 Biggest Risks

| Risk | Why it matters | Mitigation direction |
| --- | --- | --- |
| Adding many business modules before horizontal platform (files, notify, pay, bus) | Duplicated integrations, inconsistent UX, rewrite tax | Build shared platform services before 3rd+ vertical |
| Membership divergence Core vs Identity | Authz bugs / SSO listing mismatch | Explicit sync events or stricter ownership docs + tests |
| Tenant isolation regression as modules grow | Cross-tenant data leakage | Mandatory tenant denial tests per testing strategy |
| Outbox without real bus at scale | Throughput / fanout limits | Introduce broker without changing envelope (ADR-006 future) |
| Payment + subscription gaps | Cannot monetize or settle commerce | Provider + Core subscription path before marketplace |
| Doc staleness driving wrong builds | Teams implement against obsolete claims | Enforce progress/registry as status; fix architecture labels |
| Noise-neighbor DB at high tenant count | Row-level tenancy saturation | Partitioning / read replicas / eventual DB-per-large-tenant strategy |

---

# 2. High Level Architecture

## 2.1 Architectural Style

| Principle | Rule | ADR |
| --- | --- | --- |
| Service-oriented | Major capabilities are independent services | Architecture overview |
| Database-per-service | One DB ownership per service; no cross-DB FK/joins | ADR-001 |
| API-first | Versioned REST (+ events); UI never owns business rules | ADR-002 |
| Multi-tenancy | `tenant_id` on business tables; no cross-tenant queries | ADR-003 |
| Event reliability | Outbox/Inbox + `EventEnvelope` | ADR-006 |
| Financial integrity | Only Accounting Posting Engine posts journals | ADR-010 |

## 2.2 Major Layers

```mermaid
flowchart TB
  subgraph Edge["Edge Layer"]
    NGX["Nginx TLS + Host Routing"]
  end
  subgraph Clients["Client Layer"]
    FE["Next.js Frontend<br/>SuperApp + Accounting module routes"]
  end
  subgraph Platform["Platform Services"]
    CORE["Core Platform<br/>tenants · plans · entitlement · onboarding · audit · outbox"]
    IDA["Identity & Access<br/>OIDC BFF · profiles · OTP handoff"]
    KC["Keycloak<br/>superapp realm · torbatyar theme"]
  end
  subgraph Business["Business Services"]
    ACC["Accounting<br/>COA · posting · GL · treasury · AR/AP · assets · payroll · reporting · compliance"]
    FUTURE["Scaffolded/Planned<br/>CRM · Restaurant · Ecommerce · …"]
  end
  subgraph Data["Data & Workers"]
    PG["PostgreSQL DBs per service"]
    RD["Redis"]
    CEL["Celery worker/beat"]
  end
  FE --> NGX
  NGX --> CORE
  NGX --> IDA
  NGX --> KC
  NGX --> ACC
  CORE --> PG
  IDA --> PG
  ACC --> PG
  CORE --> RD
  CORE --> CEL
  IDA --> KC
  ACC -.->|"entitlement check"| CORE
  FUTURE -.->|"API/events only"| CORE
  FUTURE -.->|"posting intents"| ACC
```

## 2.3 Dependency Flow

```mermaid
flowchart LR
  FE["Frontend"] --> CORE["Core API"]
  FE --> IDA["Identity API"]
  FE --> ACC["Accounting API"]
  FE --> KC["Keycloak"]
  IDA --> KC
  IDA --> CORE
  ACC --> CORE
  CORE --> PAYAMAK["Payamak SMS"]
  CORE --> SSL["Edge SSL provision via SSH"]
  CEL["Celery"] --> CORE
  CEL --> SSL
```

**Allowed channels (integration architecture):** versioned REST, webhook, async event, Outbox/Inbox.  
**Forbidden:** cross-DB queries/FKs, importing another service’s models, frontend DB access, UI inventing journal entries.

## 2.4 Module Interaction (current vs planned)

```mermaid
sequenceDiagram
  participant U as User
  participant FE as Frontend
  participant KC as Keycloak
  participant ID as Identity
  participant C as Core
  participant A as Accounting
  U->>FE: Open /accounting
  FE->>KC: SSO (if needed)
  FE->>ID: token/me flows
  FE->>C: /me · tenant context · entitlement
  C-->>FE: tenant + roles
  FE->>A: API + Bearer + X-Tenant-ID
  A->>C: feature check (as required)
  A-->>FE: domain data
  Note over C: Outbox events for tenant/subscription lifecycle
  Note over A: voucher.posted / ledger.updated (catalog)
```

## 2.5 Runtime Topology (production canonical)

| Component | Host / Endpoint |
| --- | --- |
| App / Docker | `192.168.10.162` |
| Nginx edge | `192.168.10.156` |
| Apex / tenant FE | `torbatyar.ir`, `*.torbatyar.ir` |
| Core API | `api.torbatyar.ir` → `:8000` |
| Identity API | `identity.torbatyar.ir` → `:8001` |
| Keycloak | `auth.torbatyar.ir` → `:8080` |
| Accounting API | Documented service port `:8002` (frontend `NEXT_PUBLIC_ACCOUNTING_API_URL`) |

Compose services listed: `postgres`, `redis`, `keycloak`, `core-service`, `identity-access-service`, `frontend`, `celery-worker`, `celery-beat`. Accounting production deploy is called out as pending verification in `next-steps.md`.

## 2.6 Tenant Resolution & White-Label

Resolution order:

1. `X-Tenant-ID`
2. `X-Tenant-Slug`
3. Subdomain + `PLATFORM_BASE_DOMAIN`
4. Custom domain from Host
5. User `current_tenant_id`

Lifecycle: `draft → pending_activation → active → suspended / archived` (legacy `inactive`/`deleted` retained).

White-label: tenant brand fields + public tenant-site/theme by host; platform defaults from env/`theme.config.json` (ADR-008). Subdomain SSL expansion automated (ADR-009). Custom domain DNS/TXT verification **not** done.

---

# 3. Current Platform Capabilities

Capabilities below are grouped by domain using **progress**, **module registry**, **provider registry**, and **frontend scoreboard**. Items marked Planned/Scaffolded are listed as capabilities of the *platform design*, not as shipped product.

## 3.1 Core

| Capability | Status |
| --- | --- |
| Project structure FE/BE separation | Done |
| Shared library (JWT, roles, events) | Done |
| Tenant CRUD / lifecycle | Done |
| Domains (subdomain provision) | Done |
| Plans / features / subscriptions seed (FREE/STARTER) | Done |
| Entitlement check + Redis cache | Done |
| Operational tenant memberships & roles | Done |
| Onboarding wizard APIs + services | Done |
| Public tenant-site resolution | Partial / present |
| Audit log | Done (architecture ownership) |
| Outbox/Inbox tables + worker path | Done (bus later) |
| Internal service tokens | Done |
| Service/module registry concept | Done (docs + Core ownership) |
| Payment gateway for subscriptions | Missing |
| DNS/TXT custom-domain verify | Missing |
| Legacy admin tenant auto membership/plan | Intentionally incomplete |
| Advanced permissions & invites | Missing |
| Independent Subscription service | Longer-term |

## 3.2 Platform (Identity / Access / Edge)

| Capability | Status |
| --- | --- |
| Keycloak realm/clients/theme | Done |
| Identity OIDC BFF | Done |
| Mobile OTP via Payamak (Core) + Identity handoff | Done |
| JIT Core user from Keycloak JWT | Done |
| Nginx reverse proxy + base TLS | Done |
| Automatic tenant subdomain SSL | Done |
| Cross-subdomain auth cookie model | Documented in review as operational concern |
| Rich Core↔Identity membership sync | Future |

## 3.3 Business

| Capability | Status |
| --- | --- |
| Accounting foundation → compliance (5.1–5.11) | Done |
| Accounting enterprise FE baseline | Done (AI blocked) |
| CRM | Scaffolded / not started |
| Restaurant / Cafe / Digital menu | Scaffolded / candidate |
| Ecommerce / Store builder | Scaffolded |
| Marketplace | Planned |
| Website / Landing builder | Scaffolded (`website_builder`) |
| Live Chat | Scaffolded |
| Smart Messenger | Scaffolded |
| Customer Club / Wallet | Not named as Active modules in registry (treat as future product capabilities) |
| Gym / Appointment / Reservation | Not dedicated Active modules in registry (Future/product) |
| ERP umbrella | Partially realized via Accounting depth; not a single ERP module |

## 3.4 Infrastructure

| Capability | Status |
| --- | --- |
| Docker Compose local/prod pattern | Done |
| Celery worker/beat | Done |
| Health endpoints Core/Identity | Done |
| Backup/restore/DR runbooks | Documented |
| Monitoring runbook (minimal alerts) | Documented |
| Real message bus | Missing |
| Full APM/metrics stack | Not evidenced as deployed in docs |
| CI/CD architecture deep doc | Historically called out as gap; branching/release strategies exist |

## 3.5 Developer Experience

| Capability | Status |
| --- | --- |
| Developer guides | Present |
| Coding standards / principles / testing strategy | Present |
| ADR system (001–010) | Present |
| Templates (module, phase, API, provider, ADR, decision) | Present |
| Module & provider registries | Present |
| Frontend design-system docs | Present |
| Phase docs for Accounting + area READMEs | Present |
| Documentation validation as phase exit | Required by testing strategy |

---

# 4. Business Modules

Status legend from registry: **Active** · **Scaffolded** · **Planned**.

## 4.1 Accounting — Active

| Field | Detail |
| --- | --- |
| Purpose | Tenant-aware double-entry accounting; sole Posting Engine; GL, treasury, AR/AP, sales/purchase/inventory accounting hooks, assets, payroll accounting, reporting, compliance/SoD |
| Current completion | Phases 5.1–5.11 complete; FE scoreboard mostly Complete (AI 0% Blocked); version `0.5.11.0`; migration `0002_phases_57_511`; 21 tests noted in progress |
| Implemented features | COA (4-level), fiscal year/period, currencies/FX, cost centers, projects/dimensions, voucher validate/post/reverse/cancel, ledger/trial balance, treasury, customers/suppliers AR/AP, sales integration, purchase/inventory valuation, fixed assets/depreciation, HCM/payroll posting, financial reporting/export framework, compliance/audit/governance |
| Missing features | Phase 5.12 AI UI (provider Planned); optional richer PDF export delivery; full tax authority connector; payment gateway; IAM rebuilt inside Accounting (deep-links only) |
| Dependencies | Core entitlement; ADR-010; shared JWT/tenant headers |
| Expansion capability | High within finance; must remain posting-engine-centric; AI only advisory |

### Accounting FE completion snapshot (2026-07-24)

| Area | % | Gate |
| --- | --- | --- |
| Dashboard | 90 | Complete |
| COA | 98 | Complete |
| Fiscal | 98 | Complete |
| Currencies | 98 | Complete |
| Cost Centers | 95 | Complete |
| Projects | 95 | Complete |
| Vouchers | 95 | Complete |
| Ledger | 95 | Complete |
| Treasury | 90 | Complete |
| Customers / AR | 92 | Complete |
| Suppliers / AP | 85 | Complete |
| Assets | 90 | Complete |
| Payroll | 88 | Complete |
| Reports | 92 | Complete |
| Compliance / Audit | 88 | Complete |
| Settings | 85 | Complete (IAM deep-links) |
| Setup | 95 | Complete |
| Mobile / Nav | 90 | Complete |
| AI | 0 | Blocked |

## 4.2 CRM — Scaffolded

| Field | Detail |
| --- | --- |
| Purpose | Customers, leads, opportunities, pipelines, tasks, automations |
| Completion | Not started (0.0.0) |
| Implemented | Placeholder service README / phase area only |
| Missing | Full domain, APIs, events, UI |
| Dependencies | Core entitlement; optional messenger/AI |
| Expansion | High; natural consumer of notification + AI |

## 4.3 Restaurant / Cafe — Scaffolded (candidate GTM module)

| Field | Detail |
| --- | --- |
| Purpose | Digital menu, tables, orders, kitchen, loyalty on tenant domains |
| Completion | Not started; product decision Proposed as preferred first *vertical after white-label* (note Accounting already exists) |
| Implemented | Scaffold only; conceptual `restaurant_db` |
| Missing | Menu, ordering, kitchen, loyalty, guest auth local to module DB, payments |
| Dependencies | Core entitlement, white-label host, optional Accounting postings via events, payment provider |
| Expansion | High for hospitality; depends on public site polish |

## 4.4 Ecommerce — Scaffolded

| Field | Detail |
| --- | --- |
| Purpose | Store builder, catalog, cart, orders, shipments |
| Completion | Not started |
| Missing | Entire commerce stack |
| Dependencies | Core, file_storage, payment, shipping |
| Expansion | Foundation for Marketplace |

## 4.5 Marketplace — Planned

| Field | Detail |
| --- | --- |
| Purpose | Multi-vendor market capabilities |
| Completion | Future |
| Dependencies | ecommerce, identity, accounting, payment |
| Expansion | Only after ecommerce foundation |

## 4.6 Website Builder — Scaffolded

| Field | Detail |
| --- | --- |
| Purpose | Sites, pages, blocks, forms, menus, media |
| Dependencies | file_storage / S3 |
| Note | Ties into white-label public sites |

## 4.7 Live Chat — Scaffolded

| Field | Detail |
| --- | --- |
| Purpose | Embeddable widget, conversations, agent routing |
| Dependencies | Core; optional CRM/AI |

## 4.8 AI Assistant — Scaffolded

| Field | Detail |
| --- | --- |
| Purpose | Intelligent chat, KB, human handoff |
| Guardrail | Must not be authority for money, compliance, or authorization |
| Dependencies | AI model provider (Planned), Core entitlement |

## 4.9 Smart Messenger — Scaffolded

Social channels, unified inbox, automations; depends on channel providers.

## 4.10 SMS Panel — Scaffolded

Campaign SMS separate from Core OTP path; multi-provider future.

## 4.11 Link Shortener — Scaffolded

Short links, custom domains, analytics; edge SSL for custom domains future.

## 4.12 Notification — Scaffolded (critical shared)

Central fanout email/SMS/push/webhook/in-app; should consume many domain events.

## 4.13 File Storage — Scaffolded (critical shared)

Tenant-aware uploads, S3 gateway, signed URLs planned.

## 4.14 Automation — Planned

Cross-module workflows; **requires real message bus maturity**.

## 4.15 Modules named in mission but not Active registry entries

The original master-report mission listed: Digital Menu, Customer Club, Wallet, Payment, Store/Website/Landing Builder, ERP, Gym, Workflow, Chat, Appointment, Reservation, Marketplace, AI, Automation.

Mapping from docs:

| Mission name | Doc mapping |
| --- | --- |
| Digital Menu | Restaurant module |
| Customer Club | Not a dedicated Active module — future product on CRM/Restaurant/Wallet |
| Wallet / Payment | Payment Gateway provider Planned; no Active wallet module |
| Store Builder | Ecommerce |
| Website / Landing Builder | website_builder |
| ERP | Accounting depth + future modules; not single module |
| Gym | Not in registry — Future candidate |
| Workflow | Automation |
| Chat | live_chat (+ AI) |
| Appointment / Reservation | Not dedicated Active modules — Future/product |
| SMS Platform | sms_panel (+ Core OTP via Payamak) |

---

# 5. Shared Platform Services

Reusable capabilities that multiple business modules should consume rather than reimplement.

## 5.1 Core Platform

| Aspect | Assessment |
| --- | --- |
| Purpose | Tenant/plan/entitlement/onboarding/audit/outbox registry |
| Consumers | All services + Frontend |
| Quality | High relative maturity (Phases 1–4) |
| Missing | Payment, DNS verify, advanced RBAC/invites, subscription extraction |
| Recommendation | Harden production deploy + white-label; avoid stuffing business journals into Core |
| Priority | P0 continuous |

## 5.2 Identity & Access

| Aspect | Assessment |
| --- | --- |
| Purpose | SSO BFF, profiles, OTP handoff |
| Consumers | Frontend, all JWT services |
| Quality | Active and production-used |
| Missing | Richer sync with Core memberships |
| Recommendation | Define membership sync events before many staff UIs diverge |
| Priority | P0 |

## 5.3 Keycloak (IdP provider)

| Aspect | Assessment |
| --- | --- |
| Purpose | Central staff SSO |
| Consumers | Identity, Frontend, JWT validators |
| Quality | Active |
| Missing | Operational runbooks beyond architecture notes (partially in deployment) |
| Recommendation | Treat as Tier-0 dependency; monitor availability |
| Priority | P0 |

## 5.4 Entitlement / Feature Gate (in Core)

| Aspect | Assessment |
| --- | --- |
| Purpose | Plan-based feature access |
| Consumers | Accounting now; all future modules |
| Quality | Implemented with Redis cache |
| Missing | Independent subscription service (longer-term) |
| Recommendation | Keep stable feature key taxonomy `{service}.{resource}.{action}` |
| Priority | P0 |

## 5.5 Outbox / Event Backbone

| Aspect | Assessment |
| --- | --- |
| Purpose | Reliable domain events |
| Consumers | Future notification, accounting integrations, automation |
| Quality | Pattern implemented; broker not real yet |
| Missing | Message bus, broader consumer ecosystem |
| Recommendation | Introduce bus before Automation engine |
| Priority | P1 before multi-module fanout |

## 5.6 Notification (scaffolded)

| Aspect | Assessment |
| --- | --- |
| Purpose | Central delivery |
| Consumers | All business modules |
| Quality | Scaffold only |
| Missing | Everything |
| Recommendation | Build before CRM/Restaurant campaigns |
| Priority | P1 |

## 5.7 File Storage (scaffolded)

| Aspect | Assessment |
| --- | --- |
| Purpose | Tenant media/documents |
| Consumers | website_builder, ecommerce, accounting exports, KYC/assets docs |
| Quality | Scaffold; S3 provider Planned |
| Recommendation | Activate S3 provider + signed URL pattern early |
| Priority | P1 |

## 5.8 SMS Panel vs Core OTP

| Aspect | Assessment |
| --- | --- |
| Purpose | Marketing/ops SMS vs auth OTP |
| Quality | OTP Active via Payamak; panel scaffolded |
| Recommendation | Keep OTP path separate; panel multi-provider later |
| Priority | P2 for panel; P0 for OTP reliability |

## 5.9 Payment Gateway (planned provider)

| Aspect | Assessment |
| --- | --- |
| Purpose | Subscriptions + commerce + restaurant pay |
| Missing | Provider selection and adapters |
| Recommendation | Required before Marketplace and paid plans automation |
| Priority | P1 |

## 5.10 AI Model Provider (planned)

| Aspect | Assessment |
| --- | --- |
| Purpose | Assistants / Accounting 5.12 |
| Status | Planned → blocks AI UI |
| Recommendation | Mark Active only with adapters + entitlement + non-authority guards |
| Priority | P1 for 5.12; P2 for broad AI |

## 5.11 Shared Library

| Aspect | Assessment |
| --- | --- |
| Purpose | JWT helpers, phone normalize, event envelope, shared errors |
| Quality | Foundational |
| Recommendation | Keep free of business workflows |
| Priority | P0 |

## 5.12 Edge SSL Provisioning

| Aspect | Assessment |
| --- | --- |
| Purpose | Tenant HTTPS at scale |
| Quality | Automated via Celery→SSH→provision_ssl |
| Risk | Worker must reach nginx host; LE rate limits |
| Priority | P0 ops |

---

# 6. API Platform

## 6.1 Overall API Quality

The platform is explicitly **API-first**. Core and Identity contracts live under `docs/reference/services-contracts.md` with an API index in `api-reference.md`. Accounting exposes versioned `/api/v1` areas for foundation, posting, ledger, treasury, AR/AP, assets, payroll, reporting, and compliance. Frontend typed clients call real endpoints (Accounting client documented as no-mocks).

**Quality posture:** Strong conventions and versioning intent; consistency depends on each service following the same layering and error patterns. Historical review noted incomplete Identity README tables vs contracts—contracts should remain canonical.

## 6.2 Consistency

| Expected convention | Documented practice |
| --- | --- |
| Prefix | `/api/v1` per service |
| Auth header | `Authorization: Bearer <token>` |
| Tenant header | `X-Tenant-ID` (and slug/host resolution) |
| DTOs | Pydantic schemas at API boundary |
| Feature keys | `{service}.{resource}.{action}` |
| Events | `{aggregate}.{past_tense_verb}` + EventEnvelope |

**Gaps:** Dual frontend client naming historically (`api.ts` vs `api-client.ts`) called out in architecture review—document or consolidate. New modules must not invent alternate auth/tenant schemes.

## 6.3 Versioning

APIs are organized under `api/v1/`. Architecture requires versioned REST. No separate public v2 strategy is detailed yet—future breaking changes should add v2 rather than silently break v1 consumers (Frontend + future partners).

## 6.4 Security

- Configurable `AUTH_REQUIRED` on Core
- Role dependencies: authenticated, platform_admin, tenant_admin, membership role ensures
- Accounting UI gated by AuthGuard + tenant id
- Internal service tokens scoped; hashed at rest
- Public tenant-site limited to public theme/site reads

## 6.5 Validation

Service architecture forbids business rules in routers but requires validation/HTTP mapping there. Accounting flows emphasize validate-before-post for vouchers. Testing strategy requires API contract tests including authz status codes.

## 6.6 Performance

Documented hot path: entitlement checks cached in Redis. Performance testing called out for entitlement/resolve paths “as needed.” No published SLA/latency budgets in the reviewed docs—treat as **UNKNOWN beyond caching intent**.

## 6.7 Future Readiness

| Need | Readiness |
| --- | --- |
| Many module UIs on same auth | Ready (SSO JWT) |
| Event-driven integrations | Pattern ready; bus not ready |
| External partner APIs | Needs stronger public API program (not fully specified) |
| Webhooks as product | Allowed channel; productized webhook platform not Active |

---

# 7. Database

## 7.1 Overall Schema Quality

**Pattern:** Database-per-service with UUID IDs and timezone-aware timestamps. Core and Identity schemas are documented; Accounting has migrations through `0002_phases_57_511`. Future service schemas remain conceptual until migrations exist.

**Conflict:** `database-architecture.md` still lists Accounting as “(future)” while registry/progress mark it Active—**update that architecture label**.

## 7.2 Scalability

Row-level multi-tenancy (ADR-003) optimizes early ops (one DB per service). Architecture acknowledges **noise-neighbor** risk at very large scale; mitigation is future (partitioning / isolation strategies)—not implemented as a current project phase.

## 7.3 Tenant Readiness

| Rule | Status |
| --- | --- |
| `tenant_id` on business tables | Required |
| No cross-tenant queries | Hard rule |
| Tenant denial tests | Required for new APIs |
| Platform admin cross-tenant support reads | Must be controlled + logged (compliance) |

## 7.4 Relationships

- **No cross-DB foreign keys**
- Dual membership tables (ADR-007):
  - `core_platform_db.tenant_memberships` — workspace authz source of truth
  - `identity_access_db.tenant_memberships` — SSO listing
- Accounting relationships remain inside `accounting_db`
- Reference data duplication across services must sync via API/events

## 7.5 Performance

Indexes and query plans are not exhaustively published in architecture docs. Entitlement caching reduces repeated plan checks. Ledger recalculation and reporting are domain-heavy—capacity planning should treat them as scale hotspots when tenant count grows (**engineering judgment labeled as planning recommendation derived from module scope, not a measured benchmark in docs**).

## 7.6 Migration Strategy

- Alembic per service
- Never edit applied migrations in production
- Historical ops caveat from architecture review: compose used `upgrade 0001_initial && stamp head` pattern—teams must understand stamp vs full upgrade risks
- Accounting progress notes migration `0002_phases_57_511`

---

# 8. Frontend

## 8.1 Architecture

- Single Next.js SuperApp (not separate apps per module)
- Accounting under `app/accounting/**` with `AccountingShell`
- Strict FE/BE separation (ADR-002)
- AuthGuard + `/me` + onboarding redirects
- Design system tokens light/dark + `components/ds`
- Catalog tile → `/accounting`

## 8.2 UI System

Documented design system, layout, navigation, tables, forms, dialogs, drawers, theme, responsive, accessibility docs under `docs/frontend/`. Accounting uses DS components and ColorModeProvider.

## 8.3 Routing

Module route placement under SuperApp. Platform routes include login/callback/dashboard/onboarding/tenant site paths (progress). Mobile nav polish marked Complete at 90% on scoreboard.

## 8.4 State Management

TanStack Query providers for server state; toasts via Sonner. Tenant via `useTenantId` / `useMe`. No indication that business writes bypass APIs.

## 8.5 Permission System

UI gated by roles from `/me` mirroring Core roles. Accounting settings IAM is deep-linked to SuperApp settings rather than rebuilt. Advanced permission trees still roadmap.

## 8.6 Reusable Components

Shared DS library intended for cross-module reuse. Frontend docs include component library and page/table/form patterns—good foundation for CRM/Restaurant UIs if enforced.

## 8.7 Scalability (FE)

Adding modules as route trees scales organizationally if:

1. Each module keeps its own API client
2. Shell/nav remains entitlement-aware
3. Bundle splitting discipline is maintained (performance doc exists; no numeric budgets extracted here)

White-label runtime polish remains a cross-cutting FE concern for public tenant hosts.

---

# 9. Backend

## 9.1 Architecture

Every backend service follows:

```
API (routers) → Services → Repositories → Models
                 ↑
              Schemas (DTOs)
```

Core layout includes `core/`, `middlewares/` (tenant), `workers/`, `api/v1/`, `tests/`.

## 9.2 Modules

| Service | DB | Status |
| --- | --- | --- |
| core-platform | `core_platform_db` | Active |
| identity-access | `identity_access_db` | Active |
| accounting | `accounting_db` | Active 5.1–5.11 |
| Others in registry | dedicated `*_db` | Scaffolded/Planned |

## 9.3 Dependency Quality

- Accounting → Core entitlement
- Identity → Keycloak + Core OTP
- Frontend → Core + Identity + Accounting + Keycloak
- Business modules must not import each other’s models
- Financial postings only via Accounting posting engine

## 9.4 Transaction Handling

Outbox pattern requires business row + `outbox_events` in **one transaction**. Accounting posting flows are transactional domain operations (validate/post/reverse/cancel). Cross-DB transactions are intentionally impossible—use eventual consistency via events.

## 9.5 Caching

Redis used for entitlement checks. Broader cache strategy for public tenant-site themes is implied by white-label architecture (“must stay cacheable”) but not fully specified as a platform cache product.

## 9.6 Queues & Background Jobs

Celery worker/beat:

- `process_outbox_events`
- `provision_domain_ssl` / SSL expansion path
- Future jobs should follow same worker model until bus exists

## 9.7 Health Monitoring

Documented health checks for Core and Identity; Frontend HTTP 200; Keycloak realm availability. Suggested alerts: restart loops, Postgres/Redis down, cert expiry < 14 days, OTP error spikes, outbox failed growth.

---

# 10. Security

## 10.1 Authentication

| Surface | Mechanism |
| --- | --- |
| Staff (platform/tenant) | Keycloak OIDC JWT RS256 |
| OTP users | HS256 JWT after SMS verify |
| Service-to-service | Internal tokens (scoped, hashed) |
| Public tenant site | Unauthenticated public reads only |

Mobile number mandatory + OTP verified (ADR-005). Passwords only in Keycloak.

## 10.2 Authorization

Two axes must pass: **role** + **entitlement**. Core memberships are operational SoT. Identity memberships are listing-oriented.

## 10.3 Permissions

Feature keys namespaced per service. Accounting uses `accounting.*`, `treasury.*`, `receivable.*`, `payable.*`, `sales_accounting.*`. Advanced custom permission trees / invites: roadmap.

## 10.4 Secrets & Configuration

Secrets in environment / secret stores—never git. Brand values not hardcoded (ADR-008). Backup docs call out storing `.env` outside git.

## 10.5 Potential Risks

1. Dual membership divergence
2. SSH-based SSL provision surface (worker → nginx host)
3. OTP provider outage blocking login paths
4. Incomplete custom-domain verify → spoofing/ops risk if misissued
5. Cross-tenant bugs as module count grows
6. AI future risk of over-authority (explicitly forbidden by AI architecture)

---

# 11. Infrastructure

## 11.1 Docker

Compose-based local and production app host. Services listed in deployment architecture. Accounting container deploy called out in next-steps exit criteria.

## 11.2 Deployment

Two-host production model: app `192.168.10.162`, edge `192.168.10.156`. Public DNS names for apex, API, identity, auth, wildcard tenants. Runbooks under `docs/deployment/`.

## 11.3 CI/CD

Branching and release strategies exist under `docs/development/`. Earlier architecture review flagged CI/CD as poorly documented relative to Gitea remote existence. Treat CI maturity as **partially documented**—do not invent pipeline details not present in docs.

## 11.4 Monitoring

Health endpoints + log locations + suggested minimum alerts. Not a full metrics/tracing platform description.

## 11.5 Backups

`pg_dump` for core/identity (and Keycloak DB if separate); retain 7/4/3 suggested; verify restores; include certs/nginx maps; future file buckets.

## 11.6 Scaling

Vertical VPS-oriented today. Horizontal scale requires: stateless API replicas, Redis/Celery scaling, Postgres capacity, edge capacity, and eventually a real message bus. Tenant SSL automation must respect LE rate limits.

---

# 12. Technical Debt

Grouped by severity using conflicts, intentional incompletes, and architectural risks documented across progress/roadmap/review/architecture.

## 12.1 Critical

| ID | Finding | Notes |
| --- | --- | --- |
| C1 | Tenant isolation must remain perfect as modules explode | Testing strategy requires denial cases; failure is a company-ending bug class |
| C2 | Financial integrity depends on universal ADR-010 adherence | Any module writing journals directly breaks compliance story |
| C3 | Production hardening for Accounting deploy still open in next-steps | PATCH/setup/template import verification pending |

## 12.2 High

| ID | Finding | Notes |
| --- | --- | --- |
| H1 | No real message bus yet | Blocks Automation; limits fanout |
| H2 | Notification & File Storage not built | Will be reimplemented ad hoc if modules proceed |
| H3 | Payment gateway missing | Blocks monetization & commerce |
| H4 | Custom domain DNS/TXT verification missing | White-label enterprise expectation |
| H5 | Dual membership sync incomplete | ADR-007 accepted but unfinished operationally |
| H6 | Doc drift (Accounting “future” in DB architecture; older review claims) | Misleads planning |
| H7 | Advanced RBAC/invites missing | Enterprise tenant admin UX gap |

## 12.3 Medium

| ID | Finding | Notes |
| --- | --- | --- |
| M1 | White-label runtime partial | Near-term roadmap item |
| M2 | AI provider Planned blocks 5.12 | Scoreboard 0% |
| M3 | Observability minimal | Suggested alerts not a full SRE stack |
| M4 | Frontend API client dual naming history | DX confusion |
| M5 | Legacy admin tenant auto provision incomplete | Tracked intentionally |
| M6 | PDF export file delivery optional gap | Accounting FE remaining |
| M7 | Product decision “first module = Restaurant” stale vs Accounting shipped | Update decision status |

## 12.4 Low

| ID | Finding | Notes |
| --- | --- | --- |
| L1 | Phase numbering alias confusion (external vs internal) | Glossary/decision exists—keep linking |
| L2 | Placeholder service READMEs easy to misread as implemented | Registry status must be checked |
| L3 | Independent Subscription service deferred | Acceptable mid-term |
| L4 | Tax authority connector deferred | Explicitly out of early accounting scope |

---

# 13. Refactoring Roadmap

Work that should happen **before proliferating new business modules** (CRM + Restaurant + Ecommerce simultaneously). Rationale: shared platform leverage and isolation safety.

## 13.1 Before next vertical (ordered)

| # | Item | Why | Impact |
| --- | --- | --- | --- |
| 1 | Finish white-label public tenant runtime polish | Restaurant/digital menu depends on host branding/public paths | Unblocks hospitality GTM |
| 2 | Production-verify Accounting + FE | Avoid building on unstable prod baseline | Reduces incident risk |
| 3 | Reconcile stale architecture labels & product decision docs | Prevent wrong sequencing | Low code, high clarity |
| 4 | Membership sync strategy (events/tests) | Every new staff UI multiplies divergence risk | Prevents authz incidents |
| 5 | Activate File Storage + S3 provider | Media/docs needed by site/commerce/accounting exports | Avoids local disk hacks |
| 6 | Stand up Notification service MVP | Stops per-module SMS/email forks | Platform consistency |
| 7 | Payment provider adapter + subscription hooks | Monetization & restaurant/ecommerce pay | Revenue path |
| 8 | Message bus behind existing outbox | Enables Automation and scale fanout | Architectural unlock |
| 9 | Custom domain verification | Enterprise white-label completeness | Sales enablement |
| 10 | Advanced invites/RBAC | Multi-user tenants beyond owner | Enterprise readiness |

**Estimate (planning, not a formal quote):** Items 1–4 are near-term hardening (days–few weeks of focused work depending on team size). Items 5–8 are multi-sprint platform investments. Items 9–10 are product-facing platform features.

## 13.2 Explicitly do *not* refactor away

- Database-per-service
- Outbox envelope
- Keycloak central SSO for staff
- ADR-010 posting ownership
- Row-level `tenant_id` model (until scale evidence demands more)

---

# 14. Future Platform Architecture

Target structure to support the SuperApp portfolio.

## 14.1 Core Services

| Service | Role |
| --- | --- |
| Core Platform | Tenants, domains, plans, entitlement, onboarding, audit, registries, internal tokens |
| Identity & Access | SSO BFF, profiles, OTP handoff |
| Keycloak | IdP |
| (Future) Subscription & Entitlement service | Extract when billing complexity demands |

## 14.2 Shared Platform Services

| Service | Role |
| --- | --- |
| Notification | Multi-channel fanout |
| File Storage | Tenant objects / signed URLs |
| SMS Panel | Campaign SMS (not auth OTP) |
| Payment | PSP adapters, webhooks |
| Link Shortener | Campaign links |
| Event Bus + Outbox workers | Reliable integration spine |
| Automation / Workflow engine | Cross-module triggers/actions |
| AI Assistant (platform) | Advisory only; provider-agnostic |
| Wallet (future) | Stored value / credits — should sit near Payment, not inside random verticals |
| Chat platform (live_chat) | Widget + routing shared by CRM/support |

## 14.3 Business Modules

| Module | Notes |
| --- | --- |
| Accounting / ERP financials | Already Active; posting hub for money |
| CRM + Customer Club features | Club can start as CRM segment/loyalty entities |
| Restaurant / Cafe / Digital Menu | Guest ordering on tenant domain |
| Appointment / Reservation / Gym | Vertical packs—prefer shared scheduling kernel later if multiple verticals need it |
| Ecommerce Store Builder | Catalog/cart/orders |
| Website / Landing Builder | Public content |
| Marketplace | After ecommerce + payment + identity maturity |
| Smart Messenger | Channel inbox |

## 14.4 Infrastructure

| Capability | Notes |
| --- | --- |
| Nginx edge + auto SSL | Keep; watch rate limits |
| Postgres per service | Keep; plan replicas/partitioning |
| Redis | Cache + queues |
| Celery → evolve with bus | Keep outbox ownership |
| Observability stack | Elevate from health checks to metrics/tracing/alerting productization |
| Backup/DR | Execute runbooks on schedule |
| CI/CD | Make pipelines first-class documented |

## 14.5 Placement Map for Mission Capabilities

```mermaid
flowchart TB
  subgraph CoreSvc["Core Services"]
    CORE["Core Platform"]
    ID["Identity"]
    KC["Keycloak"]
    SUB["Subscription service future"]
  end
  subgraph Shared["Shared Platform Services"]
    NOTIF["Notification"]
    FILE["File Storage"]
    PAY["Payment"]
    SMS["SMS Panel"]
    BUS["Message Bus"]
    AUTO["Automation/Workflow"]
    AI["AI Assistant"]
    CHAT["Live Chat"]
    WALL["Wallet future"]
  end
  subgraph Biz["Business Modules"]
    ACC["Accounting/ERP finance"]
    CRM["CRM + Customer Club"]
    REST["Restaurant/Cafe/Menu"]
    ECOM["Store Builder"]
    WEB["Website/Landing Builder"]
    MKT["Marketplace"]
    GYM["Gym/Appointment/Reservation"]
  end
  Biz --> CoreSvc
  Biz --> Shared
  REST --> PAY
  ECOM --> PAY
  MKT --> ECOM
  ACC --> NOTIF
  CRM --> NOTIF
  WEB --> FILE
  ECOM --> FILE
  AUTO --> BUS
```

---

# 15. Enterprise Readiness

## 15.1 100 Tenants

**Assessment: Achievable** with current architecture if ops discipline holds.

| Area | Bottleneck risk |
| --- | --- |
| Postgres row-level tenancy | Low–moderate |
| Nginx + SSL expand | Moderate (LE limits, SSH automation) |
| Keycloak | Low if sized |
| Celery outbox | Low–moderate |
| Support/observability | Medium (process) |
| Accounting heavy reports | Medium per active finance tenants |

## 15.2 1,000 Tenants

**Assessment: Conditional — needs platform upgrades.**

| Bottleneck | Why |
| --- | --- |
| Outbox without bus | Fanout to notification/CRM will choke |
| Single Postgres per busy service | Noise-neighbor / IO |
| Edge cert automation | Operational load |
| Redis/Celery capacity | Must be sized and monitored |
| Absence of Notification/File platforms | Ad hoc load on Core |
| RBAC/invites | Support burden multiplies |
| Custom domains | Verification + SSL complexity |

## 15.3 10,000 Tenants

**Assessment: Not ready** on documented footing.

Required before serious pursuit:

1. Horizontally scaled APIs and workers
2. Real message bus + consumer autoscaling
3. DB strategy beyond naive shared tables (partitioning, replicas, possibly large-tenant isolation)
4. Mature multi-provider SMS/email/push
5. Payment + subscription systems hardened
6. Full observability and on-call
7. Self-service domain/SSL with rate-limit governance
8. Strong tenant isolation testing in CI
9. Possibly regional deployment (not documented today)

---

# 16. Recommended Development Order

Dependency-aware sequence synthesizing roadmap, next-steps, registries, and platform needs.

## 16.1 Wave 0 — Stabilize (now)

1. Accounting production deploy verification  
2. Provider AI Active → Phase 5.12 (optional parallel)  
3. Doc reconciliation (DB architecture Accounting status; product first-module decision)  
4. White-label polish completion  

## 16.2 Wave 1 — Shared platforms

1. File Storage + S3 provider  
2. Notification MVP  
3. Payment gateway provider  
4. Custom domain DNS/TXT verify  
5. Membership sync Core↔Identity  
6. Message bus behind outbox  

## 16.3 Wave 2 — GTM verticals

1. **Restaurant / Digital Menu** (depends on white-label + payment)  
2. **CRM** (depends on notification; feeds Customer Club)  
3. Customer Club / loyalty features (on CRM and/or Restaurant)  

## 16.4 Wave 3 — Builders & content

1. Website / Landing Builder (depends on file storage)  
2. Ecommerce / Store Builder (depends on file storage + payment)  
3. Link Shortener / SMS Panel campaigns  

## 16.5 Wave 4 — Conversational & AI

1. Live Chat  
2. AI Assistant (provider-agnostic; never money authority)  
3. Smart Messenger  

## 16.6 Wave 5 — Platforms of platforms

1. Automation / Workflow (requires bus)  
2. Wallet (requires payment)  
3. Appointment / Reservation / Gym packs (prefer shared scheduling once ≥2 verticals need it)  
4. Marketplace (requires ecommerce + payment + identity maturity + accounting settlement events)  
5. Subscription & Entitlement independent service  
6. Compliance connectors (tax authority)  

## 16.7 Dependency Diagram

```mermaid
flowchart TD
  WL[White-label polish] --> REST[Restaurant/Menu]
  PAY[Payment] --> REST
  PAY --> ECOM[Ecommerce]
  FILE[File Storage] --> WEB[Website Builder]
  FILE --> ECOM
  NOTIF[Notification] --> CRM[CRM]
  BUS[Message Bus] --> AUTO[Automation]
  ECOM --> MKT[Marketplace]
  PAY --> MKT
  ID[Identity maturity] --> MKT
  ACC[Accounting] --> MKT
  AIProv[AI Provider] --> AI[AI Assistant]
  AI --> CHAT[Live Chat assist]
  CRM --> CLUB[Customer Club]
  REST --> CLUB
```

---

# 17. Final Architecture Recommendations

## 17.1 Immediate Actions

- [ ] Execute `next-steps.md` exit criteria (AI provider decision, Accounting prod verify, scoreboard 5.12 unblock path)
- [ ] Complete white-label runtime rendering gaps
- [ ] Fix stale “Accounting (future)” labeling in database architecture docs
- [ ] Update product decision: Accounting is Active; Restaurant is next hospitality vertical candidate
- [ ] Enforce ADR-010 in all new module designs
- [ ] Add/keep cross-tenant denial tests for every new tenant API
- [ ] Monitor outbox failed growth + cert expiry

## 17.2 Next Phase

- [ ] File Storage + S3 Active
- [ ] Notification service MVP consuming core/accounting events
- [ ] Payment gateway Active for subscriptions/commerce
- [ ] Custom domain verification
- [ ] Core↔Identity membership sync events
- [ ] Introduce real message bus without breaking EventEnvelope
- [ ] Advanced membership permissions & invites
- [ ] Restaurant foundation after white-label+pay

## 17.3 Long-term Improvements

- [ ] Automation engine
- [ ] Marketplace
- [ ] Independent Subscription service
- [ ] Multi-region / higher-isolation tenancy options
- [ ] Full observability (metrics, tracing, SLO dashboards)
- [ ] Tax/compliance connectors
- [ ] Shared scheduling kernel if Gym/Appointment/Reservation multiply
- [ ] Wallet platform adjacent to Payment

---

# 18. Enterprise Scorecard

Scores are **documentation-grounded judgments** of current readiness (1 = absent/unfit, 10 = enterprise-proven at scale). They are not load-test results.

| Dimension | Score | Rationale |
| --- | --- | --- |
| Architecture | **8** | Clear ADRs, boundaries, layering; some doc drift |
| Modularity | **8** | DB-per-service + registries; many modules still scaffolds |
| Scalability | **5** | Fine for early SaaS; 1k–10k needs bus/DB/edge upgrades |
| Maintainability | **7** | Docs/ADR/phase discipline strong; dual memberships & drift cost |
| Security | **7** | SSO/OTP/tokens/TLS solid; RBAC depth & domain verify gaps |
| Backend | **8** | Core/Identity/Accounting real with layering; workers present |
| Frontend | **7** | SuperApp + DS + Accounting high completion; white-label partial |
| Database | **7** | Sound rules; Accounting label stale; scale strategy nascent |
| API | **7** | Versioned, tenant-aware; consistency/tooling still maturing |
| Testing | **6** | Strategy clear; Accounting 21 tests noted; not full enterprise matrix evidenced |
| Documentation | **8** | Post Phase D strong; conflicts remain in places |
| Developer Experience | **7** | Guides/templates/registries; dual clients & stubs confuse |
| Infrastructure | **6** | Compose+nginx+SSL real; monitoring/CI depth limited in docs |
| Enterprise SaaS Readiness | **6** | Strong foundation + one deep vertical; shared platforms incomplete |

### Scorecard summary chart

```mermaid
%%{init: {'theme': 'base'}}%%
quadrantChart
  title Readiness vs Strategic Importance
  x-axis Low readiness --> High readiness
  y-axis Lower leverage --> Higher leverage
  quadrant-1 Scale next
  quadrant-2 Protect & polish
  quadrant-3 Later
  quadrant-4 Foundation bets
  Architecture: [0.78, 0.85]
  Accounting: [0.82, 0.80]
  Identity: [0.80, 0.88]
  WhiteLabel: [0.55, 0.75]
  Notification: [0.20, 0.80]
  FileStorage: [0.20, 0.78]
  Payment: [0.15, 0.85]
  MessageBus: [0.25, 0.90]
  Restaurant: [0.15, 0.70]
  Marketplace: [0.05, 0.55]
```

---

# Appendix A — ADR Index

| ADR | Title | Status |
| --- | --- | --- |
| ADR-001 | Database-per-Service | Accepted |
| ADR-002 | Strict Frontend / Backend Separation | Accepted |
| ADR-003 | Row-Level Multi-Tenancy with tenant_id | Accepted |
| ADR-004 | Central SSO with Keycloak | Accepted |
| ADR-005 | Mandatory Mobile Identity with OTP | Accepted |
| ADR-006 | Transactional Outbox / Inbox for Events | Accepted |
| ADR-007 | Dual Tenant Membership Tables | Accepted |
| ADR-008 | White-Label Branding via Config and Tenant Profile | Accepted |
| ADR-009 | Nginx Edge with Automatic Tenant SSL Expansion | Accepted |
| ADR-010 | Posting Engine Ownership for Accounting Entries | Accepted |

---

# Appendix B — Provider Status Snapshot

| Provider | Status |
| --- | --- |
| Payamak | Active |
| Keycloak | Active |
| Let's Encrypt / Certbot | Active |
| S3-Compatible | Planned |
| Payment Gateway | Planned |
| AI Model Provider | Planned |

---

# Appendix C — Phase Numbering Glossary

| Internal | Meaning |
| --- | --- |
| Phase 1 | Core Platform |
| Phase 2 | Identity & Access + SSO |
| Phase 3 | OTP Login + Tenant Management |
| Phase 4 | Tenant Onboarding & Workspace Activation |
| Phase D | Documentation Architecture Consolidation |
| Phase 5.x | Accounting module phases |
| External brief “Phase 3” | Often means onboarding → internal Phase 4 |

---

# Appendix D — Event Catalog Snapshot (Core / Identity / Accounting samples)

**Core:** `tenant.created`, `tenant.suspended`, `tenant.activated`, `domain.created`, `subscription.created`, `subscription.updated`, `feature_access.changed`  

**Identity:** `user.registered`, `tenant_member.added`, `tenant_member.removed`  

**Accounting (registry):** `voucher.posted`, `ledger.updated`, `cash.received`, `settlement.completed`, `sales_invoice.posted`  

**Reserved future examples:** CRM `lead.*` / `opportunity.*`; Restaurant `order.*`; Ecommerce `order.*` / `product.*`; Notification `notification.delivered`

---

# Appendix E — Intentional Incompletes After Phase 4 (still open)

From progress:

- Real payment gateway  
- Real DNS/TXT custom-domain verification  
- Membership/plan auto-provision on legacy `POST /admin/tenants`  
- First *hospitality* business module (Restaurant)—note Accounting later became the first deep vertical  
- Advanced permissions / invites  
- Independent Subscription service  
- Real message bus  

---

# Appendix F — Source Document Index Used for Synthesis

- `docs/progress.md`, `docs/roadmap.md`, `docs/next-steps.md`, `docs/last_step.md` (if present), `docs/module-registry.md`, `docs/provider-registry.md`, `docs/glossary.md`
- `docs/current-architecture-review.md`
- `docs/architecture/*`, `docs/architecture/adr/*`
- `docs/reference/*`
- `docs/deployment/*`
- `docs/development/*` (principles, testing, etc.)
- `docs/frontend/*` (architecture + completion scoreboard)
- `docs/phases/**/README.md` and Accounting phase area
- `docs/decisions/product/first-business-module.md`, phase-numbering decision

**Not used:** application source code (per mission constraint for this master report generation pass).

---

# Appendix G — Narrative Architecture Brief (extended)

TorbatYar’s strategic bet is that a SuperApp can share **identity, tenancy, entitlement, edge TLS, and eventing**, while each vertical owns its database and domain API. That bet is already partially validated: Core + Identity + edge SSL support real onboarding and host-based tenants; Accounting proves a deep vertical can live beside the platform without collapsing into a monolith—**provided** posting ownership and entitlement checks remain sacred.

The primary failure mode for the next 12–24 months is not “wrong framework choice.” It is **premature module sprawl**: scaffolding CRM, Restaurant, Ecommerce, Chat, and Messenger in parallel without Notification, File Storage, Payment, and a real bus. That path recreates N SMS integrations, N upload hacks, and N inconsistent authz bugs.

The primary success path is sequenced: **harden platform polish → ship shared services → open verticals in dependency order → only then marketplace/automation at scale**. Accounting should remain the financial spine; AI must remain advisory; guest experiences may use local auth inside vertical DBs without weakening staff SSO.

Operationally, the two-host VPS topology is appropriate for early production and ~100 tenants with discipline. Crossing into thousands of tenants is an infrastructure program, not a feature sprint.

---

# Appendix H — Module Expansion Playbooks (summary)

### H.1 Adding a business module

1. Create `backend/services/<name>/` + DB + Alembic  
2. Register in Core + `module-registry.md`  
3. Feature keys + entitlement wiring  
4. Events in catalog + outbox producers  
5. Frontend module routes using DS + typed client  
6. Tenant denial tests + docs/phase updates first if boundaries change  

### H.2 Adding a provider

1. `provider-registry.md` entry  
2. Adapter boundary (no domain hardcode)  
3. `provider-reference.md` ops sheet when Active  
4. Tests for failure modes  
5. Never mark Active without config + ownership  

### H.3 Touching money

1. Emit posting intent / use Accounting APIs  
2. Never write `JournalEntry` lines in foreign modules  
3. Keep audit metadata tenant-scoped  

---

# Appendix I — Risk Register (consolidated)

| Risk | Likelihood | Impact | Owner lens | Treatment |
| --- | --- | --- | --- | --- |
| Cross-tenant leak | Med if rushed | Critical | Every module | Mandatory tests + review |
| Journal fragmentation | Med without ADR education | Critical | Accounting + platform | ADR-010 gates |
| Busless fanout collapse | High as modules grow | High | Platform | Bus before Automation |
| Membership drift | Med | High | Identity + Core | Sync events |
| LE rate limit / SSL ops | Med | High | Ops | Throttle + monitoring |
| Doc-driven wrong build | Med | Med | Architecture | SoT hierarchy |
| Payment delay | High | High | Product | Provider wave 1 |
| AI overreach | Low if guarded | High | AI + Compliance | Architecture rules |

---

# Appendix J — Readiness Checklist for “Open Next Vertical”

- [ ] White-label public paths accepted by product  
- [ ] Entitlement keys reserved in registry  
- [ ] File upload story decided (File Storage or explicit exception)  
- [ ] Notification story decided  
- [ ] Payment needed? If yes, provider Active  
- [ ] Accounting impact? If yes, posting contracts defined  
- [ ] Guest auth decision (local vs SSO) documented  
- [ ] Phase docs created under `docs/phases/`  
- [ ] Scoreboard/progress hooks agreed  

---

# Appendix K — Glossary Essentials

- **Tenant:** workspace/organization  
- **Entitlement:** plan feature gate  
- **Posting Engine:** only writer of accounting journals  
- **Outbox/Inbox:** reliable event publish/consume  
- **JIT:** just-in-time Core user link/create from Keycloak JWT  
- **Platform admin:** cross-tenant operator role  
- **Tenant owner:** required steward of an active workspace  

---

# Appendix L — Closing Statement

TorbatYar is past the “empty platform” stage. It has a coherent multi-tenant architecture, a working identity edge, and a serious Accounting vertical. Enterprise ambition is credible **if** shared platform services and operational scale work are sequenced ahead of SuperApp breadth. This master report should be treated as the planning baseline for that sequencing; update it when `progress.md` / registries change materially.

---

*End of Master Architecture Report v1.0 — 2026-07-24*

---

# Appendix M — Accounting Phase Deep Dive (5.1–5.11)

This appendix expands Business Module Accounting using phase documents. All phases below are marked **Complete** in phase docs unless noted.

## M.1 Phase 5.1 — Accounting Foundation (v0.5.1.0)

**Delivered:** Chart of Accounts, Account, Currency, Exchange Rate, Fiscal Year/Period, Cost Center, Project, Dimension, Accounting Settings, Document Number Sequence, Tenant Accounting Configuration; full Repository/Service/Schema/API layering; foundation events; `accounting.*` permissions; Alembic `0001_initial`; tenant isolation tests.

**API:** `/api/v1/accounts`, `/api/v1/fiscal`

**Architectural significance:** Establishes the dimensional and fiscal spine every later financial feature depends on. Without open periods, active accounts, and tenant configuration, posting cannot be safe.

## M.2 Phase 5.2 — Double Entry & Posting Engine (v0.5.2.0)

**Delivered:** Voucher, VoucherLine, Journal, JournalEntry; **PostingEngine** as sole creator of journal entries (ADR-010); validation for balanced entries, active accounts, open period; lifecycle Draft → Validated → Posted → Cancelled/Reversed; PostingLog/Error/Reference; AccountingAuditLog; APIs for validate/post/reverse/cancel/audit; permissions `accounting.post`, `accounting.validate`, `accounting.reverse`, etc.; events including `voucher.posted`, `posting.completed`, `journal_entry.created`.

**Architectural significance:** This is the compliance and integrity choke point for the entire SuperApp money path. Every future Restaurant/Ecommerce settlement must aim here, not invent ledgers.

## M.3 Phase 5.3 — General Ledger & Fiscal Management

*(Summarized from phase area completion and FE ledger capabilities.)* Progress and FE architecture show ledger balances, trial balance, and recalculate against real `/api/v1/ledger/*`. Fiscal lock events appear in the event catalog (`fiscal_period.locked`, `trial_balance.generated`, `ledger.updated`).

**Architectural significance:** Turns posted vouchers into queryable financial truth for reports and period close.

## M.4 Phase 5.4 — Treasury Management

FE scoreboard: Treasury 90% Complete — cash boxes, banks, bank accounts, cash receipts. Registry events include `cash.received`. Permissions include `treasury.*`.

**Architectural significance:** Bridges operational cash movement to posting; payment gateway later should settle into treasury/accounting flows rather than bypass them.

## M.5 Phase 5.5 — Accounts Receivable & Payable

FE: Customers/AR 92%, Suppliers/AP 85%. Events include `settlement.completed`. Permission prefixes `receivable.*`, `payable.*`.

**Architectural significance:** Customer/supplier subledgers become integration points for CRM and commerce later—prefer references + events over duplicating party masters carelessly.

## M.6 Phase 5.6 — Sales Accounting Integration

Events: `sales_invoice.posted`, `revenue.recognized`. Permission prefix `sales_accounting.*`.

**Architectural significance:** Pattern for “operational document → accounting posting intent → Posting Engine.” Ecommerce/Restaurant should copy this pattern.

## M.7 Phase 5.7 — Purchase & Inventory Accounting Integration

Progress: InventoryValuationEngine delivered with migration `0002_phases_57_511` covering 5.7–5.11.

**Architectural significance:** Inventory valuation is a classic cross-module hazard; ownership stays in Accounting for valuation postings even if stock quantities later live in another service.

## M.8 Phase 5.8 — Fixed Assets Management

FE Assets 90%: categories, activate, depreciate, schedule. DepreciationEngine noted in progress.

## M.9 Phase 5.9 — HCM & Payroll Accounting

FE Payroll 88%: departments, periods, calculate, post. PayrollEngine noted in progress.

**Architectural significance:** Payroll is compliance-sensitive; AI must not become posting authority here.

## M.10 Phase 5.10 — Financial Reporting & BI (v0.5.10.0)

**Delivered:** FinancialReport, ReportTemplate, Dashboard/Widget, KPI, ReportSnapshot, ScheduledReport, ReportExport, ReportHistory, ReportConfiguration; **FinancialReportEngine** for trial balance, balance sheet, income statement from posted data; export framework PDF/Excel/CSV/JSON; API `/api/v1/reporting`; permissions `reports.*`, `dashboard.*`, `financial_statements.view`; events `financial_report.generated`, `balance_sheet.generated`, `report.exported`.

**Remaining (progress):** optional richer PDF export file delivery from storage — depends on File Storage maturity.

## M.11 Phase 5.11 — Enterprise Compliance, Audit & Governance (v0.5.11.0)

**Delivered:** immutable AuditRecord/History; CompliancePolicy; GovernanceRule; ApprovalWorkflow/Step/Request; Delegation; RiskRecord; PolicyViolation; Evidence; RetentionPolicy; ControlDefinition; **AuditFramework**, **ComplianceEngine**, **GovernanceService** (approvals, SoD, risk); API `/api/v1/compliance`; permissions `audit.*`, `compliance.*`, `governance.*`, `approval.execute`, `risk.*`; events `audit_record.created`, `approval.completed`, `policy_violation.detected`.

**Conflict note:** `compliance-architecture.md` still has a subsection titled “Accounting Compliance (future)” listing double-entry integrity and dimensions as future — but 5.2/5.11 phase docs mark substantial compliance machinery **Complete**. Prefer phase/progress for implementation status; treat the architecture subsection as needing wording refresh (tax connectors remain future).

## M.12 Phase 5.12 — AI Native Accounting (planned / blocked)

Blocked until AI Model Provider is Active in provider registry. AI architecture forbids AI as sole authority for money/compliance/authorization. FE scoreboard AI = 0% Blocked.

---

# Appendix N — Twenty Project Principles (operational translation)

| # | Principle | Architecture implication |
| --- | --- | --- |
| 1 | Tenant-aware everything | Middleware + repository filters + FE `X-Tenant-ID` |
| 2 | Auditable business actions | Core audit_logs + module audit/events |
| 3 | Logic in Services | Thin routers |
| 4 | Repositories persistence-only | No hidden workflows in ORM layer |
| 5 | Thin API handlers | Validate → authorize → service → map |
| 6 | Tests per phase | pytest per service; tenant denial cases |
| 7 | Docs per phase | registries/contracts/progress |
| 8 | No TODO in completed phases | TODOs reopen the phase |
| 9 | No cross-tenant query | Logged platform_admin exceptions only |
| 10 | No direct JournalEntry | ADR-010 |
| 11 | Compliance independent | Controls survive UI redesign |
| 12 | AI independent | Product works with AI off |
| 13 | Event-ready | Outbox-backed effects |
| 14 | API-first | UI is a client |
| 15 | Everything documented | ADRs/registries current |
| 16 | Database-per-service | ADR-001 |
| 17 | Absolute FE/BE split | ADR-002 |
| 18 | No hardcoded brand/secrets | env/config/DB |
| 19 | Docs before conflicting code | stop-the-line |
| 20 | Phase completion gate | docs README checklist |

---

# Appendix O — Frontend Platform Standards (for all future modules)

Derived from `docs/frontend/*` index hard rules and architecture.

## O.1 Hard Rules

1. Never mock accounting (or, by extension, other module) business data in enterprise screens.
2. Never bypass the owning service API.
3. Always send JWT + `X-Tenant-ID`.
4. Journal entries only via Posting Engine UI actions.
5. Reuse Design System — do not redesign per page.

## O.2 Documented FE knowledge areas

Design system (tokens, typography, themes, RTL), component library, layout/shell, page patterns (dashboard/list/form/report), RHF+Zod forms, tables, dialogs, theme/white-label, navigation maps, responsive breakpoints, API integration, TanStack Query state, performance splitting, WCAG AA baseline, testing quality gates.

## O.3 Implication for Restaurant/CRM UIs

New verticals should open as SuperApp module routes with DS components, Query providers, and entitlement-aware nav—not new Next apps—unless an ADR supersedes ADR-002’s deployment model.

---

# Appendix P — Production & SSL Operations Digest

## P.1 Hosts & public routing

| Host | Upstream |
| --- | --- |
| `torbatyar.ir` / `www` / `*.torbatyar.ir` | Frontend `:3000` |
| `api.torbatyar.ir` | Core `:8000` |
| `identity.torbatyar.ir` | Identity `:8001` |
| `auth.torbatyar.ir` | Keycloak `:8080` |
| `accounting.torbatyar.ir` | Accounting `:8002` |

App host `192.168.10.162`; Nginx edge `192.168.10.156`.

## P.2 Deploy shape

1. Pull release on app host  
2. `docker compose up -d --build`  
3. Alembic per service (document stamp vs upgrade precisely in release notes)  
4. Reload Nginx if routing changed  
5. Smoke: `/health`, login, tenant subdomain  

Critical env groups: `PLATFORM_*`, `NEXT_PUBLIC_*`, DB URLs, `KEYCLOAK_*`, `AUTH_REQUIRED`, Payamak/OTP, `PLATFORM_ADMIN_MOBILES`, `SSL_PROVISION_*`.

## P.3 TLS

Edge terminates TLS with LE material under `/etc/letsencrypt/live/torbatyar.ir/`. Platform hosts force HTTPS; ACME on port 80. Tenant subdomain SSL via Celery SSH → `provision_ssl.py` when `SSL_PROVISION_ENABLED=true`; readiness map `torbatyar-tenant-ssl.map`. Custom domains may remain `pending` until DNS verification ships.

## P.4 Backup & DR posture

Daily `pg_dump` of service DBs; retain 7 daily / 4 weekly / 3 monthly (suggested); restore drills; protect secrets, certs, nginx maps; future object storage buckets.

## P.5 Monitoring minimum

Health endpoints; Docker/Nginx/Celery logs; alerts for restart loops, DB/Redis down, cert expiry < 14 days, OTP error spikes, outbox failed growth.

---

# Appendix Q — Identity & Authorization Worked Examples

## Q.1 Staff login path

Frontend `/login` → Keycloak themed login (password or mobile OTP via Identity handoff) → `/auth/callback` → JWT in FE → Core `/me` / tenant context → module APIs with Bearer + tenant header.

## Q.2 OTP path

Core OTP request/verify via Payamak → HS256 JWT → `UserService.resolve_current` maps to `users.id`. Identity delegates SMS to Core OTP client (no duplicate SMS logic).

## Q.3 JIT path

Keycloak JWT → resolve/link via `users.keycloak_sub` (implemented; older contracts saying 403/deferred are stale).

## Q.4 Authorization decision table

| Check | Pass condition |
| --- | --- |
| Authentication | Valid JWT (Keycloak or OTP) |
| Workspace role | Core membership role sufficient for action |
| Entitlement | Plan/feature/custom override allows feature key |
| Tenant scope | Resolved tenant matches resource tenant |
| Posting | Accounting permissions + open period + balanced voucher |

## Q.5 Dual membership caution

Identity `tenant_admin`/`tenant_member` listing roles are **not** operational authz. UI and services must not authorize workspace mutations from Identity membership alone.

---

# Appendix R — Eventing Blueprint for Future Modules

## R.1 Envelope fields

`event_id`, `event_type`, `aggregate_type`, `aggregate_id`, `tenant_id`, `source_service`, `payload`, `occurred_at`.

## R.2 Producer checklist

1. Write business change + outbox row atomically  
2. Name event `{aggregate}.{past_tense}`  
3. Update event catalog + module registry producers  
4. Do not require synchronous cross-DB commit  

## R.3 Consumer checklist

1. Inbox insert by `event_id` (idempotent)  
2. Handle payload in service layer  
3. Emit follow-up events if needed  
4. Never call foreign DB  

## R.4 Suggested future event families (reserved in catalog)

| Module | Examples |
| --- | --- |
| CRM | `lead.created`, `opportunity.won` |
| Restaurant | `order.placed`, `order.completed` |
| Ecommerce | `order.placed`, `product.updated` |
| Notification | `notification.delivered` |

---

# Appendix S — Capability Matrix (Implemented vs Designed)

| Capability | Implemented | Scaffold/Planned | Depends on |
| --- | --- | --- | --- |
| Multi-tenant workspaces | Yes | | Core |
| SSO staff login | Yes | | Keycloak/Identity |
| OTP mobile login | Yes | | Payamak |
| Onboarding wizard | Yes | | Core/FE |
| Subdomain SSL auto | Yes | | Celery/Nginx/LE |
| Entitlement engine | Yes | | Redis/Core |
| Accounting full 5.1–5.11 | Yes | 5.12 AI | Core |
| Accounting FE enterprise | Mostly | AI UI | Accounting API |
| White-label polish | Partial | Complete runtime | Public site |
| Custom domain verify | | Yes | DNS |
| Payment | | Yes | PSP |
| Notification hub | | Yes | Bus helpful |
| File storage | | Yes | S3 |
| CRM | | Yes | Core/Notify |
| Restaurant | | Yes | White-label/Pay |
| Ecommerce | | Yes | File/Pay |
| Marketplace | | Yes | Ecommerce+ |
| Live chat / AI / Messenger | | Yes | Providers |
| Automation | | Yes | Bus |
| Message bus | | Yes | Infra |

---

# Appendix T — Target Operating Model for Enterprise SaaS

## T.1 Team boundaries (recommended)

| Team | Owns |
| --- | --- |
| Platform | Core, Identity edge contracts, entitlement, tenancy, edge SSL |
| FinTech/Accounting | Accounting service + posting contracts |
| Experience | SuperApp FE shells, DS, white-label |
| Growth verticals | Restaurant/CRM/Ecommerce module delivery |
| Ops | Compose, Nginx, backups, certs, alerts |

## T.2 Change control

1. Architecture/ADR update if boundaries change  
2. Registry + contracts + events  
3. Implementation + tests  
4. Progress/scoreboard  

## T.3 Definition of Ready for a new module

- Phase README created  
- DB name reserved  
- Feature key prefix reserved  
- Entitlement plan flags designed  
- Dependencies (file/notify/pay) explicit  
- FE route namespace reserved  

## T.4 Definition of Done

Aligns with principles 6–8, 15, 20: tests, docs, no TODO, registries updated, progress checked.

---

# Appendix U — Scale Bottleneck Catalog (detailed)

## U.1 Application layer

| Bottleneck | 100 | 1k | 10k |
| --- | --- | --- | --- |
| API single-node | OK | Need replicas | Mandatory HA |
| Keycloak | OK | Size up | Cluster |
| Accounting report CPU | Watch | Isolate workers | Dedicated read models |
| FE SSR/hosting | OK | CDN/cache | Multi-node |

## U.2 Data layer

| Bottleneck | 100 | 1k | 10k |
| --- | --- | --- | --- |
| Shared tenant rows | OK | Indexes/partition | Partition + large-tenant strategy |
| Backup windows | OK | Parallel dumps | Continuous/PITR |
| Cross-service sync lag | Low | Visible | Needs bus SLOs |

## U.3 Edge / certs

| Bottleneck | 100 | 1k | 10k |
| --- | --- | --- | --- |
| LE SAN expansion | Manageable | Rate-limit risk | Different cert strategy likely |
| Nginx fanout | OK | Tune | Scale edge |

## U.4 Async

| Bottleneck | 100 | 1k | 10k |
| --- | --- | --- | --- |
| Celery outbox poll | OK | Tune concurrency | Bus + partitioned consumers |
| Notification fanout without hub | Painful | Severe | Impossible cleanly |

---

# Appendix V — Prioritized Platform Backlog (architecture view)

### P0

1. Production verify Accounting host routing (`accounting.torbatyar.ir`)  
2. White-label completion  
3. Doc conflict cleanup  
4. Tenant isolation regression suite expansion  

### P1

1. File Storage + S3 Active  
2. Notification MVP  
3. Payment provider  
4. Message bus  
5. Custom domain verify  
6. Membership sync  
7. Invites/RBAC  

### P2

1. Restaurant foundation  
2. CRM foundation  
3. AI provider + 5.12  
4. Website builder  
5. SMS panel campaigns  

### P3

1. Ecommerce  
2. Chat/Messenger  
3. Automation  
4. Marketplace  
5. Wallet / Gym packs / scheduling kernel  

---

# Appendix W — Conflict Log (full)

| ID | Conflict | Resolution used here |
| --- | --- | --- |
| X1 | DB architecture lists Accounting future | Accounting Active 5.11 |
| X2 | Compliance architecture “future” subsection vs 5.11 complete | Implementation complete; tax connectors still future |
| X3 | Product decision first module Restaurant vs Accounting shipped | Accounting is first deep vertical; Restaurant next GTM candidate |
| X4 | next-steps AI/prod vs roadmap near-term Restaurant/white-label | Both valid: next-steps = immediate; roadmap = near; do Wave 0 then white-label/Restaurant |
| X5 | current-architecture-review (Jul 22) pre-Accounting depth | Historical for doc drift; not status SoT |
| X6 | Phase 3 naming external vs internal | Internal numbering wins |
| X7 | Older JIT deferred claims | JIT done |
| X8 | Older nginx later claims | Nginx/TLS done |
| X9 | services placeholder-only claims | Identity + Accounting real |
| X10 | Event catalog “Accounting 5.1–5.6” heading while 5.7–5.11 exist | Catalog needs extension note; registry lists additional events |

---

# Appendix X — Recommendation Narratives

## X.1 Why shared services before more verticals

Accounting already shows how deep a vertical can become. If Restaurant and CRM each implement uploads, SMS, and payments independently, the platform becomes a federation of accidental monoliths. Notification, File Storage, and Payment are force-multipliers: one hardening effort benefits all modules.

## X.2 Why message bus before Automation

Automation without a durable fanout fabric will either poll databases unsafely or couple modules via brittle synchronous chains. ADR-006 already anticipates swapping publish transport without rewriting producers—use that escape hatch before building workflow product UX.

## X.3 Why Restaurant still matters after Accounting

Accounting monetizes and operationalizes finance-heavy tenants. Restaurant/digital menu monetizes SMB hospitality on white-label domains—the original product wedge in the Proposed decision. They are complementary, not mutually exclusive; sequencing should still respect white-label and payment prerequisites.

## X.4 Why AI is last among Accounting phases

Principle 12 and AI architecture require business continuity without AI. Shipping 5.12 before provider governance risks putting probabilistic systems near money. Keep AI advisory with human/approval gates (especially given 5.11 SoD tooling).

---

# Appendix Y — Scorecard Narrative Detail

### Architecture (8/10)

Strength from ADRs and boundaries; deducted for stale labels and incomplete horizontal architecture realization.

### Modularity (8/10)

Physical module boundaries exist; many modules are empty shells—modularity of *design* exceeds modularity of *delivery*.

### Scalability (5/10)

Appropriate early VPS SaaS; insufficient evidence/plan execution for 10k tenants.

### Maintainability (7/10)

Docs+tests culture strong; dual membership and sprawl risk weigh down.

### Security (7/10)

Solid authn/TLS/tenant rules; enterprise RBAC/domain verify incomplete.

### Backend (8/10)

Three real services with clear layering and workers.

### Frontend (7/10)

Strong Accounting module patterns and DS; white-label and multi-module nav still maturing.

### Database (7/10)

Good rules and Accounting migrations; scale playbook thin; doc drift.

### API (7/10)

Versioned and tenant-aware; ecosystem consistency still forming.

### Testing (6/10)

Strategy excellent; breadth beyond cited suites not fully evidenced in status docs.

### Documentation (8/10)

Phase D success; conflicts remain.

### Developer Experience (7/10)

Templates/registries help; stubs and dual clients confuse.

### Infrastructure (6/10)

Real edge/app split; observability/CI depth limited in docs.

### Enterprise SaaS Readiness (6/10)

Credible mid-market start; not yet a diversified SuperApp at enterprise scale.

---

# Appendix Z — Master Checklist Recap (printable)

**Immediate**

- [ ] Accounting prod smoke on `accounting.torbatyar.ir`  
- [ ] White-label gaps closed  
- [ ] Stale docs reconciled  
- [ ] AI provider go/no-go recorded  

**Next**

- [ ] File Storage Active  
- [ ] Notification MVP  
- [ ] Payment Active  
- [ ] Bus introduced  
- [ ] Domain verify  
- [ ] Membership sync  
- [ ] Invites/RBAC  

**Later**

- [ ] Restaurant  
- [ ] CRM/Club  
- [ ] Builders  
- [ ] Chat/AI/Messenger  
- [ ] Automation  
- [ ] Marketplace  
- [ ] Wallet/Gym/scheduling  

---

# Appendix AA — Long-form Executive Briefing (for leadership)

TorbatYar set out to build a multi-tenant SuperApp that can host many business systems behind one identity and one entitlement plane. The organization has substantially delivered the **platform kernel** (Core, Identity, Keycloak, Nginx TLS, tenant SSL automation, onboarding) and has gone unusually deep on **Accounting** as a first enterprise vertical—including posting integrity, treasury, AR/AP, inventory accounting, assets, payroll accounting, reporting, and governance/SoD.

That combination is rare for early-stage platforms and should be treated as a strategic asset: the company can sell credible financial operations while the SuperApp shell continues to expand. However, leadership should not interpret Accounting depth as proof that the platform can absorb unlimited new verticals immediately. The missing middle—files, notifications, payments, and a real event bus—determines whether the next modules will compound or fragment.

Commercially, two motions can coexist:

1. **Finance-led motion:** land tenants needing accounting/compliance depth.  
2. **Hospitality-led motion:** land cafes/restaurants on white-label digital menus once public-site polish and payments exist.

Technically, the non-negotiables remain tenant isolation, posting-engine exclusivity for money, API-first boundaries, and documentation-before-code when architecture shifts. Scaling from dozens to thousands of tenants is primarily an infrastructure and shared-services program. Scaling from one vertical to many is primarily a sequencing discipline.

This master report recommends Wave 0 hardening now, Wave 1 shared platforms next, then Restaurant/CRM, then builders and conversational systems, with Marketplace and Automation last among the major bets.

---

# Appendix AB — Interface Contracts Overview (planning level)

| Consumer | Provider | Contract theme |
| --- | --- | --- |
| FE | Core | `/api/v1` tenants, onboarding, me/context, entitlement check, public tenant-site |
| FE | Identity | `/api/v1/auth` OIDC/mobile |
| FE | Accounting | `/api/v1/*` foundation→compliance |
| FE | Keycloak | OIDC browser flows |
| Identity | Core | OTP client |
| Accounting | Core | entitlement / tenant authenticity assumptions |
| Celery | Core domain | outbox publish, SSL provision |
| Future Notification | many | consume domain events |
| Future modules | Accounting | posting intents / settlement events |

Detailed endpoint tables remain in `docs/reference/services-contracts.md` and `api-reference.md` (not duplicated exhaustively here to avoid a third competing contract source).

---

# Appendix AC — Data Ownership Map

| Data class | Owner DB |
| --- | --- |
| Tenant, plan, subscription, operational membership | `core_platform_db` |
| Identity profile, SSO membership listing | `identity_access_db` |
| COA, vouchers, journals, GL, treasury, AR/AP, assets, payroll acct, reports, compliance records | `accounting_db` |
| CRM entities | `crm_db` (future) |
| Restaurant menu/orders | `restaurant_db` (future) |
| Store catalog/cart | `ecommerce_db` (future) |
| Site pages/blocks | `website_builder_db` (future) |
| Chat transcripts | `live_chat_db` (future) |
| AI KB/sessions | `ai_assistant_db` (future) |
| Notifications | `notification_db` (future) |
| Files metadata | `file_storage_db` (future) |

---

# Appendix AD — Security Control Baseline

| Control | Mechanism |
| --- | --- |
| Authn staff | Keycloak OIDC |
| Authn OTP | Payamak + Core JWT |
| Authz role | Core memberships |
| Authz feature | Entitlement service |
| Transport | TLS at edge |
| Secrets | env / vault, not git |
| Audit | Core audit_logs + accounting audit framework |
| Tenant isolation | tenant_id filters + tests |
| Service auth | hashed internal tokens + scopes |
| Money integrity | Posting Engine only |
| AI limitation | non-authority rule |

---

# Appendix AE — Open Questions (explicit UNKNOWN / pending decisions)

These items are **not answered conclusively** in the synthesized docs and should be decided deliberately:

1. Final Iranian PSP selection for Payment Gateway  
2. Final AI model vendor(s)  
3. Whether Customer Club is a CRM submodule, Restaurant loyalty, or standalone service  
4. Whether Appointment/Gym share a scheduling kernel early or duplicate per vertical  
5. When to extract Subscription/Entitlement from Core  
6. Exact production Alembic procedure standardization (upgrade vs stamp discipline)  
7. CI pipeline topology (documented strategies exist; full pipeline inventory not treated as complete in older review)  
8. Whether Accounting public hostname is fully live in all environments (next-steps still asks for deploy verification)  

---

*End of expanded appendices — Master Architecture Report v1.0*

---

# Appendix AF — Accounting Phases 5.3–5.9 Detailed Deliverables

> Source: individual phase markdown files under `docs/phases/Accounting/`.  
> Note: Phase 5.6 “Related” still links 5.7 as “(planned)” while 5.7 file Status is Complete — another small doc conflict; prefer Status fields.

## AF.1 Phase 5.3 — General Ledger & Fiscal Management

**Delivered entities/services:** GeneralLedger, LedgerBalance, TrialBalanceSnapshot, BalanceSnapshot, OpeningEntry, ClosingEntry, AccountingCalendar; **BalanceEngine** (running balances, trial balance, recalculation); **FiscalManagementService** (lock/close/reopen periods, year closing).

**API:** Ledger balances, trial balance, recalculate.

**Permissions:** `accounting.ledger.*`, `accounting.fiscal.*`, `accounting.trial_balance.view`

**Events:** `trial_balance.generated`, `ledger.updated`, `fiscal_period.locked`, etc.

**Enterprise note:** Period lock is a control boundary; Automation/AI must never reopen periods without governance approvals (5.11 tooling).

## AF.2 Phase 5.4 — Treasury Management

**Delivered:** CashBox, CashTransaction, Bank, BankAccount, BankTransaction, Cheque, ChequeBook, Transfer, ReceiptVoucher, PaymentVoucher, reconciliation framework, TreasurySettings; **TreasuryService** — cash receipt/payment **via Posting Engine only**.

**Permissions:** `treasury.*`

**Events:** `cash.received`, `bank_deposit.created`, `cheque.issued`, etc.

**Enterprise note:** Future Payment Gateway settlements should land as treasury/accounting postings, not orphaned PSP ledgers.

## AF.3 Phase 5.5 — Accounts Receivable & Payable

**Delivered:** CustomerAccount, SupplierAccount, ReceivableInvoice, PayableInvoice, Settlement, SettlementAllocation, CreditNote, DebitNote, AdvancePayment, AdvanceReceipt, CustomerStatement, SupplierStatement, AgingSnapshot; **SettlementEngine**; **AgingEngine**.

**Permissions:** `receivable.*`, `payable.*`, `settlement.manage`

**Events:** `customer_invoice.created`, `settlement.completed`, etc.

**Enterprise note:** CRM should reference accounting party accounts carefully—prefer correlation IDs/events over dual-write of balances.

## AF.4 Phase 5.6 — Sales Accounting Integration

**Delivered:** SalesPostingProfile, AccountingProfile, PostingRule, SalesAccountingConfiguration, RevenueRecognition, RevenueSchedule, AccountingPreview, PostingSimulation; **SalesAccountingService** preview + post via Posting Engine; configurable posting profiles per document type.

**Permissions:** `sales_accounting.*`

**Events:** `sales_invoice.posted`, `revenue.recognized`, `posting_rule.executed`, etc.

**Pattern to copy:** operational document → preview → post via engine.

## AF.5 Phase 5.7 — Purchase & Inventory Accounting

**Delivered:** PurchasePostingProfile, InventoryPostingProfile, InventoryValuationMethodConfig, InventoryValuationHistory, InventoryCostAdjustment, InventorySnapshot; **InventoryValuationEngine** (FIFO, weighted/moving average); **PurchaseInventoryAccountingService** goods receipt via Posting Engine.

**API:** `/api/v1/purchase-inventory`

**Permissions:** `purchase_accounting.*`, `inventory_accounting.*`

**Events:** `goods.received`, `inventory.adjusted`, `purchase_accounting.completed`

## AF.6 Phase 5.8 — Fixed Assets

**Delivered:** Asset register, categories, groups, locations; AssetDepreciation, DepreciationSchedule; AssetTransfer, Disposal, Revaluation, Impairment; AssetAccountingProfile, AssetHistory; **DepreciationEngine** (straight line, declining balance, double declining); **AssetAccountingService** activate/depreciate via Posting Engine.

**API:** `/api/v1/assets` · Permissions `assets.*` · Events `asset.depreciated`, `depreciation.calculated`, etc.

## AF.7 Phase 5.9 — HCM & Payroll Accounting

**Delivered:** Employee, Department, Position, EmploymentContract; PayrollPeriod, Payroll, PayrollItem, SalaryComponent; Benefit, Allowance, Deduction, EmployeeLoan, EmployeeAdvance; PayrollAccountingProfile, PayrollHistory, PayrollSettlement; **PayrollEngine**; **PayrollAccountingService** posting via Posting Engine.

**API:** `/api/v1/payroll` · Permissions `hr.*`, `payroll.*` · Events `payroll.calculated`, `payroll.posted`, `payroll_accounting.completed`

**Boundary caution:** This is accounting-oriented HCM, not necessarily a full HRIS product. A future standalone HR module should integrate rather than fork payroll journals.


---

# Appendix AG — Architecture Decision Records (digest)

## AG.1 ADR-001 Database-per-Service

**Decision:** Every service owns exactly one database; cross-service access only via REST/Webhook/Async Event/Outbox-Inbox.

**Why it matters:** Prevents schema coupling as SuperApp grows.

**Tradeoff:** No cross-DB joins; eventual consistency required.

## AG.2 ADR-002 Strict FE/BE Separation

**Decision:** Backend only under `backend/`, Frontend only under `frontend/`; communication via versioned APIs.

**Why:** Independent deploy/scale; multiple UIs possible.

## AG.3 ADR-003 Row-Level Multi-Tenancy

**Decision:** Shared DB per service with mandatory `tenant_id`; resolution order headers→host→current tenant.

**Tradeoff:** Noise-neighbor risk at extreme scale.

## AG.4 ADR-004 Central SSO Keycloak

**Decision:** Keycloak central login for platform/tenant staff; Identity is BFF; end-customer auth may be local to module DB.

## AG.5 ADR-005 Mandatory Mobile + OTP

**Decision:** Mobile required and OTP-verified (Payamak).

## AG.6 ADR-006 Outbox/Inbox

**Decision:** Business + outbox same transaction; inbox idempotency by event_id; envelope standardized.

**Future:** Swap to real bus without rewriting producers.

## AG.7 ADR-007 Dual Membership Tables

**Decision:** Core memberships = operational SoT; Identity memberships = SSO listing.

**Risk:** Naming collision and divergence—must stay explicit in docs/tests.

## AG.8 ADR-008 White-Label via Config/Profile

**Decision:** Platform defaults from env/theme config; tenant brand fields on tenants; FE CSS variables; public host theme resolution.

## AG.9 ADR-009 Nginx + Auto Tenant SSL

**Decision:** Nginx TLS edge; LE expand via Celery SSH `provision_ssl.py`; SSL readiness map.

## AG.10 ADR-010 Posting Engine Ownership

**Decision:** No service/UI creates JournalEntry directly; all financial postings through Accounting Posting Engine.

**Consequence:** Modules wait on Accounting contracts for money write-paths.


---

# Appendix AH — Future Capability Placement Matrix (mission list)

| Capability | Architectural placement | Status in docs | Purpose | Dependencies | Expansion |
| --- | --- | --- | --- | --- | --- |
| Restaurant Management | Business Module (`restaurant`) | Scaffolded | Digital menu, tables, orders, kitchen, loyalty | White-label host, Core entitlement, Payment (for paid orders), optional Accounting posting events | High after Wave 0–1 |
| Cafe Management | Same module family as Restaurant | Scaffolded | Cafe operations subset of restaurant | Same as Restaurant | High |
| Digital Menu | Restaurant public surface | Scaffolded | Guest menu on tenant domain; optional local guest auth | White-label public site | High |
| CRM | Business Module (`crm`) | Scaffolded | Customers, leads, opportunities, pipelines, tasks | Core entitlement; Notification; optional AI/Messenger | High |
| Customer Club | Product capability on CRM/Restaurant (not Active registry module) | Not a dedicated Active module | Loyalty segments, points, tiers — design choice open | CRM and/or Restaurant + Notification + Wallet/Payment later | Medium until ownership decided |
| SMS Platform | Shared (`sms_panel`) + Core OTP path | Panel Scaffolded; OTP Active | Campaign SMS vs auth OTP separation | Providers (Payamak+); keep OTP separate | Medium |
| Wallet | Shared platform (future) | Not Active in registry | Stored value/credits | Payment + strong ledger discipline; possibly Accounting correlation | Later (P3) |
| Payment | Shared provider + adapters | Planned provider | Checkout, refunds, webhooks for subscriptions/commerce | PSP selection; Core subscriptions; Restaurant/Ecommerce | P1 |
| Store Builder | Business (`ecommerce`) | Scaffolded | Catalog, cart, orders, shipments | File Storage, Payment, Core | After Wave 1 |
| Website Builder | Business (`website_builder`) | Scaffolded | Sites, pages, blocks, forms, menus, media | File Storage/S3 | After File Storage |
| Landing Builder | Capability of Website Builder | Scaffolded (via website_builder) | Marketing landers on tenant hosts | White-label + File Storage | With Website Builder |
| ERP | Program of modules led by Accounting | Accounting Active; broader ERP partial | Finance spine exists; supply chain/HRIS/manufacturing not claimed complete as ERP suite | Accounting + future inventory ops modules | Finance-ready; full ERP long-term |
| Gym | Future vertical (not registry Active) | UNKNOWN / Future | Memberships, classes, check-in — not specified in module registry | Prefer shared Appointment/Reservation kernel if multiple verticals | P3+ |
| AI Assistant | Shared/Business (`ai_assistant`) | Scaffolded; provider Planned | Chat, KB, handoff; never money/compliance authority | AI provider Active; entitlement | After provider |
| Automation | Shared platform | Planned | Cross-module workflow triggers/actions | Real message bus | After bus |
| Workflow | Same family as Automation | Planned | Human+system workflow orchestration | Bus + governance/approvals patterns from Accounting 5.11 | After bus |
| Chat | Business (`live_chat`) | Scaffolded | Embeddable widget, routing | Core; optional CRM/AI | Wave 4 |
| Appointment | Future capability | Not Active registry module | Booking slots | Scheduling kernel decision pending | P3 |
| Reservation | Restaurant-adjacent + generic booking | Not Active standalone | Tables/rooms/resources | Restaurant module and/or shared kernel | With Restaurant / later kernel |
| Marketplace | Business (`marketplace`) | Planned | Multi-vendor market | Ecommerce, Identity, Payment, Accounting settlement events | Wave 5 |


---

# Appendix AI — Capability Narratives (planning depth)
## AI-x — Restaurant Management

**Placement:** Business Module (`restaurant`)  
**Status:** Scaffolded  
**Purpose:** Digital menu, tables, orders, kitchen, loyalty  
**Dependencies:** White-label host, Core entitlement, Payment (for paid orders), optional Accounting posting events  
**Expansion capability:** High after Wave 0–1

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Cafe Management

**Placement:** Same module family as Restaurant  
**Status:** Scaffolded  
**Purpose:** Cafe operations subset of restaurant  
**Dependencies:** Same as Restaurant  
**Expansion capability:** High

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Digital Menu

**Placement:** Restaurant public surface  
**Status:** Scaffolded  
**Purpose:** Guest menu on tenant domain; optional local guest auth  
**Dependencies:** White-label public site  
**Expansion capability:** High

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — CRM

**Placement:** Business Module (`crm`)  
**Status:** Scaffolded  
**Purpose:** Customers, leads, opportunities, pipelines, tasks  
**Dependencies:** Core entitlement; Notification; optional AI/Messenger  
**Expansion capability:** High

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Customer Club

**Placement:** Product capability on CRM/Restaurant (not Active registry module)  
**Status:** Not a dedicated Active module  
**Purpose:** Loyalty segments, points, tiers — design choice open  
**Dependencies:** CRM and/or Restaurant + Notification + Wallet/Payment later  
**Expansion capability:** Medium until ownership decided

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — SMS Platform

**Placement:** Shared (`sms_panel`) + Core OTP path  
**Status:** Panel Scaffolded; OTP Active  
**Purpose:** Campaign SMS vs auth OTP separation  
**Dependencies:** Providers (Payamak+); keep OTP separate  
**Expansion capability:** Medium

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Wallet

**Placement:** Shared platform (future)  
**Status:** Not Active in registry  
**Purpose:** Stored value/credits  
**Dependencies:** Payment + strong ledger discipline; possibly Accounting correlation  
**Expansion capability:** Later (P3)

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Payment

**Placement:** Shared provider + adapters  
**Status:** Planned provider  
**Purpose:** Checkout, refunds, webhooks for subscriptions/commerce  
**Dependencies:** PSP selection; Core subscriptions; Restaurant/Ecommerce  
**Expansion capability:** P1

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Store Builder

**Placement:** Business (`ecommerce`)  
**Status:** Scaffolded  
**Purpose:** Catalog, cart, orders, shipments  
**Dependencies:** File Storage, Payment, Core  
**Expansion capability:** After Wave 1

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Website Builder

**Placement:** Business (`website_builder`)  
**Status:** Scaffolded  
**Purpose:** Sites, pages, blocks, forms, menus, media  
**Dependencies:** File Storage/S3  
**Expansion capability:** After File Storage

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Landing Builder

**Placement:** Capability of Website Builder  
**Status:** Scaffolded (via website_builder)  
**Purpose:** Marketing landers on tenant hosts  
**Dependencies:** White-label + File Storage  
**Expansion capability:** With Website Builder

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — ERP

**Placement:** Program of modules led by Accounting  
**Status:** Accounting Active; broader ERP partial  
**Purpose:** Finance spine exists; supply chain/HRIS/manufacturing not claimed complete as ERP suite  
**Dependencies:** Accounting + future inventory ops modules  
**Expansion capability:** Finance-ready; full ERP long-term

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Gym

**Placement:** Future vertical (not registry Active)  
**Status:** UNKNOWN / Future  
**Purpose:** Memberships, classes, check-in — not specified in module registry  
**Dependencies:** Prefer shared Appointment/Reservation kernel if multiple verticals  
**Expansion capability:** P3+

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — AI Assistant

**Placement:** Shared/Business (`ai_assistant`)  
**Status:** Scaffolded; provider Planned  
**Purpose:** Chat, KB, handoff; never money/compliance authority  
**Dependencies:** AI provider Active; entitlement  
**Expansion capability:** After provider

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Automation

**Placement:** Shared platform  
**Status:** Planned  
**Purpose:** Cross-module workflow triggers/actions  
**Dependencies:** Real message bus  
**Expansion capability:** After bus

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Workflow

**Placement:** Same family as Automation  
**Status:** Planned  
**Purpose:** Human+system workflow orchestration  
**Dependencies:** Bus + governance/approvals patterns from Accounting 5.11  
**Expansion capability:** After bus

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Chat

**Placement:** Business (`live_chat`)  
**Status:** Scaffolded  
**Purpose:** Embeddable widget, routing  
**Dependencies:** Core; optional CRM/AI  
**Expansion capability:** Wave 4

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Appointment

**Placement:** Future capability  
**Status:** Not Active registry module  
**Purpose:** Booking slots  
**Dependencies:** Scheduling kernel decision pending  
**Expansion capability:** P3

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Reservation

**Placement:** Restaurant-adjacent + generic booking  
**Status:** Not Active standalone  
**Purpose:** Tables/rooms/resources  
**Dependencies:** Restaurant module and/or shared kernel  
**Expansion capability:** With Restaurant / later kernel

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.

## AI-x — Marketplace

**Placement:** Business (`marketplace`)  
**Status:** Planned  
**Purpose:** Multi-vendor market  
**Dependencies:** Ecommerce, Identity, Payment, Accounting settlement events  
**Expansion capability:** Wave 5

**Architectural guidance:** Keep tenant isolation, entitlement gates, and API/event integration. If the capability touches money, route financial effects through Accounting Posting Engine contracts. If it sends messages, prefer Notification/SMS Panel rather than embedding providers in domain services. If it stores media, use File Storage.



---

# Appendix AJ — Multi-Tenant Threat Model (documentation-derived)

| Threat | Control in architecture |
| --- | --- |
| Cross-tenant data read | tenant_id filters; denial tests; no cross-tenant queries |
| Cross-tenant write | same + service authz |
| Host header tenant spoofing | resolution order + domain verification (custom domain verify still missing → residual risk) |
| Privilege escalation via Identity roles | Core memberships are SoT; Identity listing roles not operational |
| JWT theft | TLS; short-lived tokens (OTP expiry configured); HttpOnly cookie practices as implemented for subdomain auth (ops concern) |
| Service token leakage | hashed at rest; scoped |
| Journal tampering via UI | ADR-010; posting permissions; audit frameworks |
| AI data bleed | tenant-scoped KB only; no cross-tenant reads |
| Support break-glass | platform_admin logged |

---

# Appendix AK — Non-Functional Requirements Snapshot

| NFR | Documented expectation | Current evidence |
| --- | --- | --- |
| Multi-tenancy | Mandatory | Implemented in Core/Accounting paths |
| Auditability | Mandatory | Core audit + Accounting audit framework |
| API-first | Mandatory | Contracts + FE clients |
| Event-ready | Mandatory | Outbox pattern |
| Security secrets hygiene | Mandatory | env-based; backup notes |
| Observability | Suggested alerts | Minimal runbook |
| Performance SLOs | Not published | UNKNOWN |
| Availability SLO | Not published | UNKNOWN |
| DR | Runbooks exist | Execution cadence UNKNOWN |

---

# Appendix AL — Release & Branching Alignment

Development docs define branching and release strategies. Architecture implication:

1. Architecture changes require ADR/docs first when boundaries move.  
2. Module registry/version fields should move with releases.  
3. Production deploy steps must record Alembic procedure used.  
4. Frontend and Accounting can release on different cadences if contracts remain compatible—API versioning discipline required.

---

# Appendix AM — White-Label Readiness Rubric

| Criterion | Status |
| --- | --- |
| Tenant brand fields | Present (architecture/progress) |
| Theme CSS variables | Partial runtime |
| Public tenant-site API | Present |
| Subdomain routing | Present |
| Subdomain SSL auto | Present |
| Custom domain storage | Present with pending verify |
| DNS/TXT verification | Missing |
| Guest vs member experiences | Partial / productized via tenant site |
| Ready for Restaurant guest menu | Not fully — polish + pay still needed |

---

# Appendix AN — Entitlement Key Taxonomy Guidance

Format: `{service_key}.{resource}.{action}`  
Example: `accounting.invoice.create`

**Rules for new modules:**

1. Reserve prefix in module registry before coding.  
2. Seed plan features for FREE/STARTER (or successor plans) intentionally.  
3. Cache invalidation on `feature_access.changed`.  
4. UI must hide and API must deny (never UI-only gates).

---

# Appendix AO — Posting Integration Contract (for future modules)

When Restaurant/Ecommerce/CRM need financial effects:

1. Define posting profile / intent DTO with Accounting.  
2. Prefer preview then post.  
3. Emit domain event after operational success; Accounting posts and emits `*.posted`.  
4. Never create JournalEntry rows locally.  
5. Include tenant_id, idempotency key, source document ids.  
6. Respect fiscal period open checks (failures are expected, not bugs).  

---

# Appendix AP — Celery / Async Job Catalog (known)

| Job/area | Purpose |
| --- | --- |
| `process_outbox_events` | Publish pending outbox rows |
| SSL provision task | Expand tenant certs via SSH script |
| Future notification dispatch | Should live in Notification workers |
| Future report schedules | Accounting scheduled reports (phase 5.10 entities) |

---

# Appendix AQ — Frontend Module Onboarding Template

1. Create `app/<module>/**` routes  
2. Add shell + nav entries entitlement-aware  
3. Add typed API client (`lib/<module>-api.ts`)  
4. Use DS components only  
5. Wire AuthGuard + tenant header  
6. Add scoreboard doc if enterprise completeness tracking needed  
7. No mocks  

---

# Appendix AR — Backend Service Onboarding Template

1. `backend/services/<name>/` structure per service architecture  
2. Independent DB + Alembic  
3. Shared-lib JWT validation  
4. Tenant middleware/deps  
5. Outbox for events  
6. Register in Core + module-registry  
7. Permissions + tests + docs  

---

# Appendix AS — Documentation Drift Prevention Checklist

- [ ] Status only in progress/next-steps/roadmap (correct file)  
- [ ] Architecture docs avoid “done/not done” claims when possible  
- [ ] Registry Status fields updated same PR as code  
- [ ] Event catalog updated with producers  
- [ ] Conflicts table reviewed quarterly  
- [ ] Deprecated stubs for moved paths kept honest  

---

# Appendix AT — Financial Spine Diagram

```mermaid
flowchart LR
  OPS["Operational modules<br/>Restaurant · Ecommerce · CRM"] -->|posting intents / events| ACC["Accounting Service"]
  ACC --> PE["Posting Engine"]
  PE --> GL["General Ledger"]
  PE --> AUD["Audit / Compliance"]
  GL --> RPT["Reporting Engine"]
  OPS -->|payments| PAY["Payment Provider"]
  PAY -->|settlement events| ACC
  ACC -->|cash postings| TRY["Treasury"]
```

---

# Appendix AU — Identity Spine Diagram

```mermaid
flowchart LR
  U["User"] --> FE["Frontend"]
  FE --> KC["Keycloak"]
  FE --> ID["Identity BFF"]
  ID --> KC
  ID --> COREOTP["Core OTP / Payamak"]
  FE --> CORE["Core users + memberships"]
  CORE --> ENT["Entitlement"]
  FE --> MOD["Business module APIs"]
  MOD --> ENT
```

---

# Appendix AV — Edge Spine Diagram

```mermaid
flowchart TB
  DNS["DNS *.torbatyar.ir + custom"] --> NGX["Nginx 192.168.10.156"]
  NGX --> FE["Frontend :3000"]
  NGX --> API["Core :8000"]
  NGX --> ID["Identity :8001"]
  NGX --> AUTH["Keycloak :8080"]
  NGX --> ACC["Accounting :8002"]
  CEL["Celery on app host"] -->|SSH provision_ssl| NGX
```

---

# Appendix AW — What “Done” Means for Platform Waves

### Wave 0 Done

- Accounting hostname smoke green  
- White-label product-accepted  
- Doc conflicts X1–X10 addressed or ticketed  
- AI provider decision recorded  

### Wave 1 Done

- File Storage uploads work for at least one consumer  
- Notification delivers at least one channel for one event type  
- Payment webhook → subscription or order path proven  
- Bus publishes outbox events to a consumer service  
- Custom domain verify path proven  
- Membership sync proven with tests  

### Wave 2 Done

- Restaurant can publish a digital menu on tenant host  
- CRM can manage a lead→opportunity path  
- Both gated by entitlement  

---

# Appendix AX — Stakeholder FAQ

**Q: Is TorbatYar production-ready?**  
A: Foundation + Accounting are production-shaped; next-steps still require deploy verification and platform polish. Not full SuperApp-ready.

**Q: Why did Accounting come before Restaurant?**  
A: Delivery history in progress shows Accounting 5.x completed; product decision preferring Restaurant remains Proposed and still valuable as next GTM vertical after white-label.

**Q: Can we start Marketplace now?**  
A: No — depends on ecommerce, payment, identity maturity, accounting settlements.

**Q: Can AI post vouchers?**  
A: Architecture forbids AI as sole authority for money; at most advisory with human/approval controls.

**Q: Single database would be simpler—why not?**  
A: ADR-001 rejected shared DB to protect long-term modularity.

---

# Appendix AY — Metrics to Start Measuring (recommended; not currently published as SLOs)

These are planning recommendations consistent with monitoring docs, not claimed existing dashboards:

1. Outbox pending/failed age  
2. OTP send success rate  
3. SSL provision success/latency  
4. Entitlement cache hit ratio  
5. Accounting post latency  
6. 5xx by service host  
7. Cert days-to-expiry  
8. Backup last success timestamp  

---

# Appendix AZ — Final Synthesis Paragraph

The platform’s architecture is coherent enough to support a long SuperApp journey. The limiting factor is no longer the absence of principles—it is the **absence of shared horizontal services and scale machinery** relative to the breadth of ambitions listed in the mission catalog. Execute Wave 0 and Wave 1 with discipline; then open verticals in dependency order. Protect tenant isolation and posting integrity above feature velocity. Keep documentation conflict debt near zero so the next master report is a delta, not a rewrite.

---

*Document complete — Master Architecture Report v1.0 (2026-07-24)*
*Path: `docs/architecture-review/MASTER_ARCHITECTURE_REPORT.md`*

---

# Appendix BA — Service Contracts Digest (from reference)

## BA.1 Fundamental rules

1. No direct queries to another service database.
2. Database-per-service.
3. Inter-service channels only: REST, Webhook, Async Event, Outbox/Inbox.
4. Tenant-aware requests carry `tenant_id` (header `X-Tenant-ID` or token/event).

## BA.2 Inter-service auth

Internal Service Tokens hashed in `internal_service_tokens` with scopes. End users authenticate with Keycloak JWT (and OTP JWT where applicable).

## BA.3 Entitlement check contract

```
POST /api/v1/tenants/{tenant_id}/features/check
{ "feature_key": "accounting.invoice.create" }
→ { "tenant_id", "feature_key", "has_access", "reason" }
```

Naming: `{service_key}.{resource}.{action}` (examples include `crm.lead.create`, `ecommerce.product.create`).

## BA.4 Core API groups (Phase 1 surface)

Health; Tenants (CRUD/suspend/activate); Domains (+ resolve); Plans & Features; Subscription + feature check; Service Registry.

## BA.5 Standard responses

Errors via `shared.responses.ErrorResponse` (`success=false`, `error.code/message/details`). Lists via paginated `Page` (`items` + `meta`).

## BA.6 Onboarding / tenant context

Contracts document Phase 4 onboarding APIs under `/api/v1`, requiring Bearer auth, with explicit note that external briefs call this Phase 3. Includes `GET /api/v1/me` for current user, memberships, and onboarding need.

## BA.7 Implication for master plan

Contracts are the integration constitution. New modules must extend contracts/catalog/registry in the same change set as code—otherwise SuperApp integration decays into tribal knowledge.

---

# Appendix BB — Disaster Recovery Targets

| Metric | Initial target |
| --- | --- |
| RPO | ≤ 24 hours (improve with more frequent backups) |
| RTO | ≤ 8 hours for full stack restore |

| Scenario | Response summary |
| --- | --- |
| App host loss | New host, restore compose+env, restore DB dumps, repoint Nginx |
| Edge host loss | Rebuild Nginx from infra configs, restore certs/maps, re-provision |
| DB corruption | Restore last good dump; forward-fix if possible |
| Keycloak loss | Restore Keycloak DB + realm export; validate OIDC clients |

**Scale note:** 24h RPO is acceptable for early SaaS; 1,000+ tenants with payment/marketplace will need tighter RPO and tested runbooks—treat as Wave 1/ops upgrade.

---

# Appendix BC — Release Strategy Alignment

Semantic versioning: MAJOR breaking contracts/schema; MINOR compatible features/modules; PATCH fixes/docs/hardening.

Release notes must list features, fixes, migrations, env/config, provider changes, deprecations.

Migration order: Backup → per-service migrations (typically Core → Identity → business) → deploy compatible services → smoke auth/onboarding → then enable flags.

Rollback: prefer forward-fix; app rollback to previous image; DB downgrade only with tested path + restore point.

**Hard rule:** Do not ship half-enabled financial posting paths behind weak flags.

---

# Appendix BD — Glossary Conflict & Updates Needed

`docs/glossary.md` still titles the Accounting section as "Accounting (future)" and describes Account as a planned 4-level structure even though Accounting 5.1–5.11 and FE scoreboard show Active delivery.

**Preferred truth:** Accounting terms are current platform vocabulary; glossary heading should drop "(future)" and note Phase 5.x delivered, with remaining future items (tax connectors, AI 5.12) called out separately.

This is documentation debt severity Medium—not a runtime defect, but it mis-trains new contributors.

---

# Appendix BE — Program Roadmap Gantt (logical, not calendar dates)

```mermaid
gantt
    title TorbatYar Platform Sequencing (logical waves)
    dateFormat  X
    axisFormat %s
    section Wave0
    Accounting prod verify           :a1, 0, 1
    White-label polish               :a2, 0, 2
    Doc conflict cleanup             :a3, 0, 1
    AI provider decision             :a4, 1, 1
    section Wave1
    File Storage + S3                :b1, 2, 3
    Notification MVP                 :b2, 2, 3
    Payment provider                 :b3, 3, 3
    Message bus                      :b4, 4, 3
    Domain verify + RBAC invites     :b5, 3, 3
    Membership sync                  :b6, 3, 2
    section Wave2
    Restaurant digital menu          :c1, 6, 4
    CRM foundation                   :c2, 6, 4
    section Wave3
    Website/Landing builder          :d1, 10, 3
    Ecommerce store builder          :d2, 11, 4
    section Wave4
    Live Chat + AI assistant         :e1, 14, 4
    Smart Messenger / SMS panel      :e2, 15, 3
    section Wave5
    Automation/Workflow              :f1, 18, 4
    Marketplace                      :f2, 19, 5
    Wallet / Gym packs               :f3, 20, 4
```

---

# Appendix BF — Decision Log Impact Matrix

| Decision | Status | Impact if ignored |
| --- | --- | --- |
| ADR-001 DB-per-service | Accepted | Accidental monolith DB |
| ADR-002 FE/BE split | Accepted | Entangled deploys |
| ADR-003 tenant_id | Accepted | Data leaks |
| ADR-004 Keycloak SSO | Accepted | Fragmented logins |
| ADR-005 Mobile OTP | Accepted | Weak IR market fit |
| ADR-006 Outbox | Accepted | Dual-write bugs |
| ADR-007 Dual memberships | Accepted | Must educate constantly |
| ADR-008 White-label config | Accepted | Hardcoded brands |
| ADR-009 Nginx SSL auto | Accepted | Manual cert ops pain |
| ADR-010 Posting engine | Accepted | Broken ledger integrity |
| Phase numbering | Accepted | Confused roadmaps |
| Restaurant first module | Proposed | Already superseded in practice by Accounting delivery—update decision |
| Documentation-as-software | Accepted | Drift returns |

---

# Appendix BG — Quality Gates Before Opening a PR for New Modules

1. Phase/module docs exist
2. Registry row Status accurate
3. Feature keys reserved
4. Tenant denial test included
5. No cross-DB import
6. Events catalogued if emitted
7. FE uses DS + real API
8. If money involved: posting contract reviewed
9. Progress/roadmap updated appropriately
10. No secrets committed

---

# Appendix BH — Ops Runbook Index

| Runbook | Path |
| --- | --- |
| Deployment overview | `docs/deployment/deployment.md` |
| Production hosts/env | `docs/deployment/production.md` |
| SSL/TLS | `docs/deployment/ssl.md` |
| Monitoring | `docs/deployment/monitoring.md` |
| Backup | `docs/deployment/backup.md` |
| Restore | `docs/deployment/restore.md` |
| Disaster recovery | `docs/deployment/disaster-recovery.md` |

Architecture topology companion: `docs/architecture/deployment-architecture.md`.

---

# Appendix BI — Scorecard Action Mapping

| Low/mid score area | First action |
| --- | --- |
| Scalability 5 | Message bus + DB capacity plan |
| Testing 6 | Expand tenant isolation + contract suites; publish coverage expectations per service |
| Infrastructure 6 | Implement suggested alerts; document CI |
| Enterprise SaaS 6 | Complete Wave 1 shared services |
| Frontend 7 | Finish white-label; module nav scalability |
| Security 7 | Invites/RBAC + domain verify |

---

# Appendix BJ — Closing Cover Note for Reviewers

Reviewers should read sections 1, 12–18 first, then dive into appendices for evidence. Treat conflict tables as mandatory reading before changing roadmap. When disagreeing with a score, propose an evidence-backed adjustment tied to a doc or measurable gate—not intuition alone.

This file is the planning baseline as of **2026-07-24**. Re-issue a delta master report when Wave 0 exits or when a new Active business module ships.

---

*End of Master Architecture Report v1.0 — full synthesis*
