Skip to content

This is an internal working record, not an everyday instruction. It was written while the system was being rebuilt, for whoever maintains it. If you are here to do today's work, use the everyday documents instead: Procedures · Processes · Runbooks · The working day, step by step

MK Order-First Core Reconciliation

  • Status: SOURCE-RECONCILED PROCESS ASSEMBLY / OWNER REVIEW REQUIRED
  • Scope: Commercial Agreement, Inbound Purchase, Outbound Sales and Booking
  • Composite owner: PROC-OMS-ORDER-TO-PACKING-MK
  • Atomic owners:
  • PROC-OMS-COMMERCIAL-ORDER-MK
  • PROC-OMS-INBOUND-PURCHASE-TO-INVENTORY-MK
  • PROC-OMS-OUTBOUND-SALES-ORDER-MK
  • PROC-TMS-BOOKING-LIFECYCLE-MK
  • Rebuild packet: MK_ORDER_FIRST_CORE_CAPABILITY_REBUILD_PACKET.md
  • Source authority: MK_ORDER_FIRST_CORE_SOURCE_AUTHORITY.md
  • Effect boundary: documentation only

1. Purpose

The existing four atomic contracts are individually detailed, but a future migration still needs one precise explanation of:

  • which child owns each state and record;
  • which identities cross child boundaries;
  • which current shortcuts or hidden side effects must not be copied;
  • where a transaction ends and a new owner begins;
  • how an operator recovers when one child commits and the next child does not;
  • how MK remains order-first while moving to React + Next.js.

This document provides that reconciliation without replacing the atomic contracts.


2. Order-First Operating Model

Commercial Purchase Agreement
-> Inbound Purchase Execution
-> Scale or No-Scale Receipt
-> Inventory Lot
-> Optional Allocation

Commercial Sales Agreement
-> Outbound Sales Execution
-> Optional Booking / Container Bridge
-> Inventory Allocation
-> Optional Scale / Delivery / Packing / Cost

Booking
-> Export/container planning and terms
-> explicit Sales/equipment handoffs
-> conditional outputs

The following are not mandatory universal children:

  • Scale, when the accepted receipt/shipment path does not use the physical yard scale;
  • Booking, for work that does not require export/container planning;
  • Allocation, before an outbound demand needs existing inventory;
  • every document output;
  • one Commercial agreement for every execution row, where current compatibility permits an unlinked execution order.

3. Current Authority Matrix

Concern Authority Current mirror/projection Incorrect inference to avoid
Commercial header T_COMMERCIAL_ORDER list/detail/print status proves fulfillment
Commercial lines T_COMMERCIAL_ORDER_ITEM totals and execution reference projections line ID remains stable after replacement
Inbound/Outbound header T_LOAD with class/direction schedule/list/readiness header label proves physical completion
Execution lines T_LOAD_ITEM item operational/source projections line weight proves allocation
Booking T_BOOKING list counters, flags, bridge projections Booking Save proves child sync
Inbound bridge T_TRANSLOAD order/receipt projection transload state is order status
Scale T_SCALE_TICKET and correction events order/bridge mirror checkout proves receipt finalize
Inventory T_INVENTORY_LOT order/warehouse summaries source order total equals remaining balance
Allocation T_LOAD_ALLOCATION outbound operational projection direct order Save allocated inventory
Equipment/container T_EQUIPMENT, T_EQUIPMENT_LOAD, T_EQUIPMENT_COMMODITY Booking/Outbound projections bridge row proves delivery/packing complete

4. Commercial Agreement Reconciliation

4.1 Current behavior

  • Purchase and Sales use one header/line family with ORDER_TYPE.
  • Create writes one header and submitted lines in one transaction.
  • Update before execution can replace the current line set; line IDs can change.
  • Once header-linked execution exists, type change and deletion are blocked and item replacement is preserved/ignored according to current source.
  • LINKED_ORDER_ID is a stored one-direction relation. Current UI primarily links Purchase to Sales; Sales displays the reverse relation.
  • current status values are manual labels and are not automatically derived from execution.
  • print is a current projection without a durable print ledger.

4.2 Reconciliation risks

  1. Header-level execution detection does not prove that no item-level execution pointer exists.
  2. Current line replacement can invalidate external item references if they are not guarded.
  3. No optimistic version prevents last-write-wins.
  4. Status transition criteria and authorized actor are unresolved.
  5. Current free-text uppercasing may alter intended commercial terms.
  6. Relation cardinality, cycle and status eligibility are unresolved.
  7. Basic/advanced operations produce different accepted input surfaces.

4.3 Required target split

CommercialAgreementCommand
CommercialAgreementLineCommand
CommercialRelationCommand
CommercialStatusCommand
CommercialAgreementQuery
CommercialExecutionUtilizationQuery

A generic header PATCH must not silently imply full line replacement, relation change and status change.


5. Inbound Purchase Reconciliation

5.1 Current state families

T_LOAD header close label
T_LOAD_ITEM operational state
T_TRANSLOAD execution state
T_SCALE_TICKET physical evidence
T_INVENTORY_LOT received inventory

These states may agree, lag or conflict. They do not form one persisted state machine.

5.2 Current receipt paths

Physical Scale

scheduled Purchase
-> Scale check-in/gross
-> Scale check-out/tare
-> separate Inbound finalize command
-> item/transload receipt state
-> exact Inventory Lot materialization

Complete Without Scale

eligible scheduled Purchase
-> no-scale command
-> item/transload receipt state
-> exact Inventory Lot materialization

Legacy-compatible direct operational update

item/header operational status or first OUT_TIME change
-> transload synchronization
-> possible lot materialization

This direct path is current compatibility behavior. It is not automatically the preferred target command.

5.3 Partial-result boundaries

Boundary Possible partial result Required recovery
Scale checkout → Inbound finalize ticket complete; receipt/lot absent preserve ticket, retry finalize only after reread
item/transload → lot sync receipt state changed; lot missing/conflict stop and reconcile source item/transload/lot cardinality
multi-line weight distribution → lot distributed item weights but lot sync rejects cardinality preserve full transaction rollback or exact partial evidence; no manual second lot
post-receipt item update → lot balance source changes reset remaining values use inventory-aware correction, not source overwrite
delete → downstream dependencies allocation/ledger/placement/scale block incompletely checked preserve row and reconcile through owner
branch response → next work receipt committed; branch intent lost ask/record operator intent; do not infer from DB state

5.4 Required target split

InboundScheduledOrderCommand
InboundReceiptFinalizeCommand
InboundNoScaleCompletionCommand
InboundReceiptCorrectionCommand
ReceiptReconciliationQuery
InventoryLotMaterializationService

The receipt finalization transaction must have one accepted owner and exact readback. Scale remains the physical evidence owner; Inventory remains the lot owner.


6. Outbound Sales Reconciliation

6.1 Current state families

T_LOAD header close label
T_LOAD_ITEM requested demand/source mapping
T_LOAD_ALLOCATION actual allocation
Booking/equipment bridge
Scale/Delivery/Packing/Cost child states
readiness projection

6.2 Current order creation

  • direct Save creates requested items;
  • normal direct line writes are UNMAPPED unless an internal/allocation-enabled path explicitly writes allocation;
  • equipment/container bridge can be created/refreshed from Outbound data;
  • Ocean and Local validation differs;
  • incomplete Ocean rows can currently exist.

6.3 Partial and integrity risks

  1. direct item weight/quantity is not allocation evidence;
  2. allocated-item update can diverge from T_LOAD_ALLOCATION and lot remaining balance;
  3. allocated-item delete is blocked but no complete unallocate/reversal path is confirmed;
  4. Booking/container/size remap is locked after selected child progress, but the full policy is incomplete;
  5. delete can leave a stale Booking reverse pointer;
  6. readiness is derived and can be mistaken for completion;
  7. no idempotency or optimistic version protects create/update;
  8. direct references and role/record scope require further negative evidence.

6.4 Required target split

OutboundScheduledOrderCommand
OutboundBookingLinkCommand
OutboundEquipmentBridgeCommand
OutboundProgressedCorrectionCommand
OutboundOrderQuery
OutboundReadinessQuery

Allocation remains a separate owner. Outbound commands may request or display allocation work; they do not fabricate an allocation row.


7. Booking Reconciliation

7.1 Current Booking-owned fields

  • Booking number and invoice number;
  • shipping line and Booking type;
  • vessel, ports and cutoffs;
  • shipper/party/terminal/inspector references;
  • planned container quantities;
  • independent flags;
  • NOT_IN_USE;
  • optional Sales order link.

7.2 Current cross-owner side effects

The current Booking request calls MK compatibility helpers and synchronization work. Process/source evidence shows that this can affect:

  • execution orders and items;
  • inventory lots and remaining balances;
  • allocations;
  • linked Transload-derived state.

The operation is misleadingly named as rate synchronization in some current paths, but its scope is broader.

7.3 Critical partial-result risk

Booking header/link committed
+ some compatibility child writes committed
+ later compatibility error logged/swallowed
= user may see Booking success while child state is partial or stale

A second Booking Save is not a safe universal recovery. It may replay or further change child data.

7.4 Clone and inactive boundaries

  • clone can carry Booking header values, flags, inactive state, invoice and Sales link;
  • clone does not imply containers/files/allocations were cloned;
  • no current delete API exists;
  • NOT_IN_USE does not clean or disable every child;
  • invalid Sales links can be cleared or retained depending on create/update path.

7.5 Required target split

BookingCommand
BookingCloneCommand
BookingSalesLinkCommand
BookingInactiveCommand
BookingQuery
BookingHandoffQuery
TemporaryCompatibilityCommand or retirement

Booking Save must return exact Booking state and explicit child handoff results. It must not silently own Order/Inventory/Allocation mutation.


8. Cross-Process Sequence

sequenceDiagram
    actor Commercial as Commercial Operator
    actor Receiving as Receiving Operator
    actor Shipping as Shipping/Booking Operator
    actor Inventory as Inventory Operator
    participant CO as Commercial Owner
    participant IN as Inbound Owner
    participant OUT as Outbound Owner
    participant BK as Booking Owner
    participant SCALE as Scale Owner
    participant LOT as Inventory Owner
    participant ALLOC as Allocation Owner

    Commercial->>CO: Create Purchase/Sales agreement
    CO-->>Commercial: Agreement + lines readback
    Receiving->>IN: Create Inbound Purchase linked to Purchase agreement
    IN-->>Receiving: Scheduled order/items
    opt Physical receipt
        Receiving->>SCALE: Execute scale stages
        SCALE-->>Receiving: Completed ticket
    end
    Receiving->>IN: Finalize receipt or complete without scale
    IN->>LOT: Materialize exact source lot
    LOT-->>Receiving: Lot identity/balance
    Shipping->>OUT: Create Outbound Sales linked to Sales agreement
    OUT-->>Shipping: Requested demand, initially unallocated if direct Save
    opt Export/container work
        Shipping->>BK: Create/link Booking
        BK-->>Shipping: Booking-owned result + explicit handoff dispositions
    end
    Inventory->>ALLOC: Allocate lot to outbound demand
    ALLOC-->>Inventory: Allocation + lot balance readback
    Note over CO,ALLOC: Each child remains authoritative for its own state.

9. Current Booking Compatibility Sequence

sequenceDiagram
    actor Operator
    participant UI as Booking UI
    participant Booking as Booking Route
    database DB as MySQL
    participant MK as MK Compatibility Helper
    participant Child as Order / Lot / Allocation Children

    Operator->>UI: Save Booking
    UI->>Booking: Create/Update payload
    Booking->>DB: Begin transaction
    Booking->>DB: Write Booking/header/link
    Booking->>MK: Flush compatibility work
    MK->>Child: Upsert or delete related state
    alt all compatibility work succeeds
        Child-->>MK: Success
        Booking->>DB: Commit
        Booking-->>UI: Success
    else compatibility error is caught/logged internally
        Child-->>MK: Partial writes or error
        MK-->>Booking: Apparent success or incomplete signal
        Booking->>DB: Commit may still occur
        Booking-->>UI: Booking success without complete child disposition
    end

Target reconstruction must replace this ambiguity with explicit commands and per-child results.


10. Policy Decision Register

Decision Current fact Risk Owning decision
Commercial status policy manual list values, no derived rule false fulfillment/cancellation P6/Product/Operations
Commercial relation cardinality one stored pointer, UI Purchase→Sales cycles/multiple links/ambiguous reverse P6/Product
Commercial line identity replacement can recreate lines broken item references/audit P5/P6/DB
post-execution Commercial edits only some fields explicitly blocked changed terms after execution Product/Operations
inbound direct receipt compatibility operational/time edit can materialize lot bypassed receipt command Product/Operations/P6
multi-line receipt weight distribution exists; lot sync may reject incomplete/ambiguous lots P6/WMS/OMS
branch intent persistence not stored response-loss ambiguity Product/Operations
progressed inbound correction source edit can reset lot balance inventory corruption P6/WMS/P5
outbound required fields Ocean/Local differ; incomplete Ocean allowed unusable shell rows Product/Operations
allocated-item update/unallocate current update can diverge; unallocate unclear balance mismatch P6/WMS/OMS
Booking reverse link cleanup delete can leave stale pointer orphan relation P5/P6
Booking inactive policy manual flag only active children remain Product/Operations
clone carry policy carries flags/link, not children misleading duplicate Product/Operations
Booking compatibility sync hidden broad child mutation partial, balance reset/delete P5/P6/P12
role/capability mapping current role IDs/menu/profile compatibility unsafe access migration P2/P4/P5

No implementation task should silently decide one of these through a new column, generic status or route-specific exception.


11. Data Integrity Invariants

  1. Every child record is tenant-scoped and active-row checked.
  2. A Commercial line reference belongs to its Commercial header.
  3. An execution item reference belongs to its execution order.
  4. A Commercial execution link matches Purchase→Inbound or Sales→Outbound semantics.
  5. Receipt finalization cannot create a second logical lot for the same accepted source identity.
  6. Lot remaining quantity/weight cannot fall below allocated/consumed/reversed lower bounds.
  7. Direct Outbound Save does not reduce lot balance.
  8. Allocation changes are recorded by the Allocation owner with exact lot and demand IDs.
  9. Booking/Sales links are reconciled on both accepted sides according to one cardinality policy.
  10. Booking flags remain independent from child execution states.
  11. Clone never implies child copy unless each child is explicitly included and returned.
  12. Unknown response requires reread before replay.
  13. One migration cohort/capability has one writer.
  14. PostgreSQL conversion preserves decimal/UOM/state/link semantics.

12. Migration Boundary

Phase A — read parity

  • implement TypeScript read queries against current MySQL;
  • expose React/Next.js read-only Commercial, Inbound, Outbound, Booking and reconciliation views;
  • compare exact fields, counts, links, derived states and blockers.

Phase B — Commercial writer

  • create/update/relation/status/delete in bounded waves;
  • retain same authoritative records and generated numbers;
  • introduce accepted idempotency/version behavior;
  • keep execution children read-only.

Phase C — Inbound scheduled writer

  • create/atomic save scheduled data;
  • preserve current receipt paths under PHP until separately activated.

Phase D — Receipt writer

  • Scale remains separately owned;
  • switch receipt finalize/no-scale completion with exact item/transload/lot transaction and recovery.

Phase E — Outbound scheduled writer

  • switch requested demand and bridge fields;
  • Allocation remains separate;
  • protect progressed/allocated data.

Phase F — Booking writer

  • switch Booking-owned fields, clone, inactive and accepted Sales link;
  • hidden compatibility sync disabled for the migration cohort;
  • explicit child handoffs only.

Phase G — compatibility retirement

  • identify all legitimate current BOOKING_RATE outcomes;
  • move them to owning commands or retire them;
  • compare read/business parity;
  • reach caller-zero.

13. Completion Assessment

Current documentation result

Process ownership: SOURCE-RECONCILED
Cross-child handoff: SOURCE-RECONCILED INPUT
Data/identity model: DETAILED INPUT
Command/query/error model: DETAILED TARGET INPUT
Current role/API matrix: PARTIAL
Current Runtime/provider/device verification: EXISTING PARTIAL EVIDENCE / NEW EVIDENCE REQUIRED
Wiki content review/publication: NOT PERFORMED IN THIS WAVE
Migration readiness: M2 INPUT, NOT M4

Required before M3

  • target-role UI/API/record evidence;
  • exact MySQL schema/index readback;
  • current compatibility sync characterization with controlled fixtures;
  • receipt/lot/allocation/Booking partial-result evidence;
  • current Wiki content and field review.

Required before M4

  • critical policies accepted;
  • final command/data/error contracts approved;
  • one-writer/rollback/caller-zero design reviewed;
  • selected migration scenarios assigned and rehearsed;
  • deployment/config/observability plan accepted.

---

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