@tallyui/pos 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
1
+ import type { SettleCancelRequest, SettleOutcome, SettlePayment, SettlePayRequest, SettlePayResult } from '@tallyui/core';
2
+ import type { RxCollection } from 'rxdb';
3
+ import { outboxLogger } from './logger';
4
+ import { canCancelOnStore, canPayRestOnStore, storeOrderLeft, unrecordedLegs, uuidv7, type PosOrder, type PosOrderStoreSettlement } from '../pos-order';
5
+
6
+ export interface CancelOnStoreDeps {
7
+ orders: RxCollection<PosOrder>;
8
+ /** The connector's cancel, bound to the open store (`RefusedOrderSettlement.cancel`). */
9
+ cancel(request: SettleCancelRequest): Promise<SettleOutcome>;
10
+ now?: () => Date;
11
+ }
12
+
13
+ /**
14
+ * Cancels on the store the order a refused sale left behind (#1101), when `canCancelOnStore` allows it on the stored
15
+ * row; otherwise resolves to `not_offered` and never calls `cancel`. It first stores the attempt as `sending` (keeping
16
+ * the stored `attemptId` of a cancel still `sending`, so a repeat is the same attempt), and only once that write has
17
+ * resolved calls `cancel`. The outcome is written only while the stored settlement is still this attempt's `sending`
18
+ * one; `retry` writes nothing, and a rejected `cancel` leaves the row `sending` and rejects with the same error.
19
+ * `syncStatus`, `error`, `commandId`, `payments` and the totals are never changed. pos_orders is till-local, never
20
+ * pulled from a store, so these writes break no replication rule.
21
+ */
22
+ export async function cancelOnStore(deps: CancelOnStoreDeps, orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
23
+ const stamp = () => (deps.now?.() ?? new Date()).toISOString();
24
+ let request: SettleCancelRequest | undefined;
25
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
26
+ // The modifier runs again on a write conflict, so it decides on the stored state each run.
27
+ request = undefined;
28
+ if (data._deleted || !canCancelOnStore(data)) return data;
29
+ const stored = data.storeSettlement;
30
+ const attemptId = stored?.kind === 'cancel' && stored.state === 'sending' ? stored.attemptId : uuidv7();
31
+ const at = stamp();
32
+ data.storeSettlement = { kind: 'cancel', state: 'sending', attemptId, at };
33
+ data.updatedAt = at;
34
+ request = { storeOrderId: storeOrderLeft(data)!.orderId, clientOrderId: data.id, attemptId };
35
+ return data;
36
+ });
37
+ if (!request) return { kind: 'not_offered' };
38
+ const sent: SettleCancelRequest = request;
39
+ const outcome = await deps.cancel(sent);
40
+ if (outcome.kind === 'retry') {
41
+ outboxLogger.info('Cancelling the store order got no definite answer; it stays sending', { orderId, reason: outcome.reason });
42
+ return outcome;
43
+ }
44
+ if (outcome.kind === 'refused') outboxLogger.warn('The store refused to cancel the order', { orderId, code: outcome.code, message: outcome.message });
45
+ if (outcome.kind === 'changed') {
46
+ outboxLogger.warn('The store order changed; nothing was cancelled', { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
47
+ }
48
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
49
+ const stored = data.storeSettlement;
50
+ // A newer attempt, or an answer already written, wins over this one.
51
+ if (stored?.attemptId !== sent.attemptId || stored.state !== 'sending') return data;
52
+ const at = stamp();
53
+ const base = { kind: 'cancel' as const, attemptId: sent.attemptId, at };
54
+ const settled: PosOrderStoreSettlement = outcome.kind === 'done' ? { ...base, state: 'done', storeStatus: outcome.status }
55
+ : outcome.kind === 'changed' ? { ...base, state: 'changed', storeStatus: outcome.status, capturedMinor: outcome.capturedMinor }
56
+ : outcome.kind === 'refused' ? { ...base, state: 'refused', code: outcome.code, message: outcome.message }
57
+ : { ...base, state: 'gone' };
58
+ data.storeSettlement = settled;
59
+ data.updatedAt = at;
60
+ return data;
61
+ });
62
+ return outcome;
63
+ }
64
+
65
+ export interface PayRestOnStoreDeps {
66
+ orders: RxCollection<PosOrder>;
67
+ /** The connector's pay, bound to the open store (`RefusedOrderSettlement.pay`). */
68
+ pay(request: SettlePayRequest): Promise<SettlePayResult>;
69
+ now?: () => Date;
70
+ }
71
+
72
+ type StoredPayment = NonNullable<PosOrderStoreSettlement['payments']>[number];
73
+
74
+ /**
75
+ * Records on the store the legs of a refused sale its part-paid store order is missing (#1101 slice 3), when
76
+ * `canPayRestOnStore` allows it on the stored row; otherwise resolves to `not_offered` and never calls `pay`. No money is
77
+ * taken: each leg of `unrecordedLegs` is sent under a new id (method, amount, and `tenderedMinor` for cash only, never
78
+ * the change), except that a stored pay with one payment per leg keeps its ids, amounts and `done` flags, so the store
79
+ * skips a leg it already holds. It first stores the attempt as `sending` with those ids (a pay still `sending` also keeps
80
+ * its `attemptId`, so a repeat is the same attempt; any other mints a new one), and only once that write has resolved
81
+ * calls `pay`. The answer is written only while the stored settlement is still this attempt's `sending` one: every id in
82
+ * `recorded` is marked `done` whatever the outcome, `retry` keeps `sending`, and a rejected `pay` leaves the row
83
+ * `sending` and rejects with the same error.
84
+ * `syncStatus`, `error`, `commandId`, `payments` and the totals are never changed.
85
+ */
86
+ export async function payRestOnStore(deps: PayRestOnStoreDeps, orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
87
+ const stamp = () => (deps.now?.() ?? new Date()).toISOString();
88
+ let request: SettlePayRequest | undefined;
89
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
90
+ // The modifier runs again on a write conflict, so it decides on the stored state each run.
91
+ request = undefined;
92
+ if (data._deleted || !canPayRestOnStore(data)) return data;
93
+ const stored = data.storeSettlement;
94
+ const legs = unrecordedLegs(data);
95
+ const again = stored?.kind === 'pay' && stored.payments?.length === legs.length ? stored : undefined;
96
+ const attemptId = again?.state === 'sending' ? again.attemptId : uuidv7();
97
+ const payments: StoredPayment[] = again?.payments ?? legs.map((leg) => ({
98
+ id: uuidv7(), method: leg.method, amountMinor: leg.amountMinor,
99
+ ...(leg.method === 'cash' && leg.tenderedMinor !== undefined ? { tenderedMinor: leg.tenderedMinor } : {}),
100
+ }));
101
+ const at = stamp();
102
+ data.storeSettlement = { kind: 'pay', state: 'sending', attemptId, at, payments };
103
+ data.updatedAt = at;
104
+ request = { storeOrderId: storeOrderLeft(data)!.orderId, clientOrderId: data.id, attemptId, currency: data.currency,
105
+ payments: payments.map(({ done: _done, ...payment }) => payment as SettlePayment) };
106
+ return data;
107
+ });
108
+ if (!request) return { kind: 'not_offered' };
109
+ const sent: SettlePayRequest = request;
110
+ const { outcome, recorded } = await deps.pay(sent);
111
+ if (outcome.kind === 'retry') {
112
+ outboxLogger.info('Recording the rest on the store got no definite answer; it stays sending', { orderId, reason: outcome.reason, recorded: recorded.length });
113
+ }
114
+ if (outcome.kind === 'refused') outboxLogger.warn('The store refused to record the rest of the order', { orderId, code: outcome.code, message: outcome.message });
115
+ if (outcome.kind === 'changed') {
116
+ outboxLogger.warn('The store order changed; nothing more was recorded', { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
117
+ }
118
+ const done = new Set(recorded);
119
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
120
+ const stored = data.storeSettlement;
121
+ // A newer attempt, or an answer already written, wins over this one.
122
+ if (stored?.attemptId !== sent.attemptId || stored.state !== 'sending') return data;
123
+ const payments = (stored.payments ?? []).map((payment) => (done.has(payment.id) ? { ...payment, done: true } : payment));
124
+ if (outcome.kind === 'retry' && payments.every((payment, index) => payment.done === stored.payments?.[index]?.done)) return data;
125
+ const at = stamp();
126
+ const base = { kind: 'pay' as const, attemptId: sent.attemptId, at, payments };
127
+ data.storeSettlement = outcome.kind === 'retry' ? { ...stored, payments }
128
+ : outcome.kind === 'done' ? { ...base, state: 'done', storeStatus: outcome.status }
129
+ : outcome.kind === 'changed' ? { ...base, state: 'changed', storeStatus: outcome.status, capturedMinor: outcome.capturedMinor }
130
+ : outcome.kind === 'refused' ? { ...base, state: 'refused', code: outcome.code, message: outcome.message }
131
+ : { ...base, state: 'gone' };
132
+ data.updatedAt = outcome.kind === 'retry' ? data.updatedAt : at;
133
+ return data;
134
+ });
135
+ return outcome;
136
+ }
@@ -1,10 +1,11 @@
1
- import type { OrderCreateEnvelope, OrderUpdateEnvelope } from '@tallyui/core';
1
+ import type { OrderCreateEnvelope, OrderUpdateEnvelope, SettleCancelRequest, SettleOutcome, SettlePayRequest, SettlePayResult } from '@tallyui/core';
2
2
  import { useEffect, useMemo, useRef, useState } from 'react';
3
3
  import type { RxCollection, RxError } from 'rxdb';
4
4
  import { outboxLogger } from './logger';
5
5
  import { OrderContentMismatchError, sameSale, type PosOrder } from '../pos-order';
6
6
  import { watchFresh } from '../rxdb';
7
7
  import { createOrderOutbox, refreshOutboxState } from './order-outbox';
8
+ import { cancelOnStore as cancelStoreOrder, payRestOnStore as payStoreRest } from './store-settlement';
8
9
  import type { CommandTransport, OutboxState } from './types';
9
10
 
10
11
  const idle: OutboxState = { pending: 0, sending: false };
@@ -28,6 +29,12 @@ export interface UseOrderOutboxOptions {
28
29
  onBusy?(busy: boolean): void;
29
30
  /** Called when `open` rejects, even if the key has changed since (medusapos: reports storage worker failures). */
30
31
  onOpenError?(error: unknown): void;
32
+ /** The settlement of a refused sale's store order (#1101) for `storeKey`: the connector's `cancel` and `pay`, bound to
33
+ * that store. Read on each call, for the open store. */
34
+ storeSettlement?(storeKey: string): {
35
+ cancel?(request: SettleCancelRequest): Promise<SettleOutcome>;
36
+ pay?(request: SettlePayRequest): Promise<SettlePayResult>;
37
+ } | undefined;
31
38
  }
32
39
 
33
40
  export interface UseOrderOutboxResult {
@@ -56,6 +63,19 @@ export interface UseOrderOutboxResult {
56
63
  requeue(orderIds?: string[]): Promise<number>;
57
64
  /** Removes one rejected order (see `OrderOutbox.discard`); resolves to false before the current store is ready. */
58
65
  discard(orderId: string): Promise<boolean>;
66
+ /**
67
+ * Cancels on the store the order a refused sale left behind (`cancelOnStore`, #1101), with the `cancel` of
68
+ * `storeSettlement` for the open store, then recounts the outbox state, whether the cancel resolved or rejected.
69
+ * Resolves to `not_offered` before the current store is ready, or when there is no `storeSettlement` or no `cancel`.
70
+ */
71
+ cancelOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
72
+ /**
73
+ * Records on the store the till's legs a refused sale's part-paid store order is missing (`payRestOnStore`, #1101
74
+ * slice 3), with the `pay` of `storeSettlement` for the open store, then recounts the outbox state, whether the pay
75
+ * resolved or rejected. Resolves to `not_offered` before the current store is ready, or when there is no
76
+ * `storeSettlement` or no `pay`.
77
+ */
78
+ payRestOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
59
79
  /**
60
80
  * The count of `record()` calls not yet settled (resolved or rejected). An app holds sign-out
61
81
  * (closing the store) while this is above 0, because a close that lands under a write stuck in
@@ -135,6 +155,32 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
135
155
  const opened = current.current;
136
156
  return opened && opened.storeKey === storeKey ? opened.outbox.discard(orderId) : false;
137
157
  },
158
+ async cancelOnStore(orderId) {
159
+ const opened = current.current;
160
+ if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
161
+ const settlement = latest.current.storeSettlement?.(opened.storeKey);
162
+ const cancel = settlement?.cancel?.bind(settlement);
163
+ if (!cancel) return { kind: 'not_offered' };
164
+ try {
165
+ return await cancelStoreOrder({ orders: opened.orders, cancel }, orderId);
166
+ } finally {
167
+ // A settled row leaves state.rejected: publish it before resolving.
168
+ try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
169
+ }
170
+ },
171
+ async payRestOnStore(orderId) {
172
+ const opened = current.current;
173
+ if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
174
+ const settlement = latest.current.storeSettlement?.(opened.storeKey);
175
+ const pay = settlement?.pay?.bind(settlement);
176
+ if (!pay) return { kind: 'not_offered' };
177
+ try {
178
+ return await payStoreRest({ orders: opened.orders, pay }, orderId);
179
+ } finally {
180
+ // A settled row leaves state.rejected: publish it before resolving.
181
+ try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
182
+ }
183
+ },
138
184
  savesInFlight: savesInFlightCount,
139
185
  stuckCommandIds,
140
186
  async record(posOrder) {
@@ -5,6 +5,8 @@ import type { PosOrder } from './types';
5
5
  * Marks the order `orderId` handled for its current `commandId`, so `needsAttention` leaves it out until a requeue
6
6
  * mints a new one (ADR-092 6f, tally-woo 03). Resolves to true when the order is stamped (or already was, for this
7
7
  * commandId); false, with nothing changed, when the id is unknown or the order is pending (still the outbox's to settle).
8
+ * The stamp does not hide a refused sale whose order the store created (`storeOrderLeft`, #1101): it is still written
9
+ * and the call still resolves to true, but `needsAttention` keeps that sale.
8
10
  */
9
11
  export async function markAttentionHandled(orders: RxCollection<PosOrder>, orderId: string, now?: () => Date): Promise<boolean> {
10
12
  const doc = await orders.findOne(orderId).exec();
@@ -1,7 +1,8 @@
1
1
  import { ORDER_META_KEY_MAX, ORDER_META_MAX, ORDER_NOTE_MAX, ORDER_TAX_ID_TYPE_MAX, ORDER_TAX_ID_VALUE_MAX, ORDER_TAX_IDS_MAX } from '@tallyui/core';
2
2
  import type { OrderCreateEnvelope, OrderCreateMeta, OrderCreatePayload, OrderCreateTaxId, OrderUpdateEnvelope, OrderUpdatePayload } from '@tallyui/core';
3
3
  import { MICROS_PER_MINOR, roundMicrosToMinor, taxMicros } from '../tax/exact';
4
- import { woocommerceChargeTaxMinor } from '../order/woocommerce-tax';
4
+ import { woocommerceChargeTaxMinor, woocommerceLine } from '../order/woocommerce-tax';
5
+ import type { LineTaxLine } from '../order/types';
5
6
  import type { PosOrder, PosOrderLine } from './types';
6
7
 
7
8
  /** The highest order.create version this till sends; pos_orders' sentVersion and downgradedFrom maxima must equal it. */
@@ -82,12 +83,22 @@ export const editedSku = (line: PosOrderLine) => !line.custom && line.catalogueS
82
83
  /**
83
84
  * Version 4 (#286): a line's discount made tax-exclusive. An exclusive line's is unchanged; an inclusive line's
84
85
  * gross discount D on its amount A becomes `net(A) − net(A − D)`, exact in millionths, rounded half away from zero.
85
- * Tax comes from stored taxLines after D, recomputed before a store-priced coupon, and from `taxMicros` before D.
86
+ * A Woo-rounded line with a coupon or a compound rate takes both nets from `woocommerceLine` at its stored rates (#1342):
87
+ * its stored taxLines are after the coupon. Otherwise tax comes from stored taxLines after D, recomputed before a
88
+ * store-priced coupon, and from `taxMicros` before D.
86
89
  */
87
- function netDiscountMinor(line: PosOrderLine, pricesIncludeTax: boolean, woocommerce: boolean): number {
88
- if (!(line.taxInclusive ?? pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
89
- const ratePpm = line.taxLines.reduce((sum, tax) => sum + tax.ratePpm, 0);
90
+ function netDiscountMinor(line: PosOrderLine, order: Pick<PosOrder, 'pricesIncludeTax' | 'taxRounding' | 'coupons' | 'currency'>): number {
91
+ if (!(line.taxInclusive ?? order.pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
92
+ const woocommerce = order.taxRounding?.granularity === 'woocommerce', stored: readonly LineTaxLine[] = line.taxLines;
90
93
  const afterDiscount = line.unitPriceMinor * line.quantity - line.discountMinor;
94
+ if (woocommerce && (order.coupons?.length || stored.some((tax) => tax.compound))) {
95
+ const rates = stored.map((tax, i) => ({ id: i, code: tax.code ?? '', label: '', rate: (tax.ratePpm / 10000).toFixed(4),
96
+ priority: i, compound: tax.compound ?? false, shipping: true }));
97
+ // Only netMicros is read: the net before any coupon, which roundAtSubtotal does not change.
98
+ const net = (minor: number) => BigInt(woocommerceLine(minor, rates, true, order.currency, false).netMicros);
99
+ return roundMicrosToMinor(net(line.unitPriceMinor * line.quantity) - net(afterDiscount));
100
+ }
101
+ const ratePpm = line.taxLines.reduce((sum, tax) => sum + tax.ratePpm, 0);
91
102
  // A store-priced coupon leaves stored taxLines after the coupon; the line discount needs tax before it.
92
103
  const taxAfter = !woocommerce && line.netMinor < afterDiscount ? taxMicros(afterDiscount, ratePpm, true)
93
104
  : line.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n);
@@ -120,9 +131,17 @@ function wireNote(note: string | undefined): string | undefined {
120
131
  return newline === -1 ? undefined : note.slice(newline + 1) || undefined;
121
132
  }
122
133
 
134
+ /** #1341 (ADR-075/076): in Woo rounding a charge goes on the wire at its display row, found by id (the server checks the
135
+ * two are equal); with no such row it goes at its stored amount. Any other rounding sends the stored amount. */
136
+ function wireChargeMinor(order: PosOrder, charge: { id: string; amountMinor: number }, rows?: readonly { id: string; amountMinor: number }[]): number {
137
+ if (order.taxRounding?.granularity !== 'woocommerce') return charge.amountMinor;
138
+ return rows?.find(({ id }) => id === charge.id)?.amountMinor ?? charge.amountMinor;
139
+ }
140
+
123
141
  /**
124
142
  * Builds the ADR-038 order.create envelope for a PosOrder. It sends the stored order unchanged, so every resend of
125
- * an order is byte-identical, and an order stored by an older till goes out exactly as that till sent it:
143
+ * an order is byte-identical, except that a Woo-rounded order with charge display rows sends each charge at its row
144
+ * (`wireChargeMinor`, #1341) and everything else as stored:
126
145
  * `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
127
146
  * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
128
147
  * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
@@ -184,7 +203,7 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
184
203
  const withTaxAddress = version === 8 || (version >= 9 && taxAddress !== undefined);
185
204
  const withAddresses = withTaxAddress || version >= UNTAXED_ADDRESS_ORDER_CREATE_VERSION;
186
205
  const taxIds = version >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && sentTaxIds.length ? { taxIds: sentTaxIds } : undefined;
187
- const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order.pricesIncludeTax, order.taxRounding?.granularity === 'woocommerce') : line.discountMinor);
206
+ const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order) : line.discountMinor);
188
207
  for (const coupon of carried) {
189
208
  if (!coupon.lines) throw new Error(`Order ${order.id}: a carried coupon has no line shares`);
190
209
  for (const [i, line] of order.lines.entries()) lineDiscounts[i] += coupon.lines.find(({ lineId }) => lineId === line.id)?.discountMinor ?? 0;
@@ -215,7 +234,7 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
215
234
  ...(base === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
216
235
  })),
217
236
  ...(base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
218
- clientFeeId: fee.id, name: fee.name, amountMinor: fee.amountMinor, taxStatus: fee.taxStatus,
237
+ clientFeeId: fee.id, name: fee.name, amountMinor: wireChargeMinor(order, fee, order.display?.fees), taxStatus: fee.taxStatus,
219
238
  ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
220
239
  // #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
221
240
  taxMinor: order.taxRounding?.granularity === 'woocommerce'
@@ -224,7 +243,7 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
224
243
  })) } : {}),
225
244
  ...(base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
226
245
  clientShippingId: charge.id, name: charge.name, ...(charge.methodId !== undefined ? { methodId: charge.methodId } : {}),
227
- amountMinor: charge.amountMinor, taxStatus: charge.taxStatus,
246
+ amountMinor: wireChargeMinor(order, charge, order.display?.shipping), taxStatus: charge.taxStatus,
228
247
  ...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}),
229
248
  // #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
230
249
  taxMinor: order.taxRounding?.granularity === 'woocommerce'
@@ -1,4 +1,4 @@
1
- export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder } from './types';
1
+ export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, PosOrderStoreSettlement } from './types';
2
2
  export { uuidv7 } from './uuidv7';
3
3
  export { AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder } from './finalize';
4
4
  export type { FinalizeOptions } from './finalize';
@@ -7,6 +7,8 @@ export { posOrderSchema, posOrderCollection } from './schema';
7
7
  export { addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger } from './open';
8
8
  export { getDeviceId } from './device-id';
9
9
  export { needsAttention, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE } from './needs-attention';
10
+ export { storeOrderLeft } from './store-order-left';
11
+ export { canCancelOnStore, canPayRestOnStore, settledOnStore, unrecordedLegs } from './store-settlement';
10
12
  export { markAttentionHandled } from './attention-handled';
11
13
  export { moneyDivergence, type MoneyDivergence } from './money-divergence';
12
14
  export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './reopen';
@@ -1,5 +1,7 @@
1
1
  import { knownWarnings } from '@tallyui/core';
2
2
  import { replacedOrderIds } from './reopened';
3
+ import { storeOrderLeft } from './store-order-left';
4
+ import { settledOnStore } from './store-settlement';
3
5
  import type { PosOrder } from './types';
4
6
 
5
7
  /** The `error.code` the outbox puts on a pending reopened sale whose `order.update` it cannot build (ADR-090 W4b). The row stays pending: unsent. */
@@ -15,15 +17,18 @@ export const UPDATE_UNSENDABLE_MESSAGE = "The store can't accept this change yet
15
17
  * A refused order is left out once its finalized successor is in `orders`.
16
18
  * Pending updates marked `UPDATE_UNSENDABLE` are shown until a person acts.
17
19
  * An order a cashier marked handled (`markAttentionHandled`) is left out while its `commandId` is the one it was marked
18
- * for; a requeue mints a new `commandId`, so a fresh refusal shows again (ADR-092 6f).
20
+ * for; a requeue mints a new `commandId`, so a fresh refusal shows again (ADR-092 6f). The mark does not hide a refused
21
+ * sale whose order the store created (`storeOrderLeft`, #1101). A refused sale whose store order is settled on the store
22
+ * (`settledOnStore`: cancelled or gone, #1101) is not shown for its refusal; any other reason above still shows it.
19
23
  */
20
24
  export function needsAttention(orders: PosOrder[], options: { stuckCommandIds?: readonly string[] } = {}): PosOrder[] {
21
25
  const replaced = replacedOrderIds(orders);
22
- return orders.filter((order) => order.syncStatus === 'rejected'
26
+ return orders.filter((order) => (order.syncStatus === 'rejected' && !settledOnStore(order))
23
27
  || (order.syncStatus === 'pending' && order.error?.code === UPDATE_UNSENDABLE)
24
28
  || (order.localWarnings?.length ?? 0) > 0
25
29
  || (order.syncStatus === 'applied' && knownWarnings(order.warnings).some((warning) => warning.code !== 'register_session_unknown')) || order.lateSessionId !== undefined
26
30
  || (order.syncStatus === 'pending' && options.stuckCommandIds?.includes(order.commandId) === true))
27
- .filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== undefined && order.attentionHandledFor === order.commandId))
31
+ .filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== undefined && order.attentionHandledFor === order.commandId
32
+ && storeOrderLeft(order) === undefined))
28
33
  .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
29
34
  }
@@ -40,6 +40,8 @@ import type { PosOrder } from './types';
40
40
  * Version 19 adds a store-priced coupon's `carried` flag and its lines' `amountMinor` (a coupon the store refused at send, carried at the amount charged), and the order's `countedInClosureOf`, and changes nothing else. Its migration is the identity. It is one-way like version 18.
41
41
  * Version 20 adds a payment's optional `takenAt`, the instant the till recorded the leg; identity migration, one-way like version 19.
42
42
  * Version 21 adds the order's optional `cashRoundings` (ADR-094); identity migration, one-way like version 20.
43
+ * Version 22 adds the order's optional `storeSettlement`, the till's settlement of a refused sale's store order (#1101);
44
+ * identity migration, one-way like version 21.
43
45
  */
44
46
  /** A customer's address on an order (#722, OrderAddress): ten optional strings. */
45
47
  const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
@@ -49,7 +51,7 @@ const orderAddressSchema = { type: 'object', additionalProperties: false, proper
49
51
  } } as const;
50
52
 
51
53
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
52
- version: 21, primaryKey: 'id', type: 'object', additionalProperties: false,
54
+ version: 22, primaryKey: 'id', type: 'object', additionalProperties: false,
53
55
  properties: {
54
56
  id: { type: 'string', maxLength: 36 },
55
57
  saleId: { type: 'string', maxLength: 36 },
@@ -60,6 +62,19 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
60
62
  updatedAt: { type: 'string' },
61
63
  reopenedAt: { type: 'string', maxLength: 40 },
62
64
  attentionHandledFor: { type: 'string', maxLength: 36 },
65
+ storeSettlement: { type: 'object', additionalProperties: false, properties: {
66
+ kind: { type: 'string', enum: ['cancel', 'pay', 'reverse'] },
67
+ state: { type: 'string', enum: ['sending', 'done', 'changed', 'refused', 'gone'] },
68
+ attemptId: { type: 'string', maxLength: 36 }, at: { type: 'string', maxLength: 40 },
69
+ storeStatus: { type: 'string' }, capturedMinor: { type: 'integer' }, code: { type: 'string' }, message: { type: 'string' },
70
+ payments: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
71
+ id: { type: 'string', maxLength: 36 }, method: { type: 'string' }, amountMinor: { type: 'integer' },
72
+ tenderedMinor: { type: 'integer' }, done: { type: 'boolean' } }, required: ['id', 'method', 'amountMinor'] } },
73
+ closeId: { type: 'string', maxLength: 36 },
74
+ legs: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
75
+ paymentId: { type: 'string', maxLength: 36 }, commandId: { type: 'string', maxLength: 36 }, done: { type: 'boolean' } },
76
+ required: ['paymentId', 'commandId'] } },
77
+ }, required: ['kind', 'state', 'attemptId', 'at'] },
63
78
  currency: { type: 'string' },
64
79
  pricesIncludeTax: { type: 'boolean' },
65
80
  subtotalMinor: { type: 'integer' }, discountMinor: { type: 'integer' },
@@ -223,5 +238,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
223
238
  // it means no older sale is ever re-rounded (#287).
224
239
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
225
240
  return { schema: posOrderSchema,
226
- migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity, 12: identity, 13: identity, 14: identity, 15: identity, 16: identity, 17: identity, 18: identity, 19: identity, 20: identity, 21: identity } };
241
+ migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity, 12: identity, 13: identity, 14: identity, 15: identity, 16: identity, 17: identity, 18: identity, 19: identity, 20: identity, 21: identity, 22: identity } };
227
242
  }
@@ -0,0 +1,21 @@
1
+ import type { PosOrder } from './types';
2
+
3
+ /**
4
+ * The store order a refused sale left behind (#1101): a value only for a rejected order with no `storeOrderId` whose
5
+ * `error.data.orderId` is a non-empty string, as a transport that created the order before refusing the sale sets it.
6
+ * `reference` is `data.displayId` when a non-empty string, else `orderId`. `recordedMinor` sums the first
7
+ * `data.recorded` payments (a safe integer above 0; anything else counts as 0): what the store had recorded at the
8
+ * refusal, not the order's state now.
9
+ */
10
+ export function storeOrderLeft(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error' | 'payments'>):
11
+ { orderId: string; reference: string; recordedMinor: number } | undefined {
12
+ const data = order.error?.data;
13
+ if (order.syncStatus !== 'rejected' || order.storeOrderId !== undefined || typeof data?.orderId !== 'string' || !data.orderId) return undefined;
14
+ const { orderId, displayId, recorded } = data;
15
+ const count = Number.isSafeInteger(recorded) && (recorded as number) > 0 ? recorded as number : 0;
16
+ return {
17
+ orderId,
18
+ reference: typeof displayId === 'string' && displayId ? displayId : orderId,
19
+ recordedMinor: order.payments.slice(0, count).reduce((sum, payment) => sum + payment.amountMinor, 0),
20
+ };
21
+ }
@@ -0,0 +1,51 @@
1
+ import { storeOrderLeft } from './store-order-left';
2
+ import type { PosOrder } from './types';
3
+
4
+ type LeftOrder = Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error' | 'payments' | 'storeSettlement'>;
5
+
6
+ /**
7
+ * Whether the store order a refused sale left behind is settled on the store (#1101): its settlement is done, or gone
8
+ * while the store had recorded nothing on it (desk ruling: a gone order with money recorded still needs a manager).
9
+ */
10
+ export function settledOnStore(order: LeftOrder | Pick<PosOrder, 'storeSettlement'>): boolean {
11
+ const state = order.storeSettlement?.state;
12
+ if (state === 'done') return true;
13
+ if (state !== 'gone') return false;
14
+ const left = 'syncStatus' in order ? storeOrderLeft(order) : undefined;
15
+ return !left || left.recordedMinor === 0;
16
+ }
17
+
18
+ /**
19
+ * Whether the till may cancel the store order a refused sale left behind (#1101): there is one (`storeOrderLeft`), the
20
+ * store had recorded nothing paid on it, it is not settled (`settledOnStore`), and there is no settlement yet, or a
21
+ * cancel (whose `sending` attempt a repeat finishes), or one the store changed or refused.
22
+ */
23
+ export function canCancelOnStore(order: LeftOrder): boolean {
24
+ const left = storeOrderLeft(order);
25
+ if (!left || left.recordedMinor !== 0 || settledOnStore(order)) return false;
26
+ const settlement = order.storeSettlement;
27
+ return settlement === undefined || settlement.kind === 'cancel' || settlement.state === 'changed' || settlement.state === 'refused';
28
+ }
29
+
30
+ /** The till's legs the store had not recorded at the refusal (#1101 slice 3): the payments after `data.recorded`, counted
31
+ * as `storeOrderLeft` counts them. */
32
+ export function unrecordedLegs(order: Pick<PosOrder, 'error' | 'payments'>): PosOrder['payments'] {
33
+ const recorded = order.error?.data?.recorded;
34
+ return order.payments.slice(Number.isSafeInteger(recorded) && (recorded as number) > 0 ? recorded as number : 0);
35
+ }
36
+
37
+ /**
38
+ * Whether the till may record its unrecorded legs on the part-paid store order a refused sale left behind (#1101 slice
39
+ * 3): the store had recorded some of the sale, it is not settled, every leg left has an amount, the settlement is not
40
+ * `gone` (the order is not on the store, so a press could only read 404 again), and there is no settlement yet, or a
41
+ * pay (whose `sending` attempt a repeat finishes), or one the store changed or refused.
42
+ */
43
+ export function canPayRestOnStore(order: LeftOrder): boolean {
44
+ const left = storeOrderLeft(order);
45
+ if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
46
+ const legs = unrecordedLegs(order);
47
+ if (legs.length === 0 || !legs.every((leg) => leg.amountMinor > 0)) return false;
48
+ const settlement = order.storeSettlement;
49
+ if (settlement?.state === 'gone') return false;
50
+ return settlement === undefined || settlement.kind === 'pay' || settlement.state === 'changed' || settlement.state === 'refused';
51
+ }
@@ -164,4 +164,26 @@ export interface PosOrder {
164
164
  reopenedAt?: string;
165
165
  /** The commandId whose refusal the cashier marked handled (tally-woo 03, ADR-092 6f); the logic comes in a later PR. */
166
166
  attentionHandledFor?: string;
167
+ /** How the till settled the order the store created before it refused this sale (#1101); see `PosOrderStoreSettlement`. */
168
+ storeSettlement?: PosOrderStoreSettlement;
167
169
  }
170
+
171
+ /**
172
+ * The till's settlement of a refused sale's store order (#1101, `storeOrderLeft`). `attemptId` names the attempt and is
173
+ * kept while `state` is `sending`, so a repeat after a lost answer is the same attempt. `at` is the instant of the last
174
+ * write. `storeStatus` is the store's status word (done, changed), `capturedMinor` what the store shows captured
175
+ * (changed), `code` and `message` the store's refusal (refused), for the sync log, never shown to the cashier.
176
+ * `payments` and `closeId` are for kind `pay`, `legs` for kind `reverse` (later slices).
177
+ */
178
+ export type PosOrderStoreSettlement = {
179
+ kind: 'cancel' | 'pay' | 'reverse';
180
+ state: 'sending' | 'done' | 'changed' | 'refused' | 'gone';
181
+ attemptId: string;
182
+ at: string;
183
+ storeStatus?: string;
184
+ capturedMinor?: number;
185
+ code?: string; message?: string;
186
+ payments?: { id: string; method: string; amountMinor: number; tenderedMinor?: number; done?: boolean }[];
187
+ closeId?: string;
188
+ legs?: { paymentId: string; commandId: string; done?: boolean }[];
189
+ };
@@ -13,7 +13,7 @@ import { cleanTaxIds, TAX_IDS_INVALID } from '../order/tax-ids';
13
13
  import { finalizeOrder, uuidv7, type PosOrder } from '../pos-order';
14
14
  import { AFTER_CLOSE_PAYMENTS_CHANGED, afterCloseChanged, MESSAGE_NAME_MAX, referenceError, referenceReason, withSentForm } from '../pos-order/finalize';
15
15
  import { CUSTOMER_REFUSALS, customerRefusal, cutText, PAYLOAD_STRING_MAX } from '../pos-order/command';
16
- import { cashVoidRefusal, nearestPayableCash, remainderEntriesMinor, roundedPickTarget, roundedRemainder, settlesAtRoundedDue } from '../tender/cash-rounding';
16
+ import { cashVoidRefusal, nearestPayableCash, remainderEntriesMinor, roundedPickTarget, roundedRemainder, settlesAtRoundedDue, writeOffLeg } from '../tender/cash-rounding';
17
17
  import { useTax, type SaleTaxContext, type SaleTaxLocation, type TaxContext } from '../tax';
18
18
  import { recordRegisterFact, stampSession, type RegisterSessionCollection } from '../register';
19
19
  import { isRegisterClosing } from '../register/closing';
@@ -917,7 +917,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
917
917
  });
918
918
  },
919
919
  setTender,
920
- /** ADR-072: external is capped at the balance due; change comes only from cash. A cash leg records the amount applied, the amount handed over (`tenderedMinor`) and the change (`changeMinor`). A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. Units are checked against the units legs hold (`heldUnitsByLine`), but a leg's amount is not tied to its units' money here; the pane enforces that (#1133). A cash part pick rounds its own target on a cashRounding store (ADR-094). */
920
+ /** ADR-072: external is capped at the balance due; change comes only from cash. A cash leg records the amount applied, the amount handed over (`tenderedMinor`) and the change (`changeMinor`). A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. Units are checked against the units legs hold (`heldUnitsByLine`), but a leg's amount is not tied to its units' money here; the pane enforces that (#1133). A cash part pick rounds its target less the live entries on a cashRounding store, and one that reaches the whole-settle due is taken as that settle (ADR-094 item 7). */
921
921
  addTender(input: { method: 'cash' | 'external'; methodId?: string; amountMinor: number; tenderedMinor?: number; reference?: string; units?: Readonly<Record<string, number>>; status?: 'pending' | 'authorized' | 'captured'; rounding?: PaymentRounding }): string | null {
922
922
  const { rounding, ...tender } = input;
923
923
  if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return null; }
@@ -926,7 +926,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
926
926
  // A leg in motion means this cash leg does not settle the sale, so nothing rounds: BASE's row 500 leg, but the leg it records must still be a whole number of cash steps (refused with CASH_WAITS_FOR_PAYMENT otherwise).
927
927
  const rule = rounding && tender.tenderedMinor === undefined && opts.capabilities?.cashRounding === true
928
928
  && inMotionMinor(builderNow.current.getSnapshot().payments) === 0 ? rounding : null;
929
- // ADR-094 (cash picks): a cash part pick rounds its own target and carries its own entry.
929
+ // ADR-094 item 7 (carry): a cash part pick rounds its target less the sale's live entries, and carries amount less target.
930
930
  const pickRule = rounding && tender.method === 'cash' && opts.capabilities?.cashRounding === true
931
931
  && inMotionMinor(builderNow.current.getSnapshot().payments) === 0 ? rounding : null;
932
932
  if (locked() || !Number.isInteger(tender.amountMinor) || tender.amountMinor < 0 || (tender.amountMinor === 0 && !rule)) return null;
@@ -940,13 +940,20 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
940
940
  const unpaid = unpaidUnitsByLine(lineItems.map(({ id, quantity }) => ({ id, quantity, totalMinor: 0 })), heldUnitsByLine(payments));
941
941
  if (Object.entries(tender.units).some(([id, units]) => !id || !Number.isInteger(units) || units <= 0 || !Object.hasOwn(unpaid, id) || units > unpaid[id])) return null;
942
942
  }
943
- const pickMinor = pickRule && tender.tenderedMinor !== undefined ? roundedPickTarget(tender.amountMinor, pickRule) : tender.amountMinor;
943
+ const pickMinor = pickRule && tender.tenderedMinor !== undefined ? roundedPickTarget(tender.amountMinor, pickRule, remainderEntriesMinor(builderNow.current.getSnapshot())) : tender.amountMinor;
944
944
  if (tender.tenderedMinor !== undefined && pickMinor === 0) return null;
945
945
  if (tender.tenderedMinor !== undefined && (tender.method !== 'cash' || !tender.units || !Object.keys(tender.units).length
946
946
  || !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor < pickMinor)) return null;
947
947
  if (tender.tenderedMinor !== undefined) {
948
948
  const snapshot = builderNow.current.getSnapshot();
949
949
  if (tender.amountMinor > snapshot.balanceDueMinor - inMotionMinor(snapshot.payments)) return null;
950
+ // ADR-094 item 7 (promotion): a carried pick that reaches the whole-settle due is that settle, keeping its units; entry due - balance.
951
+ const due = snapshot.balanceDueMinor;
952
+ if (pickRule && pickMinor === roundedRemainder(due, remainderEntriesMinor(snapshot), pickRule)) {
953
+ if ((snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX + 1 && pickMinor !== due) { setError(CASH_SETTLE_LIMIT); return null; }
954
+ clearStaleError();
955
+ return addOne({ ...tender, amountMinor: pickMinor, changeMinor: tender.tenderedMinor - pickMinor }, true, pickMinor !== due ? { minor: pickMinor - due } : undefined);
956
+ }
950
957
  if (pickMinor !== tender.amountMinor && (snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX) { setError(CASH_PICK_LIMIT); return null; }
951
958
  if (rounding && opts.capabilities?.cashRounding === true && tender.method === 'cash' && inMotionMinor(snapshot.payments) > 0
952
959
  && nearestPayableCash(tender.amountMinor, rounding.incrementMinor) !== null) { setError(CASH_WAITS_FOR_PAYMENT); return null; }
@@ -965,7 +972,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
965
972
  const entries = remainderEntriesMinor(snapshot);
966
973
  const dueMinor = rule ? roundedRemainder(due, entries, rule) : due;
967
974
  if (rule && settlesAtRoundedDue({ amountMinor: Math.min(tender.amountMinor, due), tenderedMinor: tender.amountMinor, balanceMinor: due, dueMinor })) {
968
- const against = snapshot.payments.filter(countsTowardPaid).at(-1);
975
+ const against = writeOffLeg(snapshot);
969
976
  const roundings = snapshot.cashRoundings ?? [];
970
977
  // The 16-entry cap: a settle that adds an entry (a rounded leg, or a write-off onto a leg with none) is refused at 16.
971
978
  if (roundings.length >= CASH_PICK_ENTRIES_MAX + 1 && (dueMinor > 0 ? dueMinor !== due
@@ -974,7 +981,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
974
981
  if (dueMinor > 0) {
975
982
  return addOne({ ...tender, amountMinor: dueMinor, tenderedMinor: tender.amountMinor, changeMinor: tender.amountMinor - dueMinor }, true, { minor: dueMinor - due });
976
983
  }
977
- // A remainder that rounds to zero closes the sale: no leg, its entry goes on the last leg counting toward paid.
984
+ // A remainder that rounds to zero closes the sale: no leg, its entry goes on writeOffLeg (ADR-094 item 1, #1365).
978
985
  if (!against) { setError(NOTHING_TO_ROUND_AGAINST); return null; }
979
986
  builderNow.current.addCashRounding({ paymentId: against.id, minor: -due });
980
987
  return against.id;
@@ -36,17 +36,25 @@ export function roundedRemainder(balanceMinor: number, entriesMinor: number, rou
36
36
  return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
37
37
  }
38
38
 
39
- /** ADR-094 (cash picks): a cash part pick rounds its own target; 0 means cash cannot pay it. */
40
- export function roundedPickTarget(targetMinor: number, rounding: PaymentRounding | null | undefined): number {
41
- return rounding ? roundToIncrement(targetMinor, rounding.incrementMinor, rounding.mode) : targetMinor;
39
+ /** ADR-094 item 7 (carry): a cash part pick rounds its target less `entriesMinor`, the live entries the pick carries against; it defaults to 0, the 5.0.0 per-pick rounding. 0 means cash cannot pay it. */
40
+ export function roundedPickTarget(targetMinor: number, rounding: PaymentRounding | null | undefined, entriesMinor = 0): number {
41
+ if (!rounding) return targetMinor;
42
+ const unrounded = targetMinor - entriesMinor;
43
+ return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
44
+ }
45
+
46
+ /** ADR-094 items 1 and 6: the live entries a remainder rounds against, every entry on the sale (cash-pick entries included since the carry rule). */
47
+ export function remainderEntriesMinor(order: { payments: readonly { id: string; method?: string; units?: Readonly<Record<string, number>> }[]; cashRoundings?: readonly { paymentId: string; minor: number }[] }): number {
48
+ return (order.cashRoundings ?? []).reduce((sum, entry) => sum + entry.minor, 0);
42
49
  }
43
50
 
44
- /** ADR-094: the live entries a remainder rounds against, leaving out a pick leg's own entry (its leg carries units). */
45
- export function remainderEntriesMinor(order: { payments: readonly { id: string; units?: Readonly<Record<string, number>> }[]; cashRoundings?: readonly { paymentId: string; minor: number }[] }): number {
46
- return (order.cashRoundings ?? []).reduce((sum, entry) => {
47
- const units = order.payments.find((leg) => leg.id === entry.paymentId)?.units;
48
- return !units || Object.keys(units).length === 0 ? sum + entry.minor : sum;
49
- }, 0);
51
+ /**
52
+ * ADR-094 item 1 (#1365, amended by the carry rule 2026-11-26): the zero-remainder write-off's leg, the last counting leg with
53
+ * wire method 'cash', else the last counting leg. A later cash leg rounds against a non-cash leg's write-off; `cashVoidRefusal` keeps the entries a stack.
54
+ */
55
+ export function writeOffLeg<L extends { id: string; method?: string; status?: PaymentLegStatus; units?: Readonly<Record<string, number>> }>(order: { payments: readonly L[] }): L | undefined {
56
+ const counted = order.payments.filter(countsTowardPaid);
57
+ return counted.filter((leg) => leg.method === 'cash').at(-1) ?? counted.at(-1);
50
58
  }
51
59
 
52
60
  /** Why a void is refused by ADR-094 item 6 (desk ruling (i), #1292): a later live cash leg's entry was computed against this leg's. */