@tallyui/pos 3.9.2 → 3.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ import type { RxCollection } from 'rxdb';
2
+ import { createOrderBuilder } from '../order/order-builder';
3
+ import { writeOrderDraft } from '../order/order-drafts';
4
+ import { readSession, type RegisterSessionCollection } from '../register/session-store';
5
+ import { readFresh } from '../rxdb';
6
+ import type { TaxContext } from '../tax/types';
7
+ import { customerRefusal } from './command';
8
+ import type { PosOrder } from './types';
9
+
10
+ export const REOPENABLE_CODES: readonly string[] = ['coupon_invalid', 'total_mismatch'];
11
+ export type ReopenRefusal = 'not_found' | 'not_rejected' | 'code_not_reopenable' | 'already_replaced' | 'session_closed';
12
+ export class ReopenRefusedOrderError extends Error {
13
+ constructor(readonly orderId: string, readonly reason: ReopenRefusal) {
14
+ super(`Cannot reopen order ${orderId}: ${reason}`);
15
+ this.name = 'ReopenRefusedOrderError';
16
+ }
17
+ }
18
+
19
+ export async function reopenRefusedOrder(orderId: string, deps: {
20
+ orders: RxCollection<PosOrder>;
21
+ drafts: RxCollection;
22
+ sessions: RegisterSessionCollection;
23
+ taxContext: TaxContext;
24
+ /** The product's tax class from the catalogue (ProductTraits.getTaxClass); undefined falls back to 'standard'. */
25
+ taxClassOf?: (productId: string, variantId?: string) => string | undefined;
26
+ now?: () => Date;
27
+ }): Promise<string> {
28
+ const [order] = await readFresh(deps.orders, { selector: { id: orderId } });
29
+ if (!order) throw new ReopenRefusedOrderError(orderId, 'not_found');
30
+ if (order.syncStatus !== 'rejected') throw new ReopenRefusedOrderError(orderId, 'not_rejected');
31
+ if (!REOPENABLE_CODES.includes(order.error?.code ?? '')) throw new ReopenRefusedOrderError(orderId, 'code_not_reopenable');
32
+ const successors = await readFresh(deps.orders, { selector: { saleId: orderId } });
33
+ if (successors.some((successor) => successor.id !== orderId)) throw new ReopenRefusedOrderError(orderId, 'already_replaced');
34
+ if (order.sessionId) {
35
+ const session = await readSession(deps.sessions, order.sessionId);
36
+ if (!session || session.status !== 'open') throw new ReopenRefusedOrderError(orderId, 'session_closed');
37
+ }
38
+ if (!await deps.drafts.findOne(orderId).exec()) {
39
+ const builder = createOrderBuilder({ currency: order.currency, taxContext: deps.taxContext, id: order.id });
40
+ const converted = order.lines.some((line) => line.taxInclusive !== undefined && line.taxInclusive !== order.pricesIncludeTax);
41
+ const display = order.display && !converted ? order.display : undefined;
42
+ for (const [i, line] of order.lines.entries()) {
43
+ const lineId = builder.addLine({
44
+ productId: line.productId, variantId: line.variantId, name: line.name, sku: line.sku,
45
+ unitPrice: { amount: line.unitPriceMinor, currency: order.currency, taxInclusive: line.taxInclusive },
46
+ ...(line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
47
+ ...(line.attributes !== undefined ? { attributes: line.attributes } : {}),
48
+ quantity: line.quantity,
49
+ taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm })),
50
+ ...(line.custom ? { custom: true, taxClass: line.custom.taxClass, taxStatus: line.custom.taxStatus }
51
+ : { taxClass: deps.taxClassOf?.(line.productId, line.variantId) ?? 'standard', taxStatus: line.taxStatus }),
52
+ });
53
+ if (display) {
54
+ for (const row of display.lines[i].discounts) builder.applyLineDiscount(lineId, {
55
+ type: 'fixed', value: row.amountMinor, ...(row.label !== undefined ? { label: row.label } : {}),
56
+ });
57
+ } else if (line.discountMinor > 0) {
58
+ builder.applyLineDiscount(lineId, { type: 'fixed', value: line.discountMinor, label: 'Discount' });
59
+ }
60
+ }
61
+ if (display && display.orderDiscountMinor > 0) {
62
+ builder.applyOrderDiscount({ type: 'fixed', value: display.orderDiscountMinor, label: 'Discount' });
63
+ }
64
+ for (const fee of order.fees ?? []) builder.addFee({
65
+ name: fee.name, amountMinor: fee.amountMinor,
66
+ ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
67
+ ...(fee.taxStatus !== undefined ? { taxStatus: fee.taxStatus } : {}),
68
+ });
69
+ for (const shipping of order.shipping ?? []) builder.addShipping({
70
+ name: shipping.name, amountMinor: shipping.amountMinor,
71
+ ...(shipping.taxClass !== undefined ? { taxClass: shipping.taxClass } : {}),
72
+ ...(shipping.taxStatus !== undefined ? { taxStatus: shipping.taxStatus } : {}),
73
+ ...(shipping.methodId !== undefined ? { methodId: shipping.methodId } : {}),
74
+ });
75
+ for (const payment of order.payments) builder.addPayment({
76
+ method: payment.method, amountMinor: payment.amountMinor,
77
+ ...(payment.reference !== undefined ? { reference: payment.reference } : {}),
78
+ });
79
+ if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
80
+ builder.setCustomer({ id: order.customer.id, name: order.customer.name,
81
+ ...(order.customer.email !== undefined ? { email: order.customer.email } : {}) });
82
+ }
83
+ const prefix = `Refused by the store: ${order.error!.message}`;
84
+ builder.setNote(prefix + (order.note ? '\n' + order.note : ''));
85
+ await writeOrderDraft(deps.drafts, builder.getSnapshot());
86
+ }
87
+ const document = await deps.orders.findOne(orderId).exec();
88
+ await document!.incrementalModify((data) => {
89
+ if (data.syncStatus === 'rejected' && !data.reopenedAt) {
90
+ data.reopenedAt = data.updatedAt = (deps.now?.() ?? new Date()).toISOString();
91
+ }
92
+ return data;
93
+ });
94
+ return orderId;
95
+ }
@@ -0,0 +1,12 @@
1
+ import type { PosOrder } from './types';
2
+
3
+ /** Only tells that a reopen was started: a UI hint with no accounting meaning. */
4
+ export function isReopened(order: Pick<PosOrder, 'syncStatus' | 'reopenedAt'>): boolean {
5
+ return order.syncStatus === 'rejected' && order.reopenedAt !== undefined;
6
+ }
7
+
8
+ /** Payments count on the successor, so the refused order counts nowhere (ADR-077 R5 amended). Only this list is considered. */
9
+ export function replacedOrderIds(orders: readonly Pick<PosOrder, 'id' | 'saleId' | 'syncStatus'>[]): Set<string> {
10
+ const predecessors = new Set(orders.filter((order) => order.saleId !== order.id).map((order) => order.saleId));
11
+ return new Set(orders.filter((order) => order.syncStatus === 'rejected' && predecessors.has(order.id)).map((order) => order.id));
12
+ }
@@ -23,21 +23,30 @@ import type { PosOrder } from './types';
23
23
  * Version 8 adds fees, shipping, custom lines (ADR-075) and the woocommerce tax rounding (ADR-076), and changes nothing else.
24
24
  * It also stores the WooCommerce 6dp net (`netMicros`) under the woocommerce rounding (ADR-076 amendment).
25
25
  * Its migration is the identity. It is one-way like version 7.
26
+ * Version 9 adds the order's `coupons` and the receipt's `display.coupons` (ADR-077 d2), and a line's `attributes` (#495)
27
+ * and `regularUnitPriceMinor` (ADR-077 d2), and `reopenedAt`: when a refused order was reopened as a parked sale (ADR-077 d4b), and lets `sentVersion` and `downgradedFrom` be 6 (order.create version 6, ADR-077 d4), and changes nothing else.
28
+ * `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them only at version 6.
29
+ * Its migration is the identity. It is one-way like version 8.
26
30
  */
27
31
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
28
- version: 8, primaryKey: 'id', type: 'object', additionalProperties: false,
32
+ version: 9, primaryKey: 'id', type: 'object', additionalProperties: false,
29
33
  properties: {
30
34
  id: { type: 'string', maxLength: 36 },
31
35
  saleId: { type: 'string', maxLength: 36 },
32
36
  commandId: { type: 'string', maxLength: 36 },
33
37
  createdAt: { type: 'string', maxLength: 40 },
34
38
  updatedAt: { type: 'string' },
39
+ reopenedAt: { type: 'string', maxLength: 40 },
35
40
  currency: { type: 'string' },
36
41
  pricesIncludeTax: { type: 'boolean' },
37
42
  subtotalMinor: { type: 'integer' }, discountMinor: { type: 'integer' },
38
43
  taxMinor: { type: 'integer' }, totalMinor: { type: 'integer' },
39
44
  syncStatus: { type: 'string', enum: ['pending', 'applied', 'rejected'], maxLength: 10 },
40
45
  note: { type: 'string' }, registerId: { type: 'string' }, sessionId: { type: 'string', maxLength: 36 }, cashierRef: { type: 'string' },
46
+ coupons: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
47
+ code: { type: 'string', minLength: 1, maxLength: 255 }, couponId: { type: 'string', minLength: 1, maxLength: 64 },
48
+ discountMinor: { type: 'integer', minimum: 0 }, discountTaxMinor: { type: 'integer', minimum: 0 },
49
+ }, required: ['code', 'couponId', 'discountMinor', 'discountTaxMinor'] } },
41
50
  lines: { type: 'array', items: {
42
51
  type: 'object', properties: {
43
52
  id: { type: 'string', maxLength: 36 }, productId: { type: 'string' }, variantId: { type: 'string' },
@@ -48,6 +57,8 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
48
57
  taxClass: { type: 'string', maxLength: 64 }, taxStatus: { type: 'string', enum: ['taxable', 'none'] },
49
58
  }, required: ['name', 'taxStatus'] },
50
59
  unitPriceMinor: { type: 'integer' }, discountMinor: { type: 'integer' }, netMinor: { type: 'integer' },
60
+ attributes: { type: 'object', additionalProperties: { type: 'string' } },
61
+ regularUnitPriceMinor: { type: 'integer' },
51
62
  netMicros: { type: 'string', pattern: '^-?[0-9]{1,24}$', maxLength: 25 },
52
63
  taxLines: { type: 'array', items: {
53
64
  type: 'object', properties: { code: { type: 'string' }, ratePpm: { type: 'integer' }, taxMicros: { type: 'string' } },
@@ -103,13 +114,16 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
103
114
  roundAtSubtotal: { type: 'boolean' },
104
115
  mode: { type: 'string', enum: ['half_away_from_zero', 'half_up'] },
105
116
  }, required: ['granularity'] },
106
- sentVersion: { type: 'integer', minimum: 1, maximum: 5 },
107
- downgradedFrom: { type: 'integer', minimum: 1, maximum: 5 },
117
+ sentVersion: { type: 'integer', minimum: 1, maximum: 6 },
118
+ downgradedFrom: { type: 'integer', minimum: 1, maximum: 6 },
108
119
  // The nested objects are closed too: loosening a schema later is free, tightening one costs a migration.
109
120
  display: { type: 'object', additionalProperties: false, properties: {
110
121
  currency: { type: 'string' }, exponent: { type: 'integer' }, taxInclusive: { type: 'boolean' },
111
122
  subtotalMinor: { type: 'integer' }, discountMinor: { type: 'integer' }, taxMinor: { type: 'integer' },
112
123
  totalMinor: { type: 'integer' }, orderDiscountMinor: { type: 'integer' },
124
+ coupons: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
125
+ code: { type: 'string', minLength: 1, maxLength: 255 }, amountMinor: { type: 'integer' },
126
+ }, required: ['code', 'amountMinor'] } },
113
127
  fees: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
114
128
  id: { type: 'string', maxLength: 36 }, name: { type: 'string', minLength: 1, maxLength: 255 }, amountMinor: { type: 'integer' },
115
129
  }, required: ['id', 'name', 'amountMinor'] } },
@@ -165,5 +179,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
165
179
  // it means no older sale is ever re-rounded (#287).
166
180
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
167
181
  return { schema: posOrderSchema,
168
- migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity } };
182
+ migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity } };
169
183
  }
@@ -15,6 +15,14 @@ export interface PosOrderServerFailures {
15
15
  isolated: boolean;
16
16
  }
17
17
 
18
+ /** A WooCommerce coupon on the stored order (ADR-077 d2): its figures are the order builder's coupon replay. */
19
+ export interface PosOrderCoupon {
20
+ code: string; // lower-case code
21
+ couponId: string; // the connector's coupon id, as a string
22
+ discountMinor: number; // the coupon's discount, ex tax, in integer minor units
23
+ discountTaxMinor: number; // its tax, in integer minor units
24
+ }
25
+
18
26
  export interface PosOrderLine {
19
27
  id: string;
20
28
  productId: string;
@@ -25,6 +33,10 @@ export interface PosOrderLine {
25
33
  sku: string;
26
34
  quantity: number;
27
35
  unitPriceMinor: number;
36
+ /** The chosen variation attributes, name to value (pos_orders v9, #495). */
37
+ attributes?: Record<string, string>;
38
+ /** The catalogue's regular unit price, in the line's own tax mode like `unitPriceMinor` (pos_orders v9, ADR-077 d2). */
39
+ regularUnitPriceMinor?: number;
28
40
  /** Line discounts plus the allocated order-discount share, in the line's own tax mode (ADR-062). */
29
41
  discountMinor: number;
30
42
  netMinor: number;
@@ -51,6 +63,8 @@ export interface PosOrder {
51
63
  currency: string;
52
64
  pricesIncludeTax: boolean;
53
65
  lines: PosOrderLine[];
66
+ /** pos_orders v9, ADR-077 d2; present only on a sale with coupons */
67
+ coupons?: PosOrderCoupon[];
54
68
  fees?: FeeLine[];
55
69
  shipping?: ShippingLine[];
56
70
  subtotalMinor: number;
@@ -76,9 +90,9 @@ export interface PosOrder {
76
90
  * The order.create version every attempt under this `commandId` goes out at: the outbox records it before the first
77
91
  * send, and lowers it only on a downgrade (ADR-065 amendment). Absent means not sent yet (or requeued).
78
92
  */
79
- sentVersion?: 1 | 2 | 3 | 4 | 5;
93
+ sentVersion?: 1 | 2 | 3 | 4 | 5 | 6;
80
94
  /** The version first tried, before the downgrade (the order's audit). */
81
- downgradedFrom?: 1 | 2 | 3 | 4 | 5;
95
+ downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6;
82
96
  /** ADR-065: the receipt's display figures, in integer minor units of `currency` at `exponent`. */
83
97
  display?: DisplayTotals & { currency: string; exponent: number };
84
98
  /** ADR-065: tax by rate, named as `taxLinesByRate` names them (`amountMinor` is the tax). */
@@ -97,4 +111,6 @@ export interface PosOrder {
97
111
  serverFailures?: PosOrderServerFailures;
98
112
  error?: CommandError;
99
113
  updatedAt: string;
114
+ /** When the till reopened this refused order as a parked sale (ADR-077 d4b). Needs attention hides it, and it stays as the record of the refusal. */
115
+ reopenedAt?: string;
100
116
  }
@@ -49,6 +49,7 @@ export function buildReceiptData(order: SentOrder, config: ReceiptConfig): Recei
49
49
  },
50
50
  lineItems: order.lineItems.map((li, index) => ({
51
51
  name: li.name,
52
+ ...(li.attributes && Object.keys(li.attributes).length ? { attributes: { ...li.attributes } } : {}),
52
53
  sku: li.sku,
53
54
  quantity: li.quantity,
54
55
  unitPriceMinor: li.unitPriceMinor,
@@ -15,6 +15,8 @@ export interface ReceiptFiscal {
15
15
 
16
16
  export interface ReceiptLineItem {
17
17
  name: string;
18
+ /** The variant's chosen options, name to value (#495); absent when none. */
19
+ attributes?: Record<string, string>;
18
20
  sku: string;
19
21
  quantity: number;
20
22
  unitPriceMinor: number;
@@ -13,6 +13,7 @@
13
13
  import type { RxCollection } from 'rxdb';
14
14
  import { DEFAULT_TAX_ROUNDING, taxLinesByRate } from '../tax/exact';
15
15
  import type { PosOrder } from '../pos-order/types';
16
+ import { replacedOrderIds } from '../pos-order/reopened';
16
17
  import type { PosRefund } from '../refund/pos-refund';
17
18
  import { readFresh } from '../rxdb';
18
19
  import { deriveExpected, refundAmounts, type LedgerRow } from './expected';
@@ -440,7 +441,7 @@ export async function voidMovement(
440
441
  * same snapshot and number, and its period reaches the perpetual totals exactly once.
441
442
  * Only a closed session (`closed` with `closed_at_gmt`) has a closure, and a closed session is
442
443
  * final, so its existing closure is returned as it was frozen. Orders the server rejected still
443
- * count in the drawer, because the cash was taken.
444
+ * count in the drawer, because the cash was taken, until a finalized successor carries their payments (ADR-077 R5 amended).
444
445
  * A refund still pending at close is not counted, and the Z lists it.
445
446
  */
446
447
  export async function writeClosure({
@@ -490,7 +491,8 @@ export async function writeClosure({
490
491
  });
491
492
  return existing;
492
493
  }
493
- const bound = orders.filter((order) => order.sessionId === session.id);
494
+ const replaced = replacedOrderIds(orders);
495
+ const bound = orders.filter((order) => order.sessionId === session.id && !replaced.has(order.id));
494
496
  const countedRefunds = (refunds ?? []).filter((refund) => refund.status === 'applied' && refund.sessionId === session.id);
495
497
  // Each payment is captured, and a cash payment's amount is already net of change.
496
498
  const rows: LedgerRow[] = bound.flatMap((order) =>
@@ -19,6 +19,7 @@ import { combineLatest, map, of, switchMap } from 'rxjs';
19
19
  import type { RxCollection } from 'rxdb';
20
20
  import type { RegisterSessionAlreadyOpenData, ServerCapabilities } from '@tallyui/core';
21
21
  import type { PosOrder } from '../pos-order/types';
22
+ import { replacedOrderIds } from '../pos-order/reopened';
22
23
  import type { PosRefund, PosRefundCollection } from '../refund/pos-refund';
23
24
  import { readFresh, watchFresh } from '../rxdb';
24
25
  import { deriveExpected, type LedgerRow } from './expected';
@@ -147,8 +148,8 @@ function currentSession(rows: RegisterSession[], closureRows: Closure[], reserva
147
148
  }
148
149
 
149
150
  /** A session's ledger rows, built from its orders' payments the way `writeClosure` builds them. */
150
- function ledgerRows(orders: readonly PosOrder[]): LedgerRow[] {
151
- return orders.flatMap((order) => order.payments.map((payment) => ({
151
+ function ledgerRows(orders: readonly PosOrder[], replaced = replacedOrderIds(orders)): LedgerRow[] {
152
+ return orders.filter((order) => !replaced.has(order.id)).flatMap((order) => order.payments.map((payment) => ({
152
153
  session_id: order.sessionId, kind: payment.method === 'cash' ? 'cash' : 'other', method_id: payment.method,
153
154
  status: 'captured', amountMinor: payment.amountMinor,
154
155
  })));
@@ -276,8 +277,9 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
276
277
  ? { sessionId: refusal.sessionId, openedAt: refusal.openedAt, openedBy: refusal.openedBy, deviceName: refusal.deviceName, takingOver: false } : undefined;
277
278
  const entries = data?.entries ?? [];
278
279
  const sales = data?.sales ?? [];
280
+ const replaced = replacedOrderIds(sales);
279
281
  const expected = session
280
- ? deriveExpected({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales), refunds: data?.refundRows ?? [] })
282
+ ? deriveExpected({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales, replaced), refunds: data?.refundRows ?? [] })
281
283
  : {};
282
284
  const now = new Date();
283
285
  const [hour, minute] = String(expectedCloseTime ?? '').split(':').map(Number);
@@ -311,7 +313,7 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
311
313
  needsUpgrade: data?.rows.some((row) => !store.isKnownSessionStatus(row.status)) ?? false,
312
314
  movements: entries,
313
315
  expected,
314
- salesCount: sales.length,
316
+ salesCount: sales.filter((order) => !replaced.has(order.id)).length,
315
317
  overdue,
316
318
  /** A `closeSession` for this register is in flight, in any hook instance: the session can already be stored `closed` while its closure isn't written yet. */
317
319
  closing,
package/src/sale/cart.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { resolvePrice, type ProductTraits } from '@tallyui/core';
2
2
  import type { OrderBuilder } from '../order';
3
+ import { regularUnitPriceMinor } from '../order/order-builder';
3
4
  import type { CatalogueEntry } from './catalogue';
4
5
 
5
6
  export class CartError extends Error {}
@@ -13,11 +14,14 @@ export function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry
13
14
  return existing.id;
14
15
  }
15
16
  const name = traits.getName(product) + (traits.getVariantCount(product) > 1 ? ` · ${variant.title}` : '');
16
- const unitPrice = resolvePrice(variant.prices, currency)?.current;
17
- if (!unitPrice) throw new CartError(`No ${currency} price for ${name}`);
17
+ const resolved = resolvePrice(variant.prices, currency);
18
+ if (!resolved) throw new CartError(`No ${currency} price for ${name}`);
19
+ const unitPrice = resolved.current, regularPrice = regularUnitPriceMinor(resolved);
18
20
  return builder.addLine({
19
21
  productId: traits.getId(product), variantId: variant.id, name,
22
+ ...(variant.options && Object.keys(variant.options).length ? { attributes: variant.options } : {}),
20
23
  sku: variant.sku ?? '', imageUrl: traits.getImageUrl?.(product), unitPrice,
24
+ ...(regularPrice !== undefined ? { regularUnitPriceMinor: regularPrice } : {}),
21
25
  taxClass: traits.getTaxClass?.(product, variant.id),
22
26
  ...(traits.getTaxStatus?.(product, variant.id) === 'none' ? { taxStatus: 'none' as const } : {}),
23
27
  });
@@ -0,0 +1,34 @@
1
+ import type { ServerCapabilities, StoreSettings, TaxRounding } from '@tallyui/core';
2
+ import type { Order, OrderBuilder } from '../order';
3
+
4
+ /** applyCoupon's refusal when the store cannot take coupons (ADR-077 R2, R3). */
5
+ export const COUPONS_UNSUPPORTED = "This store's plugin does not support coupons yet";
6
+
7
+ /** What a platform's discount codes see of the sale (ADR-077 amendment 3). */
8
+ export interface SaleDiscountState<Accepted> {
9
+ /** The sale as it stands. */
10
+ order: Order;
11
+ /** The codes on the sale, in the order applied, each with what `find` gave for it: a copy taken for this call, so codes accepted later do not appear in it. */
12
+ accepted: ReadonlyMap<string, Accepted>;
13
+ /** The categories the sale knows for each numeric product id; `beforeResume` may add to it. */
14
+ categories: Map<number, { id: number }[]>;
15
+ settings: Pick<StoreSettings, 'calcDiscountsSequentially'>;
16
+ }
17
+
18
+ /**
19
+ * A platform's discount codes, as `useSale` takes them (ADR-077 amendment 3; Paul, 2026-10-07: each platform its own way).
20
+ * The platform's side decides what a code is, which rules it must pass, how it reaches the order and how a refusal is worded;
21
+ * `useSale` normalizes the code, keeps the accepted codes in order, and refuses a code whose sale changed during `find`.
22
+ */
23
+ export interface SaleDiscountCodes<Accepted = unknown> {
24
+ /** Whether this store can take codes in this tax context; `useSale` also requires `capabilities.coupons` and `orderCreate >= 6`. */
25
+ supports(store: { capabilities?: ServerCapabilities; rounding?: TaxRounding }): boolean;
26
+ /** Looks up a trimmed, lower-case code: what was found, or the refusal to show. */
27
+ find(code: string, sale: SaleDiscountState<Accepted>): Promise<{ found: Accepted } | { refusal: string }>;
28
+ /** Checks a found code against the sale; the refusal to show, or null when it may be applied. */
29
+ check(code: string, found: Accepted, sale: SaleDiscountState<Accepted>): string | null;
30
+ /** Puts `sale.accepted`'s codes, in order, on the builder; throws an Error whose message is the refusal. */
31
+ apply(builder: OrderBuilder, sale: SaleDiscountState<Accepted>): void;
32
+ /** Called once, before a parked sale's codes are looked up again by `resume()`. */
33
+ beforeResume?(sale: SaleDiscountState<Accepted>): Promise<void>;
34
+ }
package/src/sale/index.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, saleLogger } from './use-sale';
2
2
  export type { SaleStage } from './use-sale';
3
+ export { COUPONS_UNSUPPORTED } from './discount-codes';
4
+ export type { SaleDiscountCodes, SaleDiscountState } from './discount-codes';
5
+ export * as woocommerceDiscountCodes from './woocommerce';
3
6
  export { addEntryToCart, CartError } from './cart';
4
7
  export { catalogueEntries, findEntryByCode, variantPriceLabel } from './catalogue';
5
8
  export type { CatalogueEntry } from './catalogue';
@@ -10,6 +10,8 @@ import { recordRegisterFact, stampSession, type RegisterSessionCollection } from
10
10
  import { createLogger } from '../logging';
11
11
  import type { CatalogueEntry } from './catalogue';
12
12
  import { addEntryToCart, CartError } from './cart';
13
+ import { productCategories } from '../product/categories';
14
+ import { COUPONS_UNSUPPORTED, type SaleDiscountCodes, type SaleDiscountState } from './discount-codes';
13
15
 
14
16
  /** Logs a throw from onSaleCompleted for a confirmed pending completion newSale() has abandoned (Continue): nothing else would ever surface it. */
15
17
  export const saleLogger = createLogger('sale');
@@ -29,8 +31,10 @@ export const SALE_SAVING = 'This sale is being saved. Retry to finish it.';
29
31
  export const HUNG_SAVE_CHECK_MS = 5000;
30
32
 
31
33
  /** Call under a `TaxProvider`: its tax context and the settings' currency price every sale. */
32
- export function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
34
+ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscountsSequentially'>, opts: {
33
35
  registerId: string; cashierRef: string; capabilities?: ServerCapabilities;
36
+ /** The platform's discount codes (ADR-077 amendment 3), e.g. woocommerceDiscountCodes.createDiscountCodes(source); without them, applyCoupon refuses with COUPONS_UNSUPPORTED. */
37
+ discountCodes?: SaleDiscountCodes<any>;
34
38
  /** Where `park()` keeps parked carts; create it with `orderDraftSchema` */
35
39
  drafts?: RxCollection;
36
40
  /**
@@ -63,6 +67,16 @@ export function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
63
67
  // The live builder, which every mutator reads (#301): newSale() sets it before setBuilder(next) renders, so a
64
68
  // call from an older render never reaches a discarded builder. The state only moves the `order` subscription.
65
69
  const builderNow = useRef(rendered);
70
+ const applied = useRef(new Map<string, unknown>());
71
+ const appliedWith = useRef<SaleDiscountCodes<any> | null>(null);
72
+ const categories = useRef(new Map<number, { id: number }[]>());
73
+ function discountState(order: Order, accepted: ReadonlyMap<string, unknown>): SaleDiscountState<unknown> {
74
+ return { order, accepted: new Map(accepted), categories: categories.current, settings: { calcDiscountsSequentially: settings.calcDiscountsSequentially } };
75
+ }
76
+ function codesFor(): SaleDiscountCodes<any> | null {
77
+ return opts.capabilities?.coupons === true && (opts.capabilities?.orderCreate ?? 1) >= 6 && opts.discountCodes
78
+ && opts.discountCodes.supports({ capabilities: opts.capabilities, rounding: taxContext.rounding }) ? opts.discountCodes : null;
79
+ }
66
80
  const [order, setOrder] = useState(() => rendered.getSnapshot());
67
81
  const [stage, setStage] = useState<SaleStage>({ kind: 'cart' });
68
82
  const [saleError, setError] = useState<string | null>(null);
@@ -126,6 +140,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
126
140
  const next = restored ?? createOrderBuilder({ currency: settings.currency, taxContext });
127
141
  if (customer !== null) next.setCustomer(customer);
128
142
  builderNow.current = next;
143
+ applied.current.clear();
144
+ appliedWith.current = null;
129
145
  setBuilder(next);
130
146
  setOrder(next.getSnapshot());
131
147
  setStage({ kind: 'cart' });
@@ -261,6 +277,11 @@ export function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
261
277
  const builder = builderNow.current;
262
278
  try {
263
279
  const known = new Set(builder.getSnapshot().lineItems.map((line) => line.id));
280
+ const productId = Number(traits.getId(entry.product));
281
+ if (Number.isSafeInteger(productId) && productId >= 0) {
282
+ const ids = productCategories(entry.product, traits).map(({ id }) => ({ id: Number(id) })).filter(({ id }) => Number.isSafeInteger(id));
283
+ if (ids.length) categories.current.set(productId, ids);
284
+ }
264
285
  const lineId = addEntryToCart(builder, entry, traits, madeWith.current.currency);
265
286
  // A new line whose id or v3 tax code finalize would refuse is taken off at once, in finalize's
266
287
  // message shape; finalize stays the backstop.
@@ -353,6 +374,37 @@ export function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
353
374
  return null;
354
375
  },
355
376
  removeDiscount(id: string) { if (!locked()) builderNow.current.removeDiscount(id); },
377
+ /** ADR-077: looks up, checks and applies a discount code through the platform's discount codes; resolves to the refusal to show, or null once applied. */
378
+ async applyCoupon(code: string): Promise<string | null> {
379
+ if (locked()) return SALE_SAVING;
380
+ const codes = codesFor();
381
+ if (!codes) return COUPONS_UNSUPPORTED;
382
+ const builder = builderNow.current, normalized = code.trim().toLowerCase();
383
+ if (!normalized) return 'Enter a coupon code';
384
+ const result = await codes.find(normalized, discountState(builder.getSnapshot(), applied.current));
385
+ if ('refusal' in result) return result.refusal;
386
+ if (locked()) return SALE_SAVING;
387
+ if (builderNow.current !== builder || stageNow.current.kind === 'receipt') return 'The sale changed while the coupon was being checked; apply it again';
388
+ const refusal = codes.check(normalized, result.found, discountState(builder.getSnapshot(), applied.current));
389
+ if (refusal !== null) return refusal;
390
+ const next = new Map([...applied.current, [normalized, result.found]]);
391
+ try { codes.apply(builder, discountState(builder.getSnapshot(), next)); }
392
+ catch (error) { if (error instanceof Error) return error.message; throw error; }
393
+ applied.current.set(normalized, result.found);
394
+ appliedWith.current = codes;
395
+ setError(null);
396
+ return null;
397
+ },
398
+ /** Removes an applied coupon; returns the refusal to show, or null once removed. */
399
+ removeCoupon(code: string): string | null {
400
+ if (locked()) return SALE_SAVING;
401
+ const normalized = code.trim().toLowerCase();
402
+ if (!applied.current.has(normalized)) return null;
403
+ const remaining = new Map(applied.current); remaining.delete(normalized);
404
+ appliedWith.current!.apply(builderNow.current, discountState(builderNow.current.getSnapshot(), remaining));
405
+ applied.current.delete(normalized);
406
+ return null;
407
+ },
356
408
  /** the picked customer reaches the server as order.create v3's customer.customerId */
357
409
  setCustomer(customer: CustomerSummary | null) {
358
410
  if (locked()) return;
@@ -511,13 +563,37 @@ export function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
511
563
  }
512
564
  }
513
565
  }
566
+ const kept = new Map<string, unknown>(), messages: string[] = [];
567
+ const codes = saved.coupons?.length ? codesFor() : null;
568
+ if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? 'line' : 'lines'} updated to today's price.`);
569
+ if (saved.coupons?.length) {
570
+ const supported = codes !== null;
571
+ if (supported) await codes.beforeResume?.(discountState(builder.getSnapshot(), new Map()));
572
+ for (const { code } of saved.coupons) {
573
+ let reason: string | null = supported ? null : COUPONS_UNSUPPORTED;
574
+ if (supported) {
575
+ const result = await codes.find(code, discountState(builder.getSnapshot(), kept));
576
+ if ('refusal' in result) reason = result.refusal;
577
+ else {
578
+ reason = codes.check(code, result.found, discountState(builder.getSnapshot(), kept));
579
+ if (reason === null) try { codes.apply(builder, discountState(builder.getSnapshot(), new Map([...kept, [code, result.found]]))); kept.set(code, result.found); }
580
+ catch (error) { if (error instanceof Error) reason = error.message; else throw error; }
581
+ }
582
+ }
583
+ if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
584
+ }
585
+ }
514
586
  await doc.remove();
515
587
  if (builderNow.current !== live || live.getSnapshot() !== liveSnapshot) {
516
588
  await writeOrderDraft(opts.drafts, saved);
517
589
  return 'The sale changed while it was being resumed; resume it again';
518
590
  }
519
591
  resetSale(null, builder);
520
- if (n > 0) setError(`Prices changed since this sale was parked: ${n} ${n === 1 ? 'line' : 'lines'} updated to today's price.`);
592
+ if (builderNow.current === builder) {
593
+ applied.current = kept;
594
+ appliedWith.current = kept.size ? codes : null;
595
+ }
596
+ if (messages.length) setError(messages.join(' '));
521
597
  return null;
522
598
  },
523
599
  /**
@@ -0,0 +1,40 @@
1
+ import type { RxCollection } from 'rxdb';
2
+ import type { PosOrder } from '../../pos-order/types';
3
+ import { APPLIED_USE_GRACE_MS } from './coupon-source';
4
+ import { saleLogger } from '../use-sale';
5
+
6
+ export function startCouponUsageRefetch(deps: {
7
+ orders: RxCollection<PosOrder>;
8
+ coupons: RxCollection;
9
+ enqueue: (entries: Array<{ key: string; local: unknown; refreshOnly: true }>) => void;
10
+ reSync: () => void;
11
+ now?: () => number;
12
+ }): { stop(): void } {
13
+ const now = deps.now ?? Date.now;
14
+ const handled = new Set<string>();
15
+ let stopped = false;
16
+ const subscription = deps.orders.find({ selector: { syncStatus: 'applied' } }).$.subscribe(async (orders) => {
17
+ const ids = new Set<number>();
18
+ for (const order of orders) {
19
+ if (!order.coupons?.length || handled.has(order.id)
20
+ || !(now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS)) continue;
21
+ handled.add(order.id);
22
+ for (const coupon of order.coupons) {
23
+ const id = Number(coupon.couponId);
24
+ if (Number.isInteger(id)) ids.add(id);
25
+ }
26
+ }
27
+ if (!ids.size) return;
28
+ try {
29
+ const docs = await deps.coupons.find({ selector: { id: { $in: [...ids] } } }).exec();
30
+ if (stopped || !docs.length) return;
31
+ deps.enqueue(docs.map((doc) => ({ key: doc.uuid, local: doc.toJSON(), refreshOnly: true })));
32
+ deps.reSync();
33
+ } catch (error) {
34
+ saleLogger.warn('coupon refetch failed',
35
+ { couponIds: [...ids], error: String(error) });
36
+ // A failed read stays handled; the store remains authoritative.
37
+ }
38
+ });
39
+ return { stop() { stopped = true; subscription.unsubscribe(); } };
40
+ }
@@ -0,0 +1,55 @@
1
+ import type { RxCollection } from 'rxdb';
2
+ import type { PosOrder } from '../../pos-order/types';
3
+ import type { SaleCoupon, SaleCouponSource } from './coupons';
4
+
5
+ /** How long an applied order still counts when no pull has rewritten its coupon: a refetch that finds the coupon unchanged writes nothing, and the store is authoritative (ADR-077 amendment 2). */
6
+ export const APPLIED_USE_GRACE_MS = 600_000;
7
+
8
+ export function createSaleCouponSource(deps: {
9
+ coupons: RxCollection;
10
+ products: RxCollection;
11
+ orders: RxCollection<PosOrder>;
12
+ now?: () => number;
13
+ }): SaleCouponSource {
14
+ const now = deps.now ?? Date.now;
15
+ return {
16
+ async find(code) {
17
+ let doc = await deps.coupons.findOne({ selector: { code } }).exec();
18
+ if (!doc) {
19
+ doc = (await deps.coupons.find().exec()).find((coupon) =>
20
+ typeof coupon.code === 'string' && coupon.code.toLowerCase() === code) ?? null;
21
+ }
22
+ if (!doc) return null;
23
+ const data = doc.toJSON(true);
24
+ if (!['percent', 'fixed_cart', 'fixed_product'].includes(data.discount_type)
25
+ || !Number.isInteger(data.id) || typeof data.amount !== 'string') return null;
26
+ const orders = await deps.orders.find({ selector: { syncStatus: { $in: ['pending', 'applied'] } } }).exec();
27
+ const counted = orders.filter((order) => order.coupons?.some((coupon) => coupon.code === code)
28
+ && (order.syncStatus === 'pending' || (Date.parse(order.updatedAt) > data._meta.lwt
29
+ && now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS)));
30
+ const usedBy = [...(data.used_by ?? [])];
31
+ for (const order of counted) {
32
+ // Mirrors the identifier validate.ts compares: wooCustomerId, else the email.
33
+ const id = Number(order.customer?.id);
34
+ const email = order.customer?.email;
35
+ if (Number.isSafeInteger(id) && id > 0) usedBy.push(String(id));
36
+ else if (typeof email === 'string' && email.length > 0) usedBy.push(email.toLowerCase());
37
+ }
38
+ const fields = [
39
+ 'limit_usage_to_x_items', 'product_ids', 'excluded_product_ids',
40
+ 'product_categories', 'excluded_product_categories', 'exclude_sale_items', 'individual_use',
41
+ 'date_expires_gmt', 'usage_limit', 'usage_limit_per_user', 'minimum_amount', 'maximum_amount', 'email_restrictions',
42
+ ];
43
+ return {
44
+ ...Object.fromEntries(fields.filter((field) => field in data).map((field) => [field, data[field]])) as Partial<SaleCoupon>,
45
+ discount_type: data.discount_type, amount: data.amount,
46
+ id: data.id, code, usage_count: (data.usage_count ?? 0) + counted.length, used_by: usedBy,
47
+ };
48
+ },
49
+ async productCategories(productIds) {
50
+ const products = await deps.products.find({ selector: { id: { $in: [...productIds] } } }).exec();
51
+ return new Map(products.map((product) => [product.id,
52
+ (product.categories ?? []).map(({ id }: { id: number }) => ({ id }))]));
53
+ },
54
+ };
55
+ }