MK Trade, Cost, Rate And Document Outputs — Capability Rebuild Packet¶
- Packet status:
DETAILED SOURCE-RECONCILED INPUT / POLICY, ROLE, ACCOUNTING, WIKI AND RUNTIME REVIEW REQUIRED - Operating profile:
mk-order - Source baseline:
qa@d96498360bb9c3541a1b5f862284596a7ed217b9 - Source authority:
MK_TRADE_COST_RATE_DOCUMENT_OUTPUTS_SOURCE_AUTHORITY.md - Process family reconciliation:
MK_TRADE_COST_RATE_DOCUMENT_OUTPUTS_RECONCILIATION.md - Policy matrix:
MK_TRADE_COST_RATE_DOCUMENT_OUTPUTS_POLICY_DECISION_MATRIX.md - Migration matrix:
MK_TRADE_COST_RATE_DOCUMENT_OUTPUTS_PARITY_AND_CUTOVER_MATRIX.md - Target stack: React + Next.js + framework-independent TypeScript application/query/repository contracts + MySQL first
- Worker rule: required only for an accepted durable asynchronous export/file/email/provider effect; not required for read projections or synchronous local commands
- Later DB target: PostgreSQL after accepted React + Next.js + TypeScript + MySQL stabilization
1. Family Outcome¶
This packet defines enough information to rebuild eight related but independent capabilities:
1. Trade Summary reconciliation
2. Export Brokerage orchestration
3. Outbound Order Cost
4. Packing Rate Correction
5. Packing Document projection
6. Purchase Local Invoice projection
7. Booking Confirmation projection
8. Sales Weight Ticket projection
They share source data and user navigation, but they do not share one business state or transaction.
1.1 Required user-visible result¶
An authorized MK user can:
- inspect an explainable Trade Summary without mistaking a derived label for settlement;
- create or cancel an Export Brokerage child set once, then reconcile every child and residual effect;
- identify and update the intended Outbound Cost row without overwriting another AP workflow;
- correct the exact Booking-linked Sales item rate with per-item readback;
- render the intended current document projection from authoritative source;
- distinguish current source, rendered output, browser print and any separately accepted durable file/delivery result;
- recover from timeout or partial result by rereading the exact owner boundary rather than replaying the whole action;
- follow stable Wiki topics after PHP pages become React + Next.js.
1.2 Non-goals¶
This packet does not approve:
- one
TRADE_STATUSorDOCUMENT_STATUSfor the whole family; - derived Trade labels as accounting or shipment transitions;
- Trade CSV as QBO/provider delivery;
- Export Brokerage as a general order/allocation delete tool;
- latest AP row as automatic Outbound Cost ownership;
- silent mixed-ID rate correction;
- browser print as durable completion;
- current template constants as approved global Product policy;
- numeric Client/Role branching in target code;
- hidden child writes from report rendering;
- automatic file/email/provider creation unless Product separately accepts it;
- PostgreSQL in the initial migration wave.
2. Process And Ownership Map¶
| Capability | Process owner | Mutation owner | External/durable effect |
|---|---|---|---|
| Trade Summary | PROC-OMS-TRADE-SUMMARY-RECONCILIATION-MK |
none; read-only | browser CSV only, nondurable |
| Export Brokerage | PROC-OMS-EXPORT-BROKERAGE-MK |
orchestration delegates to child owners | none outside local DB in the current core path; AI extract is proposal input |
| Outbound Cost | PROC-BMS-OUTBOUND-ORDER-COST-MK |
typed local AP command | files/QBO remain separate |
| Packing Rate | PROC-OMS-PACKING-RATE-CORRECTION-MK |
Sales item rate command | none |
| Packing Document | PROC-TMS-PACKING-DOCUMENT-MK |
none, except separate Rate process | browser render/print only |
| Purchase Local Invoice | PROC-BMS-PURCHASE-LOCAL-INVOICE-OUTPUT-MK |
none | browser render/print only |
| Booking Confirmation | PROC-TMS-BOOKING-CONFIRMATION-OUTPUT-MK |
none | browser render/print only |
| Sales Weight Ticket | PROC-BMS-SALES-WEIGHT-TICKET-OUTPUT-MK |
none | browser render/print only |
Core invariant¶
read projection
!= mutable financial command
!= composite child orchestration
!= browser output
!= durable file/email/provider effect
3. Actors And Semantic Capabilities¶
3.1 Trade reviewer¶
Responsibilities:
- choose exact filters and query time;
- identify exact equipment/deal;
- reconcile source links and source-class totals;
- record unexplained differences;
- export only the currently reviewed projection.
Target capabilities:
oms.trade-summary.view
oms.trade-summary.detail
oms.trade-summary.export
oms.trade-summary.explain
Denied behavior:
- no source mutation;
- no close/claim/settle command;
- no direct transaction repair;
- no inference that a derived status is approved.
3.2 Export Brokerage operator¶
Responsibilities:
- review source document suggestions;
- select exact Booking where required;
- confirm supported child shape;
- create once;
- reconcile every returned child;
- request cancellation only for an identified unprogressed job result;
- preserve child owners and residual evidence.
Target capabilities:
oms.export-brokerage.view
oms.export-brokerage.propose
oms.export-brokerage.create
oms.export-brokerage.cancel
oms.export-brokerage.reconcile
Denied behavior:
- no blind Create/Cancel retry;
- no arbitrary child ID delete;
- no cancellation after progressed child effects unless accepted compensation exists;
- no AI proposal treated as authorization.
3.3 Outbound Cost operator¶
Responsibilities:
- inventory all order-linked AP rows;
- identify the one typed Outbound Cost row;
- edit only in accepted mutable state;
- preserve header metadata and complete line intent;
- reconcile Trade impact separately.
Target capabilities:
bms.outbound-cost.view
bms.outbound-cost.create
bms.outbound-cost.update
bms.outbound-cost.delete
bms.outbound-cost.correct
Denied behavior:
- no latest-row guess;
- no CONFIRMED/CLOSED rewrite;
- no file/object deletion;
- no accounting close or QBO action.
3.4 Packing rate operator¶
Responsibilities:
- identify exact Booking, Sales order and item IDs;
- compare current persisted and intended rates;
- submit an exact correction once;
- reread every intended item before print.
Target capabilities:
oms.packing-rate.view
oms.packing-rate.correct
oms.packing-rate.history.view
Denied behavior:
- no amount-only persistence claim;
- no broad ID set;
- no silent skip acceptance;
- no rate selection by AI or template.
3.5 Document reviewer¶
Responsibilities:
- verify current authoritative source;
- render exact scope;
- reconcile template/fallback/current-source differences;
- handle browser print under human custody;
- decide replacement/reprint when result is unknown.
Target capabilities:
tms.packing-document.view
bms.purchase-local-invoice.view
tms.booking-confirmation.view
bms.sales-weight-ticket.view
mk.document.print
mk.document.snapshot.create // future only if Product accepts durable snapshots
mk.document.file.deliver // future only if Product accepts file delivery
Denied behavior:
- no source correction from the output;
- no print-as-approval;
- no physical Scale inference from Sales Weight Ticket;
- no invoice lifecycle inference from order-number labels.
4. Profile, Tenant And Access Contract¶
Target request context:
interface MkExecutionContext {
tenantId: string;
operatingProfile: 'mk-order';
actorId: string;
capabilities: string[];
locale: string;
timezone: string;
documentPolicyVersion?: string;
}
Rules:
- behavior is selected by profile/capability/configuration, not
CLIENT_ID === 2; - every query and command is tenant-scoped;
- page visibility and API authorization must agree;
- record-level ownership is checked independently from menu visibility;
- direct output URLs require authentication, page capability, tenant and record scope;
- document configuration and module access are explicit dependencies;
- current role IDs are compatibility mappings, not target Domain policy.
5. State Models¶
5.1 Trade projection state¶
Trade Summary has no persisted process state. The target read model uses explanatory conditions:
EXPLAINED
UNEXPLAINED
SOURCE_AMBIGUOUS
SOURCE_STALE
SOURCE_CONFLICT
Separate display labels may be computed:
OPEN
SHIPPED
CLOSED
CLAIMED_FILTER_MATCH
but are always returned with:
- formula/policy version;
- contributing source classes;
- source cutoff/query time;
- ambiguity/warning flags;
- non-authoritative label indicator.
5.2 Export Brokerage job state¶
Current source has no durable Job row. Target semantic state:
PROPOSED
READY
CREATING
CREATED
PARTIAL_CONFLICT
RESULT_UNKNOWN
CANCEL_REQUESTED
CANCEL_BLOCKED
CANCELLED
CANCEL_UNKNOWN
MANUAL_REVIEW
A target Job manifest references child results without taking child authority.
5.3 Outbound Cost state¶
Current transaction status remains source data:
CREATED
OPEN
DRAFT
CONFIRMED
CLOSED
Target cost application distinguishes:
MUTABLE
IMMUTABLE
OWNER_AMBIGUOUS
STALE
DELETED
A separate accepted subtype or ownership marker is required before automatically selecting one AP row.
5.4 Packing rate correction state¶
UNCHANGED
DIRTY_CLIENT_ONLY
SUBMITTING
CORRECTED
PARTIAL
STALE
UNKNOWN
CONFLICT
Only server-reread CORRECTED is durable. Client dirty/success UI is not business evidence.
5.5 Document projection state¶
Current browser conditions:
SOURCE_READY
RENDERED
SOURCE_MISMATCH
PRINT_DIALOG_OPENED
PRINT_RESULT_UNKNOWN
These are not stored business states.
Future durable document capability, only if accepted:
SNAPSHOT_CREATED
FILE_CREATED
DELIVERY_REQUESTED
DELIVERED
DELIVERY_FAILED
SUPERSEDED
VOIDED
Do not introduce these states merely to modernize the UI.
6. Data And Identity Contract¶
6.1 Trade projection identity¶
interface TradeProjectionIdentity {
tenantId: string;
equipmentId: number;
inboundOrderIds: number[];
outboundOrderIds: number[];
queryTime: string;
filterFingerprint: string;
policyVersion: string;
sourceRevision: string;
}
Source classes are explicit:
EQUIPMENT_AP
EQUIPMENT_AR
OUTBOUND_ORDER_AP
COMMERCIAL_PURCHASE
COMMERCIAL_SALES
BOOKING_LOGISTICS
No source class may be hidden inside a generic total without explainability metadata.
6.2 Export Brokerage identity¶
Current immediate identity:
- inbound order ID;
- outbound order IDs;
- Booking IDs;
- Equipment/Equipment Load IDs;
- Inventory Lot IDs;
- Allocation IDs;
- shared reference/container values;
- compatibility generated markers.
Target identity:
interface ExportBrokerageJobIdentity {
jobId: string;
tenantId: string;
requestToken: string;
inputFingerprint: string;
referenceNumber: string;
childManifestVersion: number;
}
Child manifest item:
interface ExportBrokerageChildResult {
owner: 'INBOUND' | 'BOOKING' | 'OUTBOUND' | 'EQUIPMENT' | 'INVENTORY' | 'ALLOCATION';
entityId: number | string;
disposition: 'CREATED' | 'REUSED' | 'FAILED' | 'UNKNOWN' | 'CANCELLED' | 'PRESERVED';
authoritativeReadback?: Record<string, unknown>;
}
6.3 Outbound Cost identity¶
Current:
T_TRANSACTION.ID
+ TYPE=AP
+ RELATED_TABLE_NAME=T_LOAD
+ RELATED_TABLE_ID=Outbound Order ID
Target must add or otherwise prove:
business subtype = OUTBOUND_ORDER_COST
without assuming every order-linked AP row is this process.
Target command identity:
interface OutboundCostCommandIdentity {
tenantId: string;
orderId: number;
transactionId?: number;
requestToken: string;
expectedVersion?: string;
}
6.4 Packing rate identity¶
interface PackingRateCorrectionIdentity {
tenantId: string;
bookingId: number;
salesOrderId: number;
orderItemIds: number[];
requestToken: string;
expectedRates: Record<number, string>;
}
6.5 Document projection identity¶
interface DocumentProjectionIdentity {
tenantId: string;
documentType:
| 'PACKING_DOCUMENT'
| 'PURCHASE_LOCAL_INVOICE'
| 'BOOKING_CONFIRMATION'
| 'SALES_WEIGHT_TICKET';
sourceEntityIds: Array<{ type: string; id: number | string }>;
scope?: Record<string, string | number | boolean>;
sourceFingerprint: string;
templateVersion: string;
renderedAt: string;
}
Current PHP outputs do not persist this identity. Target read-only migration may return it without creating a durable snapshot.
7. Field Contracts¶
7.1 Trade Summary fields¶
| Field | Meaning | Authority/rule |
|---|---|---|
EQUIPMENT_ID |
deal projection root | equipment/deal link source |
| Purchase/Sales IDs | source relationship | must expose all matches, not only MAX |
TOTAL_AP |
equipment AP + outbound-order AP under defined policy | return source breakdown |
TOTAL_AR |
equipment AR under defined policy | return source breakdown |
MARGIN |
AR - AP | decimal policy/version required |
DEAL_STATUS |
derived display classification | not stored transition |
| ETA/ETD/SWB | logistics classification input | source/cutoff explicit |
| invoice/check/date summaries | projection labels | do not imply close/payment/provider result |
7.2 Export Brokerage input¶
- vendor/customer company IDs;
- reference number;
- order type;
- selected Booking ID for Ocean;
- container number/size/seal;
- common times;
- commodity ID;
- quantity;
- weight;
- rate;
- UOM;
- reviewed remark/context;
- request token;
- expected source/config version.
Every child result and transformation must be returned. Gross=Net, Tare=0 and copied common times are explicit current transformations, not hidden defaults in the target.
7.3 Outbound Cost fields¶
Header:
- transaction ID/version/subtype;
- order ID;
- status;
- issue/due/complete dates;
- company/billing company/address;
- reference/invoice/check number;
- remark.
Line:
- stable line ID/version where possible;
- description/category;
- quantity;
- rate;
- amount;
- amount source (
EXPLICITorQUANTITY_X_RATE).
A target update must preserve fields omitted from the UI unless the command explicitly changes them.
7.4 Packing rate fields¶
- Booking ID;
- Sales order/item IDs;
- UOM/base;
- current persisted rate;
- display rate;
- intended persisted rate;
- expected prior value/version;
- reason when policy requires;
- actor/time/request token.
7.5 Document projection fields¶
Each document lists:
- source field path;
- fallback path;
- conversion/rounding;
- template constant;
- transient editable field;
- persisted or nonpersisted result;
- warning when a fallback/template value differs from source.
No fixed template value is accepted as Product truth without a named policy owner.
8. Semantic Queries¶
8.1 Trade¶
GetTradeSummaryList
GetTradeSummaryDetail
GetTradeSourceBreakdown
GetTradeProjectionExplanation
ExportTradeProjectionCsv
GetTradeSourceBreakdown returns every contributing row class and excluded-row reason.
8.2 Export Brokerage¶
GetExportBrokerageProposal
SearchExportBrokerageBookings
PreviewExportBrokerageJob
GetExportBrokerageJobResult
GetExportBrokerageChildManifest
GetExportBrokerageCancellationPreview
Current source lacks a durable Get...JobResult; target implementation requires it before one-writer Create.
8.3 Cost and rate¶
GetOutboundCostCandidates
GetOutboundCostDetail
GetPackingRateRows
GetPackingRateCorrectionHistory
GetOutboundCostCandidates returns every order-linked AP with ownership evidence and does not silently select latest.
8.4 Documents¶
GetPackingDocumentProjection
GetPurchaseLocalInvoiceProjection
GetBookingConfirmationProjection
GetSalesWeightTicketProjection
Queries are read-only and return source fingerprint, template version, warnings and current/future route metadata.
9. Semantic Commands¶
9.1 Export Brokerage¶
CreateExportBrokerageJob
CancelExportBrokerageJob
ReconcileExportBrokerageUnknownResult
CreateExportBrokerageJob:
- authorizes actor/profile;
- validates selected Booking and source fields;
- validates supported shape;
- claims request token;
- creates child manifest;
- invokes explicit child owner commands;
- commits local job/result and child writes under the accepted transaction model;
- returns every child disposition and exact readback.
CancelExportBrokerageJob:
- requires stable Job identity;
- evaluates each child owner’s progressed blocker;
- records compensation plan;
- invokes explicit compensation commands;
- preserves pre-existing children;
- returns preserved/cancelled/blocked residual manifest.
9.2 Outbound Cost¶
CreateOutboundCost
UpdateOutboundCost
DeleteMutableOutboundCost
CorrectOutboundCost
Rules:
- exact typed target required;
- expected version required for update/delete;
- complete intended line set or explicit line commands;
- no silent header reset;
- immutable accounting states blocked;
- file/QBO effects separate;
- exact header/line/sibling readback returned.
9.3 Packing Rate¶
CorrectPackingRates
RestorePackingRates
CorrectPackingRates is all-or-explicit-partial by accepted policy. It returns per-item:
UPDATED
UNCHANGED
STALE
DENIED
NOT_FOUND
CONFLICT
A generic count is insufficient.
9.4 Document output¶
Current read-only command:
RenderDocumentProjection
Potential future commands, only after Product decision:
CreateDocumentSnapshot
CreateDocumentFile
DeliverDocument
VoidDocumentSnapshot
These future commands are not implied by browser print.
10. Planned HTTP Adapter Shapes¶
Examples only; final route naming belongs to P12 implementation design.
GET /api/mk/trade-summary
GET /api/mk/trade-summary/{equipmentId}
GET /api/mk/trade-summary/{equipmentId}/sources
POST /api/mk/export-brokerage/jobs/preview
POST /api/mk/export-brokerage/jobs
GET /api/mk/export-brokerage/jobs/{jobId}
POST /api/mk/export-brokerage/jobs/{jobId}/cancel
POST /api/mk/export-brokerage/jobs/{jobId}/reconcile
GET /api/mk/outbound-orders/{orderId}/costs
POST /api/mk/outbound-orders/{orderId}/costs
PATCH /api/mk/outbound-orders/{orderId}/costs/{transactionId}
DELETE /api/mk/outbound-orders/{orderId}/costs/{transactionId}
GET /api/mk/bookings/{bookingId}/packing-rates
POST /api/mk/bookings/{bookingId}/packing-rates/corrections
GET /api/mk/documents/packing
GET /api/mk/documents/purchase-local-invoice
GET /api/mk/documents/booking-confirmation
GET /api/mk/documents/sales-weight-ticket
The route handler parses/authenticates/maps errors. It does not own financial formulas, child compensation or document policy.
11. Stable Error Catalog¶
11.1 Shared¶
TCRD_UNAUTHENTICATED
TCRD_FORBIDDEN
TCRD_PROFILE_NOT_APPLICABLE
TCRD_RECORD_NOT_FOUND
TCRD_STALE_VERSION
TCRD_DUPLICATE_REQUEST
TCRD_RESULT_UNKNOWN
TCRD_DATA_CONFLICT
TCRD_SCHEMA_NOT_READY
TCRD_UNEXPECTED_ERROR
11.2 Trade¶
TRADE_SOURCE_AMBIGUOUS
TRADE_SOURCE_STALE
TRADE_TOTAL_UNEXPLAINED
TRADE_DELETED_SOURCE_CONFLICT
TRADE_MODULE_ACCESS_MISMATCH
TRADE_EXPORT_SOURCE_CHANGED
11.3 Export Brokerage¶
EXPORT_JOB_NOT_READY
EXPORT_JOB_UNSUPPORTED_SHAPE
EXPORT_JOB_BOOKING_REQUIRED
EXPORT_JOB_SOURCE_STALE
EXPORT_JOB_DUPLICATE
EXPORT_JOB_PAYLOAD_CONFLICT
EXPORT_JOB_CHILD_PARTIAL
EXPORT_JOB_RESULT_UNKNOWN
EXPORT_JOB_CANCEL_BLOCKED
EXPORT_JOB_CANCEL_PARTIAL
EXPORT_JOB_PROVENANCE_AMBIGUOUS
EXPORT_JOB_BALANCE_CONFLICT
11.4 Cost¶
OUTBOUND_COST_OWNER_AMBIGUOUS
OUTBOUND_COST_IMMUTABLE
OUTBOUND_COST_STALE
OUTBOUND_COST_HEADER_CONFLICT
OUTBOUND_COST_LINE_CONFLICT
OUTBOUND_COST_FILE_DEPENDENCY
OUTBOUND_COST_RESULT_UNKNOWN
11.5 Rate¶
PACKING_RATE_ITEM_NOT_ELIGIBLE
PACKING_RATE_VALUE_INVALID
PACKING_RATE_STALE
PACKING_RATE_PARTIAL
PACKING_RATE_RESULT_UNKNOWN
PACKING_RATE_PRINT_PENDING
11.6 Documents¶
DOCUMENT_SOURCE_NOT_READY
DOCUMENT_SOURCE_AMBIGUOUS
DOCUMENT_SOURCE_STALE
DOCUMENT_TEMPLATE_CONFLICT
DOCUMENT_FALLBACK_CONFLICT
DOCUMENT_OUTPUT_NOT_DURABLE
DOCUMENT_PRINT_RESULT_UNKNOWN
DOCUMENT_ACCESS_MISMATCH
Internal SQL, provider credentials, raw stack traces and unrestricted source payloads are not returned to normal users.
12. Transaction, Idempotency And Concurrency¶
12.1 Trade¶
Read-only. Query snapshot/fingerprint and source cutoff are returned. Export uses the reviewed result fingerprint; it performs no DB write.
12.2 Export Brokerage¶
Target requirements:
request token claim
+ job manifest
+ supported child transaction model
+ exact child readback
If all children remain one MySQL transaction, the Job/result identity is written in the same transaction. If future child ownership requires multiple transactions, an explicit durable workflow with per-child state/compensation is required; it must not pretend to be atomic.
Provider/AI work never runs inside the business transaction.
12.3 Outbound Cost¶
- one local cost command transaction;
- conditional expected version/status;
- exact typed transaction ownership;
- target and sibling reread;
- no file or QBO effect inside the command.
12.4 Packing Rate¶
Policy chooses one of:
ALL_OR_NOTHING intended item set
or
EXPLICIT PER_ITEM result
Current silent skip is not target parity. Conditional expected-rate update prevents lost updates.
12.5 Documents¶
Read-only render does not need idempotency. Future snapshot/delivery requires independent snapshot ID, file ID, delivery intent ID and provider result identity.
13. Exact Readback¶
Trade¶
Return:
- projection row/detail;
- all source classes and row IDs;
- formulas/policy version;
- excluded/deleted/ambiguous warnings;
- query time and source fingerprint.
Export Brokerage¶
Return:
- Job/request identity;
- inbound/Booking/outbound/equipment/lot/allocation IDs;
- each child disposition;
- current source balances;
- preserved pre-existing records;
- residual/unknown list;
- next owner.
Outbound Cost¶
Return:
- exact transaction header and lines;
- version/status;
- sibling AP list;
- files disposition as separate read;
- Trade projection freshness warning.
Packing Rate¶
Return per intended item:
- item ID;
- prior rate;
- current rate;
- disposition;
- version/readback.
Document¶
Return:
- exact source IDs;
- source fingerprint;
- template version;
- rendered fields and row source;
- fallback/template warnings;
- explicit
durable=falsefor current browser projection.
14. Exception And Recovery Matrix¶
| ID | Boundary | Current risk | Required recovery |
|---|---|---|---|
TCRD-EXC-010 |
Trade header/detail mismatch | totals cannot be reproduced from visible detail | query source breakdown; route source correction; no Trade mutation |
TCRD-EXC-020 |
Trade deleted/ambiguous source | plausible but contaminated row | preserve IDs/deleted flags; stop settlement inference |
TCRD-EXC-030 |
Export Create response lost | child set may exist | search by request/job/reference and child manifest before retry |
TCRD-EXC-040 |
Export child/balance partial | success response but source balance/pointer mismatch | freeze downstream; reconcile every child owner |
TCRD-EXC-050 |
Export Cancel unknown | some compensation may have committed | reread manifest and every child; retry only proven absent cancel |
TCRD-EXC-060 |
Cost owner ambiguous | latest AP may be unrelated | stop; inventory all AP rows and obtain ownership decision |
TCRD-EXC-070 |
Cost response unknown | create/update/delete may have committed | reread all typed/sibling AP before retry |
TCRD-EXC-080 |
Rate partial | some items updated, others skipped | reread every intended item; retry exact unchanged IDs only |
TCRD-EXC-090 |
Rate response lost / print race | display differs from persisted source | block print completion; reread source rate |
TCRD-EXC-100 |
Document fallback mismatch | output uses unexpected source class/template | stop distribution; reconcile source/template owner |
TCRD-EXC-110 |
Print result unknown | no acknowledgement exists | human custody/reprint decision; no automatic replay |
TCRD-EXC-120 |
Source changes after render | prior output is stale | reopen/reconcile; treat as new projection |
TCRD-EXC-130 |
Direct URL access mismatch | page/API/config guards differ | stop distribution; record actual role/tenant path; fix through access owner |
General rule:
error or timeout
-> reread the exact owner state
-> identify committed / absent / partial / unknown
-> resume only the missing owner action
15. Current And Target UI Responsibilities¶
15.1 React Trade Reconciliation View¶
Shows:
- filters/query time;
- equipment/deal identity;
- Purchase/Sales links and ambiguity;
- AP/AR source breakdown;
- formula-derived label with warning;
- explainability panel;
- export of the exact reviewed fingerprint.
States:
LOADING
EMPTY
DENIED
SOURCE_AMBIGUOUS
UNEXPLAINED
STALE
READY
EXPORT_FAILED
15.2 React Export Brokerage Workspace¶
Shows:
- source document proposal versus reviewed values;
- selected Booking;
- supported shape validation;
- create request identity;
- child manifest;
- source balance reconciliation;
- cancel preview/blockers;
- unknown-result recovery.
States:
PROPOSAL_ONLY
VALIDATION_BLOCKED
READY
CREATING
CREATED
PARTIAL
UNKNOWN
CANCEL_BLOCKED
CANCELLED
15.3 React Outbound Cost Editor¶
Shows all candidate AP rows and requires an explicit typed target. It never silently selects latest.
States:
NO_COST
MULTIPLE_CANDIDATES
MUTABLE
IMMUTABLE
DIRTY
SAVING
STALE
SAVED
DELETE_PENDING
UNKNOWN
15.4 React Packing Rate Editor¶
Shows persisted rate, display rate, pending state, per-item result and print readiness.
CLEAN
DIRTY
SAVING
PARTIAL
STALE
SAVED
UNKNOWN
Print action is disabled or warned while intended rate corrections are unresolved.
15.5 React Document Preview¶
Shows:
- exact source and scope;
- current/fixed/fallback field badges;
- source fingerprint and rendered time;
- warnings;
- browser print;
- optional future snapshot/file actions only when authorized.
It does not edit source data.
16. Current Caller And Target Component Map¶
flowchart TD
subgraph Current
TradePage[PHP/JS Trade Summary]
EBPage[PHP/JS Export Brokerage]
CostUI[Outbound Cost UI]
PackingPage[mkPackingList.php]
InvoicePage[localInvoice.php]
BookingPage[bookingConfirmation.php]
WeightPage[scaleticket ORDER_ID]
Helpers[Trade / Export / Cost / Booking / Report helpers]
DB[(MySQL)]
TradePage --> Helpers
EBPage --> Helpers
CostUI --> Helpers
PackingPage --> Helpers
InvoicePage --> Helpers
BookingPage --> Helpers
WeightPage --> Helpers
Helpers --> DB
end
subgraph Target
React[React Workspaces / Preview]
Next[Next.js Adapters]
TQ[Trade Query Application]
EB[Export Brokerage Application]
OC[Outbound Cost Application]
PR[Packing Rate Application]
DP[Document Projection Queries]
Repo[Typed MySQL Repositories]
Worker[Optional durable effect worker]
React --> Next
Next --> TQ
Next --> EB
Next --> OC
Next --> PR
Next --> DP
TQ --> Repo
EB --> Repo
OC --> Repo
PR --> Repo
DP --> Repo
EB -. accepted async effect only .-> Worker
DP -. accepted file/delivery only .-> Worker
end
Domain/application packages do not import React or next/*.
17. Policy Decisions Required Before Write Migration¶
Trade¶
- accepted source classes and statuses;
- meaning/naming of OPEN/SHIPPED/CLOSED/CLAIMED;
- deleted-row exclusion;
- multiple-link handling;
- date source and cutoff;
- header/detail explainability contract;
- page/API module capability.
Export Brokerage¶
- supported line/container shape;
- Job/request identity storage;
- generated Booking/equipment provenance;
- child transaction model;
- balance parity;
- AI proposal fields/confidence;
- cancellation blockers/compensation;
- retained/residual child policy.
Cost¶
- durable Outbound Cost subtype;
- one/multiple cost rows;
- mutable status and correction after confirmation;
- line identity/replace-all policy;
- file dependencies;
- valid amount/rate ranges;
- role and record scope.
Rate¶
- valid range/zero/negative;
- all-or-nothing versus explicit partial;
- expected-value/version;
- correction reason/history;
- print pending behavior.
Documents¶
- current template fields and profile configuration;
- source/fallback priority;
- UOM conversion and rounding;
- durable snapshot requirement;
- file/recipient/retention/distribution;
- print/reprint/replacement;
- direct page/API access;
- document title/branding owner.
18. Migration Waves¶
TCRD-W0 source/schema/role/Wiki/caller characterization
TCRD-W1 TypeScript Trade read model and source explainability
TCRD-W2 React + Next.js Trade and document read-only surfaces
TCRD-W3 Packing Rate correction one writer
TCRD-W4 Outbound Cost typed one writer
TCRD-W5 Export Brokerage durable Job/request/manifest one writer
TCRD-W6 Export cancellation/compensation and unknown recovery
TCRD-W7 optional accepted document snapshot/file/delivery effects
TCRD-W8 target-role stabilization and Wiki publication
TCRD-W9 PHP caller-zero and direct URL retirement
TCRD-W10 PostgreSQL later
Read-only Trade/document surfaces may migrate before mutable Cost/Rate/Export commands. A browser output migration does not require creating durable document state.
19. One-Writer And Rollback¶
For each command cohort:
PHP writer
or
TypeScript writer
Never both.
Rollback:
- restore routing to the previous writer;
- preserve committed local AP/rate/export child data;
- preserve generated child manifest/evidence;
- stop new worker claims if a durable effect exists;
- reconcile unknown in-flight results;
- do not delete/recreate child records to simulate rollback;
- do not duplicate browser print or provider delivery automatically.
Read-only rollback restores the prior query/render route and does not mutate source.
20. Caller-Zero Criteria¶
Before retiring current PHP:
- all page/menu/popup/direct URL links point to accepted replacement or compatibility redirect;
- Trade aliases and CSV callers are migrated;
- Export Create/Cancel and all child helpers are no longer active callers;
- Outbound Cost API/UI and generic transaction ambiguity are resolved;
- Packing Rate autosave and print-race callers are retired;
- all four direct output pages and report helper callers are inventoried;
- stable Wiki links are updated and accepted;
- Runtime logs show zero legacy calls for the observation window;
- rollback route remains available until stabilization;
- no in-flight Export Job or unknown Cost/Rate command remains.
21. PostgreSQL Preservation¶
Preserve explicitly:
- decimal precision and rounding policy;
- null versus empty dates/strings;
- tenant-scoped identities;
- source-class breakdown;
- request/job IDs and unique constraints;
- cost subtype and optimistic version;
- rate correction history;
- document source fingerprint/template version;
- JSON manifest schema/version if used;
- soft delete and audit/reversal evidence;
- case/collation behavior for references and markers.
Do not rely on MySQL implicit casts or permissive aggregation after migration.
22. Stable Scenario Catalog¶
22.1 Trade¶
TRADE-SCN-010 explainable single equipment deal
TRADE-SCN-020 header/detail source-class mismatch
TRADE-SCN-030 mutable outbound AP contributes to derived close
TRADE-SCN-040 multiple inbound/outbound links
TRADE-SCN-050 deleted source contamination
TRADE-SCN-060 date/filter/cutoff behavior
TRADE-SCN-070 page/API capability mismatch
TRADE-SCN-080 CSV fingerprint parity and zero writes
22.2 Export Brokerage¶
EB-SCN-010 supported one-line create
EB-SCN-020 generated equipment/Booking provenance
EB-SCN-030 multi-line/container supported-shape boundary
EB-SCN-040 create response loss / child search
EB-SCN-050 balance parity
EB-SCN-060 safe unprogressed cancel
EB-SCN-070 progressed cancel blockers
EB-SCN-080 cancel response loss
EB-SCN-090 manual/composed pair provenance denial
EB-SCN-100 AI proposal mismatch
22.3 Cost¶
COST-SCN-010 create one typed mutable cost
COST-SCN-020 multiple AP ownership ambiguity
COST-SCN-030 immutable state denial
COST-SCN-040 omitted header preservation
COST-SCN-050 replace-all line behavior
COST-SCN-060 response loss/concurrent update
COST-SCN-070 file dependency
COST-SCN-080 target-role/record denial
22.4 Rate¶
RATE-SCN-010 one exact item correction
RATE-SCN-020 multi-item all-success
RATE-SCN-030 mixed eligible/ineligible IDs
RATE-SCN-040 zero/negative/range
RATE-SCN-050 concurrent stale rate
RATE-SCN-060 response loss
RATE-SCN-070 print while pending
RATE-SCN-080 amount-only transient edit
22.5 Documents¶
DOC-SCN-010 Packing complete equipment-commodity source
DOC-SCN-020 Packing fallback switch
DOC-SCN-030 Purchase invoice formula/UOM matrix
DOC-SCN-040 Booking confirmation linked/unlinked Sales reference
DOC-SCN-050 Sales Weight Ticket with/without physical Scale
DOC-SCN-060 mixed-UOM/raw aggregation
DOC-SCN-070 direct URL role/config/tenant negatives
DOC-SCN-080 print cancel/unknown and source drift
DOC-SCN-090 zero durable file/email/state assertion
22.6 Migration¶
TCRD-MIG-SCN-010 Trade list/detail/source parity
TCRD-MIG-SCN-020 document projection parity
TCRD-MIG-SCN-030 rate one-writer and rollback
TCRD-MIG-SCN-040 cost one-writer and rollback
TCRD-MIG-SCN-050 Export Job idempotency
TCRD-MIG-SCN-060 Export cancel/compensation
TCRD-MIG-SCN-070 optional document effect idempotency
TCRD-MIG-SCN-080 PHP caller-zero
TCRD-MIG-SCN-090 PostgreSQL parity
23. Evidence Template¶
For every scenario record:
scenario ID
source and target revision
profile / tenant / role
fixture IDs
current route and target route
request token / source fingerprint
pre-state
UI/network/API result
DB authoritative readback
child/provider/file result when applicable
console/log trace
cleanup/rollback
status: PASS | FAIL | BLOCKED | NOT_RUN
Trade/document read scenarios require zero writes. Export/Cost/Rate write scenarios require exact disposable fixture cleanup and sibling/non-target verification.
24. Definition Of Ready¶
A selected migration wave is ready only when:
- applicable
TCRD-POL-*decisions are accepted; - target role/page/API/record access is defined;
- data/field/precision/source priority is defined;
- stable DTO/error/idempotency/transaction/readback exists;
- current callers are inventoried;
- duplicate/timeout/partial recovery is accepted;
- one-writer/rollback is approved;
- current Wiki content and stable route are known;
- required scenario fixtures/evidence plan exists;
- no hidden cross-owner write remains in the proposed adapter.
25. Definition Of Complete¶
A capability is complete only when:
- current and target behavior parity or approved difference is proven;
- target-role UI and API paths pass;
- exact state/data/readback passes;
- unknown/partial/correction recovery passes;
- Wiki is published and rendered under named authorization;
- observation shows no unexplained errors/duplicates;
- legacy caller-zero is proven;
- rollback is tested;
- the user accepts the visible result;
- no output is mislabeled as durable completion.
---¶
Source:
docs/reconstruction/MK_TRADE_COST_RATE_DOCUMENT_OUTPUTS_CAPABILITY_REBUILD_PACKET.md— ctc repository · This page is an English translation of the source document. Identifiers, file paths and code symbols are unchanged.