TorbatYar/architecture-reference.md
Mortezakoohjani 0d424c500a feat(platform): complete commercial runtime consolidation
Unify commercial runtime ownership across backend and frontend so platform, experience, and hospitality modules use the shared commercial source of truth.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 11:11:53 +03:30

248 lines
12 KiB
Markdown

====================
FILE: F:\TorbatYar\docs\architecture\module-boundaries.md
====================
# Module Boundaries
> Architecture only. Module inventory → [module-registry.md](../module-registry.md)
## Core Platform
**Owns:** tenants, domains, plans, features, subscriptions, entitlement checks, service/module registry, internal service tokens, outbox/inbox (core), audit log, core users, tenant memberships (operational), onboarding, public tenant-site resolution.
**Must not own:** business journals, CRM entities, restaurant menus, file blobs, SMS campaigns.
## Identity & Access
**Owns:** user profiles linked to Keycloak, identity-layer memberships, OIDC BFF (config/token/me), mobile OTP handoff/session redeem, Keycloak admin sync.
**Must not own:** workspace onboarding lifecycle, plan/subscription, operational tenant roles source of truth (Core).
## Frontend
**Owns:** UI, theme application, client-side auth redirects, dashboards, onboarding wizard UX.
**Must not own:** business rules, direct DB access, SQLAlchemy/Alembic, entitlement computation.
## Future Business Modules
Each module (Accounting, CRM, Restaurant, Ecommerce, …) owns its database and domain APIs. Cross-module coupling is API/event only. Financial postings go only through Accounting Posting Engine ([ADR-010](adr/ADR-010.md)).
### CRM (Sales CRM)
**Owns:** Lead, Contact, Organization (business account), Opportunity, Pipeline, PipelineStage, SalesActivity, Task, Meeting, CallLog, Sales Timeline, Comment/Mention, Bookmark, Sales Team, Playbook, Forecast, Goal, Target, Win/Loss, Quote (sales), CRM publish events.
**Must not own:** Automation/workflows, Customer360, Marketing, Notification delivery, Messaging, Communication, Helpdesk, Analytics, AI, Identity, Accounting, Inventory, Restaurant, Marketplace, Files, Search, Loyalty, Sports Center, Delivery, Experience.
### Loyalty (Enterprise Loyalty Platform)
**Owns:** LoyaltyProgram, MembershipTier, Member, PointAccount (shell; ledger in later phases), Reward catalog shell, Campaign shell, Loyalty audit, Loyalty publish events.
**Must not own:** CRM sales entities, Accounting postings, Notification delivery, Identity, Wallet UI (frontend), Restaurant/Marketplace/Ecommerce/Sports Center/Delivery/Experience domain data — those modules consume Loyalty via API/Events only.
### Communication (Enterprise Communication Platform)
**Owns:** Provider configs, sender numbers, message templates, manual contacts, dynamic contact-source configs, messages, queue/DLQ, delivery timeline, provider logs, OTP challenges, webhook receipts, communication audit; outbound provider adapters.
**Must not own:** CRM/Loyalty/Restaurant/Marketplace/Sports Center/Delivery/Experience business entities; must not be embedded inside those modules. Auth OTP path in Core remains separate until explicitly migrated.
### Sports Center Platform
**Owns:** Sports members, memberships/membership types, coaches, attendance/access devices, bookings, facilities/courts/equipment, programs/workouts, competitions/sports events, locker/medical/nutrition shells as scoped, sports reports/analytics shells, sports_center publish events, integrations adapters (client-side only).
**Must not own:** Accounting journals/Posting Engine, Sales CRM aggregates, Loyalty ledger/campaigns, Communication providers, Core tenant membership, Restaurant/Ecommerce domains, Delivery logistics domain, Experience page/site/theme ownership, product AI platform, Automation engine.
### Delivery & Fleet Platform
**Owns:** Drivers, fleets, vehicle types/vehicles, availability/shifts/working zones, pricing/capabilities/bundles, dispatch engine, routing/optimization, tracking, proof of delivery, settlement intents, merchant connector contracts, driver/dispatcher API surfaces, fleet analytics shells, delivery publish events, routing/fleet provider adapters.
**Must not own:** Accounting journals/Posting Engine, Sales CRM aggregates, Loyalty ledger/campaigns, Communication providers or message delivery timeline, Core tenant membership, Restaurant/Marketplace/Clinic/Sports Center order/menu/catalog domains, Experience page/site ownership, product AI platform, Automation engine, Driver App / Dispatcher Panel UI (frontend).
### Experience Platform
**Owns:** Sites, page resources and page types, versioned components, themes, layouts, templates, locales/RTL-LTR shells, media references (not binaries), forms/surveys/appointment page shells, publishing workflows, custom domain binding refs, SEO/PWA shells, capability bundles and feature toggles, widgets, consumer connector contracts, experience analytics/AI hooks shells, experience publish events.
**Must not own:** Accounting journals/Posting Engine, Sales CRM aggregates, Loyalty ledger/campaigns, Communication providers, Core tenant membership / white-label brand source of truth, File Storage binaries, Hospitality menu/item or Marketplace product catalogs as source of truth, Delivery logistics, product AI platform, Automation engine, Page Builder / public site UI (frontend).
### Hospitality Platform
**Owns:** Venues (cafe/restaurant/bakery/… formats), branches, dining areas/tables, menus/categories/items shells, hospitality roles/permissions, bundle definitions, tenant bundle activation, feature toggles, hospitality configurations/settings/events/audit, hospitality publish events, connector contracts (client-side only).
**Must not own:** Accounting journals/Posting Engine, Sales CRM aggregates, Loyalty ledger/campaigns, Communication providers, Core tenant membership, Delivery logistics domain, Experience page/site/theme ownership (menus-as-pages are Experience; menu/item catalog source of truth is Hospitality), product AI platform, Automation engine, POS/kitchen/ordering engines until their phases.
## Shared Library (`backend/shared-lib`)
**Owns:** JWT validation helpers, phone normalization, event envelope types, shared exceptions/responses.
**Must not own:** tenant business workflows or service-specific repositories.
## Boundary Rules
1. No cross-database foreign keys.
2. No importing another service's models.
3. Feature gates use Core entitlement API.
4. Frontend talks to public/versioned APIs only.
5. Providers are integrated behind module/provider adapters — see [integration-architecture.md](integration-architecture.md).
## Related Documents
- [Service Architecture](service-architecture.md)
- [ADR-001](adr/ADR-001.md) آ· [ADR-002](adr/ADR-002.md) آ· [ADR-007](adr/ADR-007.md) آ· [ADR-014](adr/ADR-014.md) آ· [ADR-015](adr/ADR-015.md) آ· [ADR-016](adr/ADR-016.md) آ· [ADR-017](adr/ADR-017.md)
- [Module Registry](../module-registry.md)
- [Sports Center Roadmap](../sports-center-roadmap.md)
- [Delivery Roadmap](../delivery-roadmap.md)
- [Experience Roadmap](../experience-roadmap.md)
- [Hospitality Roadmap](../hospitality-roadmap.md)
====================
FILE: F:\TorbatYar\docs\architecture\service-architecture.md
====================
# Service Architecture
## Internal Layering (every backend service)
```
API (routers) → Services (business logic) → Repositories → Models (DB)
↑
Schemas (Pydantic DTOs)
```
| Layer | Allowed | Forbidden |
| --- | --- | --- |
| API / Views | Auth deps, validation, HTTP mapping | Business rules, raw SQL |
| Services | Domain logic, orchestration, events | HTTP concerns, UI |
| Repositories | Queries/persistence | Business decisions |
| Models | Schema mapping | Business workflows |
## Core Package Layout
- `core/` — config, database, cache, security, logging
- `middlewares/` — tenant resolution
- `workers/` — Celery tasks (outbox, SSL provision, …)
- `api/v1/` — versioned routers
- `tests/` — automated tests
## Adding a Service
1. New folder under `backend/services/<name>/`
2. Independent database + Alembic
3. Register in Core service/module registry
4. Document in [module-registry.md](../module-registry.md)
5. UI only in `frontend/`, API-only access
6. Follow [coding-standards.md](../development/coding-standards.md)
## Related Documents
- [Module Boundaries](module-boundaries.md)
- [Developer Guide](../development/developer-guide.md)
- [Project Principles](../development/project-principles.md)
====================
FILE: F:\TorbatYar\docs\architecture\database-architecture.md
====================
# Database Architecture
> Architecture only. Column-level reference → [database-schema.md](../reference/database-schema.md)
## Pattern
**Database-per-service** ([ADR-001](adr/ADR-001.md)).
| Service | Database |
| --- | --- |
| Core Platform | `core_platform_db` |
| Identity & Access | `identity_access_db` |
| Accounting (future) | `accounting_db` |
| CRM | `crm_db` |
| Loyalty | `loyalty_db` |
| Communication | `communication_db` |
| Sports Center | `sports_center_db` |
| Delivery (planned) | `delivery_db` |
| Experience Platform (registered) | `experience_db` |
| Hospitality | `hospitality_db` |
| Ecommerce (future) | `ecommerce_db` |
| Website Builder (historical scaffold; prefer `experience_db`) | `website_builder_db` |
| Live Chat (future) | `live_chat_db` |
| AI Assistant (future) | `ai_assistant_db` |
| Smart Messenger (future) | `smart_messenger_db` |
| SMS Panel (future) | `sms_panel_db` |
| Link Shortener (future) | `link_shortener_db` |
| Notification (future) | `notification_db` |
| File Storage (future) | `file_storage_db` |
## Hard Rules
1. No direct queries across service databases.
2. No cross-DB foreign keys.
3. Every business table includes `tenant_id` ([ADR-003](adr/ADR-003.md)).
4. IDs are UUID; timestamps are timezone-aware.
5. Migrations via Alembic per service; never edit applied migrations in production.
6. Conceptual schemas for future services are documented in reference docs until migrations exist.
## Core Platform Ownership
Tenants, domains, plans/features/subscriptions, registries, internal tokens, outbox/inbox, audit logs, core users, operational `tenant_memberships`.
## Identity Ownership
`user_profiles`, identity-layer `tenant_memberships` (not the Core table — [ADR-007](adr/ADR-007.md)).
## Dual Membership Clarification
| Database | Table | Role |
| --- | --- | --- |
| `core_platform_db` | `tenant_memberships` | Workspace authorization source of truth |
| `identity_access_db` | `tenant_memberships` | SSO membership listing |
## Related Documents
- [Database Schema](../reference/database-schema.md)
- [Multi-Tenant Architecture](multi-tenant-architecture.md)
- [ADR-001](adr/ADR-001.md) آ· [ADR-007](adr/ADR-007.md)
====================
FILE: F:\TorbatYar\docs\architecture\event-driven-architecture.md
====================
# Event-Driven Architecture
## Envelope
All events use `shared.events.EventEnvelope`:
```json
{
"event_id": "uuid",
"event_type": "tenant.created",
"aggregate_type": "tenant",
"aggregate_id": "uuid",
"tenant_id": "uuid|null",
"source_service": "core-service",
"payload": {},
"occurred_at": "ISO-8601"
}
```
## Outbox → Inbox ([ADR-006](adr/ADR-006.md))
1. Producer writes business row + `outbox_events` in one transaction.
2. Worker (`process_outbox_events`) publishes pending rows.
3. Consumer inserts `inbox_events` keyed by `event_id` (idempotency) then handles payload.
## Naming
`{aggregate}.{past_tense_verb}` — e.g. `tenant.created`, `subscription.updated`, `user.registered`.
## Catalog
Canonical list → [event-catalog.md](../reference/event-catalog.md)
## Future
Replace in-process/Celery-only publish with a real message bus without changing envelope or outbox ownership.
## Related Documents
- [Services Contracts](../reference/services-contracts.md)
- [Service Architecture](service-architecture.md)
- [ADR-006](adr/ADR-006.md)