Skip to content

CTC System Rebuild Blueprint

  • Status: CURRENT RECONSTRUCTION BLUEPRINT
  • Context: Context Appendix N
  • Product owner: docs/PRODUCT.md
  • Target architecture owner: docs/DESIGN.md
  • Current Runtime owner: .agents/rules/ARCHITECTURE.md
  • Current schema owner: .agents/rules/DB_SCHEMA.md
  • Process owner: docs/processes/
  • Reconstruction baseline for the first detailed slices: 4fc2f5a893765fbb95e0a2bdcb971322b0ec9fc0
  • Target stack: React + Next.js App Router + Tailwind CSS + framework-independent TypeScript application/domain/repository contracts + separate Node.js worker; MySQL first, PostgreSQL later

1. Purpose

This document is the central assembly guide for rebuilding CTC deliberately.

It does not duplicate every field, route or process step. It connects the documents that own those details and makes the intended system shape explicit enough that a future migration team can implement capability-by-capability without rediscovering the business from legacy source.

A rebuild must preserve:

  • Product outcomes and operating profiles;
  • current live-tenant behavior that is accepted and still required;
  • role, capability and tenant boundaries;
  • process states, authoritative records and stable identities;
  • transaction, provider, file, device and physical-work boundaries;
  • exact readback and recovery behavior;
  • operator-facing workflow and terminology;
  • one-writer migration and rollback;
  • audit, correction and caller-zero evidence.

A rebuild must not preserve accidental legacy structure merely because it exists.

Preserve business meaning and accepted compatibility.
Do not preserve giant helpers, page-owned SQL, numeric tenant branches,
shared shell coupling or generic table mutation as target architecture.

2. Authority Map

Question Canonical owner
What Product are we building? docs/PRODUCT.md
What target architecture and stack are approved? docs/DESIGN.md, Context Appendices K–N
What is the current PHP Runtime structure? .agents/rules/ARCHITECTURE.md and source
What is the current MySQL schema and data authority? .agents/rules/DB_SCHEMA.md, verified schema and source
What Phase/Task is active? docs/ROADMAP.md
What does a business process mean? owning file under docs/processes/
What is the current cross-process identity/handoff? docs/processes/CROSS_PROCESS_HANDOFF_AND_IDENTITY_MATRIX.md
What must a migration packet contain? docs/processes/PROCESS_MIGRATION_READINESS_EXTENSION.md and this dossier
How does an operator perform/recover the work? docs/runbooks/ and published Wiki
What Wiki content should exist? docs/wiki/internal/ projection packets; published content remains in T_WIKI_PAGE
What current adapter implements a capability? source plus current architecture/API/UI/DB rules

This blueprint is a reconstruction index and synthesis. It does not override those owners.


3. System Context

flowchart LR
    Office[Office / Dispatch / Manager]
    Loader[Forklift Operator]
    Yard[Yard Truck Driver]
    Driver[Truck Operator]
    Admin[Administrator / Super Admin]
    Customer[Customer / Supplier / Carrier]

    CTC[CTC Operations Platform]

    Gmail[Gmail / Workspace Add-on]
    Telegram[Telegram]
    QBO[QuickBooks Online]
    QBTime[QuickBooks Time]
    AI[Gemini / AI Extraction]
    Storage[File Storage / S3 / EFS]
    Scale[Scale / Weight Input]
    MySQL[(MySQL)]
    Control[Control Tower]

    Office --> CTC
    Loader --> CTC
    Yard --> CTC
    Driver --> CTC
    Admin --> CTC
    Customer --> Gmail
    Gmail <--> CTC
    CTC --> Telegram
    CTC <--> QBO
    CTC <--> QBTime
    CTC --> AI
    CTC <--> Storage
    Scale --> CTC
    CTC <--> MySQL
    Control -. published deployment / tenant / config context .-> CTC

Context rules

  • Control Tower is not a synchronous dependency for ordinary business requests.
  • MySQL remains authoritative during initial React + Next.js conversion.
  • Provider success is independent from local business-record success unless an owning process explicitly defines otherwise.
  • Physical work and system state must be reconciled; neither automatically proves the other.
  • Every person operates with a personal account unless an explicitly approved manager/Office override exists.

4. Current Runtime Component View

flowchart TB
    Browser[Browser]
    Apache[Apache / router.php / index.php]
    PageRouter[Page route + session + menu/module guard]
    PHPPage[Server-rendered PHP page]
    SharedJS[Shared and page-local JavaScript]
    APIEntry[api/index.php]
    RouteFiles[platform/shared/addon/system api_routes.php]
    Handlers[Module helpers / query handlers / post handlers]
    Common[Shared compatibility helpers]
    DB[KJDatabase / MySQL]
    Files[File storage]
    Providers[Telegram / Gmail / QBO / AI / QB Time]

    Browser --> Apache
    Apache --> PageRouter
    PageRouter --> PHPPage
    PHPPage --> SharedJS
    SharedJS --> APIEntry
    APIEntry --> RouteFiles
    RouteFiles --> Handlers
    Handlers --> Common
    Handlers --> DB
    Common --> DB
    Handlers --> Files
    Handlers --> Providers

Current strengths to preserve

  • explicit API v2 routes exist for many active capabilities;
  • tenant-scoped SQL is common in current source;
  • current process-specific commands exist for important workflows;
  • MySQL transactions and conditional updates already protect some transitions;
  • current pages contain substantial operational knowledge;
  • existing source and process documents contain role, state, recovery and provider information.

Current structural constraints not to reproduce as target design

  • browser/page files contain large amounts of UI, workflow and request logic;
  • many API route files load through one broad registry;
  • module handlers include other modules' internal helpers;
  • common_* and generic mutation helpers own too many responsibilities;
  • session/config/tenant/page behavior is globally coupled;
  • customer or numeric CLIENT_ID branches select business behavior;
  • provider calls sometimes occur inside or immediately around local transactions;
  • physical, provider and local business completion are not always represented as separate checkpoints;
  • shared JavaScript/CSS shell loads unrelated workflow assets.

5. Approved Target Runtime

flowchart TB
    User[Browser / Mobile Web]

    subgraph Web[React + Next.js Web Runtime]
        React[React components]
        RSC[Next.js Server Components]
        Actions[Bounded Server Actions]
        Routes[Route Handlers / BFF API]
    end

    subgraph Core[Framework-independent TypeScript]
        Queries[Application Queries]
        Commands[Application Commands]
        Policies[Domain / Profile / Capability Policies]
        Repos[Repository and Transaction Interfaces]
        Effects[Effect / Integration Interfaces]
    end

    subgraph Infra[Infrastructure]
        MySQLRepo[MySQL repositories]
        Worker[Node.js Worker]
        Outbox[Outbox / Queue]
        FileAdapter[File adapters]
        ProviderAdapters[Provider / Device adapters]
    end

    DB[(MySQL first)]
    Future[(PostgreSQL later)]

    User --> React
    React --> RSC
    React --> Actions
    React --> Routes
    RSC --> Queries
    Actions --> Commands
    Routes --> Queries
    Routes --> Commands
    Queries --> Policies
    Commands --> Policies
    Queries --> Repos
    Commands --> Repos
    Commands --> Effects
    Repos --> MySQLRepo
    MySQLRepo --> DB
    Effects --> Outbox
    Outbox --> Worker
    Worker --> FileAdapter
    Worker --> ProviderAdapters
    DB -. later P11 migration .-> Future

Target dependency rules

  • React owns presentation, interaction, form state and accessibility—not business authority.
  • Next.js owns routing, rendering, request adaptation and Web/API boundaries—not domain decisions.
  • TypeScript application/domain layers own commands, queries, policies, transaction intent and error semantics.
  • Repository implementations own SQL and persistence mapping.
  • The worker owns retryable, delayed, scheduled and long-running effects.
  • Domain/application packages must not import React or next/*.
  • Server Components must call application queries rather than HTTP-calling their own Route Handlers.
  • Server Actions are UI adapters to application commands; they are not the only stable API when another consumer exists.
  • One use case has one authoritative writer during migration.

6. Operating Profiles

CTC Execution profile

Emphasis:

  • appointment and field execution;
  • Loader and Yard workflows;
  • Driver delivery;
  • warehouse/inventory review;
  • billing, documents and provider close;
  • dedicated deployment reference.

MK Recycling / Order profile

Emphasis:

  • Commercial Purchase/Sales agreements;
  • Inbound Purchase and Outbound Sales;
  • Booking and inventory allocation;
  • conditional Scale;
  • costs, rates, Trade Summary and document outputs;
  • Shared SaaS reference.

Profile implementation rule

Tenant context
-> Operating profile
-> Capabilities / policies / configuration
-> page and application contract

Do not select behavior through:

CLIENT_ID === 1
CLIENT_ID === 2
customer display name
customer-specific copied controller/page/schema

A customer-specific legal, operational or provider exception must be represented through stable policy/configuration and documented owner approval.


7. Logical Module Ownership

Module / platform area Rebuild responsibility Must not own
Platform Core tenant/deployment context, auth, role, menu, capability, config, audit, files, notification contract, observability yard/order/inventory/scale state transitions
TMS appointment, planning, assignment, Loader execution, delivery/dispatch, booking/transport context inventory ledger or physical yard authority
YMS yard location, movement, queue, claim, physical placement and closing handoff delivery or commercial-order completion
WMS / Inventory lots, balances, ledger, placement, adjustment, warehouse review/reconciliation transport execution or commercial document authority
OMS / Orders purchase/sales agreements, order lines, demand, booking/allocation handoffs physical Scale readings or Yard occupancy
Scale scale session, readings, ticket, correction/void and accepted weight purchase/sales/yard owner finalization
BMS / Billing transaction, rate, invoice, QBO and financial evidence physical process completion
Documents / Reports source-backed projection, file, template and export underlying source mutation unless an explicit command owns it
Integrations provider-specific translation and effect execution core business completion policy

Module placement must follow authority, not the page where a button happens to appear.


8. Core Operational Value Streams

8.1 CTC execution-first value stream

flowchart LR
    Intake[Email / Manual Appointment]
    Plan[Inbound Planning]
    Assign[Assignment]
    Loader[Loader Execution]
    Review[Final Loading Review]
    Adjust[Source / Leftover Adjustment]
    Inventory[Inventory / Warehouse]
    Yard[Yard Queue / Physical Move]
    Driver[Driver Delivery]
    Billing[Billing / Documents / Providers]

    Intake --> Plan
    Plan --> Assign
    Assign --> Loader
    Loader --> Review
    Review --> Adjust
    Review --> Inventory
    Adjust --> Review
    Inventory --> Yard
    Loader --> Yard
    Yard --> Driver
    Driver --> Billing
    Inventory --> Billing

Non-implication rules:

Appointment accepted != Loader assigned
Loader assigned != work started
Loader complete != Final Loading Review confirmed
Review confirmed != inventory adjustment completed
Inventory ready != Yard move completed
Yard complete != Driver delivery complete
Local billing complete != QBO/file/email complete

8.2 MK order-first value stream

flowchart LR
    Commercial[Commercial Purchase / Sales]
    Inbound[Inbound Purchase]
    Outbound[Outbound Sales]
    Booking[Booking / Equipment]
    Scale[Conditional Physical Scale]
    Lot[Inventory Lot]
    Allocation[Inventory Allocation]
    Cost[Cost / Rate]
    Docs[Documents / Outputs]
    Trade[Trade Summary]

    Commercial --> Inbound
    Commercial --> Outbound
    Inbound --> Scale
    Inbound --> Lot
    Outbound --> Booking
    Lot --> Allocation
    Outbound --> Allocation
    Booking --> Scale
    Outbound --> Cost
    Booking --> Docs
    Inbound --> Docs
    Outbound --> Docs
    Inbound --> Trade
    Outbound --> Trade
    Allocation --> Trade
    Cost --> Trade

Scale and document outputs are conditional children, not mandatory universal states.


9. Data Domain Map

The detailed data contract is in DATA_AUTHORITY_AND_STATE_RECONSTRUCTION_MAP.md. This section shows the major domains.

flowchart TB
    Platform[T_CLIENT / T_USER / T_ROLE / T_MENU / T_MODULE / T_TENANT_CONFIG]
    Master[T_COMPANY / T_COMMODITY / T_MASTER]
    TMS[T_TRANSLOAD / T_LOADING_PLANNER / T_STAFF_TIME_EVENT / T_DELIVERY / T_BOOKING / T_DRIVER_LOG]
    YMS[T_YARD_LOCATION / T_YARD_DISPATCH_QUEUE / T_EQUIPMENT / T_EQUIPMENT_LOAD]
    WMS[T_INVENTORY_LOT / T_INVENTORY_LOT_LEDGER / T_WAREHOUSE_LOCATION / T_WAREHOUSE_GRID]
    OMS[T_COMMERCIAL_ORDER / T_COMMERCIAL_ORDER_ITEM / T_LOAD / T_LOAD_ITEM / T_LOAD_ALLOCATION]
    Scale[T_SCALE_TICKET / T_SCALE_TICKET_EVENT]
    Billing[T_TRANSACTION / T_TRANSACTION_LIST / T_BILLING_PRESET / rates]
    Files[T_FILE]
    Mail[T_MAIL_MESSAGE / T_MAIL_REQUEST_ITEM / mailbox state]
    Audit[T_OPERATION_EVENT / T_PROCESS_TRANSITION_AUDIT family]

    Platform --> Master
    Platform --> TMS
    Platform --> YMS
    Platform --> WMS
    Platform --> OMS
    Platform --> Scale
    Platform --> Billing
    TMS --> YMS
    TMS --> WMS
    OMS --> WMS
    OMS --> TMS
    OMS --> Scale
    TMS --> Scale
    TMS --> Billing
    OMS --> Billing
    Files --> TMS
    Files --> Billing
    Mail --> TMS
    Audit --> TMS
    Audit --> YMS
    Audit --> WMS
    Audit --> OMS

Data reconstruction rules

  • CLIENT_ID is the current local tenant key; portable tenant identity is a future mapped UUID.
  • Every tenant-owned read/write is tenant-scoped.
  • Numeric local IDs and durable UUIDs have different responsibilities.
  • Soft delete and active-row filters must be explicit.
  • Authoritative state and compatibility mirrors must be identified separately.
  • Audit/evidence is not business approval.
  • A derived report does not become a mutation authority.
  • Provider identifiers and local identifiers require a reconciliation contract.
  • PostgreSQL redesign must preserve business identity, state, correction and audit semantics rather than mechanically copying MySQL quirks.

10. Priority State Machines

10.1 Inbound execution compatibility state

stateDiagram-v2
    [*] --> SCHEDULED
    SCHEDULED --> PRE_PLANNED: optional pre-plan
    SCHEDULED --> ARRIVED: Check In
    PRE_PLANNED --> ARRIVED: Check In
    ARRIVED --> AUTO_PLANNED: Plan saved/applied
    AUTO_PLANNED --> DOCKED: Confirm assignment
    DOCKED --> UNLOADING: Start unload
    DOCKED --> TRANSLOADING: Start transload/reload
    UNLOADING --> UNLOADED: Complete unload
    TRANSLOADING --> TRANSLOADED: Complete transload/reload
    UNLOADED --> SPARE: approved Office path
    SCHEDULED --> CANCELLED: cancel/no-show path
    PRE_PLANNED --> CANCELLED

Important limitations:

  • UI sequence is not proof of one universal server-enforced transition graph.
  • Planner job state and transload state are related but distinct.
  • Undo and completion compensation are not equivalent.

10.2 Planner / Loader job state

stateDiagram-v2
    [*] --> SCHEDULED
    SCHEDULED --> STARTED: Loader Start
    STARTED --> FINISHED: Complete
    STARTED --> SCHEDULED: Undo compensation / retry preparation
    SCHEDULED --> CANCELED: Plan delete / release / cancel

The target model must separate assignment, queue order, accepted actor, job attempt and immutable staff-time evidence.

10.3 Final Loading Review

stateDiagram-v2
    [*] --> PENDING
    PENDING --> PENDING: readiness/source/weight data changes
    PENDING --> CONFIRMED: Confirm / Bulk row success
    CONFIRMED --> PENDING: Reopen

Reopen changes review state. It does not reverse inventory ledger movement or operational completion.

10.4 Yard queue

stateDiagram-v2
    [*] --> QUEUED
    QUEUED --> SCHEDULED: Office schedule
    SCHEDULED --> CLAIMED: Yard Driver claim
    CLAIMED --> SCHEDULED: Unclaim
    CLAIMED --> COMPLETED: Physical move/closing complete
    QUEUED --> CANCELLED: Office cancel
    SCHEDULED --> CANCELLED: Office cancel

Physical Yard occupancy is separately authoritative in T_YARD_LOCATION.

10.5 Driver delivery

stateDiagram-v2
    [*] --> SCHEDULED
    SCHEDULED --> DISPATCHED: Start
    DISPATCHED --> DELIVERED: Finish
    DISPATCHED --> TROUBLE: Trouble
    DELIVERED --> DISPATCHED: Undo command
    TROUBLE --> DISPATCHED: Undo command

Undo does not automatically compensate photo, equipment, Yard, parking or provider effects.


11. Command, Query And Effect Model

The detailed catalog is in INTERFACE_INTEGRATION_AND_EFFECT_CATALOG.md.

Application contract shape

Query
- actor/tenant context
- filter/identity
- freshness and authorization
- typed result

Command
- actor/tenant context
- stable command/request identity
- input DTO
- validation and state predicate
- one transaction owner
- committed result/readback
- effect intents
- error and recovery semantics

Effect
- local intent/outbox identity
- provider/file/device target
- idempotency
- attempt/result
- retry/backoff
- reconciliation
- manual recovery

Representative capability commands

Capability Target command Primary authoritative writes Separate effects
Assignment AssignLoader planner assignment/order Telegram notification
Loader execution StartLoaderJob, CompleteLoaderJob transload + planner + staff evidence under defined boundary Telegram, downstream operation events
Workforce ClockInStaff, ClockOutStaff, StartBreak, EndBreak staff event and approved local assignment release QuickBooks Time
Final Review ConfirmFinalLoadingReview, ReopenFinalLoadingReview review fields and immutable transition evidence none or notification only
Bale adjustment ApplySourceLot, CreateLeftoverLot, VoidInventoryAdjustment lot/ledger/placement report/event notification
Yard ClaimYardWork, CompleteYardMove queue + location + approved mirrors operation event
Pull Out RecordClosing, CompletePullOut or resumable orchestration scale/closing checkpoint then Yard queue/location file/provider effects as separate owners
Driver StartDelivery, FinishDelivery, RequestParking, ConfirmParking delivery/equipment/Yard checkpoints Telegram / geolocation event
Billing ConfirmLocalInvoice, SendInvoiceToQbo local transaction and provider reconciliation separately QBO, file, email
Allocation AllocateInventory allocation and lot/demand balance under one predicate audit/report events

Do not build a target /api/table-mutation contract.


12. UI Reconstruction Map

Current operational surfaces

Surface Primary user outcome Current owner inputs Target reconstruction requirement
Inbound Planning turn arrived work into an executable plan transload/planner/Yard/equipment/master data React workspace with explicit planning query/commands and role-safe actions
Assignment Board assign and order Loader work planner, Loader roster, queue status focused assignment UI; Telegram shown as separate result
Inbound Loader personal current/next work, Clock/Break, Start/Complete planner/transload/staff/file/warehouse mobile-first React UI; personal actor enforced server-side
Loader Timeline review/correct staff/job evidence staff events + planner context separate manager query/correction commands
Final Loading Review accept or reopen reconciliation checkpoint transload metrics + review fields + inventory evidence dedicated page/capability, not generic inventory mutation
Inventory Adjustment Source/Leftover/void/reversal lot/ledger/placement explicit inventory commands and audit lineage
Yard Dispatch plan and monitor Yard queue queue/location/equipment Office planning UI
Yard Instruction claim and physically execute one Yard job queue/location personal Yard Driver UI
Yard Closing save closing/scale checkpoint and finish Pull Out scale ticket + queue resumable checkpoint UI
Driver workday and assigned delivery driver log/delivery/files/Yard/parking personal mobile UI with independent effect/readback states
Billing / QBO local invoice and provider close transaction/rate/file/provider local and external checkpoints displayed separately
MK Orders / Booking / Allocation / Scale order-first commercial execution OMS/TMS/WMS/Scale profile-driven React workspaces without customer forks

Shared React component families

  • page/workspace shell;
  • authenticated tenant/profile context;
  • role/capability-aware action boundary;
  • queue/list/card/table states;
  • status badge and state history;
  • form field contract and validation summary;
  • exact readback panel;
  • partial-result/recovery banner;
  • file/evidence panel;
  • provider-effect status;
  • timeline/audit panel;
  • mobile current-work card;
  • accessible modal/drawer only where page context cannot hold the action safely.

Shared components must not hide process-specific state or validation inside presentation utilities.


13. Integration Reconstruction

Integration Local owner Required target behavior
Gmail appointment intake mail/request + TMS appointment process ingest identity, idempotent request items, operator review, draft/reply outcome, reconciliation
Telegram assignment/break/driver/operation notification owners local business commit first where appropriate, notification intent/result, safe retry without repeating business command
QuickBooks Online BMS invoice/provider process local invoice identity, provider request/result, search/reconcile, no blind resend
QuickBooks Time workforce event process local staff-time remains source of truth; provider sync independently observable and retryable
AI extraction owning document/intake capability source file/prompt/model/result provenance, human review, no direct uncontrolled mutation
File storage shared file service plus owning process link object identity, link identity, content metadata, readable result, deletion/retention policy
Scale/device input Scale owner reading provenance, accepted/corrected/voided weight, unit conversion, owner-process finalization
Control Tower platform deployment/config publication asynchronous published context, no per-request business dependency

A provider adapter must not return a generic success that erases the distinction between local intent, provider acceptance and final reconciliation.


14. Deployment Reconstruction

Current general topology

flowchart LR
    User[Users]
    Proxy[Apache / TLS / routing]
    PHP[PHP application]
    DB[(MySQL)]
    File[File storage]
    Provider[External providers]

    User --> Proxy
    Proxy --> PHP
    PHP --> DB
    PHP --> File
    PHP --> Provider

Target Shared SaaS / Dedicated-compatible topology

flowchart TB
    User[Users]
    Proxy[Reverse proxy / TLS]

    subgraph Deployment[One deployment image per environment]
        Web[Next.js Web/API]
        Worker[Node Worker]
    end

    DB[(MySQL initially)]
    Cache[Optional shared cache / queue backend]
    Files[Object/file storage]
    Providers[Providers / devices]
    Obs[Logs / metrics / traces]

    User --> Proxy
    Proxy --> Web
    Web --> DB
    Web --> Cache
    Web --> Files
    Web --> Obs
    Worker --> DB
    Worker --> Cache
    Worker --> Files
    Worker --> Providers
    Worker --> Obs

Deployment invariants

  • the same application source and image support Shared SaaS and Dedicated modes;
  • environment, deployment and tenant configuration are externalized;
  • secrets are never committed;
  • web nodes are replaceable and do not own durable jobs in memory;
  • background retries survive restart;
  • multi-instance cache, Server Action encryption and deployment identity are coordinated if used;
  • DB and application region/latency are considered;
  • release and rollback identify exact source, schema/config compatibility and deployed revision;
  • backup/restore is independently documented and tested before database migration.

15. Rebuild And Migration Sequence

sequenceDiagram
    participant Docs as Accepted Process/Data/Interface Docs
    participant PHP as Current PHP Writer
    participant Next as React + Next.js
    participant App as TypeScript Application
    participant DB as MySQL
    participant Worker as Node Worker
    participant User as Target Role

    Docs->>Next: Define selected capability packet
    Next->>App: Implement query contract
    App->>DB: Read current authority
    User->>Next: Compare read-only result with current page

    alt Read parity accepted
        Docs->>App: Authorize one command cutover packet
        PHP->>DB: Remains sole writer until cutover
        Next->>App: Shadow validation / no write
        App->>DB: Reread current result

        Docs->>Next: Activate new command for bounded cohort
        User->>Next: Execute command
        Next->>App: Call typed command
        App->>DB: Conditional transaction as sole writer
        App->>Worker: Persist effect intent after commit
        App-->>Next: Exact committed readback
        Next-->>User: Visible result and next action

        alt Rollback required
            Next-->>User: Disable new command entry
            PHP->>DB: Resume legacy writer from current DB state
            Note over PHP,DB: Do not replay completed business or provider effects
        else Accepted and stable
            Docs->>PHP: Prove source and runtime caller-zero
            PHP-->>Docs: Retire old route/helper/page for capability
        end
    else Read parity rejected
        Next-->>Docs: Record discrepancy; do not enable write
    end
  1. shared platform context and read-only query foundations;
  2. read-only operational dashboards and lists;
  3. bounded master-data command;
  4. assignment command without physical completion;
  5. Final Loading Review individual Confirm/Reopen;
  6. Yard claim/non-Pull completion;
  7. Loader Start/Complete with evidence and downstream handoffs;
  8. worker-based Telegram/QB Time/provider effects;
  9. Pull Out Closing resumable orchestration;
  10. Driver Finish/Parking;
  11. billing/QBO/file/email;
  12. MK commercial/order/booking;
  13. allocation and Scale;
  14. capability caller-zero and PHP/KJDatabase retirement;
  15. PostgreSQL transition under P11.

16. Capability Acceptance Checklist

A rebuilt capability is not accepted because a page renders or an endpoint returns 200.

Product and operator result

  • [ ] intended role reaches the normal entry;
  • [ ] current context is visible before action;
  • [ ] minimum required input is clear;
  • [ ] one primary action produces the intended business result;
  • [ ] exact authoritative result is visible after reread;
  • [ ] next owner/action is explicit;
  • [ ] mobile/accessibility requirements are met where applicable.

State and data

  • [ ] tenant isolation;
  • [ ] state predicates and invalid transitions;
  • [ ] authoritative record versus mirrors;
  • [ ] stable ID and correlation;
  • [ ] soft delete/retention/audit;
  • [ ] correction/Reopen/Undo/Void/Reversal lineage;
  • [ ] unit/precision/rounding where applicable.

Failure and recovery

  • [ ] duplicate click/request;
  • [ ] stale UI state;
  • [ ] timeout before known result;
  • [ ] local partial success;
  • [ ] provider/file/device partial success;
  • [ ] physical/system mismatch;
  • [ ] manual recovery and escalation;
  • [ ] rollback without replaying completed effects.

Migration

  • [ ] current and target read parity;
  • [ ] one writer;
  • [ ] feature/capability cutover selector;
  • [ ] legacy compatibility documented;
  • [ ] target-role verification;
  • [ ] observation period;
  • [ ] source and runtime caller-zero;
  • [ ] Wiki/runbook current;
  • [ ] old entry retirement.

17. Documentation Gap Register

The following remain insufficient for a complete rebuild and must be developed in P6/P5/P7/P8/P12 work.

Platform foundation

  • exact role/capability matrix across Client 1 and Client 2;
  • canonical tenant/profile/capability resolution fields;
  • session/impersonation and future Next.js auth bridge;
  • complete menu/page/API ownership matrix;
  • audit/evidence retention and operator access;
  • file storage lifecycle and deletion matrix;
  • deployment/config publication and rollback details.

CTC execution

  • approved decomposition and stable child process IDs for Planning, Assignment, Loader and Workforce;
  • multi-Loader policy;
  • Clock Out with active job/open Break policy;
  • Break approval/notification/expiry policy;
  • Loader completion server-side evidence rules;
  • Final Review role, weight, reason and Reopen policy;
  • Yard claim uniqueness, Pull Out recovery and queue-after-clear idempotency;
  • Driver Undo/parking/provider compensation policy.

Billing and providers

  • local transaction completion versus QBO/file/email matrix;
  • durable provider intent/result identities;
  • no-blind-retry procedures;
  • reconciliation and manual recovery owners;
  • financial correction/delete policy.

MK order-first

  • parameterized field contracts replacing client-specific branches;
  • Commercial/Inbound/Outbound/Booking state and role policy;
  • allocation reversal/concurrency;
  • Scale stage/finalization/device/correction;
  • derived report freshness and attribution;
  • document output durability policy.

Target application

  • package/module directory design after P5 boundaries are accepted;
  • auth/session/tenant bridge;
  • error taxonomy;
  • outbox/worker technology and operation;
  • observability and support tooling;
  • deployment promotion and rollback for web + worker + schema/config;
  • MySQL-to-PostgreSQL data type, constraint, sequence and failback plan.

18. Required Follow-On Documents

Each remaining process family should produce:

source reconciliation
+ process/policy contract
+ data/state diagram
+ command/query/effect catalog
+ sequence and recovery diagrams
+ operator runbook
+ Wiki projection
+ migration/parity/cutover packet
+ accepted test and observation matrix

The next full packet should be CTC Billing / QBO / Files / Email because it is the clearest input to the future worker/outbox and provider-reconciliation architecture.


19. Rebuild Definition Of Done

The documentation set is sufficient for a capability rebuild when a new team can implement the capability and explain every consequential behavior without asking an operator to reconstruct hidden rules from memory or reading legacy helper code.

The system rebuild is complete only when:

all in-scope capabilities have accepted packets
+ React/Next.js/TypeScript/worker implementation matches them
+ live roles and profiles pass normal/recovery acceptance
+ operational Wiki and runbooks are current
+ legacy writers and callers are removed
+ MySQL state is stable
+ later PostgreSQL transition is separately proven

Until then, this blueprint is the assembly map and gap register for deliberate migration.

---

Source: docs/reconstruction/CTC_SYSTEM_REBUILD_BLUEPRINT.md — ctc repository · This page is an English translation of the source document. Identifiers, file paths and code symbols are unchanged.