Skip to content

CTC Billing, QBO, Files And Email Capability Rebuild Packet

  • Packet status: DETAILED SOURCE-RECONCILED CAPABILITY FAMILY INPUT / POLICY AND RUNTIME ACCEPTANCE INCOMPLETE
  • Operating profile: ctc-execution
  • Composite process: PROC-BMS-BILLING-CLOSE-CTC
  • Atomic process owners:
  • PROC-BMS-TRANSACTION-LIFECYCLE-CTC
  • PROC-BMS-AR-BILLING-CONFIRM-CTC
  • PROC-BMS-AR-QBO-DELIVERY-CTC
  • PROC-BMS-TRANSACTION-DOCUMENT-CTC
  • PROC-TMS-BOL-EMAIL-CTC
  • PROC-TMS-PACKING-LIST-EMAIL-CTC
  • Source baseline: qa@8fbe3529792db8b6dcdc18abbea8e52ccebc68a4
  • Source reconciliation: CTC_BILLING_QBO_FILES_EMAIL_RECONCILIATION.md
  • Policy decisions: CTC_BILLING_QBO_FILES_EMAIL_POLICY_DECISION_MATRIX.md
  • Parity/cutover: CTC_BILLING_QBO_FILES_EMAIL_PARITY_AND_CUTOVER_MATRIX.md
  • Diagrams: CTC_BILLING_QBO_FILES_EMAIL_SEQUENCE_DIAGRAMS.md
  • Operator runbook: CTC_BILLING_QBO_FILES_EMAIL_OPERATOR_RUNBOOK.md
  • Wiki projection: CTC_BILLING_QBO_FILES_EMAIL_WIKI_PROJECTION_PACKET.md
  • Packet owner: P6 process/effect semantics with P5/P7/P8/P12/P11 implementation, UI, knowledge and migration handoff.
  • Effect boundary: documentation only; no current Runtime, schema, business data, QBO, Gmail, file object, Wiki DB, deployment or Production action is authorized.

1. Capability Family Outcome

1.1 Business problem

CTC must create and review local AP/AR accounting records, optionally create container AR invoices, optionally deliver them to QuickBooks Online, associate readable documents, send operational BOL/Packing List emails, and close the operating day without confusing one checkpoint for another.

The system must prevent or make recoverable the highest-risk failures:

  • duplicate local financial records after retry or concurrent confirm;
  • duplicate QuickBooks invoices after provider-created/local-save-uncertain results;
  • lost or duplicate file objects/links after partial upload/registration/delete;
  • duplicate Gmail messages after timeout or multipart partial results;
  • a false single complete status that hides unresolved provider/file/email work.

1.2 Required user-visible outcome

For each business item, an authorized Office/Billing operator can determine:

  1. whether a local transaction exists and which source/account/company it represents;
  2. whether local AR invoice lines were reviewed and committed;
  3. whether QBO delivery is not requested, pending, in progress, synced, failed or unknown;
  4. whether each intended document object is stored, linked and readable;
  5. whether BOL email is ready, sent, failed or unknown;
  6. whether every intended Packing List target/part is sent, failed or unknown;
  7. what completed, what did not complete, and which owner/action is next;
  8. what must be reread before any retry or correction.

1.3 Explicit non-goals

This packet does not authorize:

  • one universal Billing/Document status column;
  • a generic finance workflow engine;
  • copying current table-mutation APIs into TypeScript;
  • clearing QBO fields to force resend;
  • retrying an email batch because one part failed;
  • deleting a stored object because one link is removed without reference review;
  • using username, numeric tenant ID or customer name as target policy;
  • React components, Server Components, Route Handlers or Server Actions owning financial/provider SQL or business state;
  • simultaneous React/Next.js, provider-worker and PostgreSQL big-bang migration.

2. Current Truth And Target Truth

Statement Current truth Target direction
Billing close is one stored state No Remains a composite reconciliation, not child authority.
Generic transaction form is semantic No; schema-shaped mutation is used in part Explicit commands/queries.
Generic close has prior-state/QBO guard Not proven Required state/version/provider predicate.
AR confirm is locally atomic across request items Yes Preserve unless an explicit policy changes it.
AR preview is mandatory No Server recomputation/fingerprint must guarantee consistency.
Active booking/container AR uniqueness is proven No Required target constraint/serialized command.
QBO delivery is part of AR local DB transaction No Remains separate durable effect.
Current QBO sender supports provider search/idempotency No Required target reconciliation strategy.
SYNCING means provider invoice absent No First-class unknown/in-flight state.
File object and business link are one concept Current implementation partially conflates them Target separates object/link/readability/cleanup.
BOL send has durable local ledger No Target email intent/attempt/reconciliation.
Packing target-part sends are durable/resumable No Target persists each target/part identity/result.
Current Wiki content was read in this packet No P8 named-slug review required.
Current Runtime/provider behavior was executed by this packet No Controlled verification remains required.

3. Actors, Roles And Capabilities

3.1 Actor matrix

Actor Normal responsibility Allowed future actions Read visibility Correction/recovery Prohibited behavior
Office/Billing operator review source work, local transactions, AR candidates and child checkpoints create/edit/close eligible local transactions; preview/confirm AR; request eligible effects; attach files; review daily close authorized tenant/account/source/customer records correct eligible local state; carry/escalate unresolved child infer QBO/email/file completion; replay unknown effects blindly
Accounting manager approve financial corrections and provider reconciliation all approved Billing actions plus explicit correct/void/reconcile commands tenant/accounting scope authorize synced correction/void/manual reconciliation raw-update provider IDs/status or delete financial evidence
Operations Office send operational BOL/Packing email and verify source/recipients request BOL/Packing sends, review target/part results assigned/authorized source records retry only reconciled missing effect; fix recipient/source evidence resend whole batch after partial result without reconciliation
File/document operator upload/link/read/unlink authorized transaction documents object upload, link, unlink under policy target transaction/file metadata reconcile object/link/readability; request cleanup delete shared object or bypass retention/reference check
QBO effect worker/operator deliver and reconcile provider invoices claim intent, search/create, persist attempt/result effect/provider/local group evidence retry/reconcile/manual review under policy create without intent; reset unknown state solely by age
Gmail effect worker/operator deliver and reconcile BOL/Packing target-parts claim intent/part, search/send, persist provider result recipient/content/attachment/effect metadata retry exact unresolved intent/part full replay of known successes
Support/migration operator investigate request/effect state and cut over one writer read state/evidence, operate approved selector/rollback cross-component support data in approved tenant reconcile unknown result, execute approved failback dual-write, fabricate local/provider success, replay physical/provider effects
Super Admin technical/platform support under explicit tenant/subject only approved support capabilities effective-tenant scoped route to business owner use admin visibility as accounting approval or email recipient policy

3.2 Proposed semantic capabilities

These are target names. Current role/menu rows require mapping and testing.

bms.transaction.view
bms.transaction.create
bms.transaction.edit
bms.transaction.close
bms.transaction.correct
bms.transaction.delete-draft
bms.transaction.void

bms.ar-billing.view
bms.ar-billing.preview
bms.ar-billing.confirm
bms.ar-billing.correct

bms.qbo.view
bms.qbo.request-delivery
bms.qbo.reconcile
bms.qbo.retry
bms.qbo.correct

files.transaction.view
files.transaction.upload
files.transaction.link
files.transaction.unlink
files.object.reconcile
files.object.cleanup

tms.bol-email.view
tms.bol-email.send
tms.bol-email.reconcile

tms.packing-email.view
tms.packing-email.send
tms.packing-email.reconcile

operations.billing-close.review
operations.billing-close.disposition

3.3 Authorization rules

  • Tenant and actor derive from authenticated server context.
  • Browser-supplied tenant, billing company, source, transaction, file or provider IDs are inputs to validate, never authority.
  • Menu visibility does not grant API or record mutation.
  • Every mutation rereads the exact same-tenant record and current state.
  • Provider-effect retry requires effect identity and current reconciliation state.
  • Financial correction and provider correction are different capabilities.
  • File object cleanup is not implied by file-link unlink permission.
  • BOL/Packing send authority does not grant recipient-master editing.
  • Foreign-tenant identifiers return safe not-found/forbidden behavior without data disclosure.

4. Process Trigger, Completion And Non-Implication

4.1 Generic transaction trigger

A reviewed source record or manual accounting need requires a local AP/AR transaction.

4.2 Generic transaction completion

intended transaction header
+ intended active lines
+ reviewed local status/close fields
+ exact same-tenant reread
= local generic transaction result

4.3 AR confirm trigger

An eligible booking/container candidate has one resolved billing customer, valid source/rate/preset/transaction-type inputs and no conflicting provider-protected invoice.

4.4 AR confirm completion

one intended active local container AR header/version
+ reviewed active lines
+ local provider projection READY/PENDING as applicable
+ exact header/line reread
= local container AR confirmed

4.5 QBO completion

intended QuickBooks invoice exists
+ customer/doc number/amount/content reconcile
+ every local group transaction points to provider ID
+ every local group transaction/provider projection is SYNCED
= QBO invoice delivery reconciled

4.6 File completion

stored object exists
+ every intended business link exists
+ every intended link resolves to readable object
= transaction document attached

4.7 BOL email completion

intended source/reference/recipient/subject/attachment set
+ one reconciled Gmail provider message
= BOL email sent

4.8 Packing List email completion

for every intended target
+ for every immutable generated part
+ one reconciled Gmail provider message
= Packing List batch complete

4.9 Daily close completion

The daily composite has no universal database completion. The operator verifies or carries each applicable child with exact evidence and owner.

4.10 Non-implication catalog

Transaction created != transaction reviewed/closed
Transaction closed != paid
Transaction closed != AR container invoice confirmed
AR READY != QBO sent
QBO HTTP success != local SYNCED
QBO ERROR != provider invoice absent
Object uploaded != business link registered
T_FILE link exists != object readable
File attached != email sent
BOL source complete != BOL email sent
Packing target CUSTOMER sent != INSPECTOR sent
Packing Part 1 sent != all parts sent
Provider message sent != daily close complete
Daily close carried != child process completed

5. End-To-End Operator Flow

Step ID Actor Entry/topic Verify Action Visible result Authoritative reread Next owner
BILL-STEP-010 Office/Billing Billing worklist/source pages tenant, account, source identity, company, date, rate classify applicable local transaction candidate/source detail source + existing transaction local transaction owner
BILL-STEP-020 Office/Billing transaction list/form exact header/lines and compatibility of selected rows create/edit/close eligible local rows local result message every selected header/line AR/file/email child as applicable
BILL-STEP-030 Office/Billing AR Billing booking/container/customer/warnings/rates/preset/existing state preview reviewed invoice calculated lines/total authoritative preview context same operator
BILL-STEP-040 Office/Billing AR Billing preview/source still valid confirm local invoice once local invoice UUID/status header + active lines QBO owner if applicable
BILL-STEP-050 Office/Billing/QBO AR Billing/QBO reconciliation local group, mapping, existing provider/local state request or review QBO delivery per-group state effect/provider/local rows QBO support or next child
BILL-STEP-060 File operator transaction file action target transactions, object, type/name/retention upload and link per-target file result object + links + readability document consumer
BILL-STEP-070 Operations Office Transload BOL action source, recipient, subject, scale/files request send once sent/failed/unknown provider/Sent evidence Billing close
BILL-STEP-080 Operations Office Booking Packing List source/options/targets/recipients/parts request batch once per-target/part result provider messages per part Billing close
BILL-STEP-090 Office/Billing daily close topic/worklist all applicable child identities verify/carry/block each checkpoint explicit disposition and owner child records/effects accountable close owner

6. State Models

6.1 Generic local transaction states

Current source uses table fields and status values not fully normalized into one versioned state machine. Target semantic states:

DRAFT
REVIEWED
CLOSED
CORRECTION_REQUIRED
VOIDED
DELETED_DRAFT

PAID, QBO_SYNCED, FILED or EMAILED are not generic transaction states.

stateDiagram-v2
    [*] --> DRAFT: Create local transaction
    DRAFT --> REVIEWED: Review/validate
    REVIEWED --> CLOSED: CloseTransactions
    DRAFT --> DELETED_DRAFT: Delete draft
    REVIEWED --> DRAFT: Approved edit
    CLOSED --> CORRECTION_REQUIRED: Error identified
    CORRECTION_REQUIRED --> CLOSED: Approved correction/version
    CLOSED --> VOIDED: Approved accounting void

Current compatibility may not store every semantic state distinctly. Target application policy owns the transition meaning.

6.2 Local container AR states

NO_INVOICE
READY_TO_PREVIEW
PREVIEWED (derived/non-durable unless tokenized)
LOCAL_READY
PROVIDER_PENDING
PROVIDER_SYNCED
LOCAL_CORRECTION_REQUIRED
PROVIDER_CORRECTION_REQUIRED
VOIDED

Current QBO_SYNC_STATUS='READY' corresponds to local provider-ready projection, not full invoice completion.

6.3 QBO effect states

Target:

PENDING
CLAIMED
PROVIDER_ACCEPTED
SYNCED
FAILED_RETRYABLE
FAILED_FINAL
UNKNOWN_PROVIDER_RESULT
MANUAL_REVIEW
CANCELLED_BEFORE_ATTEMPT

Current compatibility mapping:

Current Target interpretation
blank/NOT_SYNCED no proven effect or legacy not-synced
READY eligible/pending local delivery
SYNCING claimed/in-flight/unknown; requires attempt evidence
SYNCED + provider ID local reconciled projection
ERROR handled local error; provider result can still be unknown

6.4 File object state

UPLOADING
STORED
READABLE
UNREADABLE
ORPHAN_CANDIDATE
CLEANUP_ELIGIBLE
CLEANUP_FAILED
DELETED
HELD
PENDING_LINK
ACTIVE
UNLINKED
INVALID_TARGET
BROKEN_OBJECT

6.6 Email batch/target/part state

DRAFT
PENDING
CLAIMED
SENT
FAILED_RETRYABLE
FAILED_FINAL
UNKNOWN_PROVIDER_RESULT
MANUAL_REVIEW
SUPERSEDED_BY_NEW_VERSION

A Packing batch is COMPLETE only when every required target-part is SENT or intentionally not applicable through approved disposition.

6.7 Composite disposition

Human/derived only:

VERIFIED
CARRIED
NOT_APPLICABLE
BLOCKED
UNKNOWN

This does not change child states.


7. Data Contract

7.1 Current authoritative records

Record Identity Owns Important relationships
T_TRANSACTION local ID; UUID where migrated/current AR local AP/AR header, source relation, close fields, container billing and QBO projection active T_TRANSACTION_LIST, source record, billing company, preset, provider projection
T_TRANSACTION_LIST local ID; UUID where migrated/current AR one charge/line and source/rate provenance transaction header, transaction type, source/rate record
T_BILLING_PRESET UUID + tenant customer-specific charge calculation configuration billing company, charge definitions
T_COMPANY ID/UUID + tenant billing company and QBO customer mapping, email recipient configuration through related current models preset, transaction, QBO, email
T_TRANSACTION_TYPE ID/UUID + tenant service/transaction type and QBO item mapping transaction line
T_FILE ID/UUID + tenant current combined object/link metadata target table/ID, storage object
QuickBooks invoice provider ID provider accounting representation local transaction group
Gmail message provider message ID/thread ID provider send evidence BOL or Packing effect intent/part
Tenant config key + tenant QBO credentials/endpoints/timeouts and integration config provider adapter, not business invoice state

7.2 T_TRANSACTION consequential field dictionary

Exact SQL types and all legacy fields require schema reread before implementation.

Field Meaning Validation/source Mutable boundary Audit/recovery
ID local relational identity generated, tenant-scoped lookup immutable current API/detail references
UUID durable transaction identity canonical UUID for migrated/new paths immutable target command/effect identity
CLIENT_ID tenant scope server context only immutable every query/write predicate
TYPE AP or AR allowlist normally immutable after create source/account correction requires explicit command
COMPANY_ID company represented by transaction same-tenant active company draft/correction policy reread/audit
BILLING_COMPANY_ID payer/payee/billing company same-tenant active company draft/approved close correction batch compatibility key
BILLING_ADDRESS snapshot used for invoice derived/reviewed from company or input version/correction policy historical snapshot must be retained
REFERENCE_NUMBER business reference bounded source/user value draft/correction duplicate/reconciliation evidence
ISSUE_DATE local invoice/transaction issue date business date policy draft/correction timezone/cutoff evidence
DUE_DATE due date validated date draft/correction provider payload
INVOICE_NUMBER local/provider document number bounded, current AR allows max 21 in UI protected after sync unless correction QBO grouping/search key
CHECK_NUMBER local close/payment reference bounded business input close/correction not provider sync proof
COMPLETE_DATE local close date business-date policy close/correction local completion only
STATUS current local status current compatibility values need exact inventory state command only no generic arbitrary write in target
REMARK operator note bounded safe text allowed states not structured correction reason
RELATED_TABLE_NAME source type/table compatibility server-owned mapping immutable after create pair with UUID target model
RELATED_TABLE_ID source local ID same-tenant source immutable after create legacy relation identity
RELATED_TABLE_UUID durable source UUID where available same-tenant source immutable target relation identity
BILLING_SCOPE generic/container/etc scope server/application immutable after create command selection
BOOKING_UUID booking relation for container AR same-tenant booking immutable/versioned active uniqueness key
BILLING_PRESET_UUID preset used selected/derived preset invoice version calculation provenance
QBO_INVOICE_ID provider invoice ID projection provider reconciliation only effect/reconciliation command never clear to force resend
QBO_DOC_NUMBER provider document number provider result effect/reconciliation provider search/readback
QBO_SYNC_TOKEN provider sync token/version provider result effect/reconciliation correction/update support input
QBO_SYNC_STATUS local provider projection effect state mapping effect/reconciliation only not local invoice authority
QBO_SYNCED_AT local reconciliation time server time after accepted result immutable except approved correction audit
QBO_ERROR current claim token/error compatibility current helper compatibility only target separates intent/attempt/error
CREATED_AT/UPDATED_AT/DELETED_AT lifecycle/version support server/DB lifecycle policy optimistic conflict and audit

7.3 T_TRANSACTION_LIST consequential fields

Field Meaning Rule
ID/UUID/CLIENT_ID line identity/tenant stable and same-tenant
TRANSACTION_ID parent header relation exact active parent
TRANSACTION_TYPE_ID / type UUID service/charge type same-tenant active mapping
DESCRIPTION invoice line description snapshot bounded; source/template provenance retained
QUANTITY line quantity numeric, defined unit/precision per charge
RATE unit rate decimal/currency policy
AMOUNT line total server calculation/rounding
SOURCE_TABLE_NAME charge source compatibility server/application mapping
SOURCE_TABLE_UUID durable source identity preferred target provenance
RATE_SOURCE_TABLE rate source compatibility explicit allowlist
RATE_SOURCE_UUID durable rate identity provenance
BILLING_PRESET_UUID preset version/source calculation provenance
LINE_ORIGIN generated/manual/source classification allowlist and audit
lifecycle fields active/version history current rewrite soft-deletes old lines; target version relation required

7.4 T_BILLING_PRESET contract

Field Meaning
UUID durable preset identity
PRESET_NAME display name; current UI can derive customer name
BILLING_COMPANY_UUID owning customer mapping
IS_DEFAULT current compatibility flag; customer-specific selection policy must remain explicit
ACTIVE preset applicability
PRESET_JSON versioned charge calculation configuration

Current normalized preset structure:

{
  "invoiceGrain": "CONTAINER",
  "charges": [
    {
      "key": "TRUCKING",
      "enabled": true,
      "source": "DELIVERY",
      "rate": "DELIVERY_AR_RATE",
      "qty": "PER_DELIVERY",
      "transactionTypeUuid": "",
      "description": "{{container}} trucking",
      "fixedRate": null,
      "fixedQty": null
    }
  ]
}

Target requirements:

  • schema version;
  • charge key/source/rate/quantity allowlists;
  • customer ownership;
  • effective/version dates or immutable version relation when policy needs historical reproducibility;
  • server validation;
  • no raw arbitrary JSON execution.

7.5 Current T_FILE conceptual field contract

Exact schema varies by migration and must be reread.

Field/concept Current meaning Target classification
ID local row/link identity compatibility link identity
UUID current file row/object metadata UUID map to file-object or link UUID explicitly
CLIENT_ID tenant scope mandatory
TABLE_NAME/TABLE_ID target relation FileLink target; migrate to entity UUID
TYPE link/file usage category link type
NAME/ORIGINAL_FILENAME stored/display filename object/display metadata
PATH/URL/STORAGE storage location FileObject provider/key metadata
SIZE object size FileObject metadata
SEQUENCE display ordering FileLink presentation only
OBJECT_CLEANUP_AT where present cleanup projection cleanup result evidence
lifecycle fields active link/object compatibility separate object/link lifecycle target

7.6 Target effect records

These are conceptual target entities; physical schema is designed in P5/P12/DB work.

EffectIntent

intentUuid
tenantUuid
capability
sourceEntityType/sourceEntityUuid
idempotencyKey
payloadHash
requestedBy/requestedAt
status
notBefore
currentAttempt

EffectAttempt

attemptUuid
intentUuid
attemptNumber
claimedBy/claimedAt
providerRequestId
requestFingerprint
startedAt/finishedAt
resultStatus
safeErrorCode/safeErrorMessage
providerMetadata

EffectReconciliation

reconciliationUuid
intentUuid/attemptUuid
providerEntityId/messageId/threadId
providerDocumentNumber
matchedBy
result
reviewedBy/reviewedAt
notes/evidenceRefs

EmailTargetPart

batchUuid
version
target
partIndex/partCount
recipientSetHash
subjectHash
bodyHash
attachmentSetHash
intentUuid
FileObject:
objectUuid, tenantUuid, storageProvider, objectKey,
contentHash, size, contentType, originalName,
retention/hold/cleanup state

FileLink:
linkUuid, tenantUuid, objectUuid,
targetEntityType/Uuid, linkType, sequence, lifecycle

8. Stable Identity And Idempotency

8.1 Generic source transaction

Recommended identity:

tenant UUID
+ source entity type
+ source entity UUID
+ account AP/AR
+ semantic transaction type/scope

A duplicate create returns the existing compatible transaction or a conflict; it does not insert another header/line set silently.

8.2 Local container AR

Recommended active uniqueness:

tenant
+ BILLING_SCOPE='CONTAINER'
+ booking UUID
+ container/equipment UUID
+ active invoice generation/version

Correction creates or records version lineage; it does not erase prior invoice meaning.

8.3 QBO effect

intent UUID
+ sorted local transaction UUID set
+ customer reference
+ invoice/document number
+ currency/amount
+ immutable payload hash

Provider subject or current QBO_ERROR claim token is not durable identity.

8.4 File object

tenant
+ object UUID
+ storage provider/key
+ content hash
tenant
+ target entity UUID
+ object UUID
+ link type

8.6 BOL email

intent UUID
+ transload UUID
+ recipient-set hash
+ subject/content version
+ attachment-set hash

8.7 Packing email

batch UUID/version
+ target
+ part index/total
+ recipient-set hash
+ content/attachment hashes

9. Query Contracts

9.1 GetTransactions

Audience: Office/Billing
Input: account, source type, company, date/status/search, pagination
Scope: authenticated tenant and record capability
Sources: T_TRANSACTION + active lines/source/company projections
Output: transaction UUID/ID, account, source, company, amount, status, close/provider/file summaries
Freshness: request-time operational
Denied: safe 403/empty per accepted contract
Cache: no shared authorization-sensitive stale cache

9.2 GetTransactionDetail

Returns:

  • header and active lines;
  • source identity;
  • billing company/address snapshots;
  • local state/version;
  • QBO projection and effect identities where available;
  • file-link summaries;
  • allowed actions derived server-side;
  • correction/audit relation.

9.3 GetTransactionCloseEligibility

For requested transaction UUIDs returns:

  • current state/version;
  • account/company compatibility group;
  • provider/file constraints;
  • allowed close fields/actions;
  • exact blocking reason.

It does not mutate.

9.4 GetArBillingWorkbench

Returns one row per current candidate identity with:

  • booking/container UUID and display;
  • billing customer UUID/name;
  • source completion/readiness;
  • source transaction conflicts;
  • calculated/known amount;
  • preset/rate warning;
  • current local container AR identity/state;
  • QBO projection;
  • allowed actions.

9.5 PreviewContainerInvoice

Input:

  • booking UUID;
  • container UUID;
  • preset UUID optional;
  • proposed invoice number/group options;
  • optional selected charge overrides only where policy permits.

Output:

  • source fingerprint/version;
  • customer/address;
  • issue/due date;
  • line DTOs with source/rate provenance;
  • totals/currency/rounding;
  • warnings/blockers;
  • preview token or equivalent integrity data.

9.6 GetQboReconciliation

Input: transaction/group/intent/provider search filters.

Output:

  • immutable group identity and local transaction UUIDs;
  • local projected state;
  • current intent/attempt/reconciliation;
  • provider invoice ID/doc/amount/customer when known;
  • stale/unknown reason;
  • allowed next action.

9.7 GetTransactionFiles

Output separates:

  • object identity/metadata;
  • business link identity/type/order;
  • readability/download result;
  • retention/hold/cleanup state;
  • allowed unlink/cleanup actions.

9.8 GetBolEmailReadiness

Returns:

  • source transload UUID/reference;
  • intended recipient set and configuration source;
  • subject;
  • scale/file attachments with object identities;
  • content/attachment hash or version;
  • prior intent/attempt/result when available;
  • blocked reason and allowed action.

9.9 GetPackingEmailReadiness

Returns:

  • booking/equipment identity;
  • selected/current report options;
  • targets and recipients;
  • body/content version;
  • immutable attachment partition plan;
  • prior batch/target/part states;
  • blocked reason and allowed action.

9.10 GetBillingCloseWorklist

Returns derived items with applicable child checkpoints:

local transaction
local AR
QBO
file
BOL
Packing targets/parts

For each child:

  • identity;
  • current status/evidence;
  • freshness;
  • completion/non-implication;
  • next owner/action;
  • human disposition.

This query never writes child status.


10. Command Contracts

10.1 CreateSourceTransactions

Purpose: create local AP/AR transactions from approved source records
Actor: Office/Billing
Input: account, source type, source UUIDs, billing company when applicable
Authorization: semantic create capability + same-tenant source visibility
Validation: active sources, compatible company/account, required rates/types
Transaction: command-owned local DB transaction
Writes: headers/lines and source relations
Idempotency: source identity + account + transaction type/scope
Return: per-source created/existing/rejected plus exact transaction readback
Timeout: query by semantic identity before repeat

10.2 EditDraftTransaction

State: draft/reviewable local state only
Input: allowlisted local financial fields and lines
Conflict: provider-protected, closed/voided or stale version
Transaction: header/line update plus version/audit
Return: exact header/line readback

10.3 CloseTransactions

Actor: authorized Billing
Input: transaction UUIDs, close DTO, expected versions
Validation: same compatible account/company/value group, allowed current states, provider constraints
Transaction: conditional per-row updates under one accepted batch transaction
Return: per-row state/readback; no generic schema payload
Idempotency: repeated same intended close returns current matching result
Timeout: reread every selected UUID before repeat

10.4 CorrectLocalTransaction

Requires:

  • explicit reason code/text;
  • actor/approval where required;
  • current state/version;
  • provider/file/email impact review;
  • immutable correction/version relation;
  • exact old/new evidence.

It must not alter provider representation silently.

10.5 DeleteOrVoidTransaction

Separate meanings:

DeleteDraftTransaction
= remove/soft-delete never-finalized local draft under policy

VoidTransaction
= preserve record and record business reversal/void

RequestProviderVoid/Correction
= separate external effect capability

10.6 ConfirmContainerInvoices

Actor: Office/Billing
Input: one or more candidate DTOs + preview integrity data
Validation: source, customer, preset/rate/type, active uniqueness, existing invoice/provider state
Transaction: current accepted all-items local atomicity
Writes: header/version, active lines, provenance, optional QBO intent
Return: confirmed local invoice UUIDs and exact lines/state
Duplicate/concurrent: existing compatible result or conflict, never second active invoice
Timeout: query by booking/container active identity

10.7 CorrectLocalContainerInvoice

Policy remains open. Required target contract:

  • allowed only before provider sync or through explicit provider-aware correction;
  • records prior invoice/version and line set;
  • protects provider ID/state;
  • recalculates/revalidates source/preset/rates;
  • invalidates/supersedes pending effect intent only when safe and auditable.

10.8 RequestQboInvoiceDelivery

Actor: Billing or automatic local-confirm policy
Input: local transaction UUIDs, group mode/intent version
Validation: local eligibility, mappings, active uniqueness, no synced/in-flight duplicate
Transaction: create/reuse durable effect intent only
Return: intent/group state
Provider call: none in web command

10.9 ProcessQboInvoiceIntent

Worker command:

claim one eligible intent/attempt
-> search/reconcile prior unknown as required
-> create provider invoice only when absence/eligibility established
-> persist provider response/unknown/error
-> update reconciliation projection atomically with attempt result

10.10 ReconcileQboInvoice

Actor: worker or authorized accounting support.

Input/evidence:

  • intent/group identity;
  • provider search/reference;
  • customer/doc/amount/payload hash;
  • local transaction UUIDs;
  • provider invoice ID/token.

Possible dispositions:

SYNCED
FAILED_RETRYABLE
FAILED_FINAL
UNKNOWN_PROVIDER_RESULT
MANUAL_REVIEW

10.11 UploadFileObject

Actor: authorized document operator
Input: binary/direct-upload metadata, target-independent object request
Validation: type/content/size/tenant/storage policy
Effect: object store
Writes: FileObject metadata and upload result/intent
Return: object UUID, safe metadata, readability state
Idempotency: upload/request token and/or accepted content identity policy

The first compatibility implementation may still perform synchronous upload but must return object identity independent of link.

10.12 LinkFileToTransactions

Input: object UUID, target transaction UUIDs, link type, optional label/order
Validation: object stored/readable or accepted pending state, targets authorized
Transaction: idempotent FileLink rows
Partial batch: explicit per-target result or accepted all-or-nothing policy
Return: links + readability projection

10.13 UnlinkFileFromTransaction

  • soft-delete/deactivate one link;
  • never assume object cleanup;
  • return remaining active-link count/cleanup eligibility;
  • record actor/reason where required.

10.14 DeleteUnreferencedFileObject

Worker/privileged cleanup only:

  • no active link;
  • no retention/legal hold;
  • object identity known;
  • cleanup intent claimed;
  • storage delete result persisted;
  • retry/manual review on unknown result.

10.15 RequestBolEmail

Actor: Operations Office
Input: transload UUID and accepted content version/options
Validation: source, recipient, subject, attachments/readability, prior active intent
Transaction: persist immutable EmailIntent/target/attachment refs
Return: intent status/readiness
Provider call: worker only after migration

10.16 RequestPackingListEmail

Actor: Operations Office
Input: booking UUID, targets, weight/reference options, content version
Validation: source/equipment/recipient and immutable attachment partition plan
Transaction: persist batch/version, target and part intents
Return: per-target/part pending/current result

10.17 ProcessEmailTargetPart

Worker:

  • claim exact target/part intent;
  • reconcile prior unknown using provider headers/message IDs;
  • build/fetch immutable body and attachment object set;
  • send once when eligible;
  • persist message/thread ID and result;
  • never replay known-success parts.

10.18 ReviewBillingClose

This command, if persisted, writes only a human composite disposition referencing child identities/evidence/owner. It does not mutate child status.


11. Planned HTTP/API Adapter Contracts

Final route naming is decided during implementation. Semantic shape:

11.1 Generic transactions

GET    /api/billing/transactions
GET    /api/billing/transactions/{uuid}
POST   /api/billing/transactions/source
PATCH  /api/billing/transactions/{uuid}/draft
POST   /api/billing/transactions/close
POST   /api/billing/transactions/{uuid}/corrections
POST   /api/billing/transactions/{uuid}/void
DELETE /api/billing/transactions/{uuid}/draft

11.2 AR/QBO

GET  /api/billing/ar/workbench
POST /api/billing/ar/preview
POST /api/billing/ar/confirm
POST /api/billing/qbo/intents
GET  /api/billing/qbo/intents/{uuid}
POST /api/billing/qbo/intents/{uuid}/reconcile
POST /api/billing/qbo/intents/{uuid}/retry

11.3 Files

POST   /api/files/objects
GET    /api/files/objects/{uuid}
POST   /api/billing/transactions/files/links
DELETE /api/billing/transactions/{transactionUuid}/files/{linkUuid}
POST   /api/files/objects/{uuid}/reconcile
POST   /api/files/objects/{uuid}/cleanup

11.4 Emails

GET  /api/operations/transloads/{uuid}/bol-email/readiness
POST /api/operations/transloads/{uuid}/bol-email/intents
GET  /api/operations/bookings/{uuid}/packing-email/readiness
POST /api/operations/bookings/{uuid}/packing-email/batches
GET  /api/email/batches/{uuid}
POST /api/email/intents/{uuid}/reconcile
POST /api/email/intents/{uuid}/retry

11.5 Composite

GET  /api/operations/billing-close/worklist
POST /api/operations/billing-close/dispositions

Adapters remain thin and call application commands/queries.


12. Representative DTOs

12.1 Close transactions request

{
  "transactionUuids": [
    "17a8a0ec-7144-4cd4-aab7-000000000001",
    "17a8a0ec-7144-4cd4-aab7-000000000002"
  ],
  "close": {
    "completeDate": "2026-08-07",
    "invoiceNumber": "INV-20260807-10",
    "checkNumber": "",
    "remark": "Reviewed for August close"
  },
  "expectedVersions": {
    "17a8a0ec-7144-4cd4-aab7-000000000001": "2026-08-07T15:10:20Z",
    "17a8a0ec-7144-4cd4-aab7-000000000002": "2026-08-07T15:11:05Z"
  },
  "requestToken": "8b59f4ce-4ac7-4c4f-bf83-157b4689b78e"
}

12.2 Close response

{
  "data": {
    "requestToken": "8b59f4ce-4ac7-4c4f-bf83-157b4689b78e",
    "items": [
      {
        "transactionUuid": "17a8a0ec-7144-4cd4-aab7-000000000001",
        "result": "CLOSED",
        "status": "CLOSED",
        "completeDate": "2026-08-07",
        "updatedAt": "2026-08-07T15:20:00Z"
      }
    ]
  },
  "requestId": "..."
}

12.3 AR preview response

{
  "data": {
    "previewToken": "...",
    "sourceFingerprint": "sha256:...",
    "bookingUuid": "...",
    "containerUuid": "...",
    "billingCompany": {
      "uuid": "...",
      "name": "Customer"
    },
    "invoiceNumber": "",
    "issueDate": "2026-08-07",
    "dueDate": "2026-09-06",
    "currency": "USD",
    "lines": [
      {
        "serviceCode": "TRUCKING",
        "description": "CONT123 trucking",
        "quantity": 1,
        "unit": "DELIVERY",
        "rate": "150.00",
        "amount": "150.00",
        "sourceEntityUuid": "...",
        "rateSourceUuid": "..."
      }
    ],
    "total": "150.00",
    "warnings": [],
    "blockingErrors": []
  },
  "requestId": "..."
}

12.4 AR confirm request

{
  "requestToken": "...",
  "items": [
    {
      "bookingUuid": "...",
      "containerUuid": "...",
      "previewToken": "...",
      "sourceFingerprint": "sha256:...",
      "invoiceNumber": "INV-001",
      "qboGroupMode": "INVOICE_NUMBER"
    }
  ],
  "requestQboDelivery": true
}

12.5 QBO effect result

{
  "data": {
    "intentUuid": "...",
    "groupKey": "...",
    "status": "UNKNOWN_PROVIDER_RESULT",
    "localTransactionUuids": ["..."],
    "provider": {
      "invoiceId": null,
      "docNumber": "INV-001"
    },
    "allowedActions": ["RECONCILE"],
    "message": "The provider result is uncertain. Reconcile before retrying."
  },
  "requestId": "..."
}
{
  "objectUuid": "...",
  "transactionUuids": ["...", "..."],
  "linkType": "INVOICE_SUPPORT",
  "label": "Signed supporting document",
  "requestToken": "..."
}

12.7 Packing email batch result

{
  "data": {
    "batchUuid": "...",
    "version": 1,
    "status": "PARTIAL",
    "items": [
      {
        "target": "CUSTOMER",
        "part": 1,
        "parts": 2,
        "status": "SENT",
        "messageId": "...",
        "threadId": "..."
      },
      {
        "target": "CUSTOMER",
        "part": 2,
        "parts": 2,
        "status": "UNKNOWN_PROVIDER_RESULT",
        "allowedActions": ["RECONCILE"]
      }
    ]
  },
  "requestId": "..."
}

13. Stable Error Catalog

Code Meaning Normal response Required action
VALIDATION_ERROR request field invalid 400/422 correct input
UNAUTHENTICATED no valid session/actor 401 sign in
FORBIDDEN capability or record denied 403 stop/contact owner
NOT_FOUND record absent in current scope 404 refresh/search
STALE_RECORD expected version/state changed 409 reread exact record
INCOMPATIBLE_BATCH selected rows differ in company/account/close contract 409/422 split selection
TRANSACTION_ALREADY_EXISTS semantic source transaction duplicate 200/409 use existing result
TRANSACTION_PROVIDER_LOCKED provider-synced/protected local record 409 correction procedure
TRANSACTION_CORRECTION_REQUIRED normal edit cannot resolve closed/provider-linked issue 409 open correction flow
AR_SOURCE_NOT_READY source/rate/preset prerequisites invalid 422 correct source/input
AR_MULTIPLE_CUSTOMERS candidate resolves incompatible customers 409 split/correct source
AR_SOURCE_TRANSACTION_EXISTS source-specific AR conflicts with container AR 409 use existing owner
AR_INVOICE_ALREADY_SYNCED provider-protected invoice 409 provider-aware correction
AR_ACTIVE_INVOICE_CONFLICT active booking/container invoice race/duplicate 409 reread existing invoice
AR_PREVIEW_STALE source/preset/rate changed 409 review new preview
QBO_NOT_CONFIGURED module/credentials unavailable 503/422 platform/config owner
QBO_MAPPING_MISSING customer/item mapping missing 422 correct mapping
QBO_ALREADY_SYNCED provider/local result exists 200/409 use existing/reconcile
QBO_IN_PROGRESS active attempt owns intent 409/202 wait/reconcile
QBO_RESULT_UNKNOWN provider outcome uncertain 202/409 search/reconcile; no resend
QBO_PROVIDER_REJECTED clear provider rejection 422/502 correct and retry intent
QBO_LOCAL_RECONCILIATION_FAILED provider result exists, local save failed 500/202 reconcile provider/local
QBO_MANUAL_REVIEW automated disposition unsafe 409 accounting support review
FILE_TYPE_UNSUPPORTED content/type invalid 422 choose allowed file
FILE_OBJECT_UPLOAD_FAILED storage write failed 502/500 verify absence then retry object
FILE_OBJECT_RESULT_UNKNOWN storage outcome uncertain 202 reconcile object identity
FILE_LINK_CONFLICT same active link or incompatible target 409 use existing/correct target
FILE_OBJECT_UNREADABLE link exists but object cannot be read 409/502 reconcile storage/object
FILE_OBJECT_STILL_REFERENCED cleanup blocked by active links 409 unlink/review references
FILE_RETENTION_HOLD cleanup blocked by policy 409 retain/escalate
EMAIL_RECIPIENT_INVALID no valid recipient 422 correct recipient source
EMAIL_ATTACHMENT_UNREADABLE attachment cannot be prepared/read 422/502 reconcile file/source
EMAIL_SEND_FAILED clear provider failure/absence before acceptance 502/200 partial retry same intent when eligible
EMAIL_RESULT_UNKNOWN send may have succeeded 202/409 search/reconcile first
EMAIL_PART_ALREADY_SENT exact target-part exists 200/409 use existing result
EMAIL_BATCH_VERSION_CONFLICT source/options/partition changed 409 create new batch version
EMAIL_PARTIAL_RESULT some target-parts sent 200/207 preserve successes; reconcile unresolved
BILLING_CLOSE_INCOMPLETE applicable child unresolved 200 derived carry/block exact owner
CONCURRENCY_BUSY bounded serialization unavailable 409/503 reread/retry one command
SCHEMA_NOT_READY required current/target schema absent 503 release/schema owner
UNEXPECTED_ERROR unclassified defect 500 capture request ID/escalate

Internal SQL, credential or provider payload details are not public error messages.


14. Transaction, Concurrency And Idempotency

14.1 Generic transaction

  • Create uses semantic duplicate identity.
  • Edit/close/correct uses current state + version/updated timestamp or equivalent CAS.
  • Multi-row close either validates all rows and commits accepted batch semantics or returns explicit per-row/whole-batch result; behavior must be documented before implementation.
  • Provider-protected records require explicit correction capability.

14.2 AR confirm

Preserve current accepted all-items local transaction unless policy changes:

all candidate headers/lines commit
or
none commit

Required serialization/constraint prevents two active invoice results for same booking/container identity.

14.3 QBO

  • Local intent commit is separate from provider attempt.
  • One active attempt claims one intent.
  • Provider create is never repeated while state is unknown.
  • Retry creates a new attempt for the same intent, not a new invoice business intent, unless content/version changed.
  • Local projection update follows provider reconciliation.

14.4 Files

  • Object upload and link transactions remain separate checkpoints.
  • Link creation is idempotent per object/target/type.
  • Object cleanup is asynchronous/reconciled and reference-aware.
  • A link batch must expose exact committed targets.

14.5 Email

  • One immutable EmailIntent per BOL content version.
  • One immutable Packing batch/version containing target-part intents.
  • One active attempt per intent/part.
  • Provider unknown blocks resend until reconciliation.
  • Sent parts are never rolled back or replayed by later part failure.

15. Event And Effect Contract

Effect Local trigger Intent identity Provider/storage adapter Result/recovery
QBO invoice local AR confirmed and delivery applicable QBO intent/group UUID QuickBooks client/worker search/create/reconcile; unknown first-class
File object upload operator upload request object/upload request UUID EFS/S3 stored/unknown/failed; content/readability check
File link stored/known object + target link request/identity MySQL repository active/existing/rejected; exact target reread
File cleanup no links/retention hold cleanup intent UUID storage worker deleted/failed/unknown/manual review
BOL email reviewed BOL readiness email intent UUID Gmail worker message/thread ID or unknown/failure
Packing email part immutable batch target-part target-part intent UUID Gmail worker per-part message/thread ID or unknown/failure

15.1 Effect intent rule

A business command reports local success after its local transaction. Provider completion is displayed separately.

15.2 Provider retry rule

read intent
+ read attempts
+ search/reconcile provider when result can be unknown
+ establish eligibility
-> retry same unresolved intent

15.3 Effect evidence

Support evidence includes:

  • tenant/capability/source identity;
  • request/intent/attempt IDs;
  • payload/content/attachment hash;
  • provider request/result/message/invoice IDs;
  • timestamps;
  • safe error code;
  • reconciliation reviewer/disposition.

Secrets and raw sensitive payloads are not copied into operator Wiki/evidence.


16. UI Contract

16.1 Billing workspace

React target sections:

Transactions
AR Billing
Provider Reconciliation
Documents
Operational Emails
Daily Close

A shared workspace may compose them, but each child preserves its state/command authority.

16.2 Generic transaction UI states

  • loading;
  • no source/transactions;
  • denied;
  • incompatible selection;
  • validation error;
  • stale row;
  • local write pending;
  • response unknown/readback required;
  • closed/readback;
  • provider-protected/correction required.

16.3 AR Billing UI

  • candidate loading/empty;
  • warning/blocking reason;
  • review line calculation and provenance;
  • stale preview conflict;
  • local confirm pending;
  • local confirm complete/QBO pending;
  • QBO per-group synced/error/unknown;
  • correction/protected state.

The UI must not show one generic “Complete” result when local confirm succeeded and QBO failed/unknown.

16.4 File UI

  • upload progress/object result;
  • link progress per target;
  • readable/unreadable;
  • duplicate/existing link;
  • unlink result;
  • object retained/cleanup pending/held/failed;
  • no automatic object deletion message from unlink alone.

16.5 BOL email UI

Shows:

  • source/reference;
  • recipients;
  • attachment list/readiness;
  • send intent status;
  • message/thread ID where allowed;
  • sent/failed/unknown;
  • reconcile-before-retry warning.

16.6 Packing email UI

Shows every target and part:

CUSTOMER 1/2 SENT
CUSTOMER 2/2 UNKNOWN
INSPECTOR 1/1 PENDING

A partial batch remains open. Retry/reconcile actions apply to exact target-parts.

16.7 Daily close UI

Shows child checkpoint cards/rows with:

  • applicable/not-applicable;
  • current state and freshness;
  • authoritative identity/read link;
  • completion/non-implication;
  • next action/owner;
  • human disposition.

The composite does not expose a shortcut that replays every child.

16.8 Accessibility/mobile

  • table/worklist has responsive card/list alternative;
  • status not communicated by color only;
  • keyboard-accessible selection/actions/modals;
  • error linked to relevant item/field;
  • provider/file partial result remains readable on mobile;
  • no hidden hover-only evidence.

17. Exception And Recovery Matrix

ID Detection Possible committed state Required reread Safe next action Must not repeat Owner
BILL-EXC-010 source transaction create response lost header/lines may exist semantic source/account identity return existing or create only absent full source batch blindly Billing/support
BILL-EXC-020 mixed close selection no write or wrong common values possible every selected header/company/state split selection or correct committed rows same mixed request Billing
BILL-EXC-030 close response lost some/all selected rows may be closed every transaction UUID/header accept committed result or retry only unchanged missing rows bulk close blindly Billing/support
BILL-EXC-040 wrong closed field local wrong value committed header/lines/provider/file impact approved correction/version raw update/delete Accounting manager
BILL-EXC-050 AR preview changed no confirm or stale browser source/preset/rates/current invoice regenerate/review preview stale confirm Billing
BILL-EXC-060 one AR batch item fails current batch intended rollback every candidate transaction identity correct failed input and resubmit reviewed batch assume partial local success Billing
BILL-EXC-070 AR confirm response lost entire local batch may have committed booking/container active invoice/lines use existing or confirm only if absent repeat batch blindly Billing/support
BILL-EXC-080 concurrent AR confirm duplicate/conflict possible active invoices by booking/container identity retain one accepted result; reconcile duplicate through approved correction create another invoice Accounting/support
BILL-EXC-090 browser stops after local confirm local READY, no QBO attempt local invoice + effect/attempt state request delivery for existing invoice local confirm Billing
BILL-EXC-100 QBO mapping/config error before provider local READY/error, no provider expected if proven config/mapping + intent/attempt correct mapping then retry same intent new local invoice QBO owner
BILL-EXC-110 QBO SYNCING stale provider absent/in-flight/created intent/attempt + provider search + local group reconcile to synced/retryable/manual reset by age and resend QBO support
BILL-EXC-120 QBO provider created/local save failed provider invoice exists; local error/unknown provider customer/doc/amount/ID + local group reconcile local projection provider create QBO support
BILL-EXC-130 QBO mixed group result some groups synced every group intent/provider/local state work unresolved groups only whole request Billing/QBO
BILL-EXC-140 object upload response lost object may exist upload request/object UUID/storage evidence reconcile object; link existing or retry if absent upload binary blindly File owner
BILL-EXC-150 object stored/link registration failed orphan object or partial links object + all target links create missing links idempotently or mark orphan reupload object File owner
BILL-EXC-160 duplicate file links multiple links same object/target/type all active links/object retain canonical and unlink duplicate under audit delete object File owner
BILL-EXC-170 selected link delete with shared object other active links may exist reference inventory + retention unlink only; retain object physical delete File owner
BILL-EXC-180 link exists/object unreadable broken object/path/permission object metadata/storage check/all links reconcile/restore object or mark unavailable create duplicate link only File/support
BILL-EXC-190 BOL recipient invalid no send company recipient source correct recipient and retry intent alter unrelated source transaction Operations
BILL-EXC-200 BOL response lost Gmail message may exist intent/source/recipient/subject/time/provider Sent reconcile then retry if absent resend blindly Gmail support
BILL-EXC-210 BOL attachment unreadable no safe send or partial prep object/link/readability/scale source fix attachment source then same/new version intent send incomplete set unless explicitly approved Operations/File
BILL-EXC-220 Packing later target/part fails earlier messages sent batch/target/part Results + provider Sent reconcile exact unresolved parts target/full batch replay Operations/Gmail
BILL-EXC-230 Packing response lost one/more parts may exist immutable batch target-part + provider search mark found or retry absent part regenerate/replay batch Gmail support
BILL-EXC-240 Packing source/options changed mid-recovery prior parts represent old content batch version/hashes/source create intentional new version; disclose prior sends mix part versions Operations
BILL-EXC-250 daily close has unresolved child child may be partial/unknown exact child state/evidence carry/block with owner mark universal complete Billing close owner
BILL-EXC-260 role/API mismatch unauthorized read/write risk page/API/action/record logs correct access policy and retest rely on hidden button P2/P4
BILL-EXC-270 target migration response loss old/new writer/effect ambiguity selector + request/intent + DB/provider state reconcile one writer/result invoke both paths Migration support

Universal rule:

Do not repeat a financial, file-object or provider action
until its authoritative local and external checkpoints are reread.

18. Current Caller And Adapter Map

18.1 Generic transaction

Source Responsibility Target disposition
app/systems/BMS/transaction/api_routes.php route parsing and generic/source commands thin Next.js adapters after cutover
app/systems/BMS/transaction/post_helper.php multiple source/transaction and unrelated orchestration helpers replace selected functions with application commands; remove after caller-zero
app/shared/api/table_mutation_helper.php schema-shaped form mutation not target command; freeze/retire per caller
app/shared/controller/common_post_helper.php shared SQL/mutation behavior bounded compatibility; responsibility extraction
current transaction pages/JS list/form/close UI React transaction workspace

18.2 AR/QBO

Source Responsibility Target disposition
app/systems/BMS/ar-billing/api_routes.php AR options/preset/rates/workbench/preview/confirm/QBO routes Next.js adapters
app/systems/BMS/ar-billing/ar_billing_helper.php current calculation, local transaction, QBO grouping/claim/send/save/token refresh split application/repositories/provider worker/platform credentials
public/assets/js/modules/bms/ar-billing.js current workbench/review/confirm and browser QBO orchestration React UI; no provider effect ownership
app/utils/QuickBooksOnlineClient.php provider createInvoice only QBO adapter with search/reconcile/idempotency support
tenant config helper/keys credentials/endpoints/timeouts platform integration configuration owner

18.3 Files

Source Responsibility Target disposition
app/shared/files/api_routes.php current upload/register/read/delete/batch adapters Next.js/File adapters; retain cross-domain compatibility until all callers migrated
app/shared/files/media_helper.php upload validation/storage/temp/zip handling object-storage adapter/service
app/shared/storage/file_storage.php EFS/S3 abstraction target storage adapter
current file UI consumers object upload then business registration React uploader/link result UI

18.4 Emails

Source Responsibility Target disposition
app/systems/TMS/transload/api_routes.php BOL source/read/render/send/temp cleanup BOL query/application + worker adapter
app/systems/TMS/booking/api_routes.php Packing model/targets/parts/send/result Packing query/batch application + worker
app/utils/GmailSender.php Gmail MIME/send and provider message result Gmail adapter used by worker
current Transload/Booking pages/JS send controls/results React operational email UI

18.5 Documentation/knowledge callers

  • Process registry/contracts;
  • billing, ar-billing-qbo, ctc-daily, errors-recovery Wiki topics;
  • support/runbooks;
  • reports/dashboard/file consumers;
  • release/config/credential docs.

19. Target Component Map

flowchart TB
    TxUI[React Transactions]
    ARUI[React AR Billing]
    EffectUI[React Provider / Document Reconciliation]
    CloseUI[React Daily Close]

    Next[Next.js Web/API Adapters]
    TxApp[Transaction Application]
    ARApp[AR Invoice Application]
    EffectApp[Effect Application]
    FileApp[File Application]
    CloseQuery[Billing Close Query]

    Policy[State / Billing / Retry Policies]
    TxRepo[Transaction Repository]
    FileRepo[File Object/Link Repository]
    EffectRepo[Effect Intent/Attempt Repository]
    DB[(MySQL)]
    Storage[Object Storage]
    Worker[Node Worker]
    QBO[QuickBooks Online]
    Gmail[Gmail]

    TxUI --> Next
    ARUI --> Next
    EffectUI --> Next
    CloseUI --> Next
    Next --> TxApp
    Next --> ARApp
    Next --> EffectApp
    Next --> FileApp
    Next --> CloseQuery
    TxApp --> Policy
    ARApp --> Policy
    EffectApp --> Policy
    FileApp --> Policy
    TxApp --> TxRepo
    ARApp --> TxRepo
    FileApp --> FileRepo
    EffectApp --> EffectRepo
    CloseQuery --> TxRepo
    CloseQuery --> FileRepo
    CloseQuery --> EffectRepo
    TxRepo --> DB
    FileRepo --> DB
    FileRepo --> Storage
    EffectRepo --> DB
    EffectRepo --> Worker
    Worker --> QBO
    Worker --> Gmail

19.1 React responsibility

  • transaction/source list and semantic forms;
  • AR candidate/review/confirm;
  • local/provider split status;
  • file object/link/readability results;
  • BOL/Packing readiness and per-effect/part results;
  • daily close worklist and owner handoff;
  • loading/empty/denied/conflict/partial/recovery/accessibility/mobile.

19.2 Next.js responsibility

  • authenticated tenant/actor context;
  • Server Component query composition;
  • Route Handler/public API adapter;
  • bounded Server Action only as UI adapter;
  • request/error/correlation mapping;
  • no business SQL/provider effects.

19.3 TypeScript application/domain responsibility

  • semantic transaction/AR/file/email/QBO commands and queries;
  • identity/state/transition/authorization policy;
  • transaction and idempotency;
  • exact readback;
  • effect intent creation and reconciliation semantics;
  • stable errors and recovery.

19.4 Repositories

  • map current MySQL header/lines/presets/QBO projections;
  • conditional updates and active uniqueness;
  • file object/link compatibility;
  • effect intent/attempt/reconciliation storage;
  • current schema-specific performance/indexing.

19.5 Worker

  • QBO create/search/reconcile/retry;
  • Gmail BOL and Packing target-part send/search/reconcile;
  • approved orphan/object cleanup;
  • durable attempts, backoff, dead-letter/manual-review state;
  • no business-state invention.

20. Migration Sequence

Detailed waves are in the parity/cutover matrix.

M0 source and policy reconciliation
-> M1 shared tenant/actor/error/trace
-> M2 read-only React/Next.js workbench parity
-> M3 typed generic transaction reads
-> M4 bounded local transaction writes
-> M5 AR confirm one-writer
-> M6 QBO intent shadow
-> M7 QBO worker one-writer
-> M8 file object/link writes and cleanup
-> M9 BOL worker
-> M10 Packing target-part worker
-> M11 daily close worklist
-> M12 caller-zero/PHP retirement
-> M13 PostgreSQL later

20.1 One-writer rule

At every write/effect wave:

one capability/cohort
-> one selector
-> one local writer or provider sender

No PHP/TypeScript dual mutation and no PHP/worker dual provider send.

20.2 Rollback

Rollback:

  • disables new command/effect claims;
  • reconciles committed local and in-flight provider/object state;
  • restores current PHP entry for new eligible work only;
  • never deletes committed rows/effects to make old UI look clean;
  • never replays QBO/Gmail/file object actions;
  • preserves target audit/intent records.

20.3 Caller-zero

Classify:

ACTIVE
COMPATIBILITY
TEST_ONLY
HISTORICAL
UNKNOWN
REMOVED_AND_VERIFIED

Unknown blocks retirement.


21. PostgreSQL Preservation Requirements

After React + Next.js + TypeScript + MySQL stabilization, P11 preserves:

  • transaction/invoice UUID identity;
  • tenant + source/account uniqueness;
  • booking/container active invoice/version uniqueness;
  • decimal/currency precision and rounding;
  • soft-delete/audit/correction lineage;
  • conditional state/version transitions;
  • preset JSON schema/version and historical reproducibility;
  • QBO effect intent/attempt/reconciliation identity;
  • provider unknown/in-flight states;
  • FileObject/FileLink references and retention;
  • email batch/target/part identity;
  • active in-flight effect migration;
  • indexes/query plans;
  • failback representation.

Provider sends remain paused or under the same worker authority during DB cutover; first provider migration and first PostgreSQL cutover are not combined.


22. Stable Verification Scenario Catalog

22.1 Generic transaction

ID Scenario Required evidence
BILL-SCN-010 create one source AP/AR transaction one header/line set, source identity, exact readback
BILL-SCN-020 duplicate create existing result, no duplicate header/lines
BILL-SCN-030 compatible multi-row close accepted state/fields per row
BILL-SCN-040 incompatible mixed batch rejected, no mutation
BILL-SCN-050 close response lost reread determines result; no blind repeat
BILL-SCN-060 stale close/edit stable conflict and current state
BILL-SCN-070 provider-synced edit/delete attempt blocked; correction path indicated
BILL-SCN-080 approved correction prior/new evidence and downstream impact

22.2 AR Billing

ID Scenario Required evidence
BILL-SCN-110 preview one eligible candidate line provenance and total
BILL-SCN-120 stale preview conflict/new calculation, no stale commit
BILL-SCN-130 confirm one candidate one active invoice/header/lines READY
BILL-SCN-140 confirm multi-item success all committed under accepted atomicity
BILL-SCN-150 one invalid item all request items rolled back
BILL-SCN-160 existing source AR conflict no duplicate container AR
BILL-SCN-170 existing unsynced correction accepted version/rewrite result
BILL-SCN-180 existing synced confirm blocked
BILL-SCN-190 concurrent same container confirm one accepted active invoice/version
BILL-SCN-200 confirm response lost exact identity reread; no duplicate
BILL-SCN-210 local confirm/browser QBO handoff interrupted local invoice preserved; QBO intent/request recoverable

22.3 QBO

ID Scenario Required evidence
BILL-SCN-310 normal one-group delivery intent/attempt/provider/local synced
BILL-SCN-320 invoice-number grouping correct transaction set/customer/doc/total
BILL-SCN-330 maximum/multiple groups partial result successes preserved; failures independent
BILL-SCN-340 missing mapping/config no provider create; correct error
BILL-SCN-350 concurrent send one active attempt/provider create
BILL-SCN-360 provider created/local save failed provider search and local reconcile; no duplicate
BILL-SCN-370 stale SYNCING no time-only reset; safe disposition
BILL-SCN-380 already synced no resend
BILL-SCN-390 provider rejection same intent retry after correction
BILL-SCN-400 token refresh platform-owned credential update, no duplicate business effect

22.4 Files

ID Scenario Required evidence
BILL-SCN-510 upload/link one transaction object + link + readability
BILL-SCN-520 one object linked to multiple transactions one object, expected active links
BILL-SCN-530 upload response lost object reconciliation before retry
BILL-SCN-540 object success/link failure missing links recovered without duplicate object
BILL-SCN-550 duplicate link request existing link returned/no duplicate
BILL-SCN-560 unlink one shared link other links readable; object retained
BILL-SCN-570 cleanup no links object delete and cleanup evidence
BILL-SCN-580 cleanup retention hold object retained, clear blocked result
BILL-SCN-590 link exists/object missing unreadable state and recovery, no false success

22.5 BOL email

ID Scenario Required evidence
BILL-SCN-610 valid recipient/scale/files send one intent/message/thread and attachment set
BILL-SCN-620 invalid recipient no send
BILL-SCN-630 attachment unreadable no false send; source/file recovery
BILL-SCN-640 provider failure same intent retry eligibility
BILL-SCN-650 response lost Sent/provider reconcile before retry
BILL-SCN-660 test recipient configuration explicit environment-safe routing; no username policy

22.6 Packing email

ID Scenario Required evidence
BILL-SCN-710 CUSTOMER one-part send exact target-part provider result
BILL-SCN-720 BOTH targets all target results independent
BILL-SCN-730 multipart success every part identity/message
BILL-SCN-740 later part failure prior success preserved; unresolved part only
BILL-SCN-750 part response lost provider search/reconcile
BILL-SCN-760 source/options changed new batch version, no mixed parts
BILL-SCN-770 invalid recipient/no equipment/MK mode no send and clear blocker

22.7 Roles/composite/migration

ID Scenario Required evidence
BILL-SCN-810 authorized Billing role expected page/API/action access
BILL-SCN-820 denied role no mutation/effect
BILL-SCN-830 foreign tenant/record no disclosure/mutation
BILL-SCN-840 daily close all verified correct child evidence, no child mutation
BILL-SCN-850 daily close carried partial exact state/evidence/owner
BILL-SCN-860 one-writer local command cutover one writer and parity
BILL-SCN-870 one-writer provider cutover one sender and in-flight reconciliation
BILL-SCN-880 rollback local write resume from current state, no replay
BILL-SCN-890 rollback provider worker stop claims/reconcile attempts before alternate sender
BILL-SCN-900 caller-zero all static/runtime callers classified, unknown zero
BILL-SCN-910 Wiki stable route migration topic unchanged; current/future link accepted

23. Evidence Record Template

For each scenario:

Scenario ID:
Source revision:
Environment/deployment/schema identity:
Tenant/profile:
Actor/role/account:
Starting records and IDs/UUIDs:
Provider/storage configuration scope:
Action/request ID:
Expected state/effect:
Observed local readback:
Observed provider/storage readback:
UI visible result:
Negative/duplicate/timeout behavior:
Cleanup/rollback:
Logs/evidence paths:
Reviewer:
Disposition: PASS / PARTIAL / BLOCKED / FAIL
Known limitation:

Do not store credentials, customer data dumps or raw sensitive provider payloads in Git.


24. Definition Of Ready

A bounded implementation or migration wave is ready only when:

  • Product outcome and selected child capability are explicit;
  • role/API/record capability matrix exists for selected tenant/profile;
  • state/data/field/interface contracts are accepted;
  • applicable policy IDs are approved or explicitly bounded;
  • exact source/schema/caller baseline is pinned;
  • transaction/idempotency/timeout/partial recovery is defined;
  • one writer/effect selector and rollback are defined;
  • stable scenarios and fixtures/accounts are available;
  • Runbook/Wiki impact and effect authorization are identified;
  • concurrent writer conflict is absent.

25. Definition Of Complete — Current Runtime Improvement

For a current-PHP operational change, complete means:

  • bounded visible result matches the user request;
  • no broad structural rewrite;
  • exact local DB/API/browser/role tests pass;
  • no Client 1 regression;
  • provider/file effects are independently read back;
  • error/timeout/recovery result is visible;
  • Process/Runbook/Wiki current behavior is synchronized through authorized paths;
  • deployment/readback/observation is complete when release is authorized.

Documentation alone is not completion.


26. Definition Of Complete — React/Next.js Migration

A selected capability is migration-complete only when:

  • target React/Next.js/TypeScript/MySQL/worker path is accepted;
  • one writer/provider sender is active;
  • old/new parity and accepted differences pass;
  • all stable scenarios for the selected wave pass;
  • rollback has been rehearsed;
  • target roles and field operators accept the workflow;
  • observation shows no hidden callers/duplicate effects;
  • legacy callers are REMOVED_AND_VERIFIED or explicitly retained compatibility;
  • unknown caller count is zero for removed surfaces;
  • Process/Runbook/Wiki stable links are updated;
  • PHP/helper/KJDatabase ownership is removed only after caller-zero;
  • React + Next.js + MySQL is stabilized before P11 PostgreSQL work.

27. Remaining Open Inputs

Business/operations

  • accountable Billing-close role, cadence, cutoff and escalation;
  • recipient master owner/review cadence;
  • local/synced correction and provider void policy;
  • file retention/legal hold/orphan cleanup owner;
  • email partial-result support owner.

Technical

  • exact current schema/types/indexes and status inventory;
  • current role/menu/API/record matrix;
  • transaction source create idempotency by source family;
  • active container AR uniqueness implementation;
  • QBO search/idempotency/provider correction API strategy;
  • target effect tables and worker platform;
  • file object/link normalization and storage reference inventory;
  • Gmail search headers/provider retention;
  • current Wiki content and renderer evidence;
  • performance baselines and query plans;
  • controlled fault/timeout/concurrency evidence.

No open item may be answered by silently copying current accidental structure into the target.

---

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