@tallyui/pos 5.1.0 → 5.2.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.
@@ -1,12 +1,79 @@
1
- import type { SettleCancelRequest, SettleOutcome, SettlePayment, SettlePayRequest, SettlePayResult } from '@tallyui/core';
1
+ import type { SettleCancelRequest, SettleOutcome, SettlePayment, SettlePayRequest, SettlePayResult, SettleReverseRequest, SettleReverseResult } from '@tallyui/core';
2
2
  import type { RxCollection } from 'rxdb';
3
3
  import { outboxLogger } from './logger';
4
- import { canCancelOnStore, canPayRestOnStore, storeOrderLeft, unrecordedLegs, uuidv7, type PosOrder, type PosOrderStoreSettlement } from '../pos-order';
4
+ import { canCancelOnStore, canPayRestOnStore, canReverseOnStore, recordedLegs, storeOrderLeft, TILL_SESSION_CLOSED, tillPayments, unrecordedLegs, uuidv7, type PosOrder, type PosOrderStoreSettlement } from '../pos-order';
5
+
6
+ const inOpenSession = (order: PosOrder, open: string | undefined) => open !== undefined && tillPayments(order.payments).every((payment) => (payment.sessionId ?? order.sessionId) === open);
7
+ function markClosed<T extends PosOrder>(data: T, kind: 'cancel' | 'reverse', at: string, attemptId?: string): T {
8
+ const stored = data.storeSettlement;
9
+ if (stored?.kind === kind && stored.state === 'sending' && (attemptId === undefined || stored.attemptId === attemptId)) {
10
+ data.storeSettlement = { kind, state: 'refused', code: TILL_SESSION_CLOSED, attemptId: stored.attemptId, at, ...(kind === 'reverse' && stored.legs && { legs: stored.legs }) };
11
+ data.updatedAt = at;
12
+ }
13
+ return data;
14
+ }
15
+ async function closedAtLanding(deps: Pick<CancelOnStoreDeps, 'orders' | 'openSessionId'>, kind: 'cancel' | 'reverse', orderId: string, attemptId: string, outcome: SettleOutcome, stamp: () => string) {
16
+ const open = await deps.openSessionId!(), order = await deps.orders.findOne(orderId).exec();
17
+ if (!order || inOpenSession(order, open)) return false;
18
+ await order.incrementalModify((data) => markClosed(data, kind, stamp(), attemptId));
19
+ outboxLogger.warn('The store answered after the till session closed; a manager must settle the order', { orderId, outcome: outcome.kind });
20
+ return true;
21
+ }
22
+
23
+ /** Store the void command ids before sending; only the same sending attempt can receive the outcome. */
24
+ export async function reverseOnStore(deps: { orders: RxCollection<PosOrder>; reverse(request: SettleReverseRequest): Promise<SettleReverseResult>; now?: () => Date; openSessionId?: CancelOnStoreDeps['openSessionId'] },
25
+ orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
26
+ const stamp = () => (deps.now?.() ?? new Date()).toISOString();
27
+ let request: SettleReverseRequest | undefined;
28
+ const open = deps.openSessionId && await deps.openSessionId();
29
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
30
+ request = undefined;
31
+ if (data._deleted || !canReverseOnStore(data)) return data;
32
+ if (deps.openSessionId && !inOpenSession(data, open)) return markClosed(data, 'reverse', stamp());
33
+ const stored = data.storeSettlement?.kind === 'reverse' ? data.storeSettlement : undefined;
34
+ const again = stored?.state === 'sending' ? stored : undefined;
35
+ if (again && !again.legs?.length) return data;
36
+ const attemptId = again?.attemptId ?? uuidv7();
37
+ const legs = again?.legs ?? recordedLegs(data).map(({ id }) => stored?.legs?.find((leg) => leg.paymentId === id && leg.done)
38
+ ?? { paymentId: id, commandId: uuidv7() });
39
+ const requestLegs = [];
40
+ for (const { paymentId, commandId } of legs) {
41
+ const payment = data.payments.find(({ id }) => id === paymentId);
42
+ if (!payment) return data;
43
+ requestLegs.push({ paymentId, commandId, amountMinor: payment.amountMinor });
44
+ }
45
+ const at = stamp();
46
+ data.storeSettlement = { kind: 'reverse', state: 'sending', attemptId, at, legs };
47
+ data.updatedAt = at;
48
+ request = { storeOrderId: storeOrderLeft(data)!.orderId, clientOrderId: data.id, attemptId, legs: requestLegs };
49
+ return data;
50
+ });
51
+ if (!request) return { kind: 'not_offered' };
52
+ const sent: SettleReverseRequest = request;
53
+ const { outcome, voided } = await deps.reverse(sent);
54
+ if (deps.openSessionId && await closedAtLanding(deps, 'reverse', orderId, sent.attemptId, outcome, stamp)) return { kind: 'not_offered' };
55
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
56
+ const stored = data.storeSettlement;
57
+ if (stored?.kind !== 'reverse' || stored.attemptId !== sent.attemptId || stored.state !== 'sending') return data;
58
+ const legs = (stored.legs ?? []).map((leg) => voided.includes(leg.paymentId) ? { ...leg, done: true } : leg);
59
+ if (outcome.kind === 'retry' && legs.every((leg, index) => leg.done === stored.legs?.[index]?.done)) return data;
60
+ const at = stamp(), base = { kind: 'reverse' as const, attemptId: sent.attemptId, at, legs };
61
+ data.storeSettlement = outcome.kind === 'retry' ? { ...stored, legs }
62
+ : outcome.kind === 'done' ? { ...base, state: 'done', storeStatus: outcome.status }
63
+ : outcome.kind === 'changed' ? { ...base, state: 'changed', storeStatus: outcome.status, capturedMinor: outcome.capturedMinor }
64
+ : outcome.kind === 'refused' ? { ...base, state: 'refused', code: outcome.code, message: outcome.message } : { ...base, state: 'gone' };
65
+ if (outcome.kind !== 'retry') data.updatedAt = at;
66
+ return data;
67
+ });
68
+ return outcome;
69
+ }
5
70
 
6
71
  export interface CancelOnStoreDeps {
7
72
  orders: RxCollection<PosOrder>;
8
73
  /** The connector's cancel, bound to the open store (`RefusedOrderSettlement.cancel`). */
9
74
  cancel(request: SettleCancelRequest): Promise<SettleOutcome>;
75
+ /** The open register session's id. When given, the store's answer counts only while the session that took every till payment is still open. */
76
+ openSessionId?: () => string | undefined | Promise<string | undefined>;
10
77
  now?: () => Date;
11
78
  }
12
79
 
@@ -22,10 +89,12 @@ export interface CancelOnStoreDeps {
22
89
  export async function cancelOnStore(deps: CancelOnStoreDeps, orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
23
90
  const stamp = () => (deps.now?.() ?? new Date()).toISOString();
24
91
  let request: SettleCancelRequest | undefined;
92
+ const open = deps.openSessionId && await deps.openSessionId();
25
93
  await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
26
94
  // The modifier runs again on a write conflict, so it decides on the stored state each run.
27
95
  request = undefined;
28
96
  if (data._deleted || !canCancelOnStore(data)) return data;
97
+ if (deps.openSessionId && !inOpenSession(data, open)) return markClosed(data, 'cancel', stamp());
29
98
  const stored = data.storeSettlement;
30
99
  const attemptId = stored?.kind === 'cancel' && stored.state === 'sending' ? stored.attemptId : uuidv7();
31
100
  const at = stamp();
@@ -37,6 +106,7 @@ export async function cancelOnStore(deps: CancelOnStoreDeps, orderId: string): P
37
106
  if (!request) return { kind: 'not_offered' };
38
107
  const sent: SettleCancelRequest = request;
39
108
  const outcome = await deps.cancel(sent);
109
+ if (deps.openSessionId && await closedAtLanding(deps, 'cancel', orderId, sent.attemptId, outcome, stamp)) return { kind: 'not_offered' };
40
110
  if (outcome.kind === 'retry') {
41
111
  outboxLogger.info('Cancelling the store order got no definite answer; it stays sending', { orderId, reason: outcome.reason });
42
112
  return outcome;
@@ -1,11 +1,11 @@
1
- import type { OrderCreateEnvelope, OrderUpdateEnvelope, SettleCancelRequest, SettleOutcome, SettlePayRequest, SettlePayResult } from '@tallyui/core';
1
+ import type { OrderCreateEnvelope, OrderUpdateEnvelope, SettleCancelRequest, SettleOutcome, SettlePayRequest, SettlePayResult, SettleReverseRequest, SettleReverseResult } 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
+ import { cancelOnStore as cancelStoreOrder, payRestOnStore as payStoreRest, reverseOnStore } from './store-settlement';
9
9
  import type { CommandTransport, OutboxState } from './types';
10
10
 
11
11
  const idle: OutboxState = { pending: 0, sending: false };
@@ -13,6 +13,8 @@ const noneStuck: readonly string[] = [];
13
13
  export { outboxLogger } from './logger';
14
14
 
15
15
  export interface UseOrderOutboxOptions {
16
+ /** The open register session's id. Without it, `cancelOnStore` and `reverseOnStore` resolve to `not_offered`. */
17
+ openSessionId?: () => string | undefined;
16
18
  /** Which order store to use (medusapos: the backend's base URL); `null` means no store. A change reopens. */
17
19
  storeKey: string | null;
18
20
  /** Opens the order store for `storeKey`; `close()` is called when the key or device id changes, or on unmount. */
@@ -34,6 +36,7 @@ export interface UseOrderOutboxOptions {
34
36
  storeSettlement?(storeKey: string): {
35
37
  cancel?(request: SettleCancelRequest): Promise<SettleOutcome>;
36
38
  pay?(request: SettlePayRequest): Promise<SettlePayResult>;
39
+ reverse?(request: SettleReverseRequest): Promise<SettleReverseResult>;
37
40
  } | undefined;
38
41
  }
39
42
 
@@ -76,6 +79,7 @@ export interface UseOrderOutboxResult {
76
79
  * `storeSettlement` or no `pay`.
77
80
  */
78
81
  payRestOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
82
+ reverseOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
79
83
  /**
80
84
  * The count of `record()` calls not yet settled (resolved or rejected). An app holds sign-out
81
85
  * (closing the store) while this is above 0, because a close that lands under a write stuck in
@@ -156,13 +160,14 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
156
160
  return opened && opened.storeKey === storeKey ? opened.outbox.discard(orderId) : false;
157
161
  },
158
162
  async cancelOnStore(orderId) {
163
+ if (!latest.current.openSessionId) return { kind: 'not_offered' };
159
164
  const opened = current.current;
160
165
  if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
161
166
  const settlement = latest.current.storeSettlement?.(opened.storeKey);
162
167
  const cancel = settlement?.cancel?.bind(settlement);
163
168
  if (!cancel) return { kind: 'not_offered' };
164
169
  try {
165
- return await cancelStoreOrder({ orders: opened.orders, cancel }, orderId);
170
+ return await cancelStoreOrder({ orders: opened.orders, cancel, openSessionId: () => latest.current.openSessionId?.() }, orderId);
166
171
  } finally {
167
172
  // A settled row leaves state.rejected: publish it before resolving.
168
173
  try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
@@ -181,6 +186,19 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
181
186
  try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
182
187
  }
183
188
  },
189
+ async reverseOnStore(orderId) {
190
+ if (!latest.current.openSessionId) return { kind: 'not_offered' };
191
+ const opened = current.current;
192
+ if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
193
+ const settlement = latest.current.storeSettlement?.(opened.storeKey);
194
+ const reverse = settlement?.reverse?.bind(settlement);
195
+ if (!reverse) return { kind: 'not_offered' };
196
+ try {
197
+ return await reverseOnStore({ orders: opened.orders, reverse, openSessionId: () => latest.current.openSessionId?.() }, orderId);
198
+ } finally {
199
+ try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
200
+ }
201
+ },
184
202
  savesInFlight: savesInFlightCount,
185
203
  stuckCommandIds,
186
204
  async record(posOrder) {
@@ -233,23 +233,27 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
233
233
  ...(base === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
234
234
  ...(base === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
235
235
  })),
236
- ...(base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
237
- clientFeeId: fee.id, name: fee.name, amountMinor: wireChargeMinor(order, fee, order.display?.fees), taxStatus: fee.taxStatus,
238
- ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
239
- // #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
240
- taxMinor: order.taxRounding?.granularity === 'woocommerce'
241
- ? woocommerceChargeTaxMinor(fee, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax)
242
- : roundMicrosToMinor(BigInt(fee.taxMicros)),
243
- })) } : {}),
244
- ...(base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
245
- clientShippingId: charge.id, name: charge.name, ...(charge.methodId !== undefined ? { methodId: charge.methodId } : {}),
246
- amountMinor: wireChargeMinor(order, charge, order.display?.shipping), taxStatus: charge.taxStatus,
247
- ...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}),
248
- // #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
249
- taxMinor: order.taxRounding?.granularity === 'woocommerce'
250
- ? woocommerceChargeTaxMinor(charge, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax)
251
- : roundMicrosToMinor(BigInt(charge.taxMicros)),
252
- })) } : {}),
236
+ ...(base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => {
237
+ const sent = fee.entered?.sent === true ? fee.entered : undefined;
238
+ return { clientFeeId: fee.id, name: fee.name, amountMinor: sent?.amountMinor ?? wireChargeMinor(order, fee, order.display?.fees),
239
+ ...(sent ? { amountIncludesTax: sent.amountIncludesTax } : {}), taxStatus: fee.taxStatus,
240
+ ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
241
+ // #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
242
+ taxMinor: order.taxRounding?.granularity === 'woocommerce'
243
+ ? woocommerceChargeTaxMinor(fee, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax)
244
+ : roundMicrosToMinor(BigInt(fee.taxMicros)) };
245
+ }) } : {}),
246
+ ...(base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => {
247
+ const sent = charge.entered?.sent === true ? charge.entered : undefined;
248
+ return { clientShippingId: charge.id, name: charge.name, ...(charge.methodId !== undefined ? { methodId: charge.methodId } : {}),
249
+ amountMinor: sent?.amountMinor ?? wireChargeMinor(order, charge, order.display?.shipping),
250
+ ...(sent ? { amountIncludesTax: sent.amountIncludesTax } : {}), taxStatus: charge.taxStatus,
251
+ ...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}),
252
+ // #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
253
+ taxMinor: order.taxRounding?.granularity === 'woocommerce'
254
+ ? woocommerceChargeTaxMinor(charge, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax)
255
+ : roundMicrosToMinor(BigInt(charge.taxMicros)) };
256
+ }) } : {}),
253
257
  ...(base === 6 && redeemable.length ? { coupons: redeemable.map(({ code, couponId, discountMinor, discountTaxMinor, lines }) => ({
254
258
  code, couponId, discountMinor, discountTaxMinor,
255
259
  ...(version >= 9 ? { lines: lines!.map(({ lineId, discountMinor, discountTaxMinor }) =>
@@ -53,24 +53,28 @@ export const sameCharges = (a: readonly Charge[] = [], b: readonly Charge[] = []
53
53
  /** A line name in a refusal message: 60 UTF-16 units of it plus '…' at most, so a cashier-facing message stays short. */
54
54
  export const MESSAGE_NAME_MAX = 61;
55
55
 
56
- /** A charge as stored and sent: in the order's mode, without the cashier's own mode (vendurepos gap 2.10).
56
+ /** A charge as stored: in the order's mode, with the cashier's differing mode kept separately outside WooCommerce rounding.
57
57
  * A converted generic charge keeps its display row, so the payload equals the display (core fiscal-figures.ts). */
58
- function storedCharge<C extends ChargeLine>(charge: C, pricesIncludeTax: boolean, displayMinor: number | undefined): C {
58
+ function storedCharge<C extends ChargeLine>(charge: C, pricesIncludeTax: boolean, displayMinor: number | undefined,
59
+ keep: { chargeTaxMode?: boolean; granularity?: TaxRounding['granularity'] }): C {
59
60
  if (charge.amountIncludesTax === undefined && charge.percent === undefined) return charge;
60
- const { amountIncludesTax: _mode, percent: _percent, ...rest } = charge;
61
+ const { amountIncludesTax, percent: _percent, ...rest } = charge;
61
62
  const amountMinor = charge.totalMinor === undefined && displayMinor !== undefined ? displayMinor : chargeOrderModeMinor(charge, pricesIncludeTax);
62
- return { ...rest, amountMinor, ...(charge.totalMinor === undefined ? { netMinor: amountMinor } : {}) } as C;
63
+ return { ...rest, amountMinor, ...(charge.totalMinor === undefined ? { netMinor: amountMinor } : {}),
64
+ ...(amountIncludesTax !== undefined && amountIncludesTax !== pricesIncludeTax && keep.granularity !== 'woocommerce'
65
+ ? { entered: { amountMinor: charge.amountMinor, amountIncludesTax, ...(keep.chargeTaxMode === true ? { sent: true } : {}) } } : {}) } as C;
63
66
  }
64
67
 
65
68
  /** The receipt shows the order as it was stored and sent (Front desk, 2026-09-29). */
66
69
  export function withSentForm(order: Order, posOrder: PosOrder): SentOrder {
67
70
  const customer: SentOrder['customer'] = order.customer && { ...order.customer };
71
+ const keep = { granularity: order.taxRounding?.granularity };
68
72
  if (customer && posOrder.customer?.email === undefined) delete customer.email;
69
73
  if (customer && posOrder.customer?.id === undefined) delete customer.id;
70
74
  return { ...order, customer, note: posOrder.note ?? order.note,
71
75
  lineItems: order.lineItems.map((line, i) => ({ ...line, name: posOrder.lines[i].name })),
72
- ...(order.fees ? { fees: order.fees.map((fee, i) => ({ ...storedCharge(fee, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor), name: posOrder.fees![i].name })) } : {}),
73
- ...(order.shipping ? { shipping: order.shipping.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor),
76
+ ...(order.fees ? { fees: order.fees.map((fee, i) => ({ ...storedCharge(fee, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor, keep), name: posOrder.fees![i].name })) } : {}),
77
+ ...(order.shipping ? { shipping: order.shipping.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor, keep),
74
78
  name: posOrder.shipping![i].name })) } : {}),
75
79
  display: posOrder.display ? { ...order.display,
76
80
  ...(order.display.fees ? { fees: order.display.fees.map((row, i) => ({ ...row, name: posOrder.display!.fees![i].name })) } : {}),
@@ -298,8 +302,9 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
298
302
  taxLines: line.taxLines.map((tax) => ({ ...tax })),
299
303
  ...(line.priceTaxModeConverted ? { taxInclusive: line.taxInclusive } : {}),
300
304
  }));
301
- const fees = order.fees?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
302
- const shipping = order.shipping?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
305
+ const keep = { chargeTaxMode: options.capabilities?.chargeTaxMode, granularity: order.taxRounding?.granularity };
306
+ const fees = order.fees?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor, keep), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
307
+ const shipping = order.shipping?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor, keep), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
303
308
  const payments: PosOrderPayment[] = order.payments.map((payment) => ({
304
309
  id: newId(), ...(payment.storePaymentId !== undefined ? { storePaymentId: payment.storePaymentId } : {}),
305
310
  method: payment.method as PosOrderPayment['method'],
@@ -8,7 +8,8 @@ export { addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger } from
8
8
  export { getDeviceId } from './device-id';
9
9
  export { needsAttention, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE } from './needs-attention';
10
10
  export { storeOrderLeft } from './store-order-left';
11
- export { canCancelOnStore, canPayRestOnStore, settledOnStore, unrecordedLegs } from './store-settlement';
11
+ export { settledAwayOnStore, tillPayments } from './till-payments';
12
+ export { canCancelOnStore, canPayRestOnStore, canReverseOnStore, recordedLegs, settledOnStore, TILL_SESSION_CLOSED, unrecordedLegs } from './store-settlement';
12
13
  export { markAttentionHandled } from './attention-handled';
13
14
  export { moneyDivergence, type MoneyDivergence } from './money-divergence';
14
15
  export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './reopen';
@@ -8,12 +8,19 @@ import type { PosOrder } from './types';
8
8
  export const UPDATE_UNSENDABLE = 'update_unsendable';
9
9
  export const UPDATE_UNSENDABLE_MESSAGE = "The store can't accept this change yet. Ask the owner to update the POS plugin, then press Retry.";
10
10
 
11
+ /** ADR-048's T = ⌈(lines + surcharges) / 2⌉, applied once to the whole order: stored lines, fees and shipping rows. */
12
+ function roundingBridgeTolerance(order: PosOrder): number {
13
+ return Math.ceil((order.lines.length + (order.fees?.length ?? 0) + (order.shipping?.length ?? 0)) / 2);
14
+ }
15
+
11
16
  /**
12
17
  * The orders a cashier must look at: rejected, applied with a known warning, taken after their
13
18
  * session closed (`lateSessionId`) or with local warnings (whatever the sync status), or pending with a `commandId` in
14
19
  * `stuckCommandIds` (the outbox's `OutboxState.stuck`: the store keeps failing it), newest first.
15
20
  * A warning code this till version doesn't know is not shown here (`knownWarnings`). Never changes `orders`.
16
21
  * `register_session_unknown` is not shown, because the store counts the order once its session arrives (ADR-078).
22
+ * A `total_mismatch` whose rounding bridge is within ADR-048's tolerance (|`bridgeMinor`| ≤ ⌈(lines + fees + shipping) / 2⌉)
23
+ * is not shown for itself: the row's notice says it.
17
24
  * A refused order is left out once its finalized successor is in `orders`.
18
25
  * Pending updates marked `UPDATE_UNSENDABLE` are shown until a person acts.
19
26
  * An order a cashier marked handled (`markAttentionHandled`) is left out while its `commandId` is the one it was marked
@@ -23,11 +30,16 @@ export const UPDATE_UNSENDABLE_MESSAGE = "The store can't accept this change yet
23
30
  */
24
31
  export function needsAttention(orders: PosOrder[], options: { stuckCommandIds?: readonly string[] } = {}): PosOrder[] {
25
32
  const replaced = replacedOrderIds(orders);
26
- return orders.filter((order) => (order.syncStatus === 'rejected' && !settledOnStore(order))
27
- || (order.syncStatus === 'pending' && order.error?.code === UPDATE_UNSENDABLE)
28
- || (order.localWarnings?.length ?? 0) > 0
29
- || (order.syncStatus === 'applied' && knownWarnings(order.warnings).some((warning) => warning.code !== 'register_session_unknown')) || order.lateSessionId !== undefined
30
- || (order.syncStatus === 'pending' && options.stuckCommandIds?.includes(order.commandId) === true))
33
+ return orders.filter((order) => {
34
+ const tolerance = roundingBridgeTolerance(order);
35
+ return (order.syncStatus === 'rejected' && !settledOnStore(order))
36
+ || (order.syncStatus === 'pending' && order.error?.code === UPDATE_UNSENDABLE)
37
+ || (order.localWarnings?.length ?? 0) > 0
38
+ || (order.syncStatus === 'applied' && knownWarnings(order.warnings).some((warning) => warning.code !== 'register_session_unknown'
39
+ && !(warning.code === 'total_mismatch' && warning.bridgeMinor !== undefined && Math.abs(warning.bridgeMinor) <= tolerance)))
40
+ || order.lateSessionId !== undefined
41
+ || (order.syncStatus === 'pending' && options.stuckCommandIds?.includes(order.commandId) === true);
42
+ })
31
43
  .filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== undefined && order.attentionHandledFor === order.commandId
32
44
  && storeOrderLeft(order) === undefined))
33
45
  .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
@@ -114,12 +114,12 @@ export async function reopenRefusedOrder(orderId: string, deps: {
114
114
  builder.applyOrderDiscount({ type: 'fixed', value: display.orderDiscountMinor, label: 'Discount' });
115
115
  }
116
116
  for (const fee of order.fees ?? []) builder.addFee({
117
- name: fee.name, amountMinor: fee.amountMinor,
117
+ name: fee.name, ...(fee.entered ? { amountMinor: fee.entered.amountMinor, amountIncludesTax: fee.entered.amountIncludesTax } : { amountMinor: fee.amountMinor }),
118
118
  ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
119
119
  ...(fee.taxStatus !== undefined ? { taxStatus: fee.taxStatus } : {}),
120
120
  });
121
121
  for (const shipping of order.shipping ?? []) builder.addShipping({
122
- name: shipping.name, amountMinor: shipping.amountMinor,
122
+ name: shipping.name, ...(shipping.entered ? { amountMinor: shipping.entered.amountMinor, amountIncludesTax: shipping.entered.amountIncludesTax } : { amountMinor: shipping.amountMinor }),
123
123
  ...(shipping.taxClass !== undefined ? { taxClass: shipping.taxClass } : {}),
124
124
  ...(shipping.taxStatus !== undefined ? { taxStatus: shipping.taxStatus } : {}),
125
125
  ...(shipping.methodId !== undefined ? { methodId: shipping.methodId } : {}),
@@ -42,6 +42,8 @@ import type { PosOrder } from './types';
42
42
  * Version 21 adds the order's optional `cashRoundings` (ADR-094); identity migration, one-way like version 20.
43
43
  * Version 22 adds the order's optional `storeSettlement`, the till's settlement of a refused sale's store order (#1101);
44
44
  * identity migration, one-way like version 21.
45
+ * Version 23 adds a fee's and shipping line's optional `entered`, the cashier's own-mode amount for a `chargeTaxMode` store (vendurepos 2.10b); identity migration, one-way like version 22.
46
+ * `entered` is kept whenever the mode differs, and `sent` marks one sent to a `chargeTaxMode` store (#1391).
45
47
  */
46
48
  /** A customer's address on an order (#722, OrderAddress): ten optional strings. */
47
49
  const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
@@ -51,7 +53,7 @@ const orderAddressSchema = { type: 'object', additionalProperties: false, proper
51
53
  } } as const;
52
54
 
53
55
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
54
- version: 22, primaryKey: 'id', type: 'object', additionalProperties: false,
56
+ version: 23, primaryKey: 'id', type: 'object', additionalProperties: false,
55
57
  properties: {
56
58
  id: { type: 'string', maxLength: 36 },
57
59
  saleId: { type: 'string', maxLength: 36 },
@@ -117,6 +119,10 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
117
119
  required: ['id', 'productId', 'name', 'sku', 'quantity', 'unitPriceMinor', 'discountMinor', 'netMinor', 'taxLines'],
118
120
  } },
119
121
  fees: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
122
+ entered: { type: 'object', additionalProperties: false, properties: {
123
+ amountMinor: { type: 'integer', minimum: 0 }, amountIncludesTax: { type: 'boolean' },
124
+ sent: { type: 'boolean', enum: [true] },
125
+ }, required: ['amountMinor', 'amountIncludesTax'] },
120
126
  storeLineId: { type: 'string', minLength: 1, maxLength: 64 },
121
127
  id: { type: 'string', maxLength: 36 }, name: { type: 'string', minLength: 1, maxLength: 255 },
122
128
  amountMinor: { type: 'integer', minimum: 0 }, taxClass: { type: 'string', maxLength: 64 },
@@ -128,6 +134,10 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
128
134
  }, required: ['ratePpm', 'taxMicros'] } },
129
135
  }, required: ['id', 'name', 'amountMinor', 'taxStatus', 'taxLines', 'netMinor', 'taxMicros'] } },
130
136
  shipping: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
137
+ entered: { type: 'object', additionalProperties: false, properties: {
138
+ amountMinor: { type: 'integer', minimum: 0 }, amountIncludesTax: { type: 'boolean' },
139
+ sent: { type: 'boolean', enum: [true] },
140
+ }, required: ['amountMinor', 'amountIncludesTax'] },
131
141
  storeLineId: { type: 'string', minLength: 1, maxLength: 64 },
132
142
  id: { type: 'string', maxLength: 36 }, name: { type: 'string', minLength: 1, maxLength: 255 },
133
143
  methodId: { type: 'string', maxLength: 64 }, amountMinor: { type: 'integer', minimum: 0 }, taxClass: { type: 'string', maxLength: 64 },
@@ -238,5 +248,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
238
248
  // it means no older sale is ever re-rounded (#287).
239
249
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
240
250
  return { schema: posOrderSchema,
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 } };
251
+ 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, 23: identity } };
242
252
  }
@@ -2,6 +2,7 @@ import { storeOrderLeft } from './store-order-left';
2
2
  import type { PosOrder } from './types';
3
3
 
4
4
  type LeftOrder = Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error' | 'payments' | 'storeSettlement'>;
5
+ export const TILL_SESSION_CLOSED = 'till_session_closed';
5
6
 
6
7
  /**
7
8
  * Whether the store order a refused sale left behind is settled on the store (#1101): its settlement is done, or gone
@@ -21,31 +22,54 @@ export function settledOnStore(order: LeftOrder | Pick<PosOrder, 'storeSettlemen
21
22
  * cancel (whose `sending` attempt a repeat finishes), or one the store changed or refused.
22
23
  */
23
24
  export function canCancelOnStore(order: LeftOrder): boolean {
25
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
24
26
  const left = storeOrderLeft(order);
25
27
  if (!left || left.recordedMinor !== 0 || settledOnStore(order)) return false;
26
28
  const settlement = order.storeSettlement;
27
29
  return settlement === undefined || settlement.kind === 'cancel' || settlement.state === 'changed' || settlement.state === 'refused';
28
30
  }
29
31
 
32
+ function recordedCount(order: Pick<PosOrder, 'error'>): number {
33
+ const recorded = order.error?.data?.recorded;
34
+ return Number.isSafeInteger(recorded) && (recorded as number) > 0 ? recorded as number : 0;
35
+ }
36
+
37
+ /** The till's legs the store had recorded at the refusal, in recording order. */
38
+ export function recordedLegs(order: Pick<PosOrder, 'error' | 'payments'>): PosOrder['payments'] {
39
+ return order.payments.slice(0, recordedCount(order));
40
+ }
41
+
30
42
  /** The till's legs the store had not recorded at the refusal (#1101 slice 3): the payments after `data.recorded`, counted
31
43
  * as `storeOrderLeft` counts them. */
32
44
  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);
45
+ return order.payments.slice(recordedCount(order));
46
+ }
47
+
48
+ /** Whether the till can take its recorded legs off the store order and cancel it (#1101 slice 4). */
49
+ export function canReverseOnStore(order: LeftOrder): boolean {
50
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
51
+ const left = storeOrderLeft(order), stored = order.storeSettlement;
52
+ if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
53
+ const legs = recordedLegs(order);
54
+ if (!legs.length || !legs.every((leg) => leg.amountMinor > 0)) return false;
55
+ return !stored || (stored.kind === 'reverse' && ['sending', 'changed', 'refused'].includes(stored.state))
56
+ || (stored.kind === 'pay' && ['changed', 'refused'].includes(stored.state) && !stored.payments?.some((payment) => payment.done));
35
57
  }
36
58
 
37
59
  /**
38
60
  * Whether the till may record its unrecorded legs on the part-paid store order a refused sale left behind (#1101 slice
39
61
  * 3): the store had recorded some of the sale, it is not settled, every leg left has an amount, the settlement is not
40
62
  * `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.
63
+ * pay (whose `sending` attempt a repeat finishes), or one the store changed or refused without a reverse leg taken off.
42
64
  */
43
65
  export function canPayRestOnStore(order: LeftOrder): boolean {
66
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
44
67
  const left = storeOrderLeft(order);
45
68
  if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
46
69
  const legs = unrecordedLegs(order);
47
70
  if (legs.length === 0 || !legs.every((leg) => leg.amountMinor > 0)) return false;
48
71
  const settlement = order.storeSettlement;
49
72
  if (settlement?.state === 'gone') return false;
73
+ if (settlement?.kind === 'reverse' && settlement.legs?.some((leg) => leg.done)) return false;
50
74
  return settlement === undefined || settlement.kind === 'pay' || settlement.state === 'changed' || settlement.state === 'refused';
51
75
  }
@@ -1,4 +1,21 @@
1
+ import type { PosOrderStoreSettlement } from './types';
2
+
1
3
  /** The payments this till took: a locked store payment (storePaymentId set) is the store's earlier money (ADR-090 gate 11). */
2
4
  export function tillPayments<P extends { storePaymentId?: string }>(payments: readonly P[]): P[] {
3
5
  return payments.filter((payment) => payment.storePaymentId === undefined);
4
6
  }
7
+
8
+ export function settledAwayOnStore(order: { storeSettlement?: Pick<PosOrderStoreSettlement, 'kind' | 'state'> }): boolean {
9
+ const settlement = order.storeSettlement;
10
+ return (settlement?.kind === 'cancel' || settlement?.kind === 'reverse') && settlement.state === 'done';
11
+ }
12
+
13
+ /** #1380: follow the plugin's captured-only Z, leaving out cancelled sales and confirmed voids. */
14
+ export function countedTillPayments<P extends { id?: string; storePaymentId?: string }>(order: {
15
+ payments: readonly P[]; storeSettlement?: Pick<PosOrderStoreSettlement, 'kind' | 'state' | 'legs'>;
16
+ }): P[] {
17
+ const settlement = order.storeSettlement;
18
+ if (settledAwayOnStore(order)) return [];
19
+ const payments = tillPayments(order.payments);
20
+ return settlement?.kind === 'reverse' ? payments.filter((payment) => !settlement.legs?.some((leg) => leg.done && leg.paymentId === payment.id)) : payments;
21
+ }
@@ -95,10 +95,14 @@ export interface PosOrder {
95
95
  /** pos_orders v9, ADR-077 d2; present only on a sale with coupons */
96
96
  coupons?: PosOrderCoupon[];
97
97
  fees?: Array<FeeLine & {
98
+ /** vendurepos 2.10b and #1391: the charge as the cashier entered it, kept whenever its mode differs from `pricesIncludeTax` (never under `woocommerce` granularity, #1392). `sent` marks an entry order.create sends as `amountMinor` + `amountIncludesTax`, set only for a store whose connector declared `chargeTaxMode` at finalize. Without `sent`, the charge is sent in the order's mode, as stored. */
99
+ entered?: { amountMinor: number; amountIncludesTax: boolean; sent?: true };
98
100
  /** The store's id of a kept fee or shipping line, in the same id space as lines (ADR-090). */
99
101
  storeLineId?: string;
100
102
  }>;
101
103
  shipping?: Array<ShippingLine & {
104
+ /** vendurepos 2.10b and #1391: the charge as the cashier entered it, kept whenever its mode differs from `pricesIncludeTax` (never under `woocommerce` granularity, #1392). `sent` marks an entry order.create sends as `amountMinor` + `amountIncludesTax`, set only for a store whose connector declared `chargeTaxMode` at finalize. Without `sent`, the charge is sent in the order's mode, as stored. */
105
+ entered?: { amountMinor: number; amountIncludesTax: boolean; sent?: true };
102
106
  /** The store's id of a kept fee or shipping line, in the same id space as lines (ADR-090). */
103
107
  storeLineId?: string;
104
108
  }>;
@@ -173,7 +177,7 @@ export interface PosOrder {
173
177
  * kept while `state` is `sending`, so a repeat after a lost answer is the same attempt. `at` is the instant of the last
174
178
  * write. `storeStatus` is the store's status word (done, changed), `capturedMinor` what the store shows captured
175
179
  * (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).
180
+ * `payments` and `closeId` are for kind `pay`. A `reverse` keeps its store payment and void command ids in `legs`, with `done` on confirmed voids.
177
181
  */
178
182
  export type PosOrderStoreSettlement = {
179
183
  kind: 'cancel' | 'pay' | 'reverse';
@@ -1,7 +1,7 @@
1
1
  import type { Discount, Order, SentOrder } from '../order/types';
2
2
  import { lockedRefundDueMinor } from '../pos-order/refund-due';
3
3
  import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
4
- import { taxedLinesFor } from '../tax/taxed-lines';
4
+ import { storedCharges, taxedLinesFor } from '../tax/taxed-lines';
5
5
  import { carriedRows } from './carried-rows';
6
6
  import type { ReceiptConfig, ReceiptData } from './types';
7
7
  import { RECEIPT_SCHEMA_VERSION } from './types';
@@ -15,7 +15,7 @@ export function receiptRounding(order: Pick<Order, 'cashRoundings'>): Pick<Recei
15
15
  export function buildReceiptData(order: SentOrder, config: ReceiptConfig): ReceiptData {
16
16
  // Drops the shared helper's `netMinor` (the Z report's own use): the receipt's tax summary
17
17
  // never showed it, and an exact-shape test elsewhere in this package pins that.
18
- const taxedLines = taxedLinesFor(order.lineItems, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
18
+ const taxedLines = taxedLinesFor(order.lineItems, storedCharges([...(order.fees ?? []), ...(order.shipping ?? [])]), order.pricesIncludeTax, order.taxRounding);
19
19
  const taxLines = taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding).map(
20
20
  ({ label, code, ratePpm, amountMinor }) => ({ label, code, ratePpm, amountMinor }),
21
21
  );
@@ -3,7 +3,7 @@ import { noteDelivery } from '../pos-order/note-delivery';
3
3
  import { refundDueOf } from '../pos-order/refund-due';
4
4
  import type { PosOrder } from '../pos-order/types';
5
5
  import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
6
- import { recordedTaxByRate, taxedLinesFor } from '../tax/taxed-lines';
6
+ import { recordedTaxByRate, storedCharges, taxedLinesFor } from '../tax/taxed-lines';
7
7
  import { receiptRounding } from './build-receipt-data';
8
8
  import { carriedRows } from './carried-rows';
9
9
  import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
@@ -69,7 +69,7 @@ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCon
69
69
  };
70
70
  });
71
71
  // Use a stored split unless recordedTaxByRate refuses it; otherwise compute it as buildReceiptData does.
72
- const taxedLines = taxedLinesFor(order.lines, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
72
+ const taxedLines = taxedLinesFor(order.lines, storedCharges([...(order.fees ?? []), ...(order.shipping ?? [])]), order.pricesIncludeTax, order.taxRounding);
73
73
  const recorded = recordedTaxByRate(order);
74
74
  const taxLines = recorded ? recorded.map((row) => ({
75
75
  label: config.taxLabels?.[row.ratePpm] ?? row.label ?? `Tax ${row.ratePpm / 10000}%`, code: row.code, ratePpm: row.ratePpm, amountMinor: row.amountMinor,
@@ -10,7 +10,8 @@
10
10
  import { legMethodId } from '@tallyui/core';
11
11
  import { parkedTakenLegs } from '../order/order-drafts';
12
12
  import type { Payment } from '../order/types';
13
- import { tillPayments } from '../pos-order/till-payments';
13
+ import { countedTillPayments } from '../pos-order/till-payments';
14
+ import type { PosOrderStoreSettlement } from '../pos-order/types';
14
15
  import type { PosRefund } from '../refund/pos-refund';
15
16
 
16
17
  export type RefundRow = Pick<PosRefund, 'id' | 'sessionId' | 'status' | 'result'>;
@@ -39,10 +40,10 @@ export type LedgerRow = {
39
40
  * A locked store payment (storePaymentId set) is the store's earlier money, not this till's, and is left out (ADR-090 gate 11).
40
41
  * A payment stamped with the session that took it counts there, else in its order's (S3).
41
42
  */
42
- export function paymentLedgerRows<P extends { method: string; amountMinor: number; storePaymentId?: string; sessionId?: string }>(
43
- orders: readonly { sessionId?: string; payments: readonly P[] }[],
43
+ export function paymentLedgerRows<P extends { id?: string; method: string; amountMinor: number; storePaymentId?: string; sessionId?: string }>(
44
+ orders: readonly { sessionId?: string; payments: readonly P[]; storeSettlement?: TillOrder['storeSettlement'] }[],
44
45
  ): LedgerRow[] {
45
- return orders.flatMap((order) => tillPayments(order.payments).map((payment) => ({
46
+ return orders.flatMap((order) => countedTillPayments(order).map((payment) => ({
46
47
  session_id: payment.sessionId ?? order.sessionId, kind: payment.method === 'cash' ? 'cash' : 'other', method_id: payment.method,
47
48
  status: 'captured', amountMinor: payment.amountMinor,
48
49
  })));
@@ -174,11 +175,11 @@ export function deriveDrawerTerms(input: Parameters<typeof deriveExpected>[0]):
174
175
  };
175
176
  }
176
177
 
177
- type TillLeg = { method: string; methodId?: string; amountMinor: number; storePaymentId?: string; sessionId?: string };
178
- type TillOrder = { sessionId?: string; payments: readonly TillLeg[] };
178
+ type TillLeg = { id?: string; method: string; methodId?: string; amountMinor: number; storePaymentId?: string; sessionId?: string };
179
+ type TillOrder = { sessionId?: string; payments: readonly TillLeg[]; storeSettlement?: Pick<PosOrderStoreSettlement, 'kind' | 'state' | 'legs'> };
179
180
 
180
181
  /**
181
- * Takings per payment method for one session, for the closure sheet: this till's captured payments (`tillPayments`) in
182
+ * Takings per payment method for one session, for the closure sheet: this till's captured payments (`countedTillPayments`) in
182
183
  * `sessionId`: a payment's own session, else its order's (S3), keyed by `legMethodId`'s kind plus id (`external:stripe`), with the number of
183
184
  * payments behind each. Local only, never synced: register rows and payloads keep `method_id: payment.method` (#256, ADR-070
184
185
  * decision 1). A leg with no methodId keys exactly as deriveDrawerTerms does (`cash` or its method); the figures sum to
@@ -192,7 +193,7 @@ export function takingsByMethod(
192
193
  ): Record<string, DrawerTerm> {
193
194
  const takings: Record<string, DrawerTerm> = Object.create(null);
194
195
  for (const order of [...orders, { payments: extra }] as readonly TillOrder[]) {
195
- for (const payment of tillPayments(order.payments)) {
196
+ for (const payment of countedTillPayments(order)) {
196
197
  if ((payment.sessionId ?? order.sessionId) !== sessionId) continue;
197
198
  const term = (takings[legMethodId(payment)] ??= { amountMinor: 0, count: 0 });
198
199
  term.amountMinor += payment.amountMinor;