@tallyui/pos 5.0.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.
@@ -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'],
@@ -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,9 @@ 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 { settledAwayOnStore, tillPayments } from './till-payments';
12
+ export { canCancelOnStore, canPayRestOnStore, canReverseOnStore, recordedLegs, settledOnStore, TILL_SESSION_CLOSED, unrecordedLegs } from './store-settlement';
10
13
  export { markAttentionHandled } from './attention-handled';
11
14
  export { moneyDivergence, type MoneyDivergence } from './money-divergence';
12
15
  export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './reopen';
@@ -1,29 +1,46 @@
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. */
6
8
  export const UPDATE_UNSENDABLE = 'update_unsendable';
7
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.";
8
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
+
9
16
  /**
10
17
  * The orders a cashier must look at: rejected, applied with a known warning, taken after their
11
18
  * session closed (`lateSessionId`) or with local warnings (whatever the sync status), or pending with a `commandId` in
12
19
  * `stuckCommandIds` (the outbox's `OutboxState.stuck`: the store keeps failing it), newest first.
13
20
  * A warning code this till version doesn't know is not shown here (`knownWarnings`). Never changes `orders`.
14
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.
15
24
  * A refused order is left out once its finalized successor is in `orders`.
16
25
  * Pending updates marked `UPDATE_UNSENDABLE` are shown until a person acts.
17
26
  * 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).
27
+ * for; a requeue mints a new `commandId`, so a fresh refusal shows again (ADR-092 6f). The mark does not hide a refused
28
+ * sale whose order the store created (`storeOrderLeft`, #1101). A refused sale whose store order is settled on the store
29
+ * (`settledOnStore`: cancelled or gone, #1101) is not shown for its refusal; any other reason above still shows it.
19
30
  */
20
31
  export function needsAttention(orders: PosOrder[], options: { stuckCommandIds?: readonly string[] } = {}): PosOrder[] {
21
32
  const replaced = replacedOrderIds(orders);
22
- return orders.filter((order) => order.syncStatus === 'rejected'
23
- || (order.syncStatus === 'pending' && order.error?.code === UPDATE_UNSENDABLE)
24
- || (order.localWarnings?.length ?? 0) > 0
25
- || (order.syncStatus === 'applied' && knownWarnings(order.warnings).some((warning) => warning.code !== 'register_session_unknown')) || order.lateSessionId !== undefined
26
- || (order.syncStatus === 'pending' && options.stuckCommandIds?.includes(order.commandId) === true))
27
- .filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== undefined && order.attentionHandledFor === order.commandId))
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
+ })
43
+ .filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== undefined && order.attentionHandledFor === order.commandId
44
+ && storeOrderLeft(order) === undefined))
28
45
  .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
29
46
  }
@@ -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 } : {}),
@@ -40,6 +40,10 @@ 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.
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).
43
47
  */
44
48
  /** A customer's address on an order (#722, OrderAddress): ten optional strings. */
45
49
  const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
@@ -49,7 +53,7 @@ const orderAddressSchema = { type: 'object', additionalProperties: false, proper
49
53
  } } as const;
50
54
 
51
55
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
52
- version: 21, primaryKey: 'id', type: 'object', additionalProperties: false,
56
+ version: 23, primaryKey: 'id', type: 'object', additionalProperties: false,
53
57
  properties: {
54
58
  id: { type: 'string', maxLength: 36 },
55
59
  saleId: { type: 'string', maxLength: 36 },
@@ -60,6 +64,19 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
60
64
  updatedAt: { type: 'string' },
61
65
  reopenedAt: { type: 'string', maxLength: 40 },
62
66
  attentionHandledFor: { type: 'string', maxLength: 36 },
67
+ storeSettlement: { type: 'object', additionalProperties: false, properties: {
68
+ kind: { type: 'string', enum: ['cancel', 'pay', 'reverse'] },
69
+ state: { type: 'string', enum: ['sending', 'done', 'changed', 'refused', 'gone'] },
70
+ attemptId: { type: 'string', maxLength: 36 }, at: { type: 'string', maxLength: 40 },
71
+ storeStatus: { type: 'string' }, capturedMinor: { type: 'integer' }, code: { type: 'string' }, message: { type: 'string' },
72
+ payments: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
73
+ id: { type: 'string', maxLength: 36 }, method: { type: 'string' }, amountMinor: { type: 'integer' },
74
+ tenderedMinor: { type: 'integer' }, done: { type: 'boolean' } }, required: ['id', 'method', 'amountMinor'] } },
75
+ closeId: { type: 'string', maxLength: 36 },
76
+ legs: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
77
+ paymentId: { type: 'string', maxLength: 36 }, commandId: { type: 'string', maxLength: 36 }, done: { type: 'boolean' } },
78
+ required: ['paymentId', 'commandId'] } },
79
+ }, required: ['kind', 'state', 'attemptId', 'at'] },
63
80
  currency: { type: 'string' },
64
81
  pricesIncludeTax: { type: 'boolean' },
65
82
  subtotalMinor: { type: 'integer' }, discountMinor: { type: 'integer' },
@@ -102,6 +119,10 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
102
119
  required: ['id', 'productId', 'name', 'sku', 'quantity', 'unitPriceMinor', 'discountMinor', 'netMinor', 'taxLines'],
103
120
  } },
104
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'] },
105
126
  storeLineId: { type: 'string', minLength: 1, maxLength: 64 },
106
127
  id: { type: 'string', maxLength: 36 }, name: { type: 'string', minLength: 1, maxLength: 255 },
107
128
  amountMinor: { type: 'integer', minimum: 0 }, taxClass: { type: 'string', maxLength: 64 },
@@ -113,6 +134,10 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
113
134
  }, required: ['ratePpm', 'taxMicros'] } },
114
135
  }, required: ['id', 'name', 'amountMinor', 'taxStatus', 'taxLines', 'netMinor', 'taxMicros'] } },
115
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'] },
116
141
  storeLineId: { type: 'string', minLength: 1, maxLength: 64 },
117
142
  id: { type: 'string', maxLength: 36 }, name: { type: 'string', minLength: 1, maxLength: 255 },
118
143
  methodId: { type: 'string', maxLength: 64 }, amountMinor: { type: 'integer', minimum: 0 }, taxClass: { type: 'string', maxLength: 64 },
@@ -223,5 +248,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
223
248
  // it means no older sale is ever re-rounded (#287).
224
249
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
225
250
  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 } };
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 } };
227
252
  }
@@ -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,75 @@
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
+ export const TILL_SESSION_CLOSED = 'till_session_closed';
6
+
7
+ /**
8
+ * Whether the store order a refused sale left behind is settled on the store (#1101): its settlement is done, or gone
9
+ * while the store had recorded nothing on it (desk ruling: a gone order with money recorded still needs a manager).
10
+ */
11
+ export function settledOnStore(order: LeftOrder | Pick<PosOrder, 'storeSettlement'>): boolean {
12
+ const state = order.storeSettlement?.state;
13
+ if (state === 'done') return true;
14
+ if (state !== 'gone') return false;
15
+ const left = 'syncStatus' in order ? storeOrderLeft(order) : undefined;
16
+ return !left || left.recordedMinor === 0;
17
+ }
18
+
19
+ /**
20
+ * Whether the till may cancel the store order a refused sale left behind (#1101): there is one (`storeOrderLeft`), the
21
+ * store had recorded nothing paid on it, it is not settled (`settledOnStore`), and there is no settlement yet, or a
22
+ * cancel (whose `sending` attempt a repeat finishes), or one the store changed or refused.
23
+ */
24
+ export function canCancelOnStore(order: LeftOrder): boolean {
25
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
26
+ const left = storeOrderLeft(order);
27
+ if (!left || left.recordedMinor !== 0 || settledOnStore(order)) return false;
28
+ const settlement = order.storeSettlement;
29
+ return settlement === undefined || settlement.kind === 'cancel' || settlement.state === 'changed' || settlement.state === 'refused';
30
+ }
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
+
42
+ /** The till's legs the store had not recorded at the refusal (#1101 slice 3): the payments after `data.recorded`, counted
43
+ * as `storeOrderLeft` counts them. */
44
+ export function unrecordedLegs(order: Pick<PosOrder, 'error' | 'payments'>): PosOrder['payments'] {
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));
57
+ }
58
+
59
+ /**
60
+ * Whether the till may record its unrecorded legs on the part-paid store order a refused sale left behind (#1101 slice
61
+ * 3): the store had recorded some of the sale, it is not settled, every leg left has an amount, the settlement is not
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
63
+ * pay (whose `sending` attempt a repeat finishes), or one the store changed or refused without a reverse leg taken off.
64
+ */
65
+ export function canPayRestOnStore(order: LeftOrder): boolean {
66
+ if (order.storeSettlement?.code === TILL_SESSION_CLOSED) return false;
67
+ const left = storeOrderLeft(order);
68
+ if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
69
+ const legs = unrecordedLegs(order);
70
+ if (legs.length === 0 || !legs.every((leg) => leg.amountMinor > 0)) return false;
71
+ const settlement = order.storeSettlement;
72
+ if (settlement?.state === 'gone') return false;
73
+ if (settlement?.kind === 'reverse' && settlement.legs?.some((leg) => leg.done)) return false;
74
+ return settlement === undefined || settlement.kind === 'pay' || settlement.state === 'changed' || settlement.state === 'refused';
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
  }>;
@@ -164,4 +168,26 @@ export interface PosOrder {
164
168
  reopenedAt?: string;
165
169
  /** The commandId whose refusal the cashier marked handled (tally-woo 03, ADR-092 6f); the logic comes in a later PR. */
166
170
  attentionHandledFor?: string;
171
+ /** How the till settled the order the store created before it refused this sale (#1101); see `PosOrderStoreSettlement`. */
172
+ storeSettlement?: PosOrderStoreSettlement;
167
173
  }
174
+
175
+ /**
176
+ * The till's settlement of a refused sale's store order (#1101, `storeOrderLeft`). `attemptId` names the attempt and is
177
+ * kept while `state` is `sending`, so a repeat after a lost answer is the same attempt. `at` is the instant of the last
178
+ * write. `storeStatus` is the store's status word (done, changed), `capturedMinor` what the store shows captured
179
+ * (changed), `code` and `message` the store's refusal (refused), for the sync log, never shown to the cashier.
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.
181
+ */
182
+ export type PosOrderStoreSettlement = {
183
+ kind: 'cancel' | 'pay' | 'reverse';
184
+ state: 'sending' | 'done' | 'changed' | 'refused' | 'gone';
185
+ attemptId: string;
186
+ at: string;
187
+ storeStatus?: string;
188
+ capturedMinor?: number;
189
+ code?: string; message?: string;
190
+ payments?: { id: string; method: string; amountMinor: number; tenderedMinor?: number; done?: boolean }[];
191
+ closeId?: string;
192
+ legs?: { paymentId: string; commandId: string; done?: boolean }[];
193
+ };
@@ -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;
@@ -12,10 +12,10 @@
12
12
  */
13
13
  import type { RxCollection } from 'rxdb';
14
14
  import { DEFAULT_TAX_ROUNDING, taxLinesByRate } from '../tax/exact';
15
- import { taxedLinesFor } from '../tax/taxed-lines';
15
+ import { storedCharges, taxedLinesFor } from '../tax/taxed-lines';
16
16
  import type { PosOrder } from '../pos-order/types';
17
17
  import { replacedOrderIds } from '../pos-order/reopened';
18
- import { tillPayments } from '../pos-order/till-payments';
18
+ import { countedTillPayments, settledAwayOnStore, tillPayments } from '../pos-order/till-payments';
19
19
  import type { PosRefund } from '../refund/pos-refund';
20
20
  import { readFresh } from '../rxdb';
21
21
  import { parkedCashRoundings, parkedTakenLegs } from '../order/order-drafts';
@@ -573,12 +573,13 @@ export async function writeClosure({
573
573
  const taxRateKey = (code: string | undefined, ratePpm: number) => `${ratePpm}:${(code ?? '').replace(/[%.[\]\\]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`;
574
574
  const taxRates = new Map<string, { ratePpm: number; code?: string; net_minor: number; tax_minor: number }>();
575
575
  const roundings = new Set<string>();
576
- for (const order of bound) {
576
+ const transactions = bound.filter((order) => !settledAwayOnStore(order));
577
+ for (const order of transactions) {
577
578
  // Grouped by the rule applied: a `custom` sale used the default figures, so it joins the default's group.
578
579
  const recorded = order.taxRounding ?? DEFAULT_TAX_ROUNDING;
579
580
  const rounding = recorded.granularity === 'custom' ? DEFAULT_TAX_ROUNDING : recorded;
580
581
  roundings.add(rounding.granularity === 'woocommerce' ? `woocommerce ${rounding.roundAtSubtotal}` : `${rounding.granularity} ${rounding.mode}`);
581
- const taxedLines = taxedLinesFor(order.lines, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
582
+ const taxedLines = taxedLinesFor(order.lines, storedCharges([...(order.fees ?? []), ...(order.shipping ?? [])]), order.pricesIncludeTax, order.taxRounding);
582
583
  for (const { ratePpm, code, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding)) {
583
584
  const existing = taxRates.get(taxRateKey(code, ratePpm));
584
585
  taxRates.set(taxRateKey(code, ratePpm), {
@@ -592,7 +593,7 @@ export async function writeClosure({
592
593
  // ADR-094: a bound order's rounding counts as its leg's money does (S3): a till leg, in the session that took it.
593
594
  // A parked or live sale's entries count by the same rule, against that sale's own taken legs (#1281).
594
595
  const cashRoundingMinor = sum(bound.flatMap((order) => {
595
- const legs = new Map(tillPayments(order.payments).map((payment) => [payment.id, payment]));
596
+ const legs = new Map(countedTillPayments(order).map((payment) => [payment.id, payment]));
596
597
  return (order.cashRoundings ?? []).filter((entry) => {
597
598
  const leg = legs.get(entry.paymentId);
598
599
  return leg !== undefined && (leg.sessionId ?? order.sessionId) === session.id;
@@ -654,7 +655,7 @@ export async function writeClosure({
654
655
  movements: entries.map(({ id, type, amountMinor, reason, voids, voided_by, created_at_gmt, created_by }) => ({
655
656
  id, type, amountMinor, reason, voids: voids ?? null, created_at_gmt, created_by: created_by ?? null, voided_by: voided_by ?? null,
656
657
  })),
657
- transaction_count: bound.length,
658
+ transaction_count: transactions.length,
658
659
  refund_count: countedRefunds.length,
659
660
  ...(refunds !== undefined ? {
660
661
  refund_ids: countedRefunds.map((refund) => refund.id),
@@ -3,7 +3,7 @@ import { tillPayments } from '../pos-order/till-payments';
3
3
  import type { PosOrder } from '../pos-order/types';
4
4
  import type { PosRefund } from '../refund/pos-refund';
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 type { LineJoin, ReportLine, ReportOrder, ReportRefund } from './types';
8
8
 
9
9
  function joinedLine(line: { productId?: string; variantId?: string; quantity: number }, join?: LineJoin): Pick<ReportLine, 'costMinor' | 'category'> {
@@ -19,7 +19,7 @@ function joinedLine(line: { productId?: string; variantId?: string; quantity: nu
19
19
  }
20
20
 
21
21
  export function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin, methodTitle?: (methodId: string) => string | undefined): ReportOrder {
22
- const taxedLines = taxedLinesFor(order.lines, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
22
+ const taxedLines = taxedLinesFor(order.lines, storedCharges([...(order.fees ?? []), ...(order.shipping ?? [])]), order.pricesIncludeTax, order.taxRounding);
23
23
  const taxes = recordedTaxByRate(order) ?? taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding);
24
24
  const till = tillPayments(order.payments);
25
25
  const amountOf = (payments: readonly { amountMinor: number }[]) => payments.reduce((total, payment) => total + payment.amountMinor, 0);
@@ -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;
@@ -1,5 +1,13 @@
1
1
  import type { TaxRounding } from '@tallyui/core';
2
2
 
3
+ /** Undoes `finalize.ts`'s `storedCharge` for taxation: restores the entered mode and, for a generic charge, the entered net. */
4
+ export function storedCharges<C extends { entered?: { amountMinor: number; amountIncludesTax: boolean }; totalMinor?: number; netMinor?: number }>(
5
+ charges: readonly C[],
6
+ ): Array<C & { amountIncludesTax?: boolean }> {
7
+ return charges.map((charge) => charge.entered === undefined ? charge : { ...charge, amountIncludesTax: charge.entered.amountIncludesTax,
8
+ ...(charge.totalMinor === undefined ? { netMinor: charge.entered.amountMinor } : {}) });
9
+ }
10
+
3
11
  /** The lines and charges `taxLinesByRate` splits, each in the tax mode its tax was rounded in (ADR-065: the
4
12
  * receipt's figures, which every per-rate split must equal). Under `woocommerce` rounding a line with `netMicros`
5
13
  * is in the store's mode, since WooCommerce rounds every line that way. Otherwise a line keeps its own mode, and