fix(ledger): an order's debt follows its status, as legacy recomputed it (ACC-03)

Legacy never posted order debt; updateRemain recomputed it as
SUM(orders.input) WHERE sts > 4. The port posted it once on entering
DELIVERED_TO_AGENT, guarded on deliveredAt, which:
- posted it twice when an order reached that status again
- posted nothing for an order sent straight to DELIVERED_TO_CUSTOMER
- kept it after a rollback or cancellation

syncOrderDebt compares what the order should owe with the confirmed
ORDER_STOCK entries on it and posts only the difference (append-only,
idempotent). Status removal runs it too, so removing «تحویل به نماینده»
is allowed again, as in legacy. Existing data: 0 orders out of line.

Owner approval: 2026-10-08.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
s.esmaeili
2026-10-08 10:57:38 +03:30
co-authored by Claude Opus 5.5
parent 5d386bf752
commit fb25b2251b
6 changed files with 169 additions and 59 deletions
@@ -31,7 +31,7 @@ export class OrdersService {
* Places a stock order. Per line item:
* w = rashWeightGrams * (1 + (wagePercent - discountPercent) / 100)
* mirrors legacy ApiMobileController::setOrder. Debt is NOT posted here —
* only once the order reaches DELIVERED_TO_AGENT (see updateStatus).
* only while the order is delivered (see updateStatus / syncOrderDebt).
*/
/**
* @param customerId taken from the caller's token by the controller, NEVER
@@ -152,14 +152,10 @@ export class OrdersService {
data: { orderId, fromStatus: order.status, toStatus: newStatus, note, actorAdminUserId },
});
// Debt recognition point — mirrors legacy sts>4, which first becomes true
// at sts=5 ("تحویل مسئول فروش" / delivered to agent), not sts=6 (delivered
// to customer). Only fires once: a second transition into this status
// (e.g. a data-fix re-save) would double-post debt, so guard on the order
// not already having deliveredAt.
if (newStatus === OrderStatus.DELIVERED_TO_AGENT && !order.deliveredAt) {
await this.ledger.postOrderDebt(orderId, tx);
}
// Debt follows the status, as legacy's recomputed `sts > 4` did: owed
// while delivered (to the expert or the customer), not otherwise, never
// twice. See LedgerService.syncOrderDebt (ACC-03 / MON-04).
await this.ledger.syncOrderDebt(orderId, tx);
// D27 — the accounting document (پیش‌فاکتور) follows the owner's rule on
// which status posts it, queued in this same transaction.