@tallyui/pos 4.2.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.d.ts +620 -166
  2. package/dist/index.js +1970 -1091
  3. package/package.json +7 -6
  4. package/src/index.ts +15 -12
  5. package/src/order/index.ts +1 -0
  6. package/src/order/order-builder.ts +64 -22
  7. package/src/order/order-drafts.ts +77 -25
  8. package/src/order/types.ts +9 -2
  9. package/src/order/woocommerce-tax.ts +9 -12
  10. package/src/outbox/http-transport.ts +16 -1
  11. package/src/outbox/index.ts +3 -1
  12. package/src/outbox/needs-admin-reason.ts +10 -0
  13. package/src/outbox/order-outbox.ts +27 -11
  14. package/src/outbox/register-outbox.ts +4 -3
  15. package/src/outbox/store-settlement.ts +136 -0
  16. package/src/outbox/types.ts +3 -1
  17. package/src/outbox/use-order-outbox.ts +54 -4
  18. package/src/pos-order/attention-handled.ts +2 -0
  19. package/src/pos-order/command.ts +31 -9
  20. package/src/pos-order/finalize.ts +9 -0
  21. package/src/pos-order/index.ts +3 -1
  22. package/src/pos-order/needs-attention.ts +8 -3
  23. package/src/pos-order/reopen.ts +9 -2
  24. package/src/pos-order/schema.ts +20 -2
  25. package/src/pos-order/store-order-left.ts +21 -0
  26. package/src/pos-order/store-settlement.ts +51 -0
  27. package/src/pos-order/types.ts +27 -1
  28. package/src/receipt/build-receipt-data.ts +8 -1
  29. package/src/receipt/reprint.ts +2 -0
  30. package/src/receipt/types.ts +2 -0
  31. package/src/receipt-template/template-data.ts +1 -1
  32. package/src/receipt-template/wcpos/from-orders.ts +5 -1
  33. package/src/refund/index.ts +1 -0
  34. package/src/refund/needs-admin-line.ts +6 -0
  35. package/src/refund/refundable-lines.ts +2 -91
  36. package/src/refund/send-order-refund.ts +6 -1
  37. package/src/refund/submit-order-refund.ts +33 -1
  38. package/src/register/closing.ts +15 -0
  39. package/src/register/closure-document.ts +13 -5
  40. package/src/register/closure-figures.ts +83 -0
  41. package/src/register/document-labels.ts +5 -3
  42. package/src/register/expected.ts +30 -9
  43. package/src/register/index.ts +3 -1
  44. package/src/register/register-adoption.ts +42 -4
  45. package/src/register/register-document.ts +17 -0
  46. package/src/register/session-store.ts +48 -12
  47. package/src/register/use-register-session.ts +53 -20
  48. package/src/reports/adapters.ts +5 -1
  49. package/src/reports/index.ts +1 -1
  50. package/src/reports/sales-figures.ts +33 -6
  51. package/src/reports/types.ts +3 -1
  52. package/src/sale/index.ts +1 -1
  53. package/src/sale/use-sale.ts +320 -134
  54. package/src/store-orders/index.ts +3 -0
  55. package/src/store-orders/sales-range-query.ts +18 -0
  56. package/src/store-orders/use-store-refunds-in-range.ts +179 -0
  57. package/src/tax/exact.ts +2 -10
  58. package/src/tender/cash-rounding.ts +57 -6
  59. package/src/tender/index.ts +1 -1
  60. package/src/tender/payment-legs.ts +5 -0
  61. package/src/tender/tender-figures.ts +3 -1
  62. package/src/outbox/types.test-d.ts +0 -27
  63. package/src/print/escpos/sinks.test-d.ts +0 -77
@@ -1,2 +1,5 @@
1
+ export { salesRangeQuery } from './sales-range-query';
1
2
  export { useStoreOrdersInRange } from './use-store-orders-in-range';
2
3
  export type { OrderDownloadProgress, StoreOrdersInRange, StoreOrdersRangeQuery } from './use-store-orders-in-range';
4
+ export { useStoreRefundsInRange } from './use-store-refunds-in-range';
5
+ export type { OtherCurrencyRefunds, StoreRefundsInRange, StoreRefundsRangeQuery } from './use-store-refunds-in-range';
@@ -0,0 +1,18 @@
1
+ import type { OrderFilterField } from '@tallyui/core';
2
+ import type { StoreOrdersRangeQuery } from './use-store-orders-in-range';
3
+
4
+ /**
5
+ * The read for a sales report over `[after, before)`: UTC instants with a `Z`, such as `orderFiltersQuery` gives for
6
+ * store days. When the connector lists `modifiedAfter`, the read is widened to orders changed at or after `after` and
7
+ * created before `before`, so an order created earlier and paid in the range is fetched. `reportOrderFromStoreOrder`
8
+ * then places each order on its paid day, and the report's own range test drops one paid outside the range.
9
+ * Otherwise the read is by creation date.
10
+ */
11
+ export function salesRangeQuery(
12
+ range: { after: string; before: string },
13
+ orderFilters: readonly OrderFilterField[] | undefined,
14
+ ): StoreOrdersRangeQuery {
15
+ return orderFilters?.includes('modifiedAfter')
16
+ ? { modifiedAfter: range.after, dateRange: { before: range.before } }
17
+ : { dateRange: { after: range.after, before: range.before } };
18
+ }
@@ -0,0 +1,179 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { StoreRefundsUnsupportedError } from '@tallyui/core';
3
+ import type { ListRefundsQuery, StoreOrder, StoreRefund, StoreRefundOrphan, StoreRefundPage, SyncContext, TallyConnector } from '@tallyui/core';
4
+ import type { DayRange, ReportRefund } from '../reports/types';
5
+ import { orderFiltersQuery } from '../sale/order-filters-query';
6
+ import type { OrderDownloadProgress } from './use-store-orders-in-range';
7
+
8
+ export interface StoreRefundsRangeQuery {
9
+ /** The report's store days, inclusive. */
10
+ range: DayRange;
11
+ /** IANA zone of the store, or 'device' (as SalesFiguresInput.timezone). */
12
+ timezone: string;
13
+ /** The report's currency (StoreOrder.currency). A refund in any other currency is never counted. */
14
+ currency: string;
15
+ /** Set fields restrict the report; a refund counts only when its order carries the same value for every set field. */
16
+ scope?: { storeId?: string; cashierId?: string; registerId?: string };
17
+ }
18
+ export interface OtherCurrencyRefunds { currency: string; count: number; amountMinor: number }
19
+ export interface StoreRefundsInRange {
20
+ /** The counted refunds as report rows. undefined when the store has no dated refunds: the report then uses its orders' embedded refunds. */
21
+ refunds: ReportRefund[] | undefined;
22
+ orphans: StoreRefundOrphan[];
23
+ unreadable: number;
24
+ unscoped: StoreRefund[];
25
+ otherCurrency: OtherCurrencyRefunds[];
26
+ progress: OrderDownloadProgress | null;
27
+ error: unknown | null;
28
+ complete: boolean;
29
+ }
30
+
31
+ /** The most `ListRefundsQuery.perPage` allows. */
32
+ const PER_PAGE = 100;
33
+ /** The error a read ends with when a page says `hasMore: true` but adds no new refund or orphan id. */
34
+ const STALLED = 'listRefunds answered hasMore: true with a page that added no new refund';
35
+ const SCOPE_FIELDS = ['storeId', 'cashierId', 'registerId'] as const;
36
+
37
+ type Sorted = Pick<StoreRefundsInRange, 'orphans' | 'unscoped' | 'otherCurrency' | 'unreadable'> & { refunds: ReportRefund[] };
38
+ type Read = Sorted & {
39
+ connector: TallyConnector;
40
+ context: SyncContext;
41
+ key: string;
42
+ /** Distinct refund and orphan ids seen. */
43
+ seen: number;
44
+ total: number | null;
45
+ } & ({ status: 'reading' | 'complete' | 'unsupported' } | { status: 'error'; error: unknown });
46
+
47
+ const EMPTY = { orphans: [], unscoped: [], otherCurrency: [], unreadable: 0 };
48
+ const IDLE: StoreRefundsInRange = { ...EMPTY, refunds: undefined, progress: null, error: null, complete: false };
49
+ const NO_DATED: StoreRefundsInRange = { ...IDLE, complete: true };
50
+ const STARTING: StoreRefundsInRange = { ...EMPTY, refunds: [], progress: { downloaded: 0, total: null }, error: null, complete: false };
51
+
52
+ /** Calls `listRefunds` page after page, one at a time, until a page has `hasMore: false` or `live()` turns false. */
53
+ async function readPages(
54
+ connector: TallyConnector,
55
+ context: SyncContext,
56
+ dateRange: ListRefundsQuery['dateRange'],
57
+ live: () => boolean,
58
+ onPage: (page: StoreRefundPage, first: boolean) => Promise<void>,
59
+ ): Promise<void> {
60
+ for (let page = 1; ; page++) {
61
+ // Yield first so a read abandoned before its call (StrictMode's double effect) calls nothing.
62
+ await Promise.resolve();
63
+ if (!live()) return;
64
+ const result = await connector.listRefunds!(context, { page, perPage: PER_PAGE, dateRange });
65
+ if (!live()) return;
66
+ await onPage(result, page === 1);
67
+ if (!live() || !result.hasMore) return;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Every refund a store made in the report's store days, read online page by page from `listRefunds` (ADR-081
73
+ * decision 7), as `useStoreOrdersInRange` reads orders (decision 6). Nothing is stored or cached.
74
+ *
75
+ * - Idle (`refunds: undefined`, `complete: false`, nothing called) without `connector`, `context` or `query`.
76
+ * - No `connector.listRefunds`, or a page rejecting with `StoreRefundsUnsupportedError`: `refunds: undefined`,
77
+ * `complete: true`, so `salesFigures` uses the orders' embedded refunds.
78
+ * - The read's `dateRange` is the store days' UTC bounds (`orderFiltersQuery`). While reading, `progress` is
79
+ * `{ downloaded, total }`: distinct refund and orphan ids plus `unreadable`, and page 1's `total` or `null`.
80
+ * - One id set covers refunds and orphans; the first copy stays. `unreadable` sums page 1's and each later page's
81
+ * that adds a new id. A `hasMore: true` page that adds no new id stops the read with an `Error`.
82
+ * - Each fresh refund is sorted into exactly one place, so none is in two of `refunds`, `unscoped`, `otherCurrency`
83
+ * and `orphans`. With a set `scope` field, each page's not-yet-asked orders are fetched with one `getOrders` call:
84
+ * an order not returned (or no `getOrders`) makes the refund `unscoped`; an order with a different value in any set
85
+ * field puts it outside the report, in no list; else an order missing a set field makes it `unscoped`. Then a
86
+ * refund in `query.currency` is counted in `refunds`, in the store's order; any other goes to `otherCurrency`, one
87
+ * row per currency, sorted by code. `orphans` are kept as they come. Only `refunds` is ever summed.
88
+ * - A page with `hasMore: false`, its orders resolved, finishes: `complete: true`, `progress: null`. Any other
89
+ * rejection, from `listRefunds` or `getOrders`, stops the read: `error` is it, `progress` is `null`, what was
90
+ * counted stays.
91
+ * - Pass `refunds` to `salesFigures` only once `complete` is `true`. While `progress` is set the list is partial.
92
+ * After an `error` it is partial and `complete` stays `false`: the report shows the error and gives no refund
93
+ * figure. It does not fall back to the embedded basis, so it never passes `undefined` for a failed read. With a
94
+ * report `compare` period, `query.range` spans both periods. `unscoped`, `otherCurrency`, `orphans` and
95
+ * `unreadable` then count the whole read, not each period.
96
+ * - A `query` that differs by value, or a new `connector` or `context`, abandons the read and starts again from
97
+ * page 1, showing none of the old rows; an equal new object changes nothing. Unmounting abandons the read.
98
+ *
99
+ * Offset paging over a live store can repeat a row, which is dropped, or push a row past a page boundary mid-read,
100
+ * which is then missed until the next read.
101
+ */
102
+ export function useStoreRefundsInRange(
103
+ connector: TallyConnector | null,
104
+ context: SyncContext | null,
105
+ query: StoreRefundsRangeQuery | null,
106
+ ): StoreRefundsInRange {
107
+ const key = query ? JSON.stringify(query) : null;
108
+ const [read, setRead] = useState<Read | null>(null);
109
+
110
+ useEffect(() => {
111
+ if (!connector?.listRefunds || !context || key === null) return;
112
+ const q = JSON.parse(key) as StoreRefundsRangeQuery;
113
+ const scope = SCOPE_FIELDS.filter((field) => q.scope?.[field] !== undefined);
114
+ let live = true;
115
+ const seen = new Set<string>();
116
+ const asked = new Set<string>();
117
+ const orders = new Map<string, StoreOrder>();
118
+ let current: Read = { connector, context, key, ...EMPTY, refunds: [], seen: 0, total: null, status: 'reading' };
119
+ const take = (row: { id: string }) => !seen.has(row.id) && seen.add(row.id).has(row.id);
120
+ const dateRange = orderFiltersQuery({ dateRange: q.range }, q.timezone).dateRange;
121
+ readPages(connector, context, dateRange, () => live, async (page, first) => {
122
+ const fresh = page.refunds.filter(take);
123
+ const orphans = page.orphans.filter(take);
124
+ if (page.hasMore && fresh.length + orphans.length === 0) throw new Error(STALLED);
125
+ if (scope.length && connector.getOrders) {
126
+ const ids = [...new Set(fresh.map((refund) => refund.orderId))].filter((id) => !asked.has(id));
127
+ ids.forEach((id) => asked.add(id));
128
+ if (ids.length) for (const order of await connector.getOrders(context, ids)) orders.set(order.id, order);
129
+ if (!live) return;
130
+ }
131
+ const refunds = [...current.refunds];
132
+ const unscoped = [...current.unscoped];
133
+ const other = new Map(current.otherCurrency.map((row) => [row.currency, row]));
134
+ for (const refund of fresh) {
135
+ const order = orders.get(refund.orderId);
136
+ if (scope.length) {
137
+ if (order && scope.some((field) => order[field] !== undefined && order[field] !== q.scope![field])) continue;
138
+ if (!order || scope.some((field) => order[field] === undefined)) { unscoped.push(refund); continue; }
139
+ }
140
+ if (refund.currency === q.currency) {
141
+ refunds.push({ id: refund.id, orderId: refund.orderId, at: refund.refundedAt, amountMinor: refund.amountMinor });
142
+ continue;
143
+ }
144
+ const row = other.get(refund.currency) ?? { currency: refund.currency, count: 0, amountMinor: 0 };
145
+ other.set(refund.currency, { ...row, count: row.count + 1, amountMinor: row.amountMinor + refund.amountMinor });
146
+ }
147
+ current = {
148
+ ...current, refunds, unscoped, orphans: [...current.orphans, ...orphans],
149
+ otherCurrency: [...other.values()].sort((a, b) => (a.currency < b.currency ? -1 : a.currency > b.currency ? 1 : 0)),
150
+ unreadable: current.unreadable + (first || fresh.length + orphans.length > 0 ? (page.unreadable ?? 0) : 0),
151
+ seen: seen.size, total: first ? (page.total ?? null) : current.total,
152
+ status: page.hasMore ? 'reading' : 'complete',
153
+ };
154
+ setRead(current);
155
+ }).catch((error: unknown) => {
156
+ if (!live) return;
157
+ current = error instanceof StoreRefundsUnsupportedError ? { ...current, status: 'unsupported' } : { ...current, status: 'error', error };
158
+ setRead(current);
159
+ });
160
+ // Abandons the read in flight on a new connector, context or query value, or on unmount, and clears its published
161
+ // value so a switch back cannot show it; the memo's check covers the render before this cleanup runs.
162
+ return () => {
163
+ live = false;
164
+ setRead(null);
165
+ };
166
+ }, [connector, context, key]);
167
+
168
+ return useMemo(() => {
169
+ if (!connector || !context || key === null) return IDLE;
170
+ if (!connector.listRefunds) return NO_DATED;
171
+ // A read for another connector, context or query is stale: the current one is only starting.
172
+ if (!read || read.connector !== connector || read.context !== context || read.key !== key) return STARTING;
173
+ if (read.status === 'unsupported') return NO_DATED;
174
+ const { refunds, orphans, unreadable, unscoped, otherCurrency, seen, total } = read;
175
+ const progress = read.status === 'reading' ? { downloaded: seen + unreadable, total } : null;
176
+ const error = read.status === 'error' ? read.error : null;
177
+ return { refunds, orphans, unreadable, unscoped, otherCurrency, progress, error, complete: read.status === 'complete' };
178
+ }, [connector, context, key, read]);
179
+ }
package/src/tax/exact.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { TaxRounding } from '@tallyui/core';
2
+ import { roundRatio, type RoundingMode } from '@tallyui/core';
2
3
  import { woocommerceTaxByRate } from '../order/woocommerce-tax';
3
4
 
4
5
  /** Micro-minor-units per minor unit. */
@@ -8,6 +9,7 @@ export const MICROS_PER_MINOR = 1_000_000n;
8
9
  export const DEFAULT_TAX_ROUNDING = { granularity: 'per_order', mode: 'half_away_from_zero' } as const satisfies TaxRounding;
9
10
 
10
11
  export { ratePpmFromPercent } from '@tallyui/core';
12
+ export { roundRatio, type RoundingMode } from '@tallyui/core';
11
13
 
12
14
  /**
13
15
  * Exact exclusive tax, or inclusive tax rounded half away from zero to a micro-minor-unit.
@@ -26,16 +28,6 @@ export function taxMicros(amountMinor: number, ratePpm: number, pricesIncludeTax
26
28
  return sign * ((sign * numerator + denominator / 2n) / denominator);
27
29
  }
28
30
 
29
- /** #287: `half_up` is Math.round's rule, Vendure's DefaultMoneyStrategy (default-money-strategy.js:19-21). */
30
- export type RoundingMode = 'half_away_from_zero' | 'half_up';
31
-
32
- /** `n / d` (d > 0) rounded to an integer in `mode`, exactly; the modes differ only on exact negative halves. */
33
- export function roundRatio(n: bigint, d: bigint, mode: RoundingMode = 'half_away_from_zero'): bigint {
34
- if (mode === 'half_away_from_zero' && n < 0n) return -roundRatio(-n, d, mode);
35
- const a = 2n * n + d, b = 2n * d; // floor(n / d + 1/2)
36
- return a / b - (a < 0n && a % b !== 0n ? 1n : 0n);
37
- }
38
-
39
31
  /** Rounds micro-minor-units to integer minor units, half away from zero unless `mode` says otherwise. */
40
32
  export function roundMicrosToMinor(micros: bigint, mode?: RoundingMode): number {
41
33
  const minor = roundRatio(micros, MICROS_PER_MINOR, mode);
@@ -2,10 +2,11 @@
2
2
  * Port of v2's cash rounding: packages/order-math/src/payments/rounding.ts and
3
3
  * packages/core/src/screens/main/pos/checkout/tender/tender-figures.ts.
4
4
  * v2's tender LEDGER: "a partial or short cash entry and every other method keep full precision".
5
- * Local figures only; writing the rounding as an order line is unit 24.
5
+ * The till records the rounding as an order field, Order.cashRoundings (ADR-094).
6
6
  */
7
- import type { PaymentMethodDescriptor, PaymentRounding } from '@tallyui/core';
7
+ import { wireMethodOf, type PaymentMethodDescriptor, type PaymentRounding } from '@tallyui/core';
8
8
  import { appliedMinor, type TenderState } from './tender-state';
9
+ import { countsTowardPaid, type PaymentLegStatus } from './payment-legs';
9
10
 
10
11
  /** How the method rounds to its increment. */
11
12
  export type RoundingMode = NonNullable<PaymentRounding>['mode'];
@@ -21,14 +22,62 @@ export function roundToIncrement(minor: number, incrementMinor: number, mode: Ro
21
22
  return remainder * 2 >= incrementMinor ? down + incrementMinor : down;
22
23
  }
23
24
 
24
- /** The balance under a manual method's rounding, with its signed difference. */
25
+ /** The nearest payable cash amounts, or null when the amount is already payable. */
26
+ export function nearestPayableCash(amountMinor: number, incrementMinor: number): { belowMinor: number; aboveMinor: number } | null {
27
+ if (!Number.isInteger(incrementMinor) || incrementMinor <= 1 || amountMinor % incrementMinor === 0) return null;
28
+ const belowMinor = Math.floor(amountMinor / incrementMinor) * incrementMinor;
29
+ return { belowMinor, aboveMinor: belowMinor + incrementMinor };
30
+ }
31
+
32
+ /** ADR-094: the sale rounds once, against its unrounded remainder. */
33
+ export function roundedRemainder(balanceMinor: number, entriesMinor: number, rounding: NonNullable<PaymentRounding>): number {
34
+ if (balanceMinor <= 0) return balanceMinor;
35
+ const unrounded = balanceMinor - entriesMinor;
36
+ return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
37
+ }
38
+
39
+ /** ADR-094 item 7 (carry): a cash part pick rounds its target less `entriesMinor`, the live entries the pick carries against; it defaults to 0, the 5.0.0 per-pick rounding. 0 means cash cannot pay it. */
40
+ export function roundedPickTarget(targetMinor: number, rounding: PaymentRounding | null | undefined, entriesMinor = 0): number {
41
+ if (!rounding) return targetMinor;
42
+ const unrounded = targetMinor - entriesMinor;
43
+ return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
44
+ }
45
+
46
+ /** ADR-094 items 1 and 6: the live entries a remainder rounds against, every entry on the sale (cash-pick entries included since the carry rule). */
47
+ export function remainderEntriesMinor(order: { payments: readonly { id: string; method?: string; units?: Readonly<Record<string, number>> }[]; cashRoundings?: readonly { paymentId: string; minor: number }[] }): number {
48
+ return (order.cashRoundings ?? []).reduce((sum, entry) => sum + entry.minor, 0);
49
+ }
50
+
51
+ /**
52
+ * ADR-094 item 1 (#1365, amended by the carry rule 2026-11-26): the zero-remainder write-off's leg, the last counting leg with
53
+ * wire method 'cash', else the last counting leg. A later cash leg rounds against a non-cash leg's write-off; `cashVoidRefusal` keeps the entries a stack.
54
+ */
55
+ export function writeOffLeg<L extends { id: string; method?: string; status?: PaymentLegStatus; units?: Readonly<Record<string, number>> }>(order: { payments: readonly L[] }): L | undefined {
56
+ const counted = order.payments.filter(countsTowardPaid);
57
+ return counted.filter((leg) => leg.method === 'cash').at(-1) ?? counted.at(-1);
58
+ }
59
+
60
+ /** Why a void is refused by ADR-094 item 6 (desk ruling (i), #1292): a later live cash leg's entry was computed against this leg's. */
61
+ export type CashVoidRefusal = 'later_cash_rounding';
62
+ /**
63
+ * ADR-094 item 6: a leg carrying a live rounding entry cannot be voided while a later live cash leg (wire method 'cash') carries one; the later cash is voided first. A non-cash leg's entry (the zero-remainder write-off) never blocks, so a leg the till cannot void never strands one it can.
64
+ */
65
+ export function cashVoidRefusal(order: { payments: readonly { id: string; method?: string; status?: PaymentLegStatus }[]; cashRoundings?: readonly { paymentId: string; minor: number }[] }, paymentId: string): CashVoidRefusal | undefined {
66
+ const carries = (id: string) => (order.cashRoundings ?? []).some((entry) => entry.paymentId === id && entry.minor !== 0);
67
+ const at = order.payments.findIndex((leg) => leg.id === paymentId);
68
+ if (at < 0 || !carries(paymentId)) return undefined;
69
+ return order.payments.slice(at + 1).some((leg) => leg.method === 'cash' && countsTowardPaid(leg) && carries(leg.id)) ? 'later_cash_rounding' : undefined;
70
+ }
71
+ /** The balance under a cash method's rounding, with its signed difference. */
25
72
  export function roundedDue(
26
73
  balanceMinor: number,
27
74
  method: PaymentMethodDescriptor | null,
75
+ /** The sum of the order's live cashRoundings, already counted in the balance. */
76
+ entriesMinor = 0,
28
77
  ): { dueMinor: number; roundingMinor: number } {
29
- const rounding = method?.capture.mode === 'manual' ? method.defaults.rounding : null;
78
+ const rounding = method?.capture.mode === 'manual' && wireMethodOf(method) === 'cash' ? method.defaults.rounding : null;
30
79
  if (!rounding) return { dueMinor: balanceMinor, roundingMinor: 0 };
31
- const dueMinor = roundToIncrement(balanceMinor, rounding.incrementMinor, rounding.mode);
80
+ const dueMinor = roundedRemainder(balanceMinor, entriesMinor, rounding);
32
81
  return { dueMinor, roundingMinor: dueMinor - balanceMinor };
33
82
  }
34
83
 
@@ -60,8 +109,10 @@ export function tenderRounding(
60
109
  state: Pick<TenderState, 'entryMinor' | 'entryDirty'>,
61
110
  balanceMinor: number,
62
111
  method: PaymentMethodDescriptor | null,
112
+ /** The sum of the order's live cashRoundings, already counted in the balance. */
113
+ entriesMinor = 0,
63
114
  ): TenderRounding {
64
- const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
115
+ const roundedDueMinor = roundedDue(balanceMinor, method, entriesMinor).dueMinor;
65
116
  const entryMinor = !state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor;
66
117
  const legMinor = appliedMinor(entryMinor, balanceMinor);
67
118
  const roundingMinor = settlesAtRoundedDue({
@@ -7,7 +7,7 @@ export { tenderFigures, runsWholeOrder } from './tender-figures';
7
7
  export type { TenderFacts, TenderFigures } from './tender-figures';
8
8
  export { tenderVoidSchema, tenderVoidCollection } from './tender-void';
9
9
  export type { TenderVoid } from './tender-void';
10
- export { roundedDue, tenderRounding } from './cash-rounding';
10
+ export { cashVoidRefusal, type CashVoidRefusal, nearestPayableCash, roundedPickTarget, remainderEntriesMinor, writeOffLeg, roundedDue, tenderRounding } from './cash-rounding';
11
11
  export type { TenderRounding } from './cash-rounding';
12
12
  export { legStatus, countsTowardPaid, isInMotion, capturedMinor, inMotionMinor, canMoveLeg, canVoidLeg } from './payment-legs';
13
13
  export type { PaymentLegStatus } from './payment-legs';
@@ -46,3 +46,8 @@ export function canMoveLeg(from: PaymentLegStatus, to: PaymentLegStatus): boolea
46
46
  export function canVoidLeg(leg: { status?: PaymentLegStatus }, method: PaymentMethodDescriptor): boolean {
47
47
  return method.capabilities.void && (isInMotion(leg) || (legStatus(leg) === 'captured' && method.capture.mode === 'manual'));
48
48
  }
49
+
50
+ /** Money was taken (captured, or voided after capture): the leg is never removed (ADR-072 d3, amended 2026-11-22). */
51
+ export function takenLeg(leg: { status?: PaymentLegStatus; takenAt?: string }): boolean {
52
+ return (legStatus(leg) === 'captured' || legStatus(leg) === 'voided') && leg.takenAt !== undefined;
53
+ }
@@ -22,6 +22,8 @@ export interface TenderFacts {
22
22
  /** Currency decimal places; every `*Minor` number is in these units. */
23
23
  dp: number;
24
24
  balanceMinor: number;
25
+ /** The sum of the order's live cashRoundings, already counted in the balance. */
26
+ entriesMinor?: number;
25
27
  /** The order's payment legs in ledger order; only those that count toward paid are numbered. */
26
28
  payments: readonly { status?: PaymentLegStatus }[];
27
29
  /** The plan's counted legs (by `plan.before`, else since `plan.from`), as `tender-recorded` and `planLegs` read them. */
@@ -47,7 +49,7 @@ export function tenderFigures(facts: TenderFacts) {
47
49
  plan?.kind === 'items' && done.reduce((sum, leg) => sum + leg.minor, 0) >= plan.firstMinor;
48
50
  const thisPaymentMinor = split?.thisPaymentMinor ?? balanceMinor;
49
51
  const legCapMinor = method?.capabilities.change ? thisPaymentMinor : balanceMinor;
50
- const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
52
+ const roundedDueMinor = roundedDue(balanceMinor, method, facts.entriesMinor ?? 0).dueMinor;
51
53
  const percent = state.entryMode === 'percent';
52
54
  const percentMinor = percent ? percentOfMinor(balanceMinor, state.entryMinor) : null;
53
55
  const entryMinor =
@@ -1,27 +0,0 @@
1
- import { describe, expectTypeOf, it } from 'vitest';
2
- import type { AnyCommandEnvelope, CommandEnvelope, OrderCreateEnvelope, OrderCreatePayload, RegisterCommandEnvelope } from '@tallyui/core';
3
- import type { CommandTransport } from './types';
4
- import { sendOrderRefund } from '../refund';
5
-
6
- describe('CommandTransport', () => {
7
- it('defaults to order.create envelopes', () => {
8
- expectTypeOf<Parameters<CommandTransport['send']>[0]>().toEqualTypeOf<CommandEnvelope<OrderCreatePayload>[]>();
9
- const transport: CommandTransport = { send: async () => ({ kind: 'results', results: [] }) };
10
- const batch: CommandEnvelope<OrderCreatePayload>[] = [];
11
- transport.send(batch);
12
- });
13
-
14
- it('the wide transport is accepted where the order outbox wants the order transport', () => {
15
- expectTypeOf<CommandTransport<AnyCommandEnvelope>>().toMatchTypeOf<CommandTransport<OrderCreateEnvelope>>();
16
- });
17
-
18
- it('the wide transport is accepted where sendOrderRefund wants the refund transport', () => {
19
- expectTypeOf<CommandTransport<AnyCommandEnvelope>>().toMatchTypeOf<Parameters<typeof sendOrderRefund>[0]>();
20
- });
21
-
22
- it('the wide transport accepts register command envelopes', () => {
23
- const transport: CommandTransport<AnyCommandEnvelope> = { send: async () => ({ kind: 'results', results: [] }) };
24
- const batch: RegisterCommandEnvelope[] = [];
25
- transport.send(batch);
26
- });
27
- });
@@ -1,77 +0,0 @@
1
- import { describe, expectTypeOf, it } from 'vitest';
2
- import type { WebBluetoothDevice } from './bluetooth-sink';
3
- import type { WebUsbDevice } from './usb-sink';
4
-
5
- // These are written from the WebUSB and Web Bluetooth IDL, because TypeScript's DOM lib has neither. FrozenArray is readonly.
6
- // The `Missing` parameter covers the IDL's `null` and DefinitelyTyped's `undefined`.
7
- type USBDirection = 'in' | 'out';
8
- declare class USBEndpoint { readonly endpointNumber: number; readonly direction: USBDirection; readonly type: 'bulk' | 'interrupt' | 'isochronous'; readonly packetSize: number; }
9
- declare class USBAlternateInterface { readonly alternateSetting: number; readonly interfaceClass: number; readonly interfaceSubclass: number; readonly interfaceProtocol: number; readonly interfaceName?: string | null; readonly endpoints: readonly USBEndpoint[]; }
10
- declare class USBInterface { readonly interfaceNumber: number; readonly alternate: USBAlternateInterface; readonly alternates: readonly USBAlternateInterface[]; readonly claimed: boolean; }
11
- declare class USBConfiguration { readonly configurationValue: number; readonly interfaces: readonly USBInterface[]; }
12
- declare class USBOutTransferResult { readonly bytesWritten: number; readonly status: 'ok' | 'stall' | 'babble'; }
13
- declare class USBDevice<Missing extends null | undefined> {
14
- readonly productName: string | Missing;
15
- readonly configuration: USBConfiguration | Missing;
16
- readonly opened: boolean;
17
- open(): Promise<void>;
18
- selectConfiguration(configurationValue: number): Promise<void>;
19
- claimInterface(interfaceNumber: number): Promise<void>;
20
- clearHalt(direction: USBDirection, endpointNumber: number): Promise<void>;
21
- transferOut(endpointNumber: number, data: BufferSource): Promise<USBOutTransferResult>;
22
- }
23
-
24
- declare class BluetoothCharacteristicProperties {
25
- readonly broadcast: boolean; readonly read: boolean; readonly writeWithoutResponse: boolean; readonly write: boolean;
26
- readonly notify: boolean; readonly indicate: boolean; readonly authenticatedSignedWrites: boolean;
27
- readonly reliableWrite: boolean; readonly writableAuxiliaries: boolean;
28
- }
29
- declare class BluetoothRemoteGATTCharacteristic extends EventTarget {
30
- readonly service: BluetoothRemoteGATTService; readonly uuid: string;
31
- readonly properties: BluetoothCharacteristicProperties; readonly value?: DataView;
32
- readValue(): Promise<DataView>;
33
- writeValue(value: BufferSource): Promise<void>;
34
- writeValueWithResponse(value: BufferSource): Promise<void>;
35
- writeValueWithoutResponse(value: BufferSource): Promise<void>;
36
- }
37
- declare class BluetoothRemoteGATTService extends EventTarget {
38
- readonly uuid: string; readonly isPrimary: boolean;
39
- getCharacteristic(characteristic: number | string): Promise<BluetoothRemoteGATTCharacteristic>;
40
- getCharacteristics(characteristic?: number | string): Promise<BluetoothRemoteGATTCharacteristic[]>;
41
- }
42
- declare class BluetoothRemoteGATTServer {
43
- readonly connected: boolean;
44
- connect(): Promise<BluetoothRemoteGATTServer>;
45
- disconnect(): void;
46
- getPrimaryService(service: number | string): Promise<BluetoothRemoteGATTService>;
47
- getPrimaryServices(service?: number | string): Promise<BluetoothRemoteGATTService[]>;
48
- }
49
- declare class BluetoothDevice<Missing extends null | undefined> extends EventTarget {
50
- readonly id: string;
51
- readonly name: string | Missing;
52
- readonly gatt: BluetoothRemoteGATTServer | Missing;
53
- }
54
-
55
- type SinkGatt = NonNullable<WebBluetoothDevice['gatt']>;
56
- type SinkService = Awaited<ReturnType<SinkGatt['getPrimaryService']>>;
57
- type SinkCharacteristic = Awaited<ReturnType<SinkService['getCharacteristic']>>;
58
-
59
- describe('ESC/POS sink device types', () => {
60
- it('a WebUSB device with null fields fits WebUsbDevice', () => expectTypeOf<USBDevice<null>>().toExtend<WebUsbDevice>());
61
- it('a WebUSB device with undefined fields fits WebUsbDevice', () => expectTypeOf<USBDevice<undefined>>().toExtend<WebUsbDevice>());
62
- it('a Web Bluetooth device with null fields fits WebBluetoothDevice', () => expectTypeOf<BluetoothDevice<null>>().toExtend<WebBluetoothDevice>());
63
- it('a Web Bluetooth device with undefined fields fits WebBluetoothDevice', () => expectTypeOf<BluetoothDevice<undefined>>().toExtend<WebBluetoothDevice>());
64
- });
65
-
66
- describe('ESC/POS sink calls fit the real device methods', () => {
67
- it('open', () => expectTypeOf<Parameters<WebUsbDevice['open']>>().toExtend<Parameters<USBDevice<null>['open']>>());
68
- it('selectConfiguration', () => expectTypeOf<Parameters<WebUsbDevice['selectConfiguration']>>().toExtend<Parameters<USBDevice<null>['selectConfiguration']>>());
69
- it('claimInterface', () => expectTypeOf<Parameters<WebUsbDevice['claimInterface']>>().toExtend<Parameters<USBDevice<null>['claimInterface']>>());
70
- it('clearHalt', () => expectTypeOf<Parameters<WebUsbDevice['clearHalt']>>().toExtend<Parameters<USBDevice<null>['clearHalt']>>());
71
- it('transferOut', () => expectTypeOf<Parameters<WebUsbDevice['transferOut']>>().toExtend<Parameters<USBDevice<null>['transferOut']>>());
72
- it('connect', () => expectTypeOf<Parameters<SinkGatt['connect']>>().toExtend<Parameters<BluetoothRemoteGATTServer['connect']>>());
73
- it('getPrimaryService', () => expectTypeOf<Parameters<SinkGatt['getPrimaryService']>>().toExtend<Parameters<BluetoothRemoteGATTServer['getPrimaryService']>>());
74
- it('getCharacteristic', () => expectTypeOf<Parameters<SinkService['getCharacteristic']>>().toExtend<Parameters<BluetoothRemoteGATTService['getCharacteristic']>>());
75
- it('writeValueWithResponse', () => expectTypeOf<Parameters<SinkCharacteristic['writeValueWithResponse']>>().toExtend<Parameters<BluetoothRemoteGATTCharacteristic['writeValueWithResponse']>>());
76
- it('writeValueWithoutResponse', () => expectTypeOf<Parameters<SinkCharacteristic['writeValueWithoutResponse']>>().toExtend<Parameters<BluetoothRemoteGATTCharacteristic['writeValueWithoutResponse']>>());
77
- });