# Final Project Architecture Blueprint

> Phase: `ARCH.FullProjectSeniorCleanArchitecture`
>
> Date: 2026-08-04
>
> Status: **EXECUTED_SAFE_FOUNDATION**
>
> Runtime changes in this checkpoint: **compatibility-preserving module ownership only**

## 1. Executive summary

KamTeswa is a production-style modular monolith with four interface surfaces:

1. REST API under `/api`;
2. authenticated EJS dashboard under `/dashboard`;
3. Socket.IO listeners for auctions, live sessions, chat, and calls;
4. scheduled jobs, QA scripts, OpenAPI/Postman delivery, and webview/info-site adapters.

The repository now has an enforced domain-first foundation. Fourteen dashboard domains,
Content, Support, Notifications, Communications, and Scheduling expose public module
boundaries. Existing horizontal paths remain compatibility adapters where consumers or
tests still require them. High-risk domains that have not completed a dedicated contract
wave remain deliberately horizontal; this checkpoint does not disguise partial ownership
as a completed whole-project migration.

This blueprint defines the direction and records the implemented safe foundation. It is
not authorization to mass-move models, auth, orders, auctions, payments, or other
critical flows without their own contract gates.

## 1.1 Baseline gate result

The initial red baseline was reconciled before architecture movement. The current
post-migration full-suite gate is:

```text
npm test
tests:      1085
passed:     1085
failed:     0
cancelled:  0
```

The owner explicitly froze the current Auction schema. The architecture guard and a
recorded SHA-256 fingerprint verify that `src/models/auctionModel.js` did not change.
Auction handler logic also remains in its existing registry; only generic scheduling
persistence/runtime ownership moved behind compatibility adapters.

## 1.2 Implemented ownership checkpoint

- 14 dashboard domains expose canonical `src/modules/<domain>` public entries;
- `src/modules/dashboard/<domain>` remains an identity-preserving compatibility layer;
- low-risk catalogue APIs own repositories, services, policies, DTOs, and controllers;
- Content owns About, FAQ, Privacy, Terms, and Intros API reads;
- Support owns Contact and Complaint API orchestration and owner-scoped queries;
- Notifications owns list/seen/delete/toggle/keys/broadcast API orchestration;
- Communications owns Chat API plus Chat/Call Socket runtimes and event constants;
- Scheduling owns Cron persistence, dispatch, and in-memory runtime;
- shared infrastructure facades preserve legacy constructor/singleton identity;
- architecture ownership is machine-readable in
  `docs/architecture/module-ownership.json` and enforced in tests.

## 1.3 Final browser checkpoint

The architecture smoke covered Dashboard Home, Clients, Settings, Products, and Reasons
across light, dark, compact, and mobile scenarios. It found zero horizontal overflow,
broken images, duplicate IDs, console errors, failed requests, CSRF failures, table
alignment errors, or light/dark token leaks.

The smoke did report 28 vertically clipped leaf-text nodes, all on Dashboard Home. Source
inspection confirmed these are existing intentional `-webkit-line-clamp` rules on provider
metadata and long latest-product names. They are not caused by the module migration, and
the QA detector was deliberately not weakened to hide them. Resolving that visual policy
requires a separate Dashboard Home UI acceptance pass; no frozen Home view or asset was
changed by this architecture checkpoint.

Therefore the safe architecture foundation is executed and green, but the whole-project
program is not represented as globally complete. High-risk domain moves and the existing
Home text-clamp visual debt remain explicit follow-up work.

## 2. Verified current state

The following figures describe the pre-migration inventory; current ownership is tracked
by the manifest rather than inferred from folder counts:

| Surface | Current result |
|---|---:|
| Mongoose model files | 79 |
| API route families, excluding the aggregator | 20 |
| API controllers | 24 |
| API service/helper files in `src/helpers/api` | 33 |
| API validators | 19 |
| Dashboard vertical business modules | 14 |
| Dashboard vertical source files, including shared | 118 |
| Remaining horizontal dashboard controllers | 33 |
| Remaining dashboard validators | 29 |
| Dashboard central router size | 2,396 lines |
| Admin EJS files | 492 |
| Admin asset files | 2,373 |
| Socket/listener source files | 10 |
| Socket central registrar size | 1,077 lines |
| Test files discovered by `npm test` | 125 |
| OpenAPI path documents | 31 |

The current worktree is intentionally dirty with the architecture migration. Every
modified/untracked path is classified by
`docs/architecture/worktree-classification.json` and enforced by
`test/projectWorktreeAccountability.test.js`. No generated screenshot or Postman metadata
is part of that change set.

## 3. Current architectural shape

```text
app.js
  -> src/routes/index/index.js
       -> /api       -> src/routes/api/* -> src/controllers/api/* -> src/helpers/api/*
       -> /dashboard -> adminRoute.js -> vertical modules + horizontal controllers
       -> /web       -> webview routes/controllers

app.js
  -> listeners/socketManger/socket.js -> auction/chat/live/call helpers
  -> services/CronManger/cronJob.js -> helpers/cronJopFn/cronJobFn.js

all surfaces
  -> src/models/*
  -> src/helpers/returnObject/returnObject.js
  -> src/services/* and src/utils/*
```

The existing route classes, response envelope, validators, authentication, upload
handling, i18n, and EJS rendering strategy remain authoritative contracts during the
migration.

## 4. Target architecture

```text
src/modules/<domain>/
  domain/
    <domain>.model.js
    <domain>.repository.js
    <domain>.service.js
    <domain>.policy.js
    <domain>.constants.js
    <domain>.query.js               # only when query composition is non-trivial
    <domain>.events.js              # event names and domain event payloads

  interfaces/
    api/
      <domain>.api.controller.js
      <domain>.api.routes.js
      <domain>.api.validation.js
      <domain>.dto.js

    dashboard/
      <domain>.dashboard.controller.js
      <domain>.dashboard.routes.js
      <domain>.dashboard.validation.js
      <domain>.viewModel.js
      <domain>.uploads.js

    socket/
      <domain>.socket.js
      <domain>.socket.events.js
      <domain>.socket.dto.js
      <domain>.socket.policy.js

  index.js

src/modules/shared/
  auth/
  db/
  errors/
  files/
  http/
  localization/
  logger/
  money/
  notifications/
  pagination/
  permissions/
  security/
  sockets/
  uploads/
```

EJS stays in `views/`, and browser-served assets stay in `public/`. Their ownership is
declared through module manifests and naming conventions; they are not moved into Node
source folders while Express static delivery remains unchanged.

## 5. Dependency rules

Allowed direction:

```text
interface adapter -> application/domain service -> policy/repository -> model
interface adapter -> DTO/viewModel
socket/cron adapter -> application/domain service
domain module -> shared infrastructure contract
```

Forbidden direction:

- domain model or repository importing Express, EJS, Socket.IO, or HTTP response types;
- repository shaping API DTOs or dashboard view models;
- controller querying Mongoose directly;
- EJS deciding business permissions from raw status/type strings;
- one domain importing another domain's private file;
- shared infrastructure importing a business-domain implementation;
- API adapters importing dashboard adapters or vice versa;
- moving browser assets into `src/modules` without a separately approved static-build
  strategy.

Cross-domain calls use the target module's public `index.js` or a deliberately named
application contract. Circular domain imports are not accepted.

## 6. Domain ownership map

The table records the current owners and the intended target. A target path is a
migration destination, not proof that the move is already safe.

| Domain | Current core ownership | Interfaces and other consumers | Target | Risk |
|---|---|---|---|---|
| Account identity/auth | `accountIdentityModel`, `userModel`, `userTokensModel`; `services/account*`, Passport/token services | Account/Auth API routes, auth helpers/controllers, dashboard auth | `modules/accounts` plus shared auth/security adapters | Critical |
| Admins/supervisors | `adminModel`, `roleModel`; admin/users dashboard controllers | dashboard auth/session, permissions, reports | `modules/admins` | High |
| Clients | `clientModel`, address/device/favorite data | Auth/Home/User API; clients dashboard; orders/chat | `modules/clients` | High |
| Providers | `providerModel`, provider edit request | Auth/Home/Product/Order API; providers dashboard; auctions | `modules/providers` | Critical |
| Join requests | `providerMetaModel`; `providerApprovalService` | account provider-request, providerMeta dashboard | `modules/provider-requests` | Critical |
| Products | product, pricing request, reports/reasons, attributes | Product/Pricing/ProductReport API; Product dashboard; cron/notifications | `modules/products` with reporting/pricing sub-capabilities | Critical |
| Categories | department/subDepartment models | More/Product API; existing dashboard modules | `modules/catalog-categories` or two cohesive child modules | Medium |
| Attributes | attribute/attributeValue models | More/Product API; existing dashboard modules | `modules/catalog-attributes` | Medium |
| Packages/subscriptions | package, feature, premium package/subscription models | More API; five dashboard modules; cron | `modules/subscriptions` with package catalogue boundary | High |
| Orders | order/cart/invoice/return request models | Order/Cart/Return API; dashboard; chat/cron/notifications | `modules/orders` | Critical |
| Auctions/bids/live | auction, bid, subscription, payment, history, report, live comment | Auction/Bid API; dashboard; socket; cron; Agora | `modules/auctions` | Critical |
| Coupons | coupon model | More subscription flow; dashboard; cron | `modules/coupons` | Medium |
| Countries/cities/locations | country/city/address/shipping-address; legacy district/village | More/Home API; dashboard; location/shipping | `modules/locations` | High due legacy ambiguity |
| Settings | settings/site/sms models | More API, dashboard settings, notifications, cron | `modules/settings` | High |
| Permissions/RBAC | role model, generated route catalogue, middleware | dashboard permissions and every admin route | `modules/access-control` plus shared enforcement adapter | Critical |
| Reports/audit | report/adminReports/archive models and reporting helpers | dashboard reports, mutations across modules | `modules/audit-reports` | High |
| Notifications | notification/device models and send helpers/services | API More, dashboard, orders/auctions/chat/cron | `modules/notifications` with shared delivery ports | Critical |
| Complaints/support/contact | complaint/contact models | More API; dashboard complaints/contact/customer service | `modules/support` | Medium |
| Chat/calls | chat/message/call credential models | Chat API and chat/call socket interfaces | `modules/communications` | Critical |
| Socials | social media model | frozen dashboard vertical module | `modules/socials/interfaces/dashboard` | Low/Medium |
| Info site/content | info, sliders, intros, FAQ, how-work, banner/ads models | More/Home API, info-site/webview, dashboard | `modules/content` with explicit sub-capabilities | High |
| Payments/wallet/profits/settlements | payment methods, financial transactions, balance, settlement, profit | Payment/Financial/More API; dashboard; order/auction flows | `modules/payments` and `modules/settlements` | Critical |
| Shipping | OTO token/shipping address and shipping service | Shipping/Order API and webhooks | `modules/shipping` | High |
| Advertisements | advertisement/edit request/haraj request models | Advertisement/Haraj API and dashboard | `modules/advertisements`; legacy haraj isolated | High |
| Sockets | listener registrars and helper/validation folders | auctions, communications, notifications | domain socket adapters plus `modules/shared/sockets` | Critical |
| Cron/jobs/scripts | cron model/manager, 1,899-line handler catalogue, operational scripts | coupons, subscriptions, orders, auctions, products | domain job adapters plus shared scheduler | Critical |

## 7. Model ownership strategy

Models belong to business domains, never to `dashboard` or `api`. Model migration is
one-domain-at-a-time and follows this sequence:

1. freeze model name, indexes, hooks, population behavior, and exported shape in tests;
2. identify every import, populate path, discriminator, seed/script, socket, and cron
   consumer;
3. move the implementation to `src/modules/<domain>/domain/`;
4. leave the old `src/models/<name>Model.js` as a compatibility re-export;
5. verify only one Mongoose model is compiled;
6. migrate consumers gradually to the public module boundary;
7. remove the compatibility path only in a separately approved proof wave.

There is no authorization in this blueprint to change schemas, hooks, indexes, stored
values, or run data migrations.

## 8. API interface strategy

The public endpoint contract remains stable. Each API migration freezes:

- public/authenticated bucket placement;
- method and path;
- middleware and validator order;
- accepted fields after `matchedData`;
- response envelope, status code, message key, and DTO fields;
- pagination/filter behavior;
- upload names and lifecycle;
- OpenAPI/Postman representation.

Existing thin controllers can become compatibility re-exports while logic moves from
`src/helpers/api/<Domain>.js` into a domain service. `returnObject.js` is split by DTO
ownership only after response snapshots exist; its 8,341 lines make it a critical-risk
hotspot.

## 9. Dashboard interface strategy

The existing 14 dashboard modules are transitional adapters. They are not moved again
until a domain is ready to own API/dashboard/socket adapters together. Until then:

- central `adminRoute.js` remains the ordering authority;
- route registrars may be extracted only after method/path/middleware snapshots;
- EJS and public assets remain in place;
- policies/viewModels replace raw business comparisons before templates are simplified;
- frozen UI baselines are preserved; architecture work is not redesign authorization.

## 10. Socket interface strategy

Event names and payloads are public contracts. The 1,077-line central Socket registrar
is split by delegation, not by renaming events:

1. snapshot inbound/outbound names, ack shapes, rooms, and auth failure behavior;
2. introduce one registration function per domain;
3. move pure validation/policy and DTO mapping first;
4. move handler orchestration behind the domain service;
5. keep the original `SocketEvents` class as a compatibility registrar until every
   event family is proven;
6. assert each listener is registered exactly once.

Auction/live and chat/call are separate migration waves even if they share Socket.IO.

## 11. Jobs and operational scripts

The scheduler remains shared infrastructure; handler ownership belongs to the domain.
The current cron function catalogue must first gain a handler-name contract test. A job
handler may move only when its persisted `fn` value, timing semantics, idempotency, and
retry behavior remain unchanged.

Unregistered scripts are `MANUAL_REVIEW`, not dead. Destructive seed/import/export
scripts require explicit operator approval even when their target files are missing.

## 12. Views and asset ownership

Physical locations remain:

```text
views/admin/<resource>/
public/admin/assets/css/pages/<resource>.css
public/admin/assets/js/pages/<resource>.js
```

Each domain guide/manifest records its views and assets. An EJS view or asset is not
dead merely because static grep has no reference; dynamic render/include and browser
loading must be accounted for. Asset deletion requires authenticated browser coverage,
network 404 checks, light/dark/mobile coverage, and temporary-removal proof.

## 13. Shared infrastructure boundary

The future `modules/shared` tree contains technical capabilities only. Candidate shared
owners include response/error primitives, logger, authentication ports, CSRF, uploads,
localization, pagination, money/dates, notification delivery, and socket transport.

Business concepts such as Provider approval, Product moderation, Auction settlement,
or Order cancellation never move into shared merely because several adapters call them.

## 14. OOP and clean-code boundary

OOP is used to create ownership, not ceremony. Required abstractions are:

- constants/enums for authoritative values;
- policy functions/classes for decisions;
- query builders for reusable persistence filters;
- repositories for database access;
- services/use-cases for orchestration;
- DTO/viewModel mappers for safe output;
- interface controllers for transport-only work.

Current audit signals that need staged reduction:

- 286 direct status/type/role comparisons in controllers, services, helpers, modules,
  listeners, and admin EJS;
- 466 `console.log/debug/info` calls in runtime source;
- very large hotspots: `returnObject.js`, Product/More/Auction API helpers,
  `adminRoute.js`, cron handlers, and Socket registrar.

These counts are baselines, not authorization for a global search/replace.

## 15. Compatibility and rollback

Every migration wave has an explicit compatibility layer:

- old model/controller/helper path re-exports the new public module surface;
- route aggregators retain the original registration order;
- old DTO function name delegates to the new mapper;
- Socket registrar delegates to the extracted registration function;
- cron handler export name stays unchanged;
- EJS/render path and asset URL stay unchanged.

Rollback is domain-local: restore the old implementation import and compatibility file
without reverting unrelated domains.

## 16. Quality gates

Every implementation wave must pass:

1. focused domain tests;
2. import graph and forbidden dependency checks;
3. model registration tests when models move;
4. route method/path/order and middleware snapshots when routes move;
5. API response/DTO and OpenAPI/Postman diffs when API files move;
6. Socket event/payload/registration tests when listeners move;
7. EJS compile and authenticated browser QA when dashboard files move;
8. `node --check` on every changed JavaScript file;
9. full `npm test`;
10. `git diff --check` and, when applicable, staged diff check;
11. generated-artifact and secret scans.

No wave is complete with a red gate or an unexplained Git-status entry.

## 17. Do-not-delete list

Without candidate-specific proof, retain:

- all Mongoose models and compatibility paths;
- app/bootstrap and route aggregators;
- authentication, CSRF, error, token, logger, upload, notification, scheduler, and
  Socket transport infrastructure;
- dynamic EJS views and locale catalogues;
- operational scripts and package scripts;
- active OpenAPI/Postman delivery artifacts;
- frozen dashboard views/assets;
- `.env`, deployment files, certificates, and upload trees.

The tracked `.env` is a separate security/index-management decision. Its contents were
not inspected and it is not changed by this phase.

## 18. Risk register

| Risk | Severity | Required mitigation |
|---|---|---|
| AccountIdentity dual-stack authentication | Critical | auth/token/profile contract suite before any move |
| Products/variants/uploads/AI pricing | Critical | mutation and media lifecycle snapshots; Products last in catalogue waves |
| Orders/auctions/payments state machines | Critical | policy transition tests, transaction/cron/socket contract coverage |
| Central dashboard route ordering | Critical | complete route/middleware snapshot before registrar extraction |
| Dynamic EJS rendering | High | explicit view allowlists and browser crawl |
| Central DTO mapper | Critical | field-level response snapshots and leak tests |
| Model compile/populate behavior | Critical | compatibility export and duplicate-compilation tests |
| Socket duplicate listeners/payload drift | Critical | registration-once and payload snapshots |
| Cron persisted handler names | Critical | handler catalogue test and idempotency proof |
| Tracked `.env` | High | separate Git/security decision; never expose values |
| Stale package scripts | High | operations owner decision before removal or repair |
| Lint/format broad diff | High | changed-files-only staged adoption |

## 19. Decision record

- No runtime move or deletion occurs in Wave 0.
- No package is installed; ESLint/Prettier are currently absent.
- No API response, route, schema, database value, middleware order, Socket event, cron
  handler name, EJS path, or asset URL changes in this checkpoint.
- The next implementation wave is shared-boundary scaffolding and one low-risk domain,
  not a mass migration.
