@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,5 +1,7 @@
1
1
  import { knownWarnings } from '@tallyui/core';
2
2
  import { replacedOrderIds } from './reopened';
3
+ import { storeOrderLeft } from './store-order-left';
4
+ import { settledOnStore } from './store-settlement';
3
5
  import type { PosOrder } from './types';
4
6
 
5
7
  /** The `error.code` the outbox puts on a pending reopened sale whose `order.update` it cannot build (ADR-090 W4b). The row stays pending: unsent. */
@@ -15,15 +17,18 @@ export const UPDATE_UNSENDABLE_MESSAGE = "The store can't accept this change yet
15
17
  * A refused order is left out once its finalized successor is in `orders`.
16
18
  * Pending updates marked `UPDATE_UNSENDABLE` are shown until a person acts.
17
19
  * An order a cashier marked handled (`markAttentionHandled`) is left out while its `commandId` is the one it was marked
18
- * for; a requeue mints a new `commandId`, so a fresh refusal shows again (ADR-092 6f).
20
+ * for; a requeue mints a new `commandId`, so a fresh refusal shows again (ADR-092 6f). The mark does not hide a refused
21
+ * sale whose order the store created (`storeOrderLeft`, #1101). A refused sale whose store order is settled on the store
22
+ * (`settledOnStore`: cancelled or gone, #1101) is not shown for its refusal; any other reason above still shows it.
19
23
  */
20
24
  export function needsAttention(orders: PosOrder[], options: { stuckCommandIds?: readonly string[] } = {}): PosOrder[] {
21
25
  const replaced = replacedOrderIds(orders);
22
- return orders.filter((order) => order.syncStatus === 'rejected'
26
+ return orders.filter((order) => (order.syncStatus === 'rejected' && !settledOnStore(order))
23
27
  || (order.syncStatus === 'pending' && order.error?.code === UPDATE_UNSENDABLE)
24
28
  || (order.localWarnings?.length ?? 0) > 0
25
29
  || (order.syncStatus === 'applied' && knownWarnings(order.warnings).some((warning) => warning.code !== 'register_session_unknown')) || order.lateSessionId !== undefined
26
30
  || (order.syncStatus === 'pending' && options.stuckCommandIds?.includes(order.commandId) === true))
27
- .filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== undefined && order.attentionHandledFor === order.commandId))
31
+ .filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== undefined && order.attentionHandledFor === order.commandId
32
+ && storeOrderLeft(order) === undefined))
28
33
  .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
29
34
  }
@@ -124,13 +124,20 @@ export async function reopenRefusedOrder(orderId: string, deps: {
124
124
  ...(shipping.taxStatus !== undefined ? { taxStatus: shipping.taxStatus } : {}),
125
125
  ...(shipping.methodId !== undefined ? { methodId: shipping.methodId } : {}),
126
126
  });
127
- for (const payment of order.payments) builder.addPayment({
127
+ const legIds = new Map<string, string>();
128
+ for (const payment of order.payments) legIds.set(payment.id, builder.addPayment({
128
129
  // After close each leg keeps the refused order's id, so finalize knows it for the leg that closure counted.
129
130
  ...(afterClose ? { id: payment.id } : {}), method: payment.method, amountMinor: payment.amountMinor, reopened: true,
130
131
  ...(payment.reference !== undefined ? { reference: payment.reference } : {}),
131
132
  ...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
132
133
  ...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
133
- });
134
+ ...(payment.sessionId !== undefined ? { sessionId: payment.sessionId } : {}),
135
+ }));
136
+ // ADR-094: each entry follows its leg's new id; an entry whose stored leg is not found is dropped.
137
+ for (const entry of order.cashRoundings ?? []) {
138
+ const paymentId = legIds.get(entry.paymentId);
139
+ if (paymentId) builder.addCashRounding({ paymentId, minor: entry.minor });
140
+ }
134
141
  if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
135
142
  builder.setCustomer({ id: order.customer.id, name: order.customer.name,
136
143
  ...(order.customer.email !== undefined ? { email: order.customer.email } : {}),
@@ -39,6 +39,9 @@ import type { PosOrder } from './types';
39
39
  * Version 18 adds the customer's `taxIds`, the order's `meta`, a line's `catalogueSku` and `attentionHandledFor` (ADR-092), and lets sentVersion and downgradedFrom be 12 (order.create version 12), and changes nothing else. Its migration is the identity. It is one-way like version 17.
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
+ * 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.
42
45
  */
43
46
  /** A customer's address on an order (#722, OrderAddress): ten optional strings. */
44
47
  const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
@@ -48,7 +51,7 @@ const orderAddressSchema = { type: 'object', additionalProperties: false, proper
48
51
  } } as const;
49
52
 
50
53
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
51
- version: 20, primaryKey: 'id', type: 'object', additionalProperties: false,
54
+ version: 22, primaryKey: 'id', type: 'object', additionalProperties: false,
52
55
  properties: {
53
56
  id: { type: 'string', maxLength: 36 },
54
57
  saleId: { type: 'string', maxLength: 36 },
@@ -59,6 +62,19 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
59
62
  updatedAt: { type: 'string' },
60
63
  reopenedAt: { type: 'string', maxLength: 40 },
61
64
  attentionHandledFor: { type: 'string', maxLength: 36 },
65
+ storeSettlement: { type: 'object', additionalProperties: false, properties: {
66
+ kind: { type: 'string', enum: ['cancel', 'pay', 'reverse'] },
67
+ state: { type: 'string', enum: ['sending', 'done', 'changed', 'refused', 'gone'] },
68
+ attemptId: { type: 'string', maxLength: 36 }, at: { type: 'string', maxLength: 40 },
69
+ storeStatus: { type: 'string' }, capturedMinor: { type: 'integer' }, code: { type: 'string' }, message: { type: 'string' },
70
+ payments: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
71
+ id: { type: 'string', maxLength: 36 }, method: { type: 'string' }, amountMinor: { type: 'integer' },
72
+ tenderedMinor: { type: 'integer' }, done: { type: 'boolean' } }, required: ['id', 'method', 'amountMinor'] } },
73
+ closeId: { type: 'string', maxLength: 36 },
74
+ legs: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
75
+ paymentId: { type: 'string', maxLength: 36 }, commandId: { type: 'string', maxLength: 36 }, done: { type: 'boolean' } },
76
+ required: ['paymentId', 'commandId'] } },
77
+ }, required: ['kind', 'state', 'attemptId', 'at'] },
62
78
  currency: { type: 'string' },
63
79
  pricesIncludeTax: { type: 'boolean' },
64
80
  subtotalMinor: { type: 'integer' }, discountMinor: { type: 'integer' },
@@ -131,6 +147,8 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
131
147
  takenAt: { type: 'string', maxLength: 40 },
132
148
  }, required: ['id', 'method', 'amountMinor'],
133
149
  } },
150
+ cashRoundings: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
151
+ paymentId: { type: 'string', maxLength: 36 }, minor: { type: 'integer' } }, required: ['paymentId', 'minor'] } },
134
152
  customer: { type: ['object', 'null'], properties: { id: { type: 'string' }, name: { type: 'string' }, email: { type: 'string' },
135
153
  billing: orderAddressSchema, shipping: orderAddressSchema, taxIds: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
136
154
  type: { type: 'string' }, value: { type: 'string' }, country: { type: 'string' }, label: { type: 'string' } }, required: ['type', 'value'] } } } },
@@ -220,5 +238,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
220
238
  // it means no older sale is ever re-rounded (#287).
221
239
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
222
240
  return { schema: posOrderSchema,
223
- 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 } };
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 } };
224
242
  }
@@ -0,0 +1,21 @@
1
+ import type { PosOrder } from './types';
2
+
3
+ /**
4
+ * The store order a refused sale left behind (#1101): a value only for a rejected order with no `storeOrderId` whose
5
+ * `error.data.orderId` is a non-empty string, as a transport that created the order before refusing the sale sets it.
6
+ * `reference` is `data.displayId` when a non-empty string, else `orderId`. `recordedMinor` sums the first
7
+ * `data.recorded` payments (a safe integer above 0; anything else counts as 0): what the store had recorded at the
8
+ * refusal, not the order's state now.
9
+ */
10
+ export function storeOrderLeft(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error' | 'payments'>):
11
+ { orderId: string; reference: string; recordedMinor: number } | undefined {
12
+ const data = order.error?.data;
13
+ if (order.syncStatus !== 'rejected' || order.storeOrderId !== undefined || typeof data?.orderId !== 'string' || !data.orderId) return undefined;
14
+ const { orderId, displayId, recorded } = data;
15
+ const count = Number.isSafeInteger(recorded) && (recorded as number) > 0 ? recorded as number : 0;
16
+ return {
17
+ orderId,
18
+ reference: typeof displayId === 'string' && displayId ? displayId : orderId,
19
+ recordedMinor: order.payments.slice(0, count).reduce((sum, payment) => sum + payment.amountMinor, 0),
20
+ };
21
+ }
@@ -0,0 +1,51 @@
1
+ import { storeOrderLeft } from './store-order-left';
2
+ import type { PosOrder } from './types';
3
+
4
+ type LeftOrder = Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error' | 'payments' | 'storeSettlement'>;
5
+
6
+ /**
7
+ * Whether the store order a refused sale left behind is settled on the store (#1101): its settlement is done, or gone
8
+ * while the store had recorded nothing on it (desk ruling: a gone order with money recorded still needs a manager).
9
+ */
10
+ export function settledOnStore(order: LeftOrder | Pick<PosOrder, 'storeSettlement'>): boolean {
11
+ const state = order.storeSettlement?.state;
12
+ if (state === 'done') return true;
13
+ if (state !== 'gone') return false;
14
+ const left = 'syncStatus' in order ? storeOrderLeft(order) : undefined;
15
+ return !left || left.recordedMinor === 0;
16
+ }
17
+
18
+ /**
19
+ * Whether the till may cancel the store order a refused sale left behind (#1101): there is one (`storeOrderLeft`), the
20
+ * store had recorded nothing paid on it, it is not settled (`settledOnStore`), and there is no settlement yet, or a
21
+ * cancel (whose `sending` attempt a repeat finishes), or one the store changed or refused.
22
+ */
23
+ export function canCancelOnStore(order: LeftOrder): boolean {
24
+ const left = storeOrderLeft(order);
25
+ if (!left || left.recordedMinor !== 0 || settledOnStore(order)) return false;
26
+ const settlement = order.storeSettlement;
27
+ return settlement === undefined || settlement.kind === 'cancel' || settlement.state === 'changed' || settlement.state === 'refused';
28
+ }
29
+
30
+ /** The till's legs the store had not recorded at the refusal (#1101 slice 3): the payments after `data.recorded`, counted
31
+ * as `storeOrderLeft` counts them. */
32
+ export function unrecordedLegs(order: Pick<PosOrder, 'error' | 'payments'>): PosOrder['payments'] {
33
+ const recorded = order.error?.data?.recorded;
34
+ return order.payments.slice(Number.isSafeInteger(recorded) && (recorded as number) > 0 ? recorded as number : 0);
35
+ }
36
+
37
+ /**
38
+ * Whether the till may record its unrecorded legs on the part-paid store order a refused sale left behind (#1101 slice
39
+ * 3): the store had recorded some of the sale, it is not settled, every leg left has an amount, the settlement is not
40
+ * `gone` (the order is not on the store, so a press could only read 404 again), and there is no settlement yet, or a
41
+ * pay (whose `sending` attempt a repeat finishes), or one the store changed or refused.
42
+ */
43
+ export function canPayRestOnStore(order: LeftOrder): boolean {
44
+ const left = storeOrderLeft(order);
45
+ if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
46
+ const legs = unrecordedLegs(order);
47
+ if (legs.length === 0 || !legs.every((leg) => leg.amountMinor > 0)) return false;
48
+ const settlement = order.storeSettlement;
49
+ if (settlement?.state === 'gone') return false;
50
+ return settlement === undefined || settlement.kind === 'pay' || settlement.state === 'changed' || settlement.state === 'refused';
51
+ }
@@ -1,5 +1,5 @@
1
1
  import type { CommandError, CommandServerRefs, CommandWarning, OrderAddress, OrderCreateLine, PaymentMethodKind, TaxRounding } from '@tallyui/core';
2
- import type { DisplayTotals, FeeLine, ShippingLine } from '../order/types';
2
+ import type { CashRounding, DisplayTotals, FeeLine, ShippingLine } from '../order/types';
3
3
 
4
4
  export type PosOrderSyncStatus = 'pending' | 'applied' | 'rejected';
5
5
 
@@ -76,6 +76,8 @@ export interface PosOrderPayment {
76
76
  reference?: string;
77
77
  /** When the till recorded the leg (`Payment.takenAt`); absent on store-held and older legs. */
78
78
  takenAt?: string;
79
+ /** The session the leg was taken in (`Payment.sessionId`, S3); absent means the order's session. */
80
+ sessionId?: string;
79
81
  }
80
82
 
81
83
  export interface PosOrder {
@@ -107,6 +109,8 @@ export interface PosOrder {
107
109
  /** What the store owes back on a reopened sale whose locked payments exceed its new total, in minor units (pos_orders v15, ADR-090). `finalizeOrder` writes it on every reopened sale, 0 when nothing is due; absent on a till sale. */
108
110
  refundDueMinor?: number;
109
111
  payments: PosOrderPayment[];
112
+ /** ADR-094: the cash rounding entries, keyed by this order's payment ids and counted in totalMinor. Absent when empty. */
113
+ cashRoundings?: CashRounding[];
110
114
  /** `billing` and `shipping` (#722) are frozen copies of the customer's addresses, stored only with `taxAddress`. */
111
115
  customer: { id?: string; name?: string; email?: string; billing?: OrderAddress; shipping?: OrderAddress;
112
116
  /** The sale's tax ids (pos_orders v18, ADR-092), sent at order.create 12; `label` is kept on the till and is not sent. */
@@ -160,4 +164,26 @@ export interface PosOrder {
160
164
  reopenedAt?: string;
161
165
  /** The commandId whose refusal the cashier marked handled (tally-woo 03, ADR-092 6f); the logic comes in a later PR. */
162
166
  attentionHandledFor?: string;
167
+ /** How the till settled the order the store created before it refused this sale (#1101); see `PosOrderStoreSettlement`. */
168
+ storeSettlement?: PosOrderStoreSettlement;
163
169
  }
170
+
171
+ /**
172
+ * The till's settlement of a refused sale's store order (#1101, `storeOrderLeft`). `attemptId` names the attempt and is
173
+ * kept while `state` is `sending`, so a repeat after a lost answer is the same attempt. `at` is the instant of the last
174
+ * write. `storeStatus` is the store's status word (done, changed), `capturedMinor` what the store shows captured
175
+ * (changed), `code` and `message` the store's refusal (refused), for the sync log, never shown to the cashier.
176
+ * `payments` and `closeId` are for kind `pay`, `legs` for kind `reverse` (later slices).
177
+ */
178
+ export type PosOrderStoreSettlement = {
179
+ kind: 'cancel' | 'pay' | 'reverse';
180
+ state: 'sending' | 'done' | 'changed' | 'refused' | 'gone';
181
+ attemptId: string;
182
+ at: string;
183
+ storeStatus?: string;
184
+ capturedMinor?: number;
185
+ code?: string; message?: string;
186
+ payments?: { id: string; method: string; amountMinor: number; tenderedMinor?: number; done?: boolean }[];
187
+ closeId?: string;
188
+ legs?: { paymentId: string; commandId: string; done?: boolean }[];
189
+ };
@@ -1,4 +1,4 @@
1
- import type { Discount, SentOrder } from '../order/types';
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
4
  import { taxedLinesFor } from '../tax/taxed-lines';
@@ -6,6 +6,12 @@ import { carriedRows } from './carried-rows';
6
6
  import type { ReceiptConfig, ReceiptData } from './types';
7
7
  import { RECEIPT_SCHEMA_VERSION } from './types';
8
8
 
9
+ /** ADR-094: the receipt's Rounding row, the sum of the order's cash roundings; none when the sum is 0. */
10
+ export function receiptRounding(order: Pick<Order, 'cashRoundings'>): Pick<ReceiptData, 'rounding'> {
11
+ const amountMinor = (order.cashRoundings ?? []).reduce((sum, entry) => sum + entry.minor, 0);
12
+ return amountMinor !== 0 ? { rounding: { name: 'Rounding', amountMinor } } : {};
13
+ }
14
+
9
15
  export function buildReceiptData(order: SentOrder, config: ReceiptConfig): ReceiptData {
10
16
  // Drops the shared helper's `netMinor` (the Z report's own use): the receipt's tax summary
11
17
  // never showed it, and an exact-shape test elsewhere in this package pins that.
@@ -68,6 +74,7 @@ export function buildReceiptData(order: SentOrder, config: ReceiptConfig): Recei
68
74
  })),
69
75
  fees: (order.display.fees ?? []).map(({ name, amountMinor }) => ({ name, amountMinor })),
70
76
  shipping: (order.display.shipping ?? []).map(({ name, amountMinor }) => ({ name, amountMinor })),
77
+ ...receiptRounding(order),
71
78
  orderDiscountMinor: order.display.orderDiscountMinor,
72
79
  totals: {
73
80
  taxInclusive: order.display.taxInclusive,
@@ -4,6 +4,7 @@ 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
6
  import { recordedTaxByRate, taxedLinesFor } from '../tax/taxed-lines';
7
+ import { receiptRounding } from './build-receipt-data';
7
8
  import { carriedRows } from './carried-rows';
8
9
  import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
9
10
  import { RECEIPT_SCHEMA_VERSION } from './types';
@@ -84,6 +85,7 @@ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCon
84
85
  discounts: display && display.orderDiscountMinor > 0 ? [{ label: 'Order discount', amountMinor: display.orderDiscountMinor }] : [],
85
86
  fees: charges(display ? display.fees : order.fees),
86
87
  shipping: charges(display ? display.shipping : order.shipping),
88
+ ...receiptRounding(order),
87
89
  orderDiscountMinor: display ? display.orderDiscountMinor : 0,
88
90
  totals: display
89
91
  ? {
@@ -44,6 +44,8 @@ export interface ReceiptData {
44
44
  lineItems: ReceiptLineItem[];
45
45
  fees: Array<{ name: string; amountMinor: number }>;
46
46
  shipping: Array<{ name: string; amountMinor: number }>;
47
+ /** ADR-094: the sum of the order's cash roundings, signed; present only when non-zero. Counted in totals.totalMinor. */
48
+ rounding?: { name: string; amountMinor: number };
47
49
  discounts: { label: string; amountMinor: number }[];
48
50
  orderDiscountMinor: number; // the order discounts as one row, in the display mode; + Σ displayDiscounts = totals.discountMinor
49
51
  totals: {
@@ -82,7 +82,7 @@ export function receiptTemplateData(receipt: ReceiptData, options: ReceiptTempla
82
82
  subtotal: money(totals.subtotalMinor),
83
83
  lineDiscount: lineDiscountMinor > 0 ? `−${money(lineDiscountMinor)}` : '',
84
84
  orderDiscount: receipt.orderDiscountMinor > 0 ? `−${money(receipt.orderDiscountMinor)}` : '',
85
- charges: [...receipt.fees, ...receipt.shipping].map((charge) => ({
85
+ charges: [...receipt.fees, ...receipt.shipping, ...(receipt.rounding ? [receipt.rounding] : [])].map((charge) => ({
86
86
  label: charge.name, amount: money(charge.amountMinor),
87
87
  })),
88
88
  taxes: totals.taxLines.map((tax) => ({
@@ -110,7 +110,11 @@ function tillSource(order: TillOrder, receipt: ReceiptData, lines: TillLine[]) {
110
110
  status: 'completed', currency: order.currency, pricesIncludeTax: order.pricesIncludeTax,
111
111
  customer: order.customer && { id: order.customer.id, firstName: order.customer.name, email: order.customer.email },
112
112
  lines: lines.map((line) => tillLine(line, key)),
113
- fees: (order.fees ?? []).map((fee) => ({ name: fee.name, ...tillCharge(fee, context, key) })),
113
+ fees: [
114
+ ...(order.fees ?? []).map((fee) => ({ name: fee.name, ...tillCharge(fee, context, key) })),
115
+ // ADR-094 detail 5: the rounding prints as WooCommerce carries it, a tax-free fee row named 'Rounding'.
116
+ ...(receipt.rounding ? [{ name: receipt.rounding.name, totalMinor: receipt.rounding.amountMinor, totalTaxMinor: 0 }] : []),
117
+ ],
114
118
  shipping: (order.shipping ?? []).map((row) => ({
115
119
  methodTitle: row.name, ...(row.methodId !== undefined ? { methodId: row.methodId } : {}), ...tillCharge(row, context, key),
116
120
  })),
@@ -1,4 +1,5 @@
1
1
  export { sendOrderRefund, type OrderRefundOutcome } from './send-order-refund';
2
+ export { refundNeedsAdminLine } from './needs-admin-line';
2
3
  export { posRefundSchema, posRefundCollection, type PosRefund, type PosRefundStatus, type PosRefundCollection } from './pos-refund';
3
4
  export { submitOrderRefund, RefundAnswerPendingError } from './submit-order-refund';
4
5
  export { refundableLines, priceRefund } from './refundable-lines';
@@ -0,0 +1,6 @@
1
+ /** The till's lead line for a refund parked needs_admin, by reason (TallyUI #1280). Only session_closed guarantees no money moved. */
2
+ export function refundNeedsAdminLine(reason: string): string {
3
+ return reason === 'session_closed'
4
+ ? 'Not paid. This refund needs a manager to finish it in the store admin.'
5
+ : 'Not finished. A manager must check this refund in the store admin before any money is handed over.';
6
+ }
@@ -1,91 +1,2 @@
1
- /**
2
- * Ports v2 calculate-refund.ts (calculateLineItemRefund, computeRemainingRefundQuantity).
3
- * Amounts follow ADR-080 amendment 2's cumulative-share rule.
4
- */
5
- import type { StoreOrderLine, OrderRefundLine } from '@tallyui/core';
6
- import { roundRatio } from '../tax/exact';
7
-
8
- /** The fields of an order line this needs; a StoreOrderLine fits. */
9
- export type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
10
- /** Earlier refund lines; negative quantities count by magnitude. */
11
- export interface EarlierRefund { lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>> }
12
-
13
- /** Remaining quantities and amounts, with earlier refund magnitudes capped at the line quantity. */
14
- export interface RefundableLine {
15
- orderLineId: string;
16
- refundedQuantity: number;
17
- refundableQuantity: number;
18
- netMinor: number;
19
- taxMinor: number;
20
- }
21
-
22
- /** A selected quantity's cumulative shares of net and tax, and their sum. */
23
- export interface PricedRefundLine {
24
- orderLineId: string; quantity: number; netMinor: number; taxMinor: number;
25
- totalMinor: number;
26
- }
27
-
28
- /** Payload-ready lines and their amounts; the caller adds shipping and adjustment to totalMinor. */
29
- export interface PricedRefund {
30
- /** Exactly orderLineId, quantity (>= 1), and restock. */
31
- lines: OrderRefundLine[];
32
- /** Amounts in the same order as lines. */
33
- priced: PricedRefundLine[];
34
- /** Requests cut to availability, including unknown lines cut to zero. */
35
- clamped: Array<{ orderLineId: string; requestedQuantity: number; quantity: number }>;
36
- netMinor: number; taxMinor: number; totalMinor: number;
37
- }
38
-
39
- /** Returns the quantities and amounts still refundable, in order-line order. */
40
- export function refundableLines(
41
- lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[],
42
- ): RefundableLine[] {
43
- const earlier = refunds.flatMap((refund) => refund.lines);
44
- for (const refund of earlier) {
45
- if (!Number.isSafeInteger(refund.quantity)) throw new RangeError('Earlier refund quantity must be a safe integer');
46
- }
47
- return lines.map((line) => {
48
- if (!Number.isSafeInteger(line.quantity) || line.quantity < 0
49
- || !Number.isSafeInteger(line.totalMinor) || !Number.isSafeInteger(line.taxMinor)) {
50
- throw new RangeError('Order line values must be safe integers and quantity non-negative');
51
- }
52
- const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id
53
- ? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
54
- const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => line.quantity === 0 ? 0
55
- : total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
56
- return {
57
- orderLineId: line.id, refundedQuantity, refundableQuantity: line.quantity - refundedQuantity, netMinor, taxMinor,
58
- };
59
- });
60
- }
61
-
62
- /** Prices requested quantities with cumulative shares, clamping them to what remains refundable. */
63
- export function priceRefund(
64
- lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[], request: readonly OrderRefundLine[],
65
- ): PricedRefund {
66
- const available = refundableLines(lines, refunds);
67
- const seen = new Set<string>();
68
- const result: PricedRefund = { lines: [], priced: [], clamped: [], netMinor: 0, taxMinor: 0, totalMinor: 0 };
69
- for (const { orderLineId, quantity: requestedQuantity, restock } of request) {
70
- if (!Number.isSafeInteger(requestedQuantity) || requestedQuantity < 0 || seen.has(orderLineId)) {
71
- throw new RangeError('Request quantities must be non-negative safe integers and line ids unique');
72
- }
73
- seen.add(orderLineId);
74
- const index = lines.findIndex((line) => line.id === orderLineId);
75
- const quantity = Math.min(requestedQuantity, available[index]?.refundableQuantity ?? 0);
76
- if (quantity < requestedQuantity) result.clamped.push({ orderLineId, requestedQuantity, quantity });
77
- if (quantity < 1) continue;
78
- const line = lines[index];
79
- const refundedQuantity = available[index].refundedQuantity;
80
- const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) =>
81
- Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), 'half_up'))
82
- - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
83
- const totalMinor = netMinor + taxMinor;
84
- result.lines.push({ orderLineId, quantity, restock });
85
- result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
86
- result.netMinor += netMinor;
87
- result.taxMinor += taxMinor;
88
- result.totalMinor += totalMinor;
89
- }
90
- return result;
91
- }
1
+ // Moved to @tallyui/core (arch 1a); re-exported so the till's names stay.
2
+ export { refundableLines, priceRefund, type RefundableOrderLine, type EarlierRefund, type RefundableLine, type PricedRefundLine, type PricedRefund } from '@tallyui/core';
@@ -5,11 +5,12 @@ import type { CommandTransport } from '../outbox/types';
5
5
  export type OrderRefundOutcome =
6
6
  | { kind: 'applied'; refund: OrderRefundResult; duplicate: boolean }
7
7
  | { kind: 'rejected'; error: CommandError }
8
+ | { kind: 'needs_admin'; reason: string; message: string }
8
9
  | { kind: 'unknown'; reason: string; retryAfterMs?: number }
9
10
  | { kind: 'refused'; status: number; reason: string }
10
11
  | { kind: 'unauthorized' };
11
12
 
12
- /** Online only, never queued (ADR-080). On unknown, resend the same envelope (same id).
13
+ /** Online only, never queued (ADR-080). On unknown or needs_admin, resend the same envelope (same id; Check again).
13
14
  * After rejected, a new attempt needs a new id. Refused and unauthorized mean the store did not take the batch. */
14
15
  export async function sendOrderRefund(
15
16
  transport: CommandTransport<OrderRefundEnvelope>, envelope: OrderRefundEnvelope,
@@ -21,6 +22,10 @@ export async function sendOrderRefund(
21
22
  return { kind: 'unknown', reason: 'transport_error' };
22
23
  }
23
24
  if (outcome.kind === 'retry') {
25
+ const { needsAdmin } = outcome;
26
+ if (needsAdmin?.id === envelope.id) {
27
+ return { kind: 'needs_admin', reason: needsAdmin.reason, message: needsAdmin.message };
28
+ }
24
29
  return {
25
30
  kind: 'unknown', reason: outcome.reason,
26
31
  ...(outcome.retryAfterMs !== undefined ? { retryAfterMs: outcome.retryAfterMs } : {}),
@@ -12,14 +12,36 @@ export class RefundAnswerPendingError extends Error {
12
12
  }
13
13
  }
14
14
 
15
+ // Calls for one refund envelope run one at a time in this process, because the till is single-instance (#1290).
16
+ const inFlight = new WeakMap<PosRefundCollection, Map<string, Promise<unknown>>>();
17
+
15
18
  /** Online only, never queued; the record is written before the send.
16
19
  * An applied record is final; a pending one is resent only with its own envelope
17
20
  * (ADR-080 amendment 1). */
18
- export async function submitOrderRefund({ refunds, transport, envelope, now = () => new Date().toISOString() }: {
21
+ export async function submitOrderRefund(args: {
22
+ refunds: PosRefundCollection; transport: CommandTransport<OrderRefundEnvelope>;
23
+ envelope: OrderRefundEnvelope; now?: () => string;
24
+ }): Promise<{ outcome: OrderRefundOutcome; record: PosRefund }> {
25
+ const { refunds, envelope } = args;
26
+ let calls = inFlight.get(refunds);
27
+ if (!calls) { calls = new Map(); inFlight.set(refunds, calls); }
28
+ const key = `${envelope.payload.clientRefundId} ${envelope.id}`;
29
+ const run = (calls.get(key) ?? Promise.resolve()).catch(() => undefined).then(() => submitOnce(args));
30
+ calls.set(key, run);
31
+ try {
32
+ return await run;
33
+ } finally {
34
+ if (calls.get(key) === run) calls.delete(key);
35
+ }
36
+ }
37
+
38
+ async function submitOnce({ refunds, transport, envelope, now = () => new Date().toISOString() }: {
19
39
  refunds: PosRefundCollection; transport: CommandTransport<OrderRefundEnvelope>;
20
40
  envelope: OrderRefundEnvelope; now?: () => string;
21
41
  }): Promise<{ outcome: OrderRefundOutcome; record: PosRefund }> {
22
42
  const id = envelope.payload.clientRefundId;
43
+ // The record may already be held by the store unless this call wrote its pending attempt (#1285).
44
+ let mayBeHeld = true;
23
45
  let doc = await refunds.findOne(id).exec();
24
46
  if (!doc) {
25
47
  const at = now();
@@ -29,6 +51,7 @@ export async function submitOrderRefund({ refunds, transport, envelope, now = ()
29
51
  id, commandId: envelope.id, orderId, sessionId, registerId, envelope,
30
52
  status: 'pending', createdAt: at, updatedAt: at,
31
53
  });
54
+ mayBeHeld = false;
32
55
  } catch (error) {
33
56
  if (!(error instanceof RxError) || error.code !== 'CONFLICT') throw error;
34
57
  doc = (await refunds.findOne(id).exec())!;
@@ -50,16 +73,20 @@ export async function submitOrderRefund({ refunds, transport, envelope, now = ()
50
73
  }
51
74
  if (record.status === 'unsent' && record.commandId === envelope.id) {
52
75
  doc = await doc.incrementalModify((stored) => {
76
+ mayBeHeld = true;
53
77
  if (stored.status !== 'unsent' || stored.commandId !== envelope.id) return stored;
54
78
  const { error, ...rest } = stored;
79
+ mayBeHeld = false;
55
80
  return { ...rest, status: 'pending', updatedAt: now() };
56
81
  });
57
82
  record = doc.toJSON() as PosRefund;
58
83
  continue;
59
84
  }
60
85
  doc = await doc.incrementalModify((stored) => {
86
+ mayBeHeld = true;
61
87
  if (stored.status !== 'rejected' && stored.status !== 'unsent') return stored;
62
88
  const { result, duplicate, error, ...rest } = stored;
89
+ mayBeHeld = false;
63
90
  return { ...rest, commandId: envelope.id, envelope, status: 'pending', updatedAt: now() };
64
91
  });
65
92
  record = doc.toJSON() as PosRefund;
@@ -69,7 +96,12 @@ export async function submitOrderRefund({ refunds, transport, envelope, now = ()
69
96
  if (outcome.kind !== 'unknown') {
70
97
  doc = await doc.incrementalModify((stored) => {
71
98
  if (stored.status !== 'pending' || stored.commandId !== envelope.id) return stored;
99
+ if ((outcome.kind === 'refused' || outcome.kind === 'unauthorized') && (mayBeHeld || stored.error?.code === 'needs_admin')) return stored;
72
100
  const updatedAt = now();
101
+ if (outcome.kind === 'needs_admin') {
102
+ return { ...stored, error: { code: 'needs_admin', message: outcome.message,
103
+ data: { reason: outcome.reason, at: updatedAt } }, updatedAt };
104
+ }
73
105
  if (outcome.kind === 'applied') {
74
106
  const { error, ...rest } = stored;
75
107
  return { ...rest, status: 'applied', result: outcome.refund, duplicate: outcome.duplicate, updatedAt };
@@ -0,0 +1,15 @@
1
+ import type * as store from './session-store';
2
+
3
+ // The close in flight per register, which a second close joins; its listeners re-render `closing`.
4
+ export const closingByRegister = new Map<string, ReturnType<typeof store.writeClosure>>();
5
+ const closingListeners = new Set<() => void>();
6
+ export const notifyClosing = () => closingListeners.forEach((listener) => listener());
7
+ export const subscribeClosing = (listener: () => void) => {
8
+ closingListeners.add(listener);
9
+ return () => { closingListeners.delete(listener); };
10
+ };
11
+
12
+ /** A `closeSession` for this register is in flight, in any hook instance. */
13
+ export function isRegisterClosing(registerId: string): boolean {
14
+ return closingByRegister.has(registerId);
15
+ }
@@ -14,6 +14,7 @@
14
14
  * string id (not WCPOS's numeric one).
15
15
  */
16
16
  import { minorUnitDigits } from '@tallyui/core';
17
+ import { closureFigures } from './closure-figures';
17
18
  import { ENGLISH_CLOSURE_LABELS } from './document-labels';
18
19
  import { minorToDecimal, formatDecimalMoney } from './money';
19
20
  import type { Closure, RegisterSession } from './schemas';
@@ -102,7 +103,9 @@ function decimalizeBreakdowns(breakdowns: Values, exponent: number): Values {
102
103
  )
103
104
  );
104
105
  };
105
- const openingFloat = breakdowns.opening_float as Values | undefined;
106
+ // The float's figures through closureFigures; an unknown one stays `null`, as writeClosure writes it.
107
+ const float = closureFigures({ breakdowns }).openingFloat;
108
+ const decOrNull = (m: number | undefined) => (m === undefined ? null : minorToDecimal(m, exponent));
106
109
  return {
107
110
  ...breakdowns,
108
111
  ...(breakdowns.payment_methods
@@ -111,17 +114,19 @@ function decimalizeBreakdowns(breakdowns: Values, exponent: number): Values {
111
114
  ...(breakdowns.tax_rates
112
115
  ? { tax_rates: group('tax_rates', [['net_minor', 'net'], ['tax_minor', 'tax'], ['gross_minor', 'gross']]) }
113
116
  : {}),
114
- ...(openingFloat
117
+ ...(breakdowns.opening_float
115
118
  ? {
116
119
  opening_float: {
117
- ...openingFloat, expected: dec(openingFloat.expected_minor), counted: dec(openingFloat.counted_minor),
118
- variance: dec(openingFloat.variance_minor),
120
+ expected_minor: float.expectedMinor ?? null, counted_minor: float.countedMinor ?? null,
121
+ variance_minor: float.varianceMinor ?? null, expected: decOrNull(float.expectedMinor),
122
+ counted: decOrNull(float.countedMinor), variance: decOrNull(float.varianceMinor),
119
123
  },
120
124
  }
121
125
  : {}),
122
126
  ...(breakdowns.movements
123
127
  ? { movements: (breakdowns.movements as BreakdownMovement[]).map((m) => ({ ...m, amount: dec(m.amountMinor) })) }
124
128
  : {}),
129
+ ...(breakdowns.cash_rounding_minor !== undefined ? { cash_rounding: dec(breakdowns.cash_rounding_minor) } : {}),
125
130
  };
126
131
  }
127
132
 
@@ -214,9 +219,12 @@ function envelope<R extends Values>(row: R, context: ClosureContext, xreport = f
214
219
  ...Object.fromEntries(
215
220
  ['payment_methods', 'tax_rates', 'movements'].map((key) => [`has_${key}`, Object.keys((breakdowns[key] as Values) ?? {}).length > 0]),
216
221
  ),
222
+ has_cash_rounding: breakdowns.cash_rounding !== undefined,
217
223
  ...(breakdowns.tax_rounding_mixed === true ? { tax_rounding_note: TAX_ROUNDING_MIXED_NOTE } : {}),
218
224
  ...(breakdowns.tax_includes_store_paid === true ? { tax_store_paid_note: TAX_STORE_PAID_NOTE } : {}),
219
225
  ...money(row, ['period_sales_total', 'period_refunds_total', 'perpetual_sales_total', 'perpetual_refunds_total', 'unsynced_total']),
226
+ ...(breakdowns.cash_rounding !== undefined
227
+ ? { cash_rounding: money({ name: context.i18n.cash_rounding, amount: breakdowns.cash_rounding }, ['amount']) } : {}),
220
228
  opened_at_gmt: row.opened_at,
221
229
  opened_by: breakdowns.opened_by ?? null,
222
230
  closed_by: row.closed_by ?? null,
@@ -237,7 +245,7 @@ function envelope<R extends Values>(row: R, context: ClosureContext, xreport = f
237
245
  type_label: context.i18n[String(m.type)] ?? m.type,
238
246
  voided: !!m.voided_by,
239
247
  })),
240
- cashiers: ((breakdowns.cashiers ?? []) as (Values | string)[]).map((c) => (typeof c === 'string' ? { id: c, name: c } : c)),
248
+ cashiers: closureFigures({ breakdowns }).cashiers,
241
249
  },
242
250
  },
243
251
  store: context.store,