@tallyui/pos 3.20.1 → 4.0.1

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 (117) hide show
  1. package/dist/index.d.ts +1008 -111
  2. package/dist/index.js +3158 -907
  3. package/package.json +6 -6
  4. package/src/app-settings/app-settings.ts +77 -0
  5. package/src/app-settings/index.ts +2 -0
  6. package/src/currency/currency-provider.tsx +5 -7
  7. package/src/currency/index.ts +1 -1
  8. package/src/customer/customer-patch.ts +70 -0
  9. package/src/customer-display/display-client.ts +11 -17
  10. package/src/customer-display/display-link.ts +10 -5
  11. package/src/customer-display/index.ts +3 -1
  12. package/src/customer-display/protocol.ts +1 -1
  13. package/src/customer-display/sale-display.ts +6 -8
  14. package/src/customer-display/snapshot-fallback.ts +14 -1
  15. package/src/customer-display/till-device.ts +62 -0
  16. package/src/customer-display/till-display-service.ts +44 -42
  17. package/src/customer-display/till-pairing.ts +20 -23
  18. package/src/customer-display/use-customer-display.ts +2 -1
  19. package/src/customer-display/use-till-pairing.ts +4 -4
  20. package/src/index.ts +37 -18
  21. package/src/order/allocate-order-discount.ts +5 -17
  22. package/src/order/apportion.ts +29 -0
  23. package/src/order/from-store-order.ts +115 -0
  24. package/src/order/index.ts +1 -0
  25. package/src/order/order-builder.ts +239 -52
  26. package/src/order/order-drafts.ts +46 -6
  27. package/src/order/order-manager.ts +2 -1
  28. package/src/order/tax-ids.ts +27 -0
  29. package/src/order/types.ts +61 -5
  30. package/src/order/woocommerce-tax.ts +9 -0
  31. package/src/outbox/index.ts +1 -1
  32. package/src/outbox/order-outbox.ts +138 -43
  33. package/src/outbox/register-outbox.ts +4 -3
  34. package/src/outbox/retry-delay.ts +8 -0
  35. package/src/outbox/use-order-outbox.ts +8 -2
  36. package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
  37. package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
  38. package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
  39. package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
  40. package/src/pos-order/attention-handled.ts +24 -0
  41. package/src/pos-order/command.ts +132 -12
  42. package/src/pos-order/extras-delivery.ts +14 -0
  43. package/src/pos-order/finalize.ts +138 -29
  44. package/src/pos-order/index.ts +7 -3
  45. package/src/pos-order/money-divergence.ts +19 -0
  46. package/src/pos-order/needs-attention.ts +9 -1
  47. package/src/pos-order/refund-due.ts +35 -0
  48. package/src/pos-order/reopen.ts +96 -12
  49. package/src/pos-order/schema.ts +35 -10
  50. package/src/pos-order/till-payments.ts +4 -0
  51. package/src/pos-order/types.ts +45 -6
  52. package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
  53. package/src/print/escpos/commands.ts +79 -0
  54. package/src/print/escpos/drawer.ts +25 -0
  55. package/src/print/escpos/encode.ts +1 -0
  56. package/src/print/escpos/index.ts +6 -1
  57. package/src/print/escpos/network-sinks.ts +130 -0
  58. package/src/print/escpos/render-escpos.ts +155 -0
  59. package/src/print/escpos/transport.ts +2 -1
  60. package/src/print/index.ts +5 -2
  61. package/src/print/resolve-printer.ts +46 -0
  62. package/src/print/types.ts +1 -1
  63. package/src/product/index.ts +2 -0
  64. package/src/product/terms.ts +42 -0
  65. package/src/product/tile-fields.ts +27 -0
  66. package/src/receipt/build-receipt-data.ts +12 -7
  67. package/src/receipt/carried-rows.ts +29 -0
  68. package/src/receipt/index.ts +1 -0
  69. package/src/receipt/reprint.ts +14 -8
  70. package/src/receipt/types.ts +3 -1
  71. package/src/receipt-template/default-templates.ts +3 -0
  72. package/src/receipt-template/template-data.ts +3 -0
  73. package/src/receipt-template/wcpos/build.ts +1 -0
  74. package/src/receipt-template/wcpos/format.ts +2 -2
  75. package/src/receipt-template/wcpos/from-orders.ts +6 -2
  76. package/src/receipt-template/wcpos/types.ts +5 -1
  77. package/src/register/closure-document.ts +42 -4
  78. package/src/register/closure-rows.ts +3 -2
  79. package/src/register/document-labels.ts +25 -0
  80. package/src/register/expected.ts +49 -10
  81. package/src/register/index.ts +5 -5
  82. package/src/register/money.ts +23 -0
  83. package/src/register/register-adoption.ts +6 -5
  84. package/src/register/register-commands.ts +4 -3
  85. package/src/register/schemas.ts +11 -3
  86. package/src/register/session-store.ts +44 -23
  87. package/src/register/settled-figures.ts +5 -19
  88. package/src/register/use-register-session.ts +18 -19
  89. package/src/reopen/index.ts +3 -0
  90. package/src/reopen/reopen-entry.ts +48 -0
  91. package/src/reopen/reopen-store-order.ts +78 -0
  92. package/src/reopen/send-order-reopen.ts +61 -0
  93. package/src/reports/adapters.ts +15 -7
  94. package/src/reports/sales-figures.ts +15 -1
  95. package/src/reports/types.ts +2 -0
  96. package/src/sale/cart.ts +4 -2
  97. package/src/sale/index.ts +1 -1
  98. package/src/sale/open-sales.ts +3 -0
  99. package/src/sale/use-sale.ts +388 -83
  100. package/src/sale/woocommerce/coupon-refetch.ts +1 -0
  101. package/src/sale/woocommerce/coupon-source.ts +4 -4
  102. package/src/sale/woocommerce/coupons.ts +6 -0
  103. package/src/sale/woocommerce/discount-codes.ts +1 -6
  104. package/src/scanner/analyze-trace.ts +86 -0
  105. package/src/scanner/device-scanner.ts +57 -0
  106. package/src/scanner/hid-scanner.ts +14 -41
  107. package/src/scanner/index.ts +2 -0
  108. package/src/scanner/serial-scanner.ts +15 -42
  109. package/src/scanner/use-barcode-scanner.ts +107 -5
  110. package/src/scanner/wedge-detector.ts +33 -15
  111. package/src/tax/exact.ts +1 -13
  112. package/src/tax/taxed-lines.ts +26 -0
  113. package/src/tender/index.ts +6 -1
  114. package/src/tender/split-units.ts +109 -0
  115. package/src/tender/tender-figures.ts +114 -0
  116. package/src/tender/tender-state.ts +105 -17
  117. package/src/currency/format-money-with.ts +0 -45
@@ -1,13 +1,16 @@
1
1
  import { BehaviorSubject, type Observable } from 'rxjs';
2
- import { resolvePrice, woocommerceTax, type woocommerceCoupons, type ProductTraits, type ResolvedPrice, type TaxRounding } from '@tallyui/core';
2
+ import { resolvePrice, woocommerceTax, type woocommerceCoupons, type OrderCreateMeta, type ProductTraits, type ResolvedPrice, type TaxRounding } from '@tallyui/core';
3
3
  import type { TaxContext } from '../tax/types';
4
- import { taxMicros, roundMicrosToMinor, roundedTaxByRate } from '../tax/exact';
4
+ import { taxMicros, roundMicrosToMinor, roundedTaxByRate, MICROS_PER_MINOR } from '../tax/exact';
5
5
  import { taxLogger } from '../tax/tax-provider';
6
- import { capturedMinor, canMoveLeg, legStatus, type PaymentLegStatus } from '../tender/payment-legs';
6
+ import { capturedMinor, canMoveLeg, countsTowardPaid, isInMotion, legStatus, type PaymentLegStatus } from '../tender/payment-legs';
7
7
  import { allocateOrderDiscount } from './allocate-order-discount';
8
+ import { apportionLargestRemainders } from './apportion';
8
9
  import { woocommerceLine, woocommerceTotals, woocommerceCouponReplay } from './woocommerce-tax';
9
10
  import type {
10
11
  Order,
12
+ OrderCoupon,
13
+ StoreOrderRef,
11
14
  LineItem,
12
15
  Discount,
13
16
  AppliedDiscount,
@@ -19,6 +22,7 @@ import type {
19
22
 
20
23
  /** splitLine's refusal: a fixed line discount copied onto every split line would multiply it. */
21
24
  export const SPLIT_FIXED_DISCOUNT = 'Remove the line’s fixed discount before splitting it';
25
+ export const LOCKED_PAYMENT = 'A payment the store already holds cannot be removed';
22
26
 
23
27
  /** Tax contexts already warned that per_rate_group_items fell back to per_order for inclusive lines (#287). */
24
28
  const perRateGroupWarned = new WeakSet<TaxContext>();
@@ -32,6 +36,12 @@ function roundHalfAway(n: number): number {
32
36
  return Math.sign(n) * Math.round(Math.abs(n));
33
37
  }
34
38
 
39
+ /** A line's exact tax-exclusive amount for store-priced coupon apportionment (#790). */
40
+ function exTaxMicros(line: LineItem, woo: boolean): bigint {
41
+ if (woo) return line.netMicros !== undefined ? BigInt(line.netMicros) : BigInt(line.netMinor) * MICROS_PER_MINOR;
42
+ return BigInt(line.netMinor) * MICROS_PER_MINOR - (line.taxInclusive ? BigInt(line.taxMicros) : 0n);
43
+ }
44
+
35
45
  /** The settlement totals of recalculated lines; the display figures derive from them (ADR-063). */
36
46
  function sumLines(lines: Pick<LineItem, 'netMinor' | 'taxMicros' | 'taxInclusive' | 'taxLines'>[], rounding?: TaxRounding): { subtotalMinor: number; taxMinor: number; totalMinor: number } {
37
47
  // per_line_items, per_rate_group_items (#287): total = Σ rounded nets + tax (order-level-tax-calculation-strategy.js:44-49, order.entity.js:88-89).
@@ -48,6 +58,14 @@ function sumLines(lines: Pick<LineItem, 'netMinor' | 'taxMicros' | 'taxInclusive
48
58
  return { subtotalMinor: linesTotal - taxMinor, taxMinor, totalMinor: Math.max(0, linesTotal) };
49
59
  }
50
60
 
61
+ /** A charge's amount in the order's tax mode, from its exact figures (vendurepos gap 2.10). */
62
+ export function chargeOrderModeMinor(charge: ChargeLine, pricesIncludeTax: boolean): number {
63
+ if ((charge.amountIncludesTax ?? pricesIncludeTax) === pricesIncludeTax) return charge.amountMinor;
64
+ if (charge.totalMinor !== undefined) return pricesIncludeTax ? charge.totalMinor : charge.netMinor; // WooCommerce
65
+ const taxMinor = roundMicrosToMinor(BigInt(charge.taxMicros)); // generic: netMinor is the amount as entered
66
+ return pricesIncludeTax ? charge.netMinor + taxMinor : charge.netMinor - taxMinor;
67
+ }
68
+
51
69
  /** An own-mode amount on a line, in the display mode, converted on its own at the line's rates (ADR-063). */
52
70
  function toDisplayMode(line: LineItem, amountMinor: number, displayInclusive: boolean): number {
53
71
  if (line.taxInclusive === displayInclusive) return amountMinor;
@@ -93,17 +111,36 @@ export interface StorePricedCoupon {
93
111
  /** Coupons priced by the store (TallyUI#709): the till applies the amounts and never computes a coupon's value. */
94
112
  export interface StorePricedCouponContext {
95
113
  kind: 'store-priced';
114
+ carried?: true;
96
115
  priced: ReadonlyMap<string, StorePricedCoupon>; // lower-case code to its priced amounts
97
116
  /** couponPricingBasis(order) of the order the store priced. */
98
117
  basis: string;
99
118
  }
100
119
 
120
+ /** A parked order's coupons, display coupon rows and post-coupon line figures, kept on a paid resume (ADR-077 d3, amended
121
+ * 2026-11-19). They apply only while one of the parked live legs is live on the parked lines; else no figures, and the order is stale. */
122
+ export interface KeptCouponContext {
123
+ kind: 'kept';
124
+ coupons: readonly OrderCoupon[];
125
+ displayRows: readonly number[];
126
+ lines: ReadonlyMap<string, Pick<LineItem, 'netMinor' | 'netMicros' | 'totalMinor' | 'taxLines' | 'taxMicros'>>;
127
+ basis: string; // couponPricingBasis of the order as restored
128
+ linesBasis: string; // the same with no customer: a customer change goes stale but keeps the figures (#1059 R1)
129
+ /** The ids of the live legs the figures were kept for: a leg added later never brings them back. */
130
+ legIds: readonly string[];
131
+ }
132
+
133
+ /** An unlocked leg that is captured or in motion: the sale's total must not move (useSale's liveLeg). */
134
+ export function isLiveLeg(payment: Payment): boolean {
135
+ return !payment.locked && (countsTowardPaid(payment) || isInMotion(payment));
136
+ }
137
+
101
138
  /** What a store-priced coupon's amounts depend on (TallyUI#709). A price is good only while this is unchanged. */
102
- export function couponPricingBasis(order: Order): string {
103
- // Inputs only, never a computed figure, so applying or removing coupons can't change it.
139
+ export function couponPricingBasis(order: Pick<Order, 'currency' | 'customer' | 'lineItems' | 'discounts'>): string {
140
+ // Inputs only, never a computed figure, so applying or removing coupons can't change it; tax rates are inputs, so a re-tax moves it (#742).
104
141
  return JSON.stringify([order.currency, order.customer?.id ?? null,
105
142
  order.lineItems.map((li) => [li.id, li.productId, li.variantId ?? null, li.quantity, li.unitPriceMinor, li.taxInclusive,
106
- li.taxClass ?? null, li.taxStatus ?? null, li.discounts.map((d) => [d.type, d.value])]),
143
+ li.taxClass ?? null, li.taxStatus ?? null, li.discounts.map((d) => [d.type, d.value]), li.taxLines.map((t) => [t.code ?? null, t.ratePpm])]),
107
144
  order.discounts.map((d) => [d.type, d.value])]);
108
145
  }
109
146
 
@@ -111,6 +148,9 @@ export interface OrderBuilderOptions {
111
148
  currency: string;
112
149
  taxContext: TaxContext;
113
150
  id?: string;
151
+ createdAt?: string; // a restored order's own (#742); absent is now
152
+ storeOrder?: StoreOrderRef;
153
+ afterClose?: Order['afterClose'];
114
154
  couponContext?: OrderCouponContext;
115
155
  }
116
156
 
@@ -133,24 +173,39 @@ export interface OrderBuilder {
133
173
  splitLine(lineId: string): string[];
134
174
  /** Sets a line's unit price (a till price edit), in minor units of the order's currency and the line's own tax mode; its discounts and tax are recomputed. */
135
175
  setUnitPrice(lineId: string, amountMinor: number): void;
176
+ /**
177
+ * Edits a line's name, SKU or regular unit price (ADR-092 6b/6c); `regularUnitPriceMinor: null` removes it. Name and SKU
178
+ * are trimmed and may not be empty. A catalogue line's first SKU edit keeps the SKU it was added with as `catalogueSku`.
179
+ * A custom line refuses a regular price (ADR-077 d3). The whole patch is checked first, so a patch that throws changes nothing.
180
+ */
181
+ updateLine(lineId: string, patch: { name?: string; sku?: string; regularUnitPriceMinor?: number | null }): void;
136
182
  removeItem(lineId: string): void;
183
+ /**
184
+ * Puts a removed line, fee or shipping line back as it was (#1095), at `index` clamped to its list's end, and
185
+ * recalculates it as an add does; never re-priced. Throws a RangeError when its id, or a line discount's, is on the order.
186
+ */
187
+ restoreItem(kind: 'line' | 'fee' | 'shipping', item: LineItem | ChargeLine, index: number): void;
137
188
  applyLineDiscount(lineId: string, discount: Discount): void;
138
189
  applyOrderDiscount(discount: Discount): void;
139
190
  removeDiscount(discountId: string): void;
140
- addPayment(payment: Omit<Payment, 'id'>): string;
191
+ addPayment(payment: Omit<Payment, 'id'> & { id?: string }): string;
141
192
  setPaymentStatus(paymentId: string, status: PaymentLegStatus): boolean;
142
193
  removePayment(paymentId: string): void;
143
194
  setCustomer(customer: CustomerSummary | null): void;
144
195
  setNote(note: string): void;
196
+ /** Replaces the order meta as given (`[]` removes it); `useSale().setMeta` checks keys before it calls this. */
197
+ setMeta(meta: OrderCreateMeta[]): void;
145
198
  /** Replaces the coupon codes with their trimmed, lower-case, deduplicated list; a given context replaces the builder's coupon context. */
146
- setCoupons(codes: readonly string[], context?: OrderCouponContext | StorePricedCouponContext): void;
199
+ setCoupons(codes: readonly string[], context?: OrderCouponContext | StorePricedCouponContext | KeptCouponContext): void;
147
200
  clear(): void;
148
201
  getSnapshot(): Order;
149
202
  }
150
203
 
151
204
  export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
152
205
  const { taxContext } = options;
153
- let couponContext: OrderCouponContext | StorePricedCouponContext | undefined = options.couponContext;
206
+ let storeOrder = options.storeOrder;
207
+ let afterClose = options.afterClose;
208
+ let couponContext: OrderCouponContext | StorePricedCouponContext | KeptCouponContext | undefined = options.couponContext;
154
209
  const currency = options.currency.toUpperCase();
155
210
  const orderId = options.id ?? uid();
156
211
  const woo = taxContext.rounding?.granularity === 'woocommerce' && taxContext.getTaxRates ? taxContext.rounding : undefined;
@@ -161,6 +216,9 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
161
216
  const item = wooLine(amount, line.taxClass, line.taxInclusive, line.taxStatus === 'none');
162
217
  return taxContext.pricesIncludeTax ? item.totalMinor : item.netMinor;
163
218
  };
219
+ /** A recalculated line's remaining amount in the store's mode: the display's remaining and a percent fee's basis. */
220
+ const storeModeMinor = (li: LineItem) =>
221
+ woo ? taxContext.pricesIncludeTax ? li.totalMinor! : li.netMinor : toDisplayMode(li, li.netMinor, taxContext.pricesIncludeTax);
164
222
 
165
223
  let lineItems: LineItem[] = [];
166
224
  let fees: FeeLine[] = [];
@@ -169,8 +227,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
169
227
  let payments: Payment[] = [];
170
228
  let customer: CustomerSummary | null = null;
171
229
  let note = '';
230
+ let meta: OrderCreateMeta[] = [];
172
231
  let couponCodes: string[] = [];
173
- const now = new Date().toISOString();
232
+ const now = options.createdAt ?? new Date().toISOString();
233
+ const idFor = (given?: string) => { // an input's id (a restore's, #742), refused when already on the order; absent mints one
234
+ if (given !== undefined && [...lineItems.flatMap((li) => [li, ...li.discounts]), ...fees, ...shipping, ...orderDiscounts, ...payments].some((x) => x.id === given))
235
+ throw new RangeError(`Id ${given} is already on the order`);
236
+ return given ?? uid();
237
+ };
174
238
 
175
239
  const subject = new BehaviorSubject<Order>(buildOrder());
176
240
 
@@ -179,12 +243,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
179
243
  const grossMinor = line.unitPriceMinor * line.quantity;
180
244
 
181
245
  // Each amount is what that discount actually removed, capped at what's left, matching buildOrder's order-discount path (ADR-062).
182
- let remaining = grossMinor;
183
- const recalcedDiscounts = line.discounts.map((d) => {
184
- const amountMinor = Math.min(remaining, computeDiscountAmount(d, d.type === 'percentage' ? grossMinor : remaining));
185
- remaining -= amountMinor;
186
- return { ...d, amountMinor };
187
- });
246
+ const recalcedDiscounts = capSequentially(line.discounts, grossMinor);
188
247
 
189
248
  // The order share never exceeds what the line discounts leave (allocateOrderDiscount's bound).
190
249
  const lineDiscountMinor = Math.min(grossMinor, recalcedDiscounts.reduce((sum, d) => sum + d.amountMinor, 0));
@@ -228,6 +287,17 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
228
287
  return Math.max(0, Math.min(discount.value, base));
229
288
  }
230
289
 
290
+ /** Applies each discount in turn: a percentage is computed on `base`, a fixed one on what is left,
291
+ * and each amount is capped at what the earlier ones leave (ADR-062). */
292
+ function capSequentially<D extends Discount>(discounts: readonly D[], base: number): (D & { amountMinor: number })[] {
293
+ let remaining = base;
294
+ return discounts.map((d) => {
295
+ const amountMinor = Math.min(remaining, computeDiscountAmount(d, d.type === 'percentage' ? base : remaining));
296
+ remaining -= amountMinor;
297
+ return { ...d, amountMinor };
298
+ });
299
+ }
300
+
231
301
  function buildOrder(): Order {
232
302
  // Order discounts are pre-tax (ADR-062). The base is the lines' pre-order-discount amounts, each in its
233
303
  // own mode (an inclusive line's shelf amount, an exclusive line's net). A percentage discount is additive:
@@ -237,27 +307,44 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
237
307
  // taxed on what is left.
238
308
  const lineAmounts = lineItems.map((li) => woo ? li.unitPriceMinor * li.quantity - li.discountMinor : li.netMinor);
239
309
  const base = lineAmounts.reduce((sum, amount) => sum + Math.max(0, amount), 0);
240
- let remaining = base;
241
- const recalcedOrderDiscounts = orderDiscounts.map((d) => {
242
- const amountMinor = Math.min(remaining, computeDiscountAmount(d, d.type === 'percentage' ? base : remaining));
243
- remaining -= amountMinor;
244
- return { ...d, amountMinor };
245
- });
310
+ const recalcedOrderDiscounts = capSequentially(orderDiscounts, base);
246
311
  const shares = allocateOrderDiscount(lineAmounts, recalcedOrderDiscounts.reduce((sum, d) => sum + d.amountMinor, 0));
247
312
  const displaySourceLines = lineItems.map((li, index) => recalculateLine(li, shares[index]));
248
- const store = couponContext && 'kind' in couponContext ? couponContext : undefined;
249
- const replay = woo && couponCodes.length && !store ? woocommerceCouponReplay(displaySourceLines, couponCodes,
313
+ const tagged = couponContext && 'kind' in couponContext ? couponContext : undefined;
314
+ const store = tagged?.kind === 'store-priced' ? tagged : undefined, kept = tagged?.kind === 'kept' ? tagged : undefined;
315
+ const replay = woo && couponCodes.length && !tagged ? woocommerceCouponReplay(displaySourceLines, couponCodes,
250
316
  couponContext as OrderCouponContext, taxContext.getTaxRates!, currency, woo.roundAtSubtotal, taxContext.pricesIncludeTax) : undefined;
251
- let lines = replay?.lines ?? displaySourceLines;
317
+ // Kept figures go only on the lines they were parked for, so a line edit never meets them (it goes stale instead).
318
+ const keptOn = kept && couponCodes.length > 0 && payments.some((p) => isLiveLeg(p) && kept.legIds.includes(p.id))
319
+ && couponPricingBasis({ currency, customer: null, lineItems, discounts: orderDiscounts }) === kept.linesBasis ? kept : undefined;
320
+ let lines = replay?.lines ?? (keptOn ? displaySourceLines.map((li) => {
321
+ const k = keptOn.lines.get(li.id);
322
+ return k ? { ...li, netMinor: k.netMinor, taxLines: k.taxLines, taxMicros: k.taxMicros,
323
+ ...(k.netMicros !== undefined ? { netMicros: k.netMicros } : {}), ...(k.totalMinor !== undefined ? { totalMinor: k.totalMinor } : {}) } : li;
324
+ }) : displaySourceLines);
325
+ if (fees.some((fee) => fee.percent !== undefined)) {
326
+ // A percent fee (v2 Add Fee "%", order-math cart-line.ts calculatePercentAmount) is basis × percent / 100 of the
327
+ // lines after coupons, in the store's mode. Unlike v2, which keeps and taxes the unrounded value, TallyUI rounds it
328
+ // once, half up, to integer minor units, then builds it exactly as a fixed fee of that amount. Store-priced coupons
329
+ // (#709): the lines as the loop below leaves them after its last code, since every settle there uses the fees.
330
+ const taken = new Map<string, number>();
331
+ if (store) for (const code of couponCodes)
332
+ for (const { lineId, amountMinor } of store.priced.get(code)?.lines ?? []) taken.set(lineId, (taken.get(lineId) ?? 0) + amountMinor);
333
+ const basisLines = taken.size ? lineItems.map((li, index) => taken.has(li.id) ? recalculateLine(li, shares[index], taken.get(li.id)) : displaySourceLines[index]) : lines;
334
+ const basis = BigInt(basisLines.reduce((sum, li) => sum + storeModeMinor(li), 0));
335
+ // Exact: the percent in ten-thousandths (validated to 4 places), so 100% is 1_000_000n.
336
+ fees = fees.map((fee) => fee.percent === undefined ? fee : recalculateCharge(fee.id, { ...fee,
337
+ amountMinor: Number((basis * BigInt(Math.round(fee.percent * 10000)) + 500000n) / 1000000n) }));
338
+ }
252
339
 
253
340
  if (woo) shipping = shipping.map((charge) => ({ ...charge, ...recalculateCharge(charge.id, charge, true) }));
254
341
  const charges = [...fees, ...shipping];
255
- const taxedCharges = charges.map((charge) => ({ ...charge, taxInclusive: taxContext.pricesIncludeTax,
342
+ const taxedCharges = charges.map((charge) => ({ ...charge, taxInclusive: charge.amountIncludesTax ?? taxContext.pricesIncludeTax,
256
343
  taxMicros: charge.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n).toString() }));
257
344
  const settle = (items: LineItem[]) => woo ? woocommerceTotals(items, fees, shipping, currency, woo.roundAtSubtotal, taxContext.pricesIncludeTax)
258
345
  : { ...sumLines([...items, ...taxedCharges], taxContext.rounding), subtotalMinor: sumLines(items, taxContext.rounding).subtotalMinor };
259
346
  let totals = settle(lines);
260
- let coupons = replay?.coupons;
347
+ let coupons = replay?.coupons ?? keptOn?.coupons.map((coupon) => ({ ...coupon }));
261
348
  const displayBasis = (t: typeof totals) => taxContext.pricesIncludeTax ? t.totalMinor : t.totalMinor - t.taxMinor;
262
349
  const storeDisplayRows: number[] = [];
263
350
  if (store && couponCodes.length) {
@@ -267,14 +354,28 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
267
354
  coupons = couponCodes.map((code) => {
268
355
  const priced = store.priced.get(code);
269
356
  for (const { lineId, amountMinor } of priced?.lines ?? []) taken.set(lineId, (taken.get(lineId) ?? 0) + amountMinor);
357
+ const beforeLines = lines;
270
358
  lines = lineItems.map((li, index) => taken.has(li.id) ? recalculateLine(li, shares[index], taken.get(li.id)) : displaySourceLines[index]);
271
359
  const before = totals;
272
360
  totals = settle(lines);
273
361
  storeDisplayRows.push(displayBasis(before) - displayBasis(totals));
274
362
  // A settlement subtotal is a difference of separately rounded sums (lines total less order-rounded tax), so a
275
363
  // rounding cent could in principle move it against a coupon; a coupon never shows as raising the price.
276
- return { code, couponId: priced?.couponId ?? '', discountMinor: Math.max(0, before.subtotalMinor - totals.subtotalMinor),
277
- discountTaxMinor: Math.max(0, before.taxMinor - totals.taxMinor) };
364
+ const coupon = { code, couponId: priced?.couponId ?? '', discountMinor: Math.max(0, before.subtotalMinor - totals.subtotalMinor),
365
+ discountTaxMinor: Math.max(0, before.taxMinor - totals.taxMinor), ...(store.carried ? { carried: true as const } : {}) };
366
+ const fallbackId = priced?.lines.find(({ lineId }) => lineItems.some((li) => li.id === lineId))?.lineId;
367
+ const fallbackIndex = lineItems.findIndex((li) => li.id === fallbackId);
368
+ if (fallbackIndex === -1) {
369
+ // No priced line remains: a non-zero coupon has no split, so step 3 sends the order below version 9.
370
+ return coupon.discountMinor === 0 && coupon.discountTaxMinor === 0 ? { ...coupon, lines: [] } : coupon;
371
+ }
372
+ const e = lines.map((line, i) => exTaxMicros(beforeLines[i], !!woo) - exTaxMicros(line, !!woo));
373
+ const t = lines.map((line, i) => BigInt(beforeLines[i].taxMicros) - BigInt(line.taxMicros));
374
+ const discountShares = apportionLargestRemainders(e, coupon.discountMinor, fallbackIndex);
375
+ const taxShares = apportionLargestRemainders(t, coupon.discountTaxMinor, fallbackIndex);
376
+ return { ...coupon, lines: lineItems.map((li, i) => ({ lineId: li.id, discountMinor: discountShares[i], discountTaxMinor: taxShares[i],
377
+ ...(store.carried ? { amountMinor: priced?.lines.find(({ lineId }) => lineId === li.id)?.amountMinor ?? 0 } : {}) }))
378
+ .filter((line) => line.discountMinor !== 0 || line.discountTaxMinor !== 0 || (line.amountMinor ?? 0) !== 0) };
278
379
  });
279
380
  }
280
381
  const { subtotalMinor, taxMinor, totalMinor } = totals;
@@ -298,7 +399,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
298
399
  discountId: d.id, ...(d.label !== undefined ? { label: d.label } : {}), amountMinor: displayAmount(li, d.amountMinor),
299
400
  }));
300
401
  const shareMinor = displayAmount(li, li.orderDiscountMinor);
301
- const remainingMinor = woo ? taxInclusive ? li.totalMinor! : li.netMinor : toDisplayMode(li, li.netMinor, taxInclusive);
402
+ const remainingMinor = storeModeMinor(li);
302
403
  const amountMinor = !woo && li.taxInclusive === taxInclusive && !returned ? li.unitPriceMinor * li.quantity
303
404
  : discounts.reduce((sum, d) => sum + d.amountMinor, remainingMinor + shareMinor);
304
405
  return { line: { lineId: li.id, amountMinor, discounts }, shareMinor, remainingMinor, returned };
@@ -308,12 +409,12 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
308
409
  // A store-priced row (#709) is the drop it caused in the figure the display subtotal is derived from: the
309
410
  // order-rounded tax over lines and charges can put discountMinor + discountTaxMinor a cent off it, and the display must add up.
310
411
  const displayCoupons = coupons?.map(({ code, discountMinor, discountTaxMinor }, k) =>
311
- ({ code, amountMinor: store ? storeDisplayRows[k] : discountMinor + (taxInclusive ? discountTaxMinor : 0) }));
412
+ ({ code, amountMinor: store ? storeDisplayRows[k] : keptOn ? keptOn.displayRows[k] : discountMinor + (taxInclusive ? discountTaxMinor : 0) }));
312
413
  const displayDiscount = displayLines.reduce(
313
414
  (sum, line) => line.discounts.reduce((lineSum, d) => lineSum + d.amountMinor, sum), orderDiscountDisplay)
314
415
  + (displayCoupons?.reduce((sum, row) => sum + row.amountMinor, 0) ?? 0);
315
- const chargeRows = (items: ChargeLine[]) => items.map(({ id, name, amountMinor, netMinor, totalMinor }) =>
316
- ({ id, name, amountMinor: woo ? taxInclusive ? totalMinor! : netMinor : amountMinor }));
416
+ const chargeRows = (items: ChargeLine[]) => items.map((charge) => ({ id: charge.id, name: charge.name,
417
+ amountMinor: woo ? taxInclusive ? charge.totalMinor! : charge.netMinor : chargeOrderModeMinor(charge, taxInclusive) }));
317
418
  const displayFees = chargeRows(fees), displayShipping = chargeRows(shipping);
318
419
  let displaySubtotal = (taxInclusive ? totalMinor : totalMinor - taxMinor) + displayDiscount
319
420
  - [...displayFees, ...displayShipping].reduce((sum, charge) => sum + charge.amountMinor, 0);
@@ -329,7 +430,26 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
329
430
  const converted = displaySourceLines.flatMap((li, index) => li.taxInclusive === taxInclusive ? [] : [index]);
330
431
  const conversions = converted.reduce((count, index) => count + [displaySourceLines[index].netMinor, displaySourceLines[index].orderDiscountMinor,
331
432
  ...displaySourceLines[index].discounts.map((d) => d.amountMinor)].filter((x) => x !== 0).length, 0);
332
- assertDisplayResidue(residue, converted.length, conversions);
433
+ if (woo) assertDisplayResidue(residue, converted.length, conversions);
434
+ else {
435
+ // The generic display charge row must equal what is stored and sent (core fiscal-figures.ts), so only a taxed converted charge takes residue, a cent each, the one whose own rounding moved against the residue first.
436
+ const rows = [...fees.map((charge, i) => [charge, displayFees[i]] as const), ...shipping.map((charge, i) => [charge, displayShipping[i]] as const)]
437
+ .flatMap(([charge, row]) => (charge.amountIncludesTax ?? taxInclusive) !== taxInclusive && row.amountMinor !== 0
438
+ && BigInt(charge.taxMicros) !== 0n ? [[charge, row] as const] : []);
439
+ assertDisplayResidue(residue, converted.length + rows.length, conversions + rows.length);
440
+ const t = Math.sign(residue);
441
+ // error × t: the row's rounding error against the residue, before it takes any (exact = the charge in the order's mode).
442
+ const takers = rows.map(([charge, row], k) => ({ row, k, e: (BigInt(row.amountMinor) * MICROS_PER_MINOR - BigInt(charge.netMinor) * MICROS_PER_MINOR
443
+ - (taxInclusive ? 1n : -1n) * BigInt(charge.taxMicros)) * BigInt(t) }));
444
+ if (residue !== 0) takers.sort((a, b) => a.e < b.e ? -1 : a.e > b.e ? 1 : b.k - a.k);
445
+ // Only a row whose rounding moved against the residue (e × t < 0) takes; the rest is left to the converted lines.
446
+ for (const { row, e } of takers) {
447
+ if (residue === 0 || e >= 0n) break;
448
+ row.amountMinor += t;
449
+ displaySubtotal -= t;
450
+ residue -= t;
451
+ }
452
+ }
333
453
  // Largest converted remaining first (ties to the earlier line). A negative residue takes a line down to its rows
334
454
  // and share at most, then moves on: six 2-cent inclusive lines can owe −3 with no line above 2. The spill is a
335
455
  // crash guard; it never fired in a 200k-cart fuzz. Negative-priced (return) lines convert as they are and never
@@ -369,6 +489,8 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
369
489
 
370
490
  const order: Order = {
371
491
  id: orderId,
492
+ ...(storeOrder !== undefined ? { storeOrder } : {}),
493
+ ...(afterClose !== undefined ? { afterClose } : {}),
372
494
  status: 'draft',
373
495
  lineItems: lines,
374
496
  ...(coupons ? { coupons } : {}),
@@ -378,6 +500,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
378
500
  payments: [...payments],
379
501
  customer,
380
502
  note,
503
+ ...(meta.length ? { meta: meta.map((m) => ({ ...m })) } : {}),
381
504
  subtotalMinor,
382
505
  discountMinor,
383
506
  taxMinor,
@@ -394,6 +517,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
394
517
  };
395
518
  // #709: the store's amounts still apply while stale, so the cart shows the last known prices; finalize refuses it.
396
519
  if (store && couponCodes.length && couponPricingBasis(order) !== store.basis) order.couponPricesStale = true;
520
+ if (kept && couponCodes.length && (!keptOn || couponPricingBasis(order) !== kept.basis)) order.couponPricesStale = true;
397
521
  return order;
398
522
  }
399
523
 
@@ -405,7 +529,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
405
529
  if (!Number.isInteger(input.amountMinor)) throw new RangeError('Amount must be integer minor units');
406
530
  if (input.amountMinor < 0) throw new RangeError('Amount must be >= 0');
407
531
  if (!input.name.trim()) throw new RangeError('Name must not be empty');
532
+ if (input.amountIncludesTax !== undefined && typeof input.amountIncludesTax !== 'boolean') throw new RangeError('amountIncludesTax must be a boolean');
533
+ if (shipping && input.percent !== undefined) throw new RangeError('Shipping cannot be a percentage');
534
+ if (input.percent !== undefined && !(Number.isFinite(input.percent) && input.percent > 0 && input.percent <= 100
535
+ && Math.round(input.percent * 10000) / 10000 === input.percent)) throw new RangeError('Percent must be > 0 and <= 100, with at most 4 decimal places');
408
536
  const taxStatus = input.taxStatus ?? 'taxable';
537
+ const inclusive = input.amountIncludesTax ?? taxContext.pricesIncludeTax;
538
+ const mode = { ...(input.amountIncludesTax !== undefined ? { amountIncludesTax: input.amountIncludesTax } : {}),
539
+ ...(input.percent !== undefined ? { percent: input.percent } : {}) };
409
540
  if (woo) {
410
541
  const taxClass = shipping
411
542
  ? taxContext.shippingTaxClass === undefined || taxContext.shippingTaxClass === 'inherit'
@@ -414,10 +545,12 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
414
545
  })), taxContext.taxClassSlugs ?? [])
415
546
  : taxContext.shippingTaxClass
416
547
  : input.taxClass;
417
- const untaxed = shipping ? taxClass === woocommerceTax.NO_SHIPPING_TAX : taxStatus === 'none';
418
- const line = wooLine(input.amountMinor, taxClass === woocommerceTax.NO_SHIPPING_TAX ? undefined : taxClass,
419
- taxContext.pricesIncludeTax, untaxed, shipping);
420
- return { id, name: input.name, amountMinor: input.amountMinor, taxClass: input.taxClass, taxStatus,
548
+ // A `none` shipping line is untaxed as WCPOS saves it (its _woocommerce_pos_data meta clears the store's shipping taxes).
549
+ const untaxed = shipping ? taxStatus === 'none' || taxClass === woocommerceTax.NO_SHIPPING_TAX : taxStatus === 'none';
550
+ const line = wooLine(input.amountMinor, taxClass === woocommerceTax.NO_SHIPPING_TAX || (shipping && untaxed) ? undefined : taxClass,
551
+ inclusive, untaxed, shipping);
552
+ return { id, name: input.name, amountMinor: input.amountMinor, taxClass: input.taxClass, taxStatus, ...mode,
553
+ ...(input.storeLineId !== undefined ? { storeLineId: input.storeLineId } : {}),
421
554
  ...line };
422
555
  }
423
556
  const code = taxContext.getTaxRateCode?.(input.taxClass);
@@ -426,9 +559,10 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
426
559
  taxLines: [{ ...(code !== undefined ? { code } : {}),
427
560
  ratePpm: taxStatus === 'none' ? 0 : taxContext.getTaxRatePpm(input.taxClass), taxMicros: '0' }],
428
561
  discounts: [], discountMinor: 0, orderDiscountMinor: 0, netMinor: 0, taxMicros: '0',
429
- taxInclusive: taxContext.pricesIncludeTax,
562
+ taxInclusive: inclusive,
430
563
  });
431
- return { id, name: input.name, amountMinor: input.amountMinor, taxClass: input.taxClass, taxStatus,
564
+ return { id, name: input.name, amountMinor: input.amountMinor, taxClass: input.taxClass, taxStatus, ...mode,
565
+ ...(input.storeLineId !== undefined ? { storeLineId: input.storeLineId } : {}),
432
566
  taxLines: line.taxLines, netMinor: line.netMinor, taxMicros: line.taxMicros };
433
567
  }
434
568
 
@@ -446,11 +580,15 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
446
580
  : input.taxStatus === 'none' ? [{ ...(code !== undefined ? { code } : {}), ratePpm: 0 }]
447
581
  : input.taxRates ?? [{ ...(code !== undefined ? { code } : {}), ratePpm: taxContext.getTaxRatePpm(input.taxClass) }];
448
582
  const taxInclusive = unitPrice.taxInclusive ?? taxContext.pricesIncludeTax;
583
+ const fromClass = !woo && input.taxRates === undefined;
449
584
 
450
585
  const existing = lineItems.find(
451
- (li) => !input.custom && !li.custom && li.productId === productId && li.variantId === variantId && li.taxInclusive === taxInclusive
586
+ (li) => input.storeLineId === undefined && !input.separate && !input.custom && !li.custom && li.productId === productId && li.variantId === variantId && li.taxInclusive === taxInclusive
452
587
  && (!woo || li.taxClass === input.taxClass && (li.taxStatus === 'none') === (input.taxStatus === 'none'))
588
+ && (li.taxFromClass === true) === fromClass
453
589
  && li.regularUnitPriceMinor === input.regularUnitPriceMinor && samePicks(li, input)
590
+ // An edited name or SKU never merges (ADR-092 6b), so a later scan adds a new line.
591
+ && li.name === input.name && li.sku === (input.sku ?? '')
454
592
  && li.unitPriceMinor === unitPrice.amount && li.taxLines.length === taxRates.length
455
593
  && li.taxLines.every((tax, index) => tax.code === taxRates[index].code && tax.ratePpm === taxRates[index].ratePpm),
456
594
  );
@@ -463,10 +601,13 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
463
601
  return existing.id;
464
602
  }
465
603
 
466
- const lineId = uid();
604
+ const lineId = idFor(input.id);
467
605
  const line: LineItem = {
468
606
  id: lineId,
607
+ ...(input.storeLineId !== undefined ? { storeLineId: input.storeLineId } : {}),
469
608
  ...((input.custom ? input.taxClass !== undefined : woo) ? { taxClass: input.taxClass } : {}),
609
+ // Outside woo, a line taxed from its class keeps the class and a marker, so a re-tax or resume re-derives its rates.
610
+ ...(fromClass ? { ...(input.taxClass !== undefined ? { taxClass: input.taxClass } : {}), taxFromClass: true as const } : {}),
470
611
  productId,
471
612
  ...(input.custom ? { custom: true as const } : {}),
472
613
  ...(input.taxStatus === 'none' ? { taxStatus: 'none' as const } : {}),
@@ -506,13 +647,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
506
647
  addLine,
507
648
 
508
649
  addFee(input) {
509
- const fee = recalculateCharge(uid(), input);
650
+ const fee = recalculateCharge(idFor(input.id), input);
510
651
  fees = [...fees, fee]; emit(); return fee.id;
511
652
  },
512
653
  updateFee(id, patch) {
513
654
  const fee = fees.find((entry) => entry.id === id);
514
655
  if (!fee) throw new Error(`Unknown fee ${id}`);
515
- const updated = recalculateCharge(id, { ...fee, ...patch });
656
+ const { storeLineId: _storeLineId, ...changes } = patch;
657
+ const updated = recalculateCharge(id, { ...fee, ...changes });
516
658
  fees = fees.map((entry) => entry.id === id ? updated : entry); emit();
517
659
  },
518
660
  removeFee(id) {
@@ -520,13 +662,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
520
662
  fees = fees.filter((entry) => entry.id !== id); emit();
521
663
  },
522
664
  addShipping(input) {
523
- const charge = { ...recalculateCharge(uid(), input, true), methodId: input.methodId };
665
+ const charge = { ...recalculateCharge(idFor(input.id), input, true), methodId: input.methodId };
524
666
  shipping = [...shipping, charge]; emit(); return charge.id;
525
667
  },
526
668
  updateShipping(id, patch) {
527
669
  const charge = shipping.find((entry) => entry.id === id);
528
670
  if (!charge) throw new Error(`Unknown shipping ${id}`);
529
- const input = { ...charge, ...patch };
671
+ const { storeLineId: _storeLineId, ...changes } = patch;
672
+ const input = { ...charge, ...changes };
530
673
  const updated = { ...recalculateCharge(id, input, true), methodId: input.methodId };
531
674
  shipping = shipping.map((entry) => entry.id === id ? updated : entry); emit();
532
675
  },
@@ -577,8 +720,9 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
577
720
  if (!source || source.quantity <= 1) return [];
578
721
  if (source.discounts.some((d) => d.type === 'fixed')) throw new RangeError(SPLIT_FIXED_DISCOUNT);
579
722
  // Not through addLine, whose merge would fold the copies back into one line.
723
+ const { storeLineId: _storeLineId, ...copy } = source;
580
724
  const copies = Array.from({ length: source.quantity - 1 }, () =>
581
- recalculateLine({ ...source, id: uid(), quantity: 1, discounts: source.discounts.map((d) => ({ ...d, id: uid() })) }));
725
+ recalculateLine({ ...copy, id: uid(), quantity: 1, discounts: source.discounts.map((d) => ({ ...d, id: uid() })) }));
582
726
  lineItems = [...lineItems.slice(0, index), recalculateLine({ ...source, quantity: 1 }), ...copies, ...lineItems.slice(index + 1)];
583
727
  emit();
584
728
  return copies.map((li) => li.id);
@@ -594,18 +738,48 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
594
738
  emit();
595
739
  },
596
740
 
741
+ updateLine(lineId, patch) {
742
+ const name = patch.name?.trim();
743
+ if (name === '') throw new RangeError('A line needs a name');
744
+ const sku = patch.sku?.trim();
745
+ if (sku === '') throw new RangeError('A line needs a SKU');
746
+ const regular = patch.regularUnitPriceMinor;
747
+ if (regular != null && (!Number.isInteger(regular) || regular < 0)) throw new RangeError('Regular price must be integer minor units >= 0');
748
+ const li = lineItems.find((line) => line.id === lineId);
749
+ if (!li) throw new Error(`Unknown line ${lineId}`);
750
+ // ADR-077 d3: a custom line has no regular price; addLine drops one too.
751
+ if (li.custom && regular != null) throw new RangeError('A custom line has no regular price');
752
+ const { regularUnitPriceMinor: _regular, ...unpriced } = li;
753
+ const changes = { ...(name !== undefined ? { name } : {}),
754
+ ...(sku !== undefined ? { sku, ...(!li.custom && li.catalogueSku === undefined ? { catalogueSku: li.sku } : {}) } : {}),
755
+ ...(regular != null ? { regularUnitPriceMinor: regular } : {}) };
756
+ lineItems = lineItems.map((line) => line.id === lineId ? recalculateLine({ ...(regular === null ? unpriced : li), ...changes }) : line);
757
+ emit();
758
+ },
759
+
597
760
  removeItem(lineId) {
598
761
  lineItems = lineItems.filter((li) => li.id !== lineId);
599
762
  emit();
600
763
  },
601
764
 
765
+ restoreItem(kind, item, index) {
766
+ for (const { id } of kind === 'line' ? [item, ...(item as LineItem).discounts] : [item]) idFor(id);
767
+ const at = <T>(list: T[], entry: T) => { const i = Math.min(index, list.length); return [...list.slice(0, i), entry, ...list.slice(i)]; };
768
+ if (kind === 'line') lineItems = at(lineItems, recalculateLine(item as LineItem));
769
+ else {
770
+ const charge = item as ShippingLine, recalculated = { ...charge, ...recalculateCharge(charge.id, charge, kind === 'shipping') };
771
+ if (kind === 'fee') fees = at(fees, recalculated); else shipping = at(shipping, recalculated);
772
+ }
773
+ emit();
774
+ },
775
+
602
776
  applyLineDiscount(lineId, discount) {
603
777
  lineItems = lineItems.map((li) => {
604
778
  if (li.id !== lineId) return li;
605
779
  const base = li.unitPriceMinor * li.quantity;
606
780
  const applied: AppliedDiscount = {
607
781
  ...discount,
608
- id: uid(),
782
+ id: idFor(discount.id),
609
783
  amountMinor: computeDiscountAmount(discount, base),
610
784
  };
611
785
  return recalculateLine({ ...li, discounts: [...li.discounts, applied] });
@@ -616,7 +790,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
616
790
  applyOrderDiscount(discount) {
617
791
  const applied: AppliedDiscount = {
618
792
  ...discount,
619
- id: uid(),
793
+ id: idFor(discount.id),
620
794
  amountMinor: computeDiscountAmount(discount, 0),
621
795
  };
622
796
  orderDiscounts = [...orderDiscounts, applied];
@@ -636,7 +810,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
636
810
  },
637
811
 
638
812
  addPayment(payment) {
639
- const id = uid();
813
+ const id = idFor(payment.id);
640
814
  payments = [...payments, { ...payment, id }];
641
815
  emit();
642
816
  return id;
@@ -644,13 +818,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
644
818
 
645
819
  setPaymentStatus(paymentId, status) {
646
820
  const payment = payments.find((p) => p.id === paymentId);
647
- if (!payment || !canMoveLeg(legStatus(payment), status)) return false;
821
+ if (!payment || payment.locked || !canMoveLeg(legStatus(payment), status)) return false;
648
822
  payments = payments.map((p) => p.id === paymentId ? { ...p, status } : p);
649
823
  emit();
650
824
  return true;
651
825
  },
652
826
 
653
827
  removePayment(paymentId) {
828
+ if (payments.some((p) => p.id === paymentId && p.locked)) throw new RangeError(LOCKED_PAYMENT);
654
829
  payments = payments.filter((p) => p.id !== paymentId);
655
830
  emit();
656
831
  },
@@ -665,11 +840,20 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
665
840
  emit();
666
841
  },
667
842
 
843
+ setMeta(next) {
844
+ meta = next.map((m) => ({ ...m }));
845
+ emit();
846
+ },
847
+
668
848
  setCoupons(codes, context) {
669
849
  const nextContext = context ?? couponContext;
670
850
  const normalized = [...new Set(codes.map((code) => code.trim().toLowerCase()))];
671
851
  if (normalized.length && !nextContext) throw new Error('Coupon context is required');
672
- for (const code of normalized) {
852
+ if (nextContext && 'kind' in nextContext && nextContext.kind === 'kept') {
853
+ if (normalized.join('\n') !== nextContext.coupons.map((coupon) => coupon.code).join('\n')) throw new RangeError('Kept coupons keep their parked codes');
854
+ const ids = [...nextContext.lines.keys(), ...nextContext.coupons.flatMap((coupon) => coupon.lines?.map((line) => line.lineId) ?? [])];
855
+ if (ids.some((id) => !lineItems.some((li) => li.id === id))) throw new RangeError('Kept coupons name a line not on the sale');
856
+ } else for (const code of normalized) {
673
857
  if (nextContext && 'kind' in nextContext) {
674
858
  const priced = nextContext.priced.get(code);
675
859
  if (!priced) throw new RangeError(`Unknown coupon ${code}`);
@@ -694,6 +878,8 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
694
878
  },
695
879
 
696
880
  clear() {
881
+ storeOrder = undefined;
882
+ afterClose = undefined;
697
883
  lineItems = [];
698
884
  fees = [];
699
885
  shipping = [];
@@ -701,6 +887,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
701
887
  payments = [];
702
888
  customer = null;
703
889
  note = '';
890
+ meta = [];
704
891
  couponCodes = [];
705
892
  if (couponContext && 'kind' in couponContext) couponContext = undefined;
706
893
  emit();