MK Order-First Core Capability Rebuild Packet¶
- Packet status:
DETAILED SOURCE-RECONCILED REBUILD INPUT / PROCESS-OWNER AND TARGET-ROLE REVIEW REQUIRED - Capability family: Commercial Agreement, Inbound Purchase, Outbound Sales and Booking
- Composite owner:
PROC-OMS-ORDER-TO-PACKING-MK - Atomic owners:
PROC-OMS-COMMERCIAL-ORDER-MKPROC-OMS-INBOUND-PURCHASE-TO-INVENTORY-MKPROC-OMS-OUTBOUND-SALES-ORDER-MKPROC-TMS-BOOKING-LIFECYCLE-MK- Operating profile:
mk-order - Current data authorities:
T_COMMERCIAL_ORDER,T_COMMERCIAL_ORDER_ITEM,T_LOAD,T_LOAD_ITEM,T_BOOKINGand separately owned execution/inventory children - Target stack: React + Next.js + framework-independent TypeScript application/domain/repository contracts + MySQL first + separate Node.js worker where durable effects are required
- Later database target: PostgreSQL after accepted React + Next.js + TypeScript + MySQL stabilization
- Process sources:
- Current source authority:
MK_ORDER_FIRST_CORE_SOURCE_AUTHORITY.md - Important boundary: this packet assembles the four current owners for reconstruction and migration. It does not replace their process semantics, approve open policies or claim that the target architecture is implemented.
1. Capability Outcome¶
1.1 Business problem¶
MK is order-first. Operators must be able to establish commercial purchase and sales terms, execute inbound receipts and outbound demand, and connect export/container planning through Booking without forcing the CTC appointment/loader/yard workflow onto MK.
The system must preserve the following distinctions:
Commercial agreement
!= execution order
!= physical receipt/shipment
!= inventory lot
!= allocation
!= Booking plan
!= container/equipment execution
!= Scale completion
!= document output
A future implementation must let each owner expose its own state while making cross-owner handoffs understandable and recoverable.
1.2 Required user-visible result¶
An authorized MK operator can:
- search existing Commercial, Inbound, Outbound and Booking records before creating work;
- create or update one Commercial Purchase or Sales agreement and reread its exact terms and lines;
- create or update an Inbound Purchase linked to the intended Commercial Purchase when applicable;
- complete an eligible physical-scale or no-scale receipt and verify the exact item, transload and inventory-lot result;
- create or update an Outbound Sales order linked to the intended Commercial Sales and Booking when applicable;
- distinguish requested outbound lines from actual inventory allocation;
- create or update a Booking without treating Booking Save as proof of order, inventory, allocation, Scale, packing or document completion;
- see every incomplete child, conflict, partial result and next owner;
- recover from timeout or ambiguous response by rereading the exact owning records before retry;
- continue through stable Wiki topics even when the implementation route later moves from PHP to React + Next.js.
1.3 Explicit non-goals¶
This packet does not create or approve:
- one universal MK order status;
- one transaction spanning Commercial, Inbound, Outbound, Booking, Inventory, Allocation and Scale;
- numeric
CLIENT_IDbusiness-policy branching as the target model; - a generic order/workflow engine;
- a direct route-by-route PHP-to-TypeScript copy;
- automatic Commercial fulfillment from current execution labels;
- automatic allocation from direct Outbound Save;
- a universal requirement that every MK order use Scale, Booking or every output document;
- hidden inventory/allocation mutation inside target Booking Save;
- a new schema solely because the current source is difficult to map;
- PostgreSQL conversion in the first React/Next.js write wave.
2. Current And Target Truth Table¶
| Statement | Current truth |
|---|---|
| MK is an approved order-first operating profile | Yes |
| Commercial, Inbound, Outbound and Booking have separate registered Process owners | Yes |
| One composite DB status proves Order-to-Packing completion | No |
| Commercial status is automatically derived from execution | No |
| Inbound header label, item state, transload state and lot state are one lifecycle | No |
| Direct Outbound Save creates inventory allocation | No |
| Outbound readiness means physical/business completion | No |
| Booking flags form one approved lifecycle | No |
| Booking Save currently has cross-domain compatibility side effects | Yes |
| Current role IDs and Client 2 selectors are approved target-domain policy | No |
| React + Next.js target implementation exists | No |
| This packet can guide current characterization and future implementation | Yes |
Every document, Wiki draft and migration report must distinguish:
CURRENT SOURCE-RECONCILED
CURRENT RUNTIME-VERIFIED
USER-APPROVED FUTURE PLAN
TARGET MIGRATION DESIGN
OPEN POLICY / UNKNOWN
3. Capability Decomposition¶
3.1 Commercial Agreement¶
Owns:
- Purchase or Sales agreement identity;
- counterparty and commercial terms;
- agreement lines, quantity, UOM and rate;
- optional Purchase-to-Sales relationship;
- manual current status label;
- confirmation projection/print source.
Does not own:
- receipt/shipment execution;
- inventory lot or allocation;
- Booking/container execution;
- Scale evidence;
- financial cost or output completion.
3.2 Inbound Purchase¶
Owns:
- Purchase execution header and items;
- optional Commercial Purchase references;
- scheduled versus received/transloaded item semantics;
- inbound execution bridge synchronization;
- receipt-finalization handoff to Inventory Lot;
- current no-scale eligibility and exact receipt readback.
Does not own:
- downstream allocation;
- outbound demand;
- Scale ticket authority;
- arbitrary inventory-lot correction after receipt;
- the business meaning of target next-work intent beyond the current response.
3.3 Outbound Sales¶
Owns:
- Sales execution header and requested items;
- optional Commercial Sales and Booking references;
- outbound equipment/container bridge creation and references;
- requested demand and derived readiness projections;
- boundary to Allocation, Scale, Packing, Delivery and Cost.
Does not own:
- inventory allocation balance mutation through normal direct Save;
- Scale completion;
- Booking lifecycle;
- packing/document completion;
- Commercial Sales fulfillment policy.
3.4 Booking¶
Owns:
- ocean/export booking terms;
- shipping line, cutoffs, ports and planned container quantities;
- party/terminal/inspector references;
- independent flags and manual inactive marker;
- optional outbound Sales link;
- clone behavior and exact Booking readback.
Does not own in the target model:
- inventory-lot materialization;
- allocation deletion or restoration;
- full order/item upsert;
- Scale completion;
- document/email completion;
- hidden generic
BOOKING_RATEcompatibility mutation.
3.5 Order-First Composite¶
Owns only:
- child selection and optionality;
- cross-child identity and non-implication;
- human reconciliation of entered children;
- one explicit disposition per required child.
Suggested composite dispositions:
COMPLETE
CHILD_PENDING
PARTIAL_REVIEW
NOT_APPLICABLE
These remain reconciliation labels, not a universal persisted status.
4. Actors, Roles And Semantic Capabilities¶
4.1 Actor matrix¶
| Actor | Normal responsibility | Required visibility | Allowed command families | Recovery responsibility | Prohibited behavior |
|---|---|---|---|---|---|
| MK Commercial operator | establish Purchase/Sales terms | own tenant agreements, lines and relations | Commercial create/update/relate/status/eligible delete | ambiguous create/update/link reread | infer execution fulfillment or edit child execution directly |
| MK Receiving operator | maintain Inbound Purchase and receipt handoff | inbound header/items, Commercial link, receipt/transload/lot projection | scheduled CRUD, approved receipt-finalize/no-scale command | receipt partial and lot handoff escalation | use header label as receipt proof or bypass Inventory/Scale owner |
| MK Shipping operator | maintain Outbound Sales and Booking | outbound demand, booking/equipment/packing handoffs | outbound CRUD, eligible booking link, Booking CRUD/clone/inactivate | bridge/link/Booking partial reconciliation | treat readiness as completion or direct-save allocation |
| Inventory/allocation operator | apply and reverse inventory allocation | eligible lots, demand, current balance and allocation | allocation-owner commands only | stale/overdraw/partial allocation recovery | mutate demand/order lines to force balance parity |
| Scale operator | record physical gross/tare and finalize eligible owner handoff | ticket, exact order/item and finalization status | Scale-owner commands only | checked-out/finalize-pending recovery | rewrite order/lot from Scale UI outside owner command |
| Manager/administrator | bounded review and correction | authorized tenant-wide detail and timeline | explicitly approved correction/recovery | policy-based manual disposition | use broad visibility as evidence or raw-edit cross-owner state |
| Migration/support operator | characterize, cut over and reconcile | current and target read models, request/effect IDs | approved one-writer switches and support commands | rollback/caller-zero/unknown-result | dual-write or replay completed physical/business work |
4.2 Proposed semantic capabilities¶
Current menu/role IDs must be mapped to semantic capabilities. Do not copy numeric role IDs into TypeScript domain logic.
oms.commercial-order.view
oms.commercial-order.create
oms.commercial-order.update
oms.commercial-order.relate
oms.commercial-order.set-status
oms.commercial-order.delete-unexecuted
oms.commercial-order.print
oms.inbound-order.view
oms.inbound-order.create
oms.inbound-order.update-scheduled
oms.inbound-order.finalize-from-scale
oms.inbound-order.complete-without-scale
oms.inbound-order.correct-received
oms.inbound-order.delete-unprogressed
oms.outbound-order.view
oms.outbound-order.create
oms.outbound-order.update-scheduled
oms.outbound-order.link-booking
oms.outbound-order.correct-progressed
oms.outbound-order.delete-unprogressed
tms.booking.view
tms.booking.create
tms.booking.update
tms.booking.clone
tms.booking.link-sales-order
tms.booking.mark-inactive
tms.booking.recovery
oms.order-first.reconciliation.view
oms.order-first.recovery
4.3 Authorization invariants¶
- Tenant and operating profile are resolved server-side.
mk-orderapplicability is a profile/capability decision, notCLIENT_ID === 2domain logic.- Page visibility is not API authorization.
- Direct IDs must be verified against the current tenant, active lifecycle and expected record class.
- A commercial item reference must belong to the selected commercial agreement.
- A Booking link must point to an active same-tenant Outbound Sales order under the accepted policy.
- A self-service or record-scoped request must not accept an authoritative actor/tenant from the body.
- Denied and foreign-record responses must not disclose protected detail or mutate mirrors/children.
5. Cross-Capability Identity And Handoff Contract¶
5.1 Stable identities¶
| Concept | Current local identity | Target contract |
|---|---|---|
| Commercial agreement | T_COMMERCIAL_ORDER.ID plus UUID where present |
CommercialAgreementId and immutable tenant-scoped UUID |
| Commercial line | T_COMMERCIAL_ORDER_ITEM.ID |
CommercialAgreementLineId with parent identity |
| Inbound/Outbound order | T_LOAD.ID plus UUID |
ExecutionOrderId with explicit direction/class |
| Order item | T_LOAD_ITEM.ID plus UUID |
ExecutionOrderItemId with parent and source relation |
| Booking | T_BOOKING.ID plus UUID |
BookingId |
| Inbound execution bridge | T_TRANSLOAD.ID |
InboundExecutionId |
| Scale evidence | T_SCALE_TICKET.ID |
ScaleTicketId plus event/correction lineage |
| Received inventory | T_INVENTORY_LOT.ID |
InventoryLotId with exact source item/transload |
| Allocation | T_LOAD_ALLOCATION.ID |
AllocationId with lot, demand item and quantity/weight |
| Equipment bridge | T_EQUIPMENT.ID, T_EQUIPMENT_LOAD.ID |
EquipmentId and EquipmentLoadId |
5.2 Handoff matrix¶
| From | Completion evidence | Carried identity | To | Required reread | Does not imply |
|---|---|---|---|---|---|
| Commercial Purchase | exact agreement and lines readable | agreement/line IDs | Inbound Purchase | agreement type, counterparty, line terms | receipt or inventory |
| Commercial Sales | exact agreement and lines readable | agreement/line IDs | Outbound Sales | agreement type, customer, line terms | allocation, Booking or shipment |
| Inbound scheduled order | header/items readable | inbound/order-item IDs | Scale or no-scale completion | item state and eligibility | received lot |
| Scale checkout | completed ticket evidence | scale ticket + order/item IDs | Inbound finalize | ticket, order and item current state | lot materialization |
| Inbound finalize | item/transload receipt state plus exact lot | item, transload, lot IDs | Inventory/Allocation | lot balance/source/placement | outbound allocation |
| Inventory lot | active available balance | lot ID, UOM, quantity/weight | Allocation | current balance and demand | outbound completion |
| Outbound scheduled order | header/items readable | outbound/order-item IDs | Booking/Allocation/Scale | references, demand, bridge | allocation or physical execution |
| Booking | exact header/link/flags readable | Booking ID and optional sales-order ID | Packing/container planning | Booking and bridge projections | inventory, scale or documents |
| Allocation | allocation row and lot balance reread | allocation/lot/demand IDs | outbound execution | allocation and remaining balance | packing, scale or delivery |
5.3 Non-implication rules¶
Commercial OPEN/FULFILLED label != execution quantity reconciled
Commercial linked PO/SO != both executions exist
Inbound header COMPLETED != receipt finalized
Scale checkout != Inbound finalize
Inbound item UNLOADED != inventory lot is correct/readable
Receipt branch selection != outbound/allocation created
Outbound READY_FOR_FINAL_EXECUTION != allocated/packed/scaled/delivered
Outbound item weight != allocation row
Booking Save != Sales/Inventory/Allocation synchronized safely
Booking NOT_IN_USE != child cleanup or access denial
Clone success != cloned containers/files/children
Print/render success != durable output completion
6. Normal Operator Flows¶
6.1 Commercial Purchase/Sales agreement¶
| Step ID | Actor | Action | Authoritative readback | Next owner |
|---|---|---|---|---|
MKCORE-STEP-010 |
Commercial operator | search exact number/reference/date/counterparty before create | list/detail exact match | Commercial operator |
MKCORE-STEP-020 |
Commercial operator | create Purchase or Sales agreement with reviewed lines | header, lines, generated number, normalized totals/terms | Commercial operator |
MKCORE-STEP-030 |
Commercial operator | relate Purchase to Sales when required | Purchase stored link and Sales reverse projection | receiving/shipping owner |
MKCORE-STEP-040 |
Commercial operator | update only within accepted execution boundary | exact header/line set and execution references | child execution owner |
MKCORE-STEP-050 |
Commercial operator | set current visible status under approved business rule | exact status plus separate execution projection | reviewer |
MKCORE-STEP-060 |
Commercial operator | delete only an accepted unexecuted agreement | active row absent, counterpart unlinked | support/audit if conflict |
6.2 Inbound Purchase to Inventory¶
| Step ID | Actor | Action | Authoritative readback | Next owner |
|---|---|---|---|---|
MKCORE-STEP-110 |
Receiving operator | search and create scheduled Inbound Purchase | header/items and Commercial pointers | receiving operator |
MKCORE-STEP-120 |
Receiving operator | maintain scheduled values through atomic save | one all-or-nothing order/item result for the selected request | Scale/no-scale owner |
MKCORE-STEP-130 |
Scale operator | perform physical scale stages when applicable | Scale ticket and stage evidence | receiving operator |
MKCORE-STEP-140 |
Receiving operator | run Inbound finalize from completed Scale | item/transload receipt state and exact lot | inventory/allocation owner |
MKCORE-STEP-150 |
Receiving operator | run eligible no-scale completion when applicable | no scale ticket, item/transload receipt state and exact lot | inventory/allocation owner |
MKCORE-STEP-160 |
Receiving operator | choose next-work intent | current response and explicit operator intent | inventory/allocation operator |
The current next-work branch is not durable. If the browser response is lost, confirm intent with the operator; do not infer it from receipt rows.
6.3 Outbound Sales to Booking/Allocation¶
| Step ID | Actor | Action | Authoritative readback | Next owner |
|---|---|---|---|---|
MKCORE-STEP-210 |
Shipping operator | search and create Outbound Sales | header/items, Commercial Sales link and bridge fields | shipping operator |
MKCORE-STEP-220 |
Shipping operator | correct scheduled header/items through atomic save | exact order/item set and bridge references | allocation/booking owner |
MKCORE-STEP-230 |
Inventory operator | allocate eligible lot to demand | allocation row and updated lot balance | shipping/physical owner |
MKCORE-STEP-240 |
Shipping operator | link or create Booking when required | exact Booking and outbound reverse/forward relation | booking operator |
MKCORE-STEP-250 |
Scale/Delivery/Packing owner | perform required child process | child-owned completion evidence | order-first reconciliation |
Direct Outbound Save must remain distinct from Allocation. An UNMAPPED line is valid current data but not inventory-backed execution.
6.4 Booking lifecycle¶
| Step ID | Actor | Action | Authoritative readback | Next owner |
|---|---|---|---|---|
MKCORE-STEP-310 |
Booking operator | search Booking/invoice before create | exact list/detail match | booking operator |
MKCORE-STEP-320 |
Booking operator | create Booking and optional Sales link | header, invoice, flags, link and current compatibility-result disposition | shipping/packing owner |
MKCORE-STEP-330 |
Booking operator | update only intended Booking fields | exact Booking plus every affected child/mirror | child owner if partial |
MKCORE-STEP-340 |
Booking operator | clone one to nine rows | exact suffix search and carried/omitted values | booking operator |
MKCORE-STEP-350 |
Booking operator | mark inactive when intended | NOT_IN_USE plus child projections |
reviewer |
Target Booking commands must return explicit child/handoff outcomes. They must not report one generic success while compatibility sync partially mutates another domain.
7. State Models¶
7.1 Commercial state dimensions¶
Persisted current status label:
DRAFT
OPEN
PARTIAL
FULFILLED
CANCELLED
Current source does not prove an automatic transition policy. Target design must keep manual agreement disposition separate from derived execution utilization.
Proposed derived utilization projection:
UNREFERENCED
REFERENCED_BY_INBOUND
REFERENCED_BY_OUTBOUND
PARTIALLY_UTILIZED
FULLY_UTILIZED
CONFLICT
This projection is not permission to add a column.
stateDiagram-v2
[*] --> OPEN
OPEN --> CANCELLED: approved cancellation
OPEN --> PARTIAL: approved manual policy
PARTIAL --> FULFILLED: approved manual policy
OPEN --> FULFILLED: approved manual policy
CANCELLED --> OPEN: only if an explicit reopen policy is approved
7.2 Inbound state dimensions¶
Header close label:
OPEN
IN_PROGRESS
COMPLETED
CANCELLED
Item operational state:
SCHEDULED
UNLOADED
TRANSLOADED
Transload execution state:
SCHEDULED
UNLOADING
UNLOADED
TRANSLOADING
TRANSLOADED
terminal variants
Derived receipt checkpoint:
SCHEDULED_ONLY
SCALE_IN_PROGRESS
SCALE_CHECKED_OUT_FINALIZE_PENDING
RECEIPT_FINALIZED
LOT_MATERIALIZED
RECEIPT_CONFLICT
Inventory lot state remains inventory-owned.
stateDiagram-v2
[*] --> SCHEDULED_ONLY
SCHEDULED_ONLY --> SCALE_IN_PROGRESS: scale-in
SCALE_IN_PROGRESS --> SCALE_CHECKED_OUT_FINALIZE_PENDING: scale-out
SCALE_CHECKED_OUT_FINALIZE_PENDING --> RECEIPT_FINALIZED: finalize inbound
SCHEDULED_ONLY --> RECEIPT_FINALIZED: eligible complete-without-scale
RECEIPT_FINALIZED --> LOT_MATERIALIZED: exact source lot created/read
SCALE_CHECKED_OUT_FINALIZE_PENDING --> RECEIPT_CONFLICT: finalize fails or cardinality mismatch
RECEIPT_FINALIZED --> RECEIPT_CONFLICT: item/transload/lot disagree
7.3 Outbound state dimensions¶
Header close label:
OPEN
IN_PROGRESS
COMPLETED
CANCELLED
Derived source mapping:
UNMAPPED
SCHEDULED_LINKED
WAREHOUSE_LINKED
TRANSLOAD_LINKED
LINKED
Proposed derived allocation disposition:
UNALLOCATED
PARTIALLY_ALLOCATED
ALLOCATED
OVERDRAWN_CONFLICT
SOURCE_MISSING
Proposed bridge disposition:
NO_BOOKING
BOOKING_LINKED
EQUIPMENT_LINKED
EXECUTION_LOCKED
BRIDGE_CONFLICT
Readiness remains a projection and not a terminal command state.
7.4 Booking state dimensions¶
Current independent fields include:
NOT_IN_USE;- packing submitted;
- invoiced;
- PierPass;
- clean-truck fee;
- optional Sales link;
- container counts and cutoffs.
Proposed Booking lifecycle projection:
ACTIVE
INACTIVE
LINK_CONFLICT
CHILD_SYNC_PARTIAL
Compatibility sync disposition must be explicit during migration:
NOT_REQUESTED
SUCCEEDED
PARTIAL
FAILED
UNKNOWN
RETIRED
Do not collapse independent flags into this projection.
8. Authoritative Data And Field Contracts¶
8.1 Commercial header DTO¶
type CommercialAgreement = {
id: string;
number: string;
type: "PURCHASE" | "SALES";
statusLabel: "DRAFT" | "OPEN" | "PARTIAL" | "FULFILLED" | "CANCELLED";
counterpartyId: string;
referenceNumber: string;
contractDate: string | null;
shippingPeriod: string | null;
contactPerson: string;
buyerName: string;
incoterm: string;
paymentTerm: string;
currencyText: string;
loadingPort: string;
destinationPort: string;
weightText: string;
containerPlan: {
quantity40F: number;
quantity40S: number;
quantity40H: number;
quantity45H: number;
quantity20S: number;
displayText: string;
primarySize: string;
};
packaging: string;
shipmentAllowance: string;
estimatedTotalAmount: string;
originOfMaterial: string;
shipTo: string;
requiredDocuments: string;
remark: string;
linkedAgreementId: string | null;
totalQuantity: string;
version: string | null;
};
Consequential current rules to preserve or deliberately replace:
- quantity precision: three decimals;
- rate precision: four decimals;
- estimated amount: two decimals;
- UOM allowlist;
- positive quantity;
- tenant-scoped commodity and counterparty;
- generated PO/SO number and duplicate handling;
- signature size/storage capability;
- container quantities currently normalized/clamped;
- current request adapter uppercases many scalar/free-text values;
- pre-execution line replacement can change line IDs.
8.2 Commercial line DTO¶
type CommercialAgreementLine = {
id: string;
agreementId: string;
commodityId: string | null;
commodityName: string;
quantity: string;
uom: string;
rate: string;
lmeAluminum: string | null;
lmeCopper: string | null;
remark: string;
version: string | null;
};
Line replacement versus stable-line update is an open target decision. Migration must not silently change identity semantics.
8.3 Inbound order DTO¶
type InboundPurchase = {
id: string;
number: string;
closeLabel: "OPEN" | "IN_PROGRESS" | "COMPLETED" | "CANCELLED";
commercialAgreementId: string | null;
referenceNumber: string;
loadNumber: string;
orderType: string;
supplierId: string | null;
shipperId: string | null;
carrierId: string | null;
appointmentAt: string | null;
inTime: string | null;
outTime: string | null;
scaleTicketId: string | null;
items: InboundPurchaseItem[];
receipt: ReceiptProjection;
version: string | null;
};
type InboundPurchaseItem = {
id: string;
orderId: string;
commercialLineId: string | null;
commodityId: string | null;
commodityName: string;
quantity: string;
uom: string;
netWeight: string;
operationalState: "SCHEDULED" | "UNLOADED" | "TRANSLOADED";
sourceTransloadId: string | null;
inventoryLotId: string | null;
allocatedQuantity: string;
allocatedWeight: string;
version: string | null;
};
8.4 Receipt projection¶
type ReceiptProjection = {
state:
| "SCHEDULED_ONLY"
| "SCALE_IN_PROGRESS"
| "SCALE_CHECKED_OUT_FINALIZE_PENDING"
| "RECEIPT_FINALIZED"
| "LOT_MATERIALIZED"
| "RECEIPT_CONFLICT";
scaleTicketId: string | null;
transloadIds: string[];
inventoryLotIds: string[];
blockingReasons: string[];
allowedActions: string[];
};
The target must support the accepted multi-line policy before claiming multi-line receipt completion. Current exact source-to-lot cardinality can reject otherwise distributed scale results.
8.5 Outbound order DTO¶
type OutboundSales = {
id: string;
number: string;
closeLabel: "OPEN" | "IN_PROGRESS" | "COMPLETED" | "CANCELLED";
commercialAgreementId: string | null;
bookingId: string | null;
referenceNumber: string;
orderType: "OCEAN_FREIGHT" | "LOCAL" | string;
customerId: string | null;
containerNumber: string;
containerSize: string;
equipmentId: string | null;
equipmentLoadId: string | null;
scaleTicketId: string | null;
items: OutboundSalesItem[];
allocation: AllocationProjection;
bridge: BridgeProjection;
readiness: Record<string, boolean>;
version: string | null;
};
type OutboundSalesItem = {
id: string;
orderId: string;
commercialLineId: string | null;
commodityId: string | null;
commodityName: string;
requestedQuantity: string;
requestedWeight: string;
uom: string;
rate: string;
sourceMapping: string;
allocatedQuantity: string;
allocatedWeight: string;
version: string | null;
};
8.6 Booking DTO¶
type Booking = {
id: string;
number: string;
shippingLine: string;
bookingType: string;
billingCompanyId: string | null;
shipperIds: string[];
inspectorId: string | null;
pickupTerminalId: string | null;
returnTerminalId: string | null;
vesselName: string;
portOfLoading: string;
portOfDischarge: string;
cutoffAt: string | null;
siCutoffAt: string | null;
plannedContainers: Record<string, number>;
invoiceNumber: string;
salesOrderId: string | null;
flags: {
packingSubmitted: boolean;
invoiced: boolean;
pierPass: boolean;
cleanTruckFee: boolean;
notInUse: boolean;
};
compatibilityDisposition: "NOT_REQUESTED" | "SUCCEEDED" | "PARTIAL" | "FAILED" | "UNKNOWN" | "RETIRED";
version: string | null;
};
8.7 Mirror and derived classification¶
| Value | Classification |
|---|---|
| Commercial status | current persisted manual label |
| Commercial execution utilization | derived projection |
| Inbound header close label | current persisted manual label |
| Inbound item state | persisted operational state through compatibility mapping |
| Transload state | separately persisted execution state |
| Receipt projection | derived across ticket/item/transload/lot |
| Outbound readiness | derived projection |
| Outbound allocation status | derived from allocation and lot balance |
| Booking flags | independent persisted fields |
| Booking compatibility result | current implicit/partially observable side effect; target explicit disposition |
| Schedule pages | read projections, not state owners |
| Print/document render | nondurable projection unless a child contract says otherwise |
9. Semantic Query Contracts¶
GetMkOrderFirstOverview¶
Audience: authorized MK operator/manager
Input: date/range, exact references and filters
Output: one cross-child projection per logical work set with explicit child dispositions
Mutation: none
Freshness: request-time for action decisions
Constraint: absence under a filter is not proof of nonexistence
GetCommercialAgreementList¶
Returns exact agreement IDs, number, type, status label, counterparty, references, totals, relation and derived execution utilization.
GetCommercialAgreementDetail¶
Returns header, stable line DTOs, relation, execution references, allowed actions, warnings and current version/freshness token.
GetInboundPurchaseDetail¶
Returns:
- header and all active lines;
- Commercial references;
- item/transload/scale/lot identities;
- receipt projection;
- allocation/placement/ledger blockers relevant to correction/delete;
- exact allowed actions and blocking reasons.
GetOutboundSalesDetail¶
Returns:
- header and all active lines;
- Commercial/Booking/equipment references;
- allocation rows and lot-balance projection;
- Scale/Delivery/Packing/Cost child dispositions;
- readiness as informational fields;
- exact allowed actions and blocking reasons.
GetBookingDetail¶
Returns:
- typed Booking header and independent flags;
- linked Sales order and equipment/container projections;
- clone/inactive eligibility;
- current compatibility disposition and affected child IDs when available;
- allowed actions and blocking reasons.
GetReceiptReconciliation¶
Returns one source-backed view of:
order/items
scale ticket
transload execution
inventory lots
placement
allocation/ledger blockers
It performs no repair.
GetOrderFirstHandoffStatus¶
Returns each required/optional child with:
processId
applicability
currentDisposition
authoritativeIds
blockingReason
nextOwner
allowedRecovery
10. Semantic Command Contracts¶
10.1 CreateCommercialAgreement¶
Actor: commercial create capability
Input: requestToken + typed header/line DTOs
Validation: tenant, type, counterparty, commodities, quantity/UOM/rate, relation candidate
Transaction: header + lines + relation in one local transaction
Idempotency: tenant + requestToken or accepted natural identity
Return: agreement ID/number and exact detail
Timeout recovery: search request/natural identity before recreate
Effects: none
10.2 UpdateCommercialAgreement¶
Must declare the selected mutation mode:
PATCH_HEADER
UPDATE_LINES_IN_PLACE
REPLACE_LINE_SET
RELATE_AGREEMENT
SET_STATUS
The target must not hide a full line replacement behind a generic PATCH. Post-execution allowed fields require an accepted policy.
10.3 RelateCommercialAgreements¶
Actor: commercial relation capability
Predicate: same tenant, opposite type, non-self, active and policy-eligible
Cardinality/cycle: explicit accepted rule required
Transaction: relation write and exact two-sided read projection
Idempotency: returning the same accepted relation is not a duplicate error
10.4 DeleteUnexecutedCommercialAgreement¶
Requires explicit checks for both header-level and item-level execution references, links and archived/reference evidence. It soft-deletes under current retention semantics and returns the counterpart unlink result.
10.5 CreateInboundPurchase¶
Actor: inbound create capability
Input: requestToken + typed header and at least one accepted line
Transaction: header + lines + initial execution bridge under defined owner
Return: order ID/number + exact detail
Does not: finalize receipt, create allocation or infer branch intent
10.6 AtomicSaveInboundPurchase¶
For scheduled/unprogressed edits:
- validates complete header and item set;
- uses one local transaction;
- conditionally updates known versions;
- applies staged deletions only when allowed;
- returns exact header/items and child-impact summary;
- rejects unsafe post-receipt mutation rather than recalculating lot balance from source values.
10.7 FinalizeInboundReceiptFromScale¶
Actor: receiving/scale-finalize capability
Input: order ID, item distribution, completed scale-ticket identity, requestToken
Predicate: ticket complete, order/items current, no prior receipt finalization conflict
Transaction: item receipt state + transload finalization + inventory-lot materialization under one accepted local boundary
Return: ticket/order/items/transload/lot readback
Idempotency: repeated request returns existing logical finalization
Partial recovery: checked-out ticket is preserved; retry only finalization when absent
10.8 CompleteInboundReceiptWithoutScale¶
Requires an explicit accepted eligibility policy. Current Brokerage/OCEAN_FREIGHT restrictions and single-line/cardinality behavior must be characterized before migration.
Branch intent is returned separately:
WAREHOUSE_ONLY
DIRECT_OUTBOUND
MIXED
If branch intent must survive response loss, the target needs an approved durable field/event. Do not infer it from receipt state.
10.9 CorrectReceivedInboundPurchase¶
Must be a dedicated correction/reversal command with:
- current lot, allocation, ledger and placement reread;
- lower bounds derived from consumed/allocated quantities;
- explicit quantity/weight/UOM rules;
- audit/reason/actor;
- compensating inventory effects;
- no raw source-row overwrite that resets remaining balances.
10.10 CreateOutboundSales¶
Actor: outbound create capability
Input: requestToken + typed header/items + optional Commercial/Booking references
Transaction: header + items + approved equipment bridge setup
Return: order, items, bridge and warnings
Does not: create allocation
10.11 AtomicSaveOutboundSales¶
Scheduled/unprogressed changes only unless a progressed correction policy explicitly allows the field. Allocated items require allocation-aware commands; normal update cannot silently diverge demand from allocation.
10.12 LinkOutboundBooking¶
Actor: outbound/booking link capability
Predicate: same tenant, active compatible Sales order and Booking
Transaction: accepted forward/reverse pointer contract
Return: both sides reread
Delete cleanup: exact reverse/forward pointer disposition required
10.13 DeleteUnprogressedOutboundSales¶
Requires no Scale, Delivery, Allocation, Transload, Cost or other protected child. The command must clear or explicitly preserve Booking reverse pointers according to policy and return the exact result.
10.14 CreateBooking¶
Actor: Booking create capability
Input: requestToken + typed Booking fields + optional Sales order link
Transaction: Booking header and accepted link only
Return: Booking detail and explicit handoff requests/results
Target rule: no hidden order/inventory/allocation mutation inside Booking Save
10.15 UpdateBooking¶
Updates only Booking-owned fields and accepted link metadata. Cross-owner work is returned as explicit commands/intents, never swallowed compatibility side effects.
10.16 CloneBooking¶
Input: source Booking ID, clone count 1..9, explicit carry policy, requestToken
Return: created Booking IDs/numbers and carried/omitted fields
Idempotency: suffix search alone is not the target idempotency contract
Children: containers/files/allocations are not cloned unless a separate child command is explicitly approved
10.17 MarkBookingInactive¶
Changes the manual Booking marker only. It does not silently detach Sales, delete containers, revoke outputs or cancel child work. The UI must show remaining active children and policy warnings.
10.18 ReconcileBookingCompatibility¶
Temporary migration command only when current compatibility effects must be supported.
Input: Booking ID + exact affected child identities + requestToken
Output: per-child SUCCEEDED/PARTIAL/FAILED/UNKNOWN
Transaction: one declared owner boundary at a time
Target disposition: retire after explicit order/inventory handoffs replace current BOOKING_RATE sync
11. Planned HTTP/API Adapter Shape¶
These are target adapter names, not current route commitments.
Commercial¶
GET /api/oms/commercial-agreements
POST /api/oms/commercial-agreements
GET /api/oms/commercial-agreements/{id}
PATCH /api/oms/commercial-agreements/{id}
POST /api/oms/commercial-agreements/{id}/relation
POST /api/oms/commercial-agreements/{id}/status
DELETE /api/oms/commercial-agreements/{id}
Inbound¶
GET /api/oms/inbound-purchases
POST /api/oms/inbound-purchases
GET /api/oms/inbound-purchases/{id}
POST /api/oms/inbound-purchases/{id}/atomic-save
POST /api/oms/inbound-purchases/{id}/finalize-from-scale
POST /api/oms/inbound-purchases/{id}/complete-without-scale
POST /api/oms/inbound-purchases/{id}/correction
DELETE /api/oms/inbound-purchases/{id}
Outbound¶
GET /api/oms/outbound-sales
POST /api/oms/outbound-sales
GET /api/oms/outbound-sales/{id}
POST /api/oms/outbound-sales/{id}/atomic-save
POST /api/oms/outbound-sales/{id}/booking-link
POST /api/oms/outbound-sales/{id}/correction
DELETE /api/oms/outbound-sales/{id}
Booking¶
GET /api/tms/bookings
POST /api/tms/bookings
GET /api/tms/bookings/{id}
PATCH /api/tms/bookings/{id}
POST /api/tms/bookings/{id}/clone
POST /api/tms/bookings/{id}/sales-order-link
POST /api/tms/bookings/{id}/inactive
GET /api/tms/bookings/{id}/handoff-status
Next.js adapters remain thin. They authenticate, resolve tenant/actor/capability, validate DTO shape, call application commands/queries and map safe errors. They do not own business SQL or cross-owner compensation.
12. Example Request And Result DTOs¶
12.1 Commercial create¶
{
"requestToken": "4c92786e-2e93-4a2b-9073-a6cc5593a94d",
"type": "PURCHASE",
"counterpartyId": "company-uuid",
"referenceNumber": "SUPPLIER-REF-1001",
"contractDate": "2026-08-07",
"shippingPeriod": "2026-08-30",
"currency": "USD",
"items": [
{
"commodityId": "commodity-uuid",
"quantity": "40000.000",
"uom": "LB",
"rate": "0.1750"
}
]
}
12.2 Inbound receipt finalize result¶
{
"data": {
"orderId": "inbound-uuid",
"scaleTicketId": "scale-uuid",
"receiptState": "LOT_MATERIALIZED",
"items": [
{
"itemId": "item-uuid",
"operationalState": "UNLOADED",
"netWeight": "39750.000",
"inventoryLotId": "lot-uuid"
}
],
"transloadIds": ["transload-uuid"],
"allowedNextActions": ["OPEN_INVENTORY", "OPEN_ALLOCATION"]
},
"requestId": "..."
}
12.3 Outbound create result¶
{
"data": {
"orderId": "outbound-uuid",
"number": "SO20260807-001",
"items": [
{
"itemId": "item-uuid",
"sourceMapping": "UNMAPPED",
"allocatedQuantity": "0",
"allocatedWeight": "0"
}
],
"bookingId": null,
"bridgeState": "NO_BOOKING",
"warnings": ["Inventory has not been allocated."]
},
"requestId": "..."
}
12.4 Booking update result with explicit child disposition¶
{
"data": {
"booking": {
"id": "booking-uuid",
"number": "BK-1001",
"salesOrderId": "outbound-uuid",
"flags": {
"packingSubmitted": false,
"invoiced": false,
"notInUse": false
}
},
"handoffs": [
{
"capability": "OUTBOUND_SALES_LINK",
"status": "SUCCEEDED",
"authoritativeIds": ["outbound-uuid"]
},
{
"capability": "LEGACY_BOOKING_COMPATIBILITY",
"status": "RETIRED"
}
]
},
"requestId": "..."
}
13. Stable Semantic Error Catalog¶
| Code | Meaning | Required user/recovery action |
|---|---|---|
MK_PROFILE_NOT_APPLICABLE |
current tenant/profile does not enable MK capability | stop; use correct tenant/profile |
MK_FORBIDDEN |
actor lacks capability or record scope | stop; no alternate direct-ID path |
MK_RECORD_NOT_FOUND |
record absent in authorized tenant/scope | refresh/search exact identity |
MK_STALE_VERSION |
record changed after UI read | reload full detail before another command |
MK_DUPLICATE_REQUEST |
request token already has a logical result | use existing result |
COMMERCIAL_INVALID_RELATION |
relation is self, same type, foreign, missing or policy-ineligible | choose valid agreement |
COMMERCIAL_RELATION_CONFLICT |
cardinality/cycle/current relation conflict | reload both agreements and review policy |
COMMERCIAL_EXECUTION_LOCKED |
requested type/line/delete mutation conflicts with execution | preserve agreement; use child correction |
COMMERCIAL_STATUS_POLICY_REQUIRED |
requested status transition lacks accepted rule | stop for process-owner decision |
INBOUND_INVALID_REFERENCE |
company/commodity/commercial reference invalid | correct source reference |
INBOUND_RECEIPT_NOT_READY |
Scale/no-scale prerequisites incomplete | complete/read owning prerequisite |
INBOUND_RECEIPT_ALREADY_FINALIZED |
logical receipt already exists | open existing result; no duplicate finalize |
INBOUND_SOURCE_CARDINALITY_CONFLICT |
source item/transload/lot relation ambiguous | stop and reconcile exact IDs |
INBOUND_LOT_CONFLICT |
item/transload/lot quantity, weight or state disagree | inventory/receipt owner review |
INBOUND_PROGRESS_LOCKED |
unsafe post-receipt edit/delete | use approved correction/reversal |
OUTBOUND_INVALID_REFERENCE |
Commercial/Booking/company/equipment reference invalid | correct exact reference |
OUTBOUND_ALLOCATION_REQUIRED |
demand exists but no accepted allocation | use Allocation owner |
OUTBOUND_ALLOCATION_CONFLICT |
item demand and allocation/lot balance disagree | stop and reconcile allocation |
OUTBOUND_BRIDGE_LOCKED |
Booking/container/size remap conflicts with execution | preserve bridge and use owner recovery |
OUTBOUND_PROGRESS_LOCKED |
edit/delete conflicts with Scale/Delivery/Allocation/Cost | use owning child correction |
BOOKING_INVALID_LINK |
Sales link invalid or policy-ineligible | reload Booking and Sales order |
BOOKING_LINK_CONFLICT |
forward/reverse pointers disagree | reconcile both owners; no raw pointer edit |
BOOKING_CLONE_PARTIAL |
expected clones or carried fields differ | search exact request/result before repeat |
BOOKING_INACTIVE_CHILDREN_EXIST |
inactive marker conflicts with active children | review policy; marker alone does not clean |
BOOKING_COMPATIBILITY_PARTIAL |
hidden/current child synchronization partially changed data | stop dependent work and reconcile affected IDs |
BOOKING_COMPATIBILITY_UNKNOWN |
compatibility result cannot be established | exact child reread before another save |
MK_SCHEMA_NOT_READY |
required current schema capability absent | release/schema owner action |
MK_UNEXPECTED_ERROR |
unclassified defect | retain request ID and escalate |
Internal SQL, direct provider credentials and raw stack details are not returned as validation messages.
14. Transaction, Concurrency And Idempotency Contract¶
14.1 Transaction boundaries¶
| Command family | Target local transaction boundary |
|---|---|
| Commercial create/update | one agreement header/line/relation command |
| Inbound scheduled atomic save | one order/header/item/deletion command |
| Inbound receipt finalize | accepted item/transload/lot materialization boundary |
| Outbound scheduled atomic save | one order/header/item/bridge command without allocation |
| Booking create/update | Booking-owned fields and accepted link only |
| Allocation | allocation owner transaction only |
| Scale | Scale owner transaction/event only |
| Cross-owner handoff | explicit command/result; no implicit global transaction |
14.2 Conditional state/version writes¶
Every update/delete/finalize command must:
- resolve tenant and actor;
- reread the current record and dependent blockers;
- compare accepted version/freshness token where supported;
- perform a conditional update with expected current state/version;
- require expected affected-row count;
- reread the exact authoritative result;
- map zero-row changes to a semantic stale/conflict result.
14.3 Idempotency¶
Suggested request identities:
Commercial create:
tenant + requestToken
Inbound/Outbound create:
tenant + requestToken
Inbound receipt finalize:
tenant + order + scaleTicket/noScale intent + requestToken
Booking create/clone:
tenant + requestToken
Cross-owner link:
tenant + source ID + target ID + requested relation version
Generated order/booking numbers and suffix searches remain reconciliation evidence but are not sufficient target idempotency by themselves.
14.4 No dual write¶
During migration:
one capability/cohort
-> exactly one authoritative writer
PHP and TypeScript may both read during shadow/parity. They do not independently mutate the same capability.
15. Current Hidden Compatibility Sync Problem¶
15.1 Current source shape¶
Current Booking writes call MK helper logic from the Inbound/OMS helper family and flush synchronization work inside the Booking request transaction. Existing process evidence indicates the misnamed BOOKING_RATE compatibility path can affect:
T_LOAD
T_LOAD_ITEM
T_INVENTORY_LOT
T_LOAD_ALLOCATION
linked Transload-derived state
It can reset remaining lot quantity/weight or remove allocations/lots when a source is no longer eligible. Some internal exceptions are logged/swallowed, so the Booking request can appear successful while child effects are partial or stale.
15.2 Required target disposition¶
Target Booking Save must not own these hidden effects.
Choose and document one of:
- retire the compatibility behavior after current consumers are migrated;
- replace it with explicit owner commands and visible per-child results;
- retain a temporary compatibility command with typed input/output, idempotency, transaction boundary and operator recovery.
Prohibited target pattern:
PATCH Booking
-> hidden generic sync
-> unknown order/lot/allocation mutations
-> success response
Required target pattern:
UpdateBooking
-> exact Booking readback
-> explicit handoff request(s)
-> each owning application command
-> per-child result/disposition
-> operator-visible partial recovery
16. UI Contract¶
16.1 React workspace boundaries¶
Recommended bounded workspaces:
Commercial Agreement Workspace
Inbound Purchase Workspace
Outbound Sales Workspace
Booking Workspace
Order-First Reconciliation View
Do not create one page component that owns all child mutations.
16.2 Shared UI requirements¶
Every workspace defines:
- loading;
- empty/no-match;
- denied;
- validation error;
- stale conflict;
- partial result;
- unknown result;
- current authoritative readback;
- next owner/handoff;
- current versus optional child state;
- mobile and keyboard-accessible primary action.
16.3 Commercial UI¶
Must show separately:
- agreement status label;
- execution utilization projection;
- linked agreement;
- execution references;
- line replacement/stable-line warning;
- allowed edits and blocked reason.
16.4 Inbound UI¶
Must show separately:
- header close label;
- item operational state;
- Scale state;
- receipt-finalization state;
- transload state;
- inventory-lot state;
- next-work intent;
- correction blockers from allocation/ledger/placement.
16.5 Outbound UI¶
Must show separately:
- requested items;
- allocation status and source lots;
- Booking/equipment bridge;
- Scale/Delivery/Packing/Cost child dispositions;
- readiness projection with the label
Informationalor equivalent; - blocked remap/edit/delete reasons.
16.6 Booking UI¶
Must show separately:
- Booking-owned fields;
- Sales link;
- container/equipment projections;
- independent flags;
- inactive marker;
- explicit compatibility/handoff result;
- clone carried/omitted fields;
- child conflict/partial state.
A generic success toast does not replace the readback panel.
17. Exception And Recovery Matrix¶
| ID | Possible committed state | Required reread | Safe next action | Must not repeat blindly |
|---|---|---|---|---|
MKCORE-EXC-010 Commercial create response lost |
agreement/lines may exist | exact request/number/reference/date/counterparty | use existing or retry only when absent | create full agreement |
MKCORE-EXC-020 Commercial update stale |
later header/line set may have won | exact detail + execution refs | reconcile fields and submit one accepted change | full replacement from stale form |
MKCORE-EXC-030 Commercial relation uncertain |
one side may point to the other | both agreement details | keep accepted relation or apply one missing relation command | relation create repeatedly |
MKCORE-EXC-040 Inbound atomic save fails |
request should roll back, compatibility callers may differ | header + all items | correct rejected input and rerun one atomic save | separate header/item writes without reread |
MKCORE-EXC-050 Scale checkout done/finalize absent |
ticket complete, receipt/lot absent | ticket + order/items + transload + lot | retry finalize only | Scale checkout |
MKCORE-EXC-060 Inbound finalization unknown |
full/partial logical receipt may exist | order/items/transload/lot | use existing or repair exact missing owner boundary | complete/finalize entire path |
MKCORE-EXC-070 Inbound progressed edit conflict |
lot/allocation/placement may already depend on source | item + lot + allocation + ledger + placement | approved correction/reversal | source-row overwrite/delete |
MKCORE-EXC-080 Outbound direct line expected allocation |
order item exists, allocation absent | outbound item + allocation + lot | use Allocation owner | direct Save |
MKCORE-EXC-090 Outbound update after allocation |
demand may diverge from allocation | item + allocations + lot balances | allocation-aware correction | generic item update |
MKCORE-EXC-100 Outbound delete leaves Booking pointer |
order deleted, Booking stale | Booking + order active/deleted state | explicit link reconciliation | raw Booking pointer edit |
MKCORE-EXC-110 Booking create/update response lost |
Booking and some child effects may exist | Booking + Sales + order/item/lot/allocation children | continue only missing owner command | Booking Save |
MKCORE-EXC-120 Booking compatibility partial |
Booking committed; child state partially changed | every affected child ID/balance | stop dependent use; owner-by-owner reconcile | another Booking Save |
MKCORE-EXC-130 Booking clone response lost |
some/all clones may exist | request identity + base/suffix search + detail | use existing or create only confirmed missing result | clone batch |
MKCORE-EXC-140 Inactive Booking has active children |
flag changed, child execution remains | Booking + Sales/container/output children | policy review/explicit child command | assuming cleanup |
MKCORE-EXC-150 Cross-child totals disagree |
child states independently committed | exact owning data for each child | correct through owner | overwrite a different child for parity |
Universal rule:
Do not repeat a create, receipt, allocation, Booking or physical action until every relevant authoritative checkpoint is reread.
18. Current Runtime Caller And Consumer Map¶
Commercial¶
frontend/pages/system/OMS/commercial-order/mk-commercial-orders.php
frontend/pages/system/OMS/commercial-order/commercialOrderPrint.php
app/systems/OMS/commercial-order/api_routes.php
commercial_order_query_handler.php
commercial_order_query_helper.php
commercial_order_post_handler.php
commercial_order_post_helper.php
Inbound¶
frontend/pages/system/OMS/inbound-order/mk-inbound-orders.php
public/assets/js/modules/shared/mk-inbound-order-editor.js
app/systems/OMS/inbound-order/api_routes.php
mk_query_helper.php
mk_post_helper.php
YMS Scale purchase callers
WMS lot/transload/warehouse helpers
Export Brokerage and allocation compatibility callers
Outbound¶
frontend/pages/system/OMS/outbound-order/mk-outbound-orders.php
public/assets/js/modules/shared/mk-outbound-order-editor.js
app/systems/OMS/outbound-order/api_routes.php
query_handler.php
outbound_order_query_helper.php
post_handler.php
app/systems/OMS/inbound-order/mk_post_helper.php
Allocation, Scale, Delivery, Packing and Cost consumers
Booking¶
frontend/pages/system/TMS/booking/mk-booking-list.php
shared Booking/Packing editor modules
app/systems/TMS/booking/api_routes.php
TMS delivery query/post/out-ref helpers
app/systems/OMS/inbound-order/mk_post_helper.php
BMS transaction helper consumers
Packing, container, report and output consumers
P5 must classify each caller as:
ACTIVE
COMPATIBILITY
TEST_ONLY
HISTORICAL
UNKNOWN
REMOVED_AND_VERIFIED
UNKNOWN blocks deletion.
19. Target Component Map¶
flowchart LR
CommercialUI[React Commercial Workspace]
InboundUI[React Inbound Workspace]
OutboundUI[React Outbound Workspace]
BookingUI[React Booking Workspace]
ReconcileUI[React Order-First Reconciliation]
Next[Next.js Server Components / Route Handlers]
CommercialApp[Commercial Application]
InboundApp[Inbound Purchase Application]
OutboundApp[Outbound Sales Application]
BookingApp[Booking Application]
Handoff[Order-First Handoff Policies]
CommercialRepo[Commercial Repository]
OrderRepo[Execution Order Repository]
BookingRepo[Booking Repository]
DB[(MySQL)]
InventoryApp[Inventory/Allocation Owner]
ScaleApp[Scale Owner]
Worker[Node Worker for durable effects only]
CommercialUI --> Next
InboundUI --> Next
OutboundUI --> Next
BookingUI --> Next
ReconcileUI --> Next
Next --> CommercialApp
Next --> InboundApp
Next --> OutboundApp
Next --> BookingApp
CommercialApp --> Handoff
InboundApp --> Handoff
OutboundApp --> Handoff
BookingApp --> Handoff
CommercialApp --> CommercialRepo
InboundApp --> OrderRepo
OutboundApp --> OrderRepo
BookingApp --> BookingRepo
CommercialRepo --> DB
OrderRepo --> DB
BookingRepo --> DB
InboundApp --> InventoryApp
OutboundApp --> InventoryApp
InboundApp --> ScaleApp
OutboundApp --> ScaleApp
Handoff --> Worker
19.1 React responsibility¶
- typed forms and list/detail projections;
- child checkpoint visualization;
- conflict/partial/unknown recovery UI;
- explicit next-owner handoff;
- accessible/mobile interaction;
- stable operator labels independent from route implementation.
React does not own status criteria, allocation balance, receipt finalization or Booking compatibility mutation.
19.2 Next.js responsibility¶
- authenticated tenant/profile/actor adaptation;
- Server Component query composition;
- Route Handler/API adapter;
- request/response schema validation;
- correlation/request IDs;
- safe semantic error mapping.
19.3 TypeScript application/domain responsibility¶
- command/query and state-transition semantics;
- cross-owner handoff policy;
- idempotency and conditional-write behavior;
- exact readback;
- child dispositions;
- correction/recovery;
- no hidden compatibility side effects.
19.4 Repository responsibility¶
- current MySQL table mapping;
- tenant and lifecycle predicates;
- precision/UOM/date/nullable semantics;
- optimistic/conditional writes;
- transaction boundary;
- later PostgreSQL mapping.
19.5 Worker responsibility¶
This core family is primarily local transactional work. Use a worker only for durable asynchronous effects or reconciliation tasks. Do not move core order writes into a queue merely because the target uses Node.js.
20. Migration Sequence¶
Wave 0 — Characterization and policy lock¶
- pin accepted PHP/MySQL source and role/profile behavior;
- repin schema/indexes and current callers;
- resolve or explicitly defer critical policies;
- capture stable scenario evidence and current Wiki content;
- document compatibility sync affected rows and failure behavior.
Wave 1 — Read-only Order-First workspace¶
- TypeScript queries against current MySQL;
- React/Next.js Commercial, Inbound, Outbound, Booking and reconciliation views;
- compare counts, fields, derived states, links and child dispositions;
- no new writer.
Wave 2 — Commercial commands¶
- create/update/relation/status/eligible delete one-writer cutover;
- preserve current numbers, lines, relations and print source;
- add explicit concurrency/idempotency where approved;
- rollback to PHP using current MySQL state.
Wave 3 — Inbound scheduled CRUD¶
- create and atomic-save scheduled orders/items;
- do not migrate receipt finalization in the same first write wave;
- compare exact child bridge projections.
Wave 4 — Inbound receipt finalization¶
- Scale checkout remains Scale-owned;
- migrate
FinalizeInboundReceiptFromScaleand accepted no-scale command; - one accepted transaction owner for item/transload/lot effects;
- preserve partial recovery and current active receipts.
Wave 5 — Outbound scheduled CRUD¶
- create and atomic-save requested demand and bridge references;
- allocation remains separate owner;
- protect allocated/progressed items according to accepted policy.
Wave 6 — Booking CRUD and explicit Sales link¶
- migrate Booking-owned fields, clone and inactive marker;
- establish explicit two-sided Sales link contract;
- return child dispositions;
- do not activate hidden compatibility mutation in the new writer.
Wave 7 — Compatibility sync retirement/replacement¶
- inventory every
BOOKING_RATEand MK helper caller; - move legitimate child work to explicit owner commands;
- compare old/new read and business outcomes;
- disable hidden sync by cohort/capability;
- reconcile in-flight partial results;
- remove after caller-zero.
Wave 8 — Target-role and Wiki activation¶
- role/page/API/record matrix;
- current and target stable Wiki topics;
- mobile/accessibility and recovery review;
- named publication and rendered readback.
Wave 9 — PHP caller-zero¶
- pages;
- API route strings;
- helpers and shared
mk_post_helpercallers; - scripts/cron/integrations;
- reports/documents;
- tests;
- Wiki links/bookmarks;
- observed traffic.
21. Rollback Contract¶
Rollback:
- switches the selected capability/cohort back to the accepted PHP writer;
- preserves all committed Commercial, order, Booking, receipt, lot and allocation rows;
- disables new TypeScript writes before PHP resumes;
- reconciles in-flight commands and compatibility work;
- preserves request/audit evidence;
- updates stable application links only when required.
Rollback does not:
- delete accepted receipts or physical Scale evidence;
- recreate Commercial/Inbound/Outbound/Booking rows;
- restore lot balances by copying source totals blindly;
- dual-write both implementations;
- replay hidden Booking sync;
- drop additive schema as routine application rollback.
22. PostgreSQL Preservation Requirements¶
P11 must preserve:
- tenant-scoped immutable identities and child relationships;
- decimal precision for quantity, weight, rate and amount;
- UOM semantics;
- generated number uniqueness/idempotency;
- manual status versus derived execution/readiness projections;
- line replacement/stable-line identity decision;
- conditional state/version writes;
- receipt item/transload/lot transaction semantics;
- allocation lower bounds and balance integrity;
- Booking/Sales link direction and uniqueness;
- independent Booking flags;
- clone request/result identity;
- audit/correction/delete/void lineage;
- active/partial/unknown compatibility results during migration;
- failback representation.
Do not combine PostgreSQL cutover with the first React/Next.js writer cutover.
23. Stable Verification Scenario Catalog¶
Commercial¶
| ID | Scenario |
|---|---|
MKCO-SCN-010 |
create Purchase and exact reread |
MKCO-SCN-020 |
create Sales and exact reread |
MKCO-SCN-030 |
relate Purchase to Sales and verify both projections |
MKCO-SCN-040 |
invalid/foreign/self/same-type relation denied |
MKCO-SCN-050 |
pre-execution line update/replacement identity |
MKCO-SCN-060 |
post-execution type/item/delete guard |
MKCO-SCN-070 |
concurrent/stale update |
MKCO-SCN-080 |
create/update response loss and idempotent recovery |
MKCO-SCN-090 |
role/API/record denial |
MKCO-SCN-100 |
print projection without durable-completion claim |
Inbound¶
| ID | Scenario |
|---|---|
MKIN-SCN-010 |
scheduled create and exact header/item reread |
MKIN-SCN-020 |
atomic save rollback on invalid item/deletion |
MKIN-SCN-030 |
Commercial Purchase/item link validation |
MKIN-SCN-040 |
Scale checkout then successful finalize/lot |
MKIN-SCN-050 |
Scale checkout complete/finalize failed; resume finalize only |
MKIN-SCN-060 |
eligible complete-without-scale |
MKIN-SCN-070 |
multi-line/source cardinality conflict |
MKIN-SCN-080 |
receipt response loss and exact reconciliation |
MKIN-SCN-090 |
post-receipt edit/delete with allocation/ledger/placement |
MKIN-SCN-100 |
branch intent lost after response |
MKIN-SCN-110 |
role/API/foreign reference denial |
Outbound¶
| ID | Scenario |
|---|---|
MKOUT-SCN-010 |
Ocean create with accepted required fields |
MKOUT-SCN-020 |
Local create and equipment bridge |
MKOUT-SCN-030 |
direct item remains UNMAPPED with no lot effect |
MKOUT-SCN-040 |
allocation handoff and exact balance |
MKOUT-SCN-050 |
allocated item update conflict |
MKOUT-SCN-060 |
Booking/container bridge lock after progress |
MKOUT-SCN-070 |
Scale-owned field guard |
MKOUT-SCN-080 |
delete guard and Booking pointer cleanup |
MKOUT-SCN-090 |
response loss/concurrent update |
MKOUT-SCN-100 |
role/API/foreign reference denial |
Booking¶
| ID | Scenario |
|---|---|
MKBK-SCN-010 |
create Booking and Sales link readback |
MKBK-SCN-020 |
update independent flags without child completion inference |
MKBK-SCN-030 |
invalid Sales link clear/retain behavior characterization |
MKBK-SCN-040 |
clone one/many and carried/omitted fields |
MKBK-SCN-050 |
clone response loss and duplicate prevention |
MKBK-SCN-060 |
mark inactive with active children visible |
MKBK-SCN-070 |
current compatibility sync success with affected-child inventory |
MKBK-SCN-080 |
compatibility partial/unknown result and no-blind-save recovery |
MKBK-SCN-090 |
cross-tenant/direct-reference denial |
MKBK-SCN-100 |
target Booking Save with no hidden inventory/allocation mutation |
Cross-child and migration¶
| ID | Scenario |
|---|---|
MKCORE-SCN-010 |
Commercial Purchase → Inbound → receipt → lot |
MKCORE-SCN-020 |
Commercial Sales → Outbound → Booking → allocation handoff |
MKCORE-SCN-030 |
child state mismatch blocks composite close |
MKMIG-SCN-010 |
old/new read parity for four core workspaces |
MKMIG-SCN-020 |
Commercial one-writer cutover and rollback |
MKMIG-SCN-030 |
Inbound scheduled CRUD one-writer cutover |
MKMIG-SCN-040 |
receipt-finalize cutover with active Scale ticket |
MKMIG-SCN-050 |
Outbound one-writer cutover with existing allocations |
MKMIG-SCN-060 |
Booking cutover without hidden compatibility write |
MKMIG-SCN-070 |
compatibility caller-zero |
MKMIG-SCN-080 |
rollback preserves all child evidence |
Each scenario record must identify:
scenario ID
source/release revision
tenant/profile/account/role
fixture and stable IDs
command/query path
before state
after local state
child/effect state
visible result
negative/denied evidence
cleanup/rollback
open discrepancy
24. Open Policy Decisions¶
- Commercial status transition criteria and authorized actor.
- Commercial Purchase/Sales relation direction, cardinality, cycle and eligible status.
- Commercial line replacement versus stable-line update semantics.
- Post-execution editable Commercial fields.
- Whether current uppercase free-text normalization remains intended.
- Inbound multi-line receipt and exact lot distribution model.
- No-scale eligibility and whether next-work branch intent must persist.
- Whether direct operational-status/
OUT_TIMEreceipt materialization remains supported. - Post-receipt Inbound correction/delete and lot/allocation/ledger/placement compensation.
- Ocean/Local Outbound required-field policy.
- Allocated Outbound item correction and unallocate/reversal owner.
- Outbound delete and Booking reverse-pointer cleanup.
- Booking link direction/cardinality and invalid-link behavior.
- Booking clone carry/omit policy.
- Booking inactive meaning and child eligibility.
- Retirement/replacement contract for current
BOOKING_RATEcompatibility sync. - Semantic role/capability mapping for actual MK users.
- Stable optimistic version/idempotency implementation.
- Initial PostgreSQL representations for decimal, links, flags and compatibility audit.
Do not resolve these by introducing numeric tenant branches, generic statuses or hidden side effects during implementation.
25. Definition Of Ready For Implementation Review¶
- four current Process owners and composite boundary accepted;
- role/capability/record matrix drafted and reviewed;
- field/state/identity contracts reviewed;
- current schema/indexes and callers repinned;
- critical policy decisions accepted or bounded by a safe implementation-wave deferral;
- stable query/command/error contracts reviewed;
- receipt and allocation integrity rules accepted;
- Booking compatibility affected-row behavior characterized;
- one-writer selector and rollback designed;
- stable scenarios assigned to test layers;
- current Wiki content read before publication changes.
26. Definition Of Complete For This Documentation Packet¶
This packet is documentation-complete for owner review when:
- all linked source/process facts are reconciled to the pinned revision;
- every current/future/target statement is classified;
- every open policy has an owner;
- field/DTO/error/transaction/recovery contracts are internally consistent;
- diagrams, Runbook and Wiki projection reference the same boundaries;
- P6/P5/P7/P8/P12 handoffs are explicit.
It is not M3/M4, user acceptance, Runtime implementation, Wiki publication or Production readiness until the corresponding evidence exists.
---¶
Source:
docs/reconstruction/MK_ORDER_FIRST_CORE_CAPABILITY_REBUILD_PACKET.md— ctc repository · This page is an English translation of the source document. Identifiers, file paths and code symbols are unchanged.