@tallyui/pos 4.1.0 → 5.0.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 (64) hide show
  1. package/dist/index.d.ts +584 -161
  2. package/dist/index.js +1908 -1077
  3. package/package.json +7 -6
  4. package/src/index.ts +17 -10
  5. package/src/order/index.ts +1 -0
  6. package/src/order/order-builder.ts +65 -21
  7. package/src/order/order-drafts.ts +78 -24
  8. package/src/order/taken-at.ts +5 -0
  9. package/src/order/types.ts +11 -2
  10. package/src/order/woocommerce-tax.ts +9 -12
  11. package/src/outbox/http-transport.ts +16 -1
  12. package/src/outbox/index.ts +2 -1
  13. package/src/outbox/needs-admin-reason.ts +10 -0
  14. package/src/outbox/order-outbox.ts +14 -5
  15. package/src/outbox/register-outbox.ts +4 -3
  16. package/src/outbox/types.ts +3 -1
  17. package/src/outbox/use-order-outbox.ts +7 -3
  18. package/src/pos-order/command.ts +3 -0
  19. package/src/pos-order/finalize.ts +11 -0
  20. package/src/pos-order/reopen.ts +11 -2
  21. package/src/pos-order/schema.ts +7 -2
  22. package/src/pos-order/types.ts +7 -1
  23. package/src/print/escpos/bluetooth-sink.ts +114 -0
  24. package/src/print/escpos/index.ts +4 -0
  25. package/src/print/escpos/transport.ts +3 -2
  26. package/src/print/escpos/usb-sink.ts +84 -0
  27. package/src/print/index.ts +2 -2
  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 +321 -135
  54. package/src/store-orders/index.ts +5 -0
  55. package/src/store-orders/sales-range-query.ts +18 -0
  56. package/src/store-orders/use-store-orders-in-range.ts +127 -0
  57. package/src/store-orders/use-store-refunds-in-range.ts +179 -0
  58. package/src/tax/exact.ts +2 -10
  59. package/src/tax/index.ts +1 -0
  60. package/src/tender/cash-rounding.ts +49 -6
  61. package/src/tender/index.ts +1 -1
  62. package/src/tender/payment-legs.ts +5 -0
  63. package/src/tender/tender-figures.ts +3 -1
  64. package/src/outbox/types.test-d.ts +0 -27
@@ -1,5 +1,5 @@
1
1
  import { minorUnitDigits, woocommerceTax, woocommerceCoupons } from '@tallyui/core';
2
- import type { TaxContext, WooRate } from '../tax/types';
2
+ import type { WooRate } from '../tax/types';
3
3
  import { roundMicrosToMinor } from '../tax/exact';
4
4
  import type { RateTaxLine } from '../tax/exact';
5
5
  import type { ChargeLine, LineItem, LineTaxLine, OrderCoupon } from './types';
@@ -34,13 +34,13 @@ function lineAmounts(net: number, taxes: { total: number }[], taxLines: LineTaxL
34
34
  taxMicros: taxLines.reduce((sum, rate) => sum + BigInt(rate.taxMicros), 0n).toString() };
35
35
  }
36
36
 
37
- /** Replays coupons on the manually discounted net lines; only integer money leaves this boundary (ADR-076). */
37
+ /** Replays coupons on the discounted net lines at per-line rates (a held line's parked rates, else today's); integer money only leaves (ADR-076). */
38
38
  export function woocommerceCouponReplay(lines: readonly LineItem[], codes: readonly string[], context: OrderCouponContext,
39
- getTaxRates: NonNullable<TaxContext['getTaxRates']>, currency: string, roundAtSubtotal: boolean,
39
+ ratesFor: (line: LineItem) => readonly WooRate[], currency: string, roundAtSubtotal: boolean,
40
40
  pricesIncludeTax: boolean): { lines: LineItem[]; coupons: OrderCoupon[] } {
41
41
  const dp = minorUnitDigits(currency), factor = 10 ** dp;
42
42
  const inputLines = lines.filter((line) => line.unitPriceMinor >= 0);
43
- const lineItems: woocommerceCoupons.LineItemInput[] = inputLines.map((line) => {
43
+ const lineItems: woocommerceCoupons.LineItemInput[] = inputLines.map((line, index) => {
44
44
  const productId = Number(line.productId), variationId = Number(line.variantId);
45
45
  const net = (Number(line.netMicros) / (factor * 1e6)).toFixed(6);
46
46
  const taxes = line.taxLines.map((tax) => {
@@ -51,22 +51,19 @@ export function woocommerceCouponReplay(lines: readonly LineItem[], codes: reado
51
51
  return {
52
52
  product_id: !line.custom && Number.isSafeInteger(productId) && productId >= 0 ? productId : 0,
53
53
  ...(Number.isSafeInteger(variationId) && variationId >= 0 ? { variation_id: variationId } : {}),
54
- quantity: line.quantity, tax_class: line.taxClass ?? '',
54
+ quantity: line.quantity, tax_class: `line-${index}`,
55
55
  ...(line.taxStatus === 'none' ? { tax_status: 'none' } : {}),
56
56
  subtotal: net, total: net, taxes, subtotal_tax: tax, total_tax: tax,
57
57
  };
58
58
  });
59
- const taxRates = new Map<string, woocommerceCoupons.RecalculateInput['taxRates'][number]>();
60
- for (const line of inputLines) for (const rate of getTaxRates(line.taxClass)) {
61
- const taxClass = woocommerceTax.normalizeTaxClass(line.taxClass);
62
- taxRates.set(JSON.stringify([rate.id, taxClass]), { id: rate.id, rate: rate.rate, compound: rate.compound,
63
- order: rate.priority, priority: rate.priority, class: taxClass });
64
- }
59
+ // Row 498: rates are keyed per line, so a held line's coupon re-prices at its parked rate beside a fresh line of the same class.
60
+ const taxRates = inputLines.flatMap((line, index) => ratesFor(line).map((rate) => ({ id: rate.id, rate: rate.rate,
61
+ compound: rate.compound, order: rate.priority, priority: rate.priority, class: `line-${index}` })));
65
62
  const result = woocommerceCoupons.recalculateCoupons({
66
63
  lineItems, couponLines: codes.map((code) => ({ code })),
67
64
  couponConfigs: new Map(codes.map((code) => [code, context.configs.get(code)!])),
68
65
  pricesIncludeTax, calcDiscountsSequentially: context.calcDiscountsSequentially,
69
- productCategories: new Map(context.productCategories), taxRates: [...taxRates.values()],
66
+ productCategories: new Map(context.productCategories), taxRates,
70
67
  taxRoundAtSubtotal: roundAtSubtotal, dp,
71
68
  });
72
69
  let index = 0;
@@ -1,5 +1,6 @@
1
- import { COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, isCommandBatchResponse, type AnyCommandEnvelope } from '@tallyui/core';
1
+ import { COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, NEEDS_ADMIN_MESSAGE_MAX, isCommandBatchResponse, type AnyCommandEnvelope } from '@tallyui/core';
2
2
  import type { CommandTransport } from './types';
3
+ import { NEEDS_ADMIN_REASON, NEEDS_ADMIN_RETRY_PREFIX } from './needs-admin-reason';
3
4
 
4
5
  // These HTTP statuses permanently refuse the entire command batch.
5
6
  const PERMANENT_STATUSES = new Set([400, 403, 413, 415, 422]);
@@ -48,6 +49,20 @@ export function createHttpCommandTransport(options: HttpTransportOptions): Comma
48
49
  } catch {}
49
50
  return { kind: 'refused', status: response.status, reason };
50
51
  }
52
+ if (response.status === 409) {
53
+ try {
54
+ const body = await response.json();
55
+ if (typeof body === 'object' && body !== null && body.code === 'needs_admin'
56
+ && typeof body.id === 'string' && batch.some((command) => command.id === body.id)
57
+ && typeof body.reason === 'string' && NEEDS_ADMIN_REASON.test(body.reason)
58
+ && typeof body.message === 'string') {
59
+ return { ...retry(`${NEEDS_ADMIN_RETRY_PREFIX}${body.reason}`), needsAdmin: {
60
+ id: body.id, reason: body.reason, message: body.message.slice(0, NEEDS_ADMIN_MESSAGE_MAX),
61
+ } };
62
+ }
63
+ } catch { /* An unreadable body is a plain 409: retried as before. */ }
64
+ return retry('status_409');
65
+ }
51
66
  if (response.status !== 200) return retry(`status_${response.status}`);
52
67
  let body: unknown;
53
68
  try {
@@ -6,7 +6,8 @@ export { createRegisterOutbox, isRegisterRequeueable } from './register-outbox';
6
6
  export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';
7
7
  export { useRegisterOutbox } from './use-register-outbox';
8
8
  export type { UseRegisterOutboxOptions, UseRegisterOutboxResult } from './use-register-outbox';
9
- export type { TransportOutcome, CommandTransport, OrderTransportContext, OutboxState } from './types';
9
+ export type { TransportOutcome, NeedsAdminAnswer, CommandTransport, OrderTransportContext, OutboxState } from './types';
10
+ export { needsAdminReasonOf, NEEDS_ADMIN_RETRY_PREFIX } from './needs-admin-reason';
10
11
  export { useOrderOutbox, outboxLogger } from './use-order-outbox';
11
12
  export type { UseOrderOutboxOptions, UseOrderOutboxResult } from './use-order-outbox';
12
13
  export { summarizeOutboxHealth, watchOutboxHealth } from './outbox-health';
@@ -0,0 +1,10 @@
1
+ /** The retry reason prefix the transport gives a 409 needs_admin answer; the server's reason follows it. */
2
+ export const NEEDS_ADMIN_RETRY_PREFIX = 'needs_admin:';
3
+ /** A needs_admin reason the till accepts: snake_case, 1–40 characters, so the prefixed retry reason fits the 64 the order keeps. */
4
+ export const NEEDS_ADMIN_REASON = /^[a-z][a-z0-9_]{0,39}$/;
5
+ /** The server's needs_admin reason inside an outbox retry reason, or undefined when the reason is anything else. */
6
+ export function needsAdminReasonOf(retryReason: string): string | undefined {
7
+ if (!retryReason.startsWith(NEEDS_ADMIN_RETRY_PREFIX)) return undefined;
8
+ const reason = retryReason.slice(NEEDS_ADMIN_RETRY_PREFIX.length);
9
+ return NEEDS_ADMIN_REASON.test(reason) ? reason : undefined;
10
+ }
@@ -87,6 +87,11 @@ export interface OrderOutbox {
87
87
  state$: Observable<OutboxState>;
88
88
  }
89
89
 
90
+ // The hook's record() awaits this so a recorded order is in state.pending before it resolves (vendurepos/app#470).
91
+ const stateRefreshers = new WeakMap<OrderOutbox, () => Promise<void>>();
92
+ /** Recounts and publishes the outbox's state; internal to @tallyui/pos (not exported from the package). */
93
+ export const refreshOutboxState = (outbox: OrderOutbox): Promise<void> => stateRefreshers.get(outbox)?.() ?? Promise.resolve();
94
+
90
95
  export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
91
96
  const { collection, transport, deviceId } = options;
92
97
  // A reopened sale goes as order.update, never order.create (ADR-090 decision 4).
@@ -223,9 +228,10 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
223
228
 
224
229
  // A failure the store answered (not offline). Returns undefined when the run goes on at once, or the
225
230
  // floor for the retry: the store's Retry-After, or an isolated order's own backoff.
226
- function serverFailed(orders: PosOrder[], alone: 'probe' | 'isolated' | undefined, reason: string, retryAfterMs?: number) {
231
+ function serverFailed(orders: PosOrder[], alone: 'probe' | 'isolated' | undefined, reason: string, retryAfterMs?: number, needsAdminId?: string) {
227
232
  const at = now();
228
- for (const { commandId } of orders) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq, reason });
233
+ for (const { commandId } of orders) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq,
234
+ reason: needsAdminId === undefined || commandId === needsAdminId ? reason : 'status_409' });
229
235
  const id = orders[0].commandId;
230
236
  if (alone === 'isolated') {
231
237
  isolate(id, reason, retryAfterMs);
@@ -234,7 +240,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
234
240
  if (runProgressed && retryAfterMs === undefined && reason !== 'status_429') return undefined;
235
241
  return Math.max(retryAfterMs ?? 0, isolated.get(id)!.nextAt - now());
236
242
  }
237
- if (alone === 'probe') walk?.failed.set(id, { orderId: orders[0].id, reason });
243
+ if (alone === 'probe') walk?.failed.set(id, { orderId: orders[0].id,
244
+ reason: needsAdminId === undefined || id === needsAdminId ? reason : 'status_409' });
238
245
  else {
239
246
  head = { id, count: head?.id === id ? head.count + 1 : 1 };
240
247
  if (head.count >= isolateAfter) walk ??= { failed: new Map() };
@@ -390,7 +397,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
390
397
  // no answer in time) is not offline: it counts like a 503 and never pauses a clock.
391
398
  for (const clock of clocks.values()) clock.pausedAt ??= now();
392
399
  walk = undefined;
393
- } else if ((floor = serverFailed(orders, alone, outcome.reason, outcome.retryAfterMs)) === undefined) continue;
400
+ } else if ((floor = serverFailed(orders, alone, outcome.reason, outcome.retryAfterMs, outcome.needsAdmin?.id)) === undefined) continue;
394
401
  return scheduleRetry(outcome.reason, floor);
395
402
  }
396
403
  if (outcome.kind === 'unauthorized') {
@@ -549,7 +556,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
549
556
  }
550
557
 
551
558
  updateState().catch(() => {});
552
- return {
559
+ const outbox: OrderOutbox = {
553
560
  state$,
554
561
  flush,
555
562
  async requeue(orderIds) {
@@ -633,4 +640,6 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
633
640
  state$.next({ ...state$.value, nextAttemptAt: undefined });
634
641
  },
635
642
  };
643
+ stateRefreshers.set(outbox, () => updateState());
644
+ return outbox;
636
645
  }
@@ -116,9 +116,10 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
116
116
  reason: stuck.reduce((latest, entry) => (entry[1].seq > latest[1].seq ? entry : latest))[1].reason,
117
117
  orders: stuck.map(([commandId, { since, firstFailedAt, reason }]) => ({ commandId, since, firstFailedAt, reason })) };
118
118
  }
119
- function serverFailed(commands: RegisterCommand[], reason: string) {
119
+ function serverFailed(commands: RegisterCommand[], reason: string, needsAdminId?: string) {
120
120
  const at = now();
121
- for (const { commandId } of commands) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq, reason });
121
+ for (const { commandId } of commands) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq,
122
+ reason: needsAdminId === undefined || commandId === needsAdminId ? reason : 'status_409' });
122
123
  }
123
124
 
124
125
  function isNonBlocking(command: RegisterCommand, abandoned: ReadonlySet<string>): boolean {
@@ -202,7 +203,7 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
202
203
  clock.pausedAt = undefined;
203
204
  }
204
205
  if (outcome.kind === 'retry') {
205
- if (outcome.reason !== 'network') serverFailed(commands, outcome.reason);
206
+ if (outcome.reason !== 'network') serverFailed(commands, outcome.reason, outcome.needsAdmin?.id);
206
207
  return scheduleRetry(outcome.reason, outcome.retryAfterMs);
207
208
  }
208
209
  if (outcome.kind === 'unauthorized') {
@@ -7,13 +7,15 @@ export interface OrderTransportContext {
7
7
  local: { orders: ReadonlyMap<string, PosOrder> };
8
8
  }
9
9
 
10
+ export type NeedsAdminAnswer = { id: string; reason: string; message: string };
11
+
10
12
  export type TransportOutcome =
11
13
  | { kind: 'results'; results: CommandResult[] }
12
14
  | { kind: 'unauthorized' }
13
15
  | { kind: 'refused'; status: number; reason: string }
14
16
  /** `reason` is `network` when the store could not be reached, `timeout` when a sent request got no answer in time,
15
17
  * else what the store answered (`status_503`, `bad_body`, ...). The order outbox counts every reason but `network`. */
16
- | { kind: 'retry'; reason: string; retryAfterMs?: number };
18
+ | { kind: 'retry'; reason: string; retryAfterMs?: number; needsAdmin?: NeedsAdminAnswer };
17
19
 
18
20
  export interface CommandTransport<E extends AnyCommandEnvelope = CommandEnvelope<OrderCreatePayload>> {
19
21
  send(batch: E[], context?: OrderTransportContext): Promise<TransportOutcome>;
@@ -4,7 +4,7 @@ import type { RxCollection, RxError } from 'rxdb';
4
4
  import { outboxLogger } from './logger';
5
5
  import { OrderContentMismatchError, sameSale, type PosOrder } from '../pos-order';
6
6
  import { watchFresh } from '../rxdb';
7
- import { createOrderOutbox } from './order-outbox';
7
+ import { createOrderOutbox, refreshOutboxState } from './order-outbox';
8
8
  import type { CommandTransport, OutboxState } from './types';
9
9
 
10
10
  const idle: OutboxState = { pending: 0, sending: false };
@@ -38,7 +38,7 @@ export interface UseOrderOutboxResult {
38
38
  /** The newest 50 orders, newest first; empty until the current store is ready. */
39
39
  recent: PosOrder[];
40
40
  /**
41
- * Stores a finalized order, then flushes. Throws the opening error, or "Orders are not ready.", before the store is ready.
41
+ * Stores a finalized order, then flushes. It resolves only once `state.pending` counts the order. Throws the opening error, or "Orders are not ready.", before the store is ready.
42
42
  * Recording an order whose `id` is already stored, not deleted, with the same money-bearing content (`sameSale`;
43
43
  * a retried `complete()`) counts as stored, never overwrites it, and still flushes, whatever the stored `commandId`
44
44
  * (a requeue mints a new one; the difference is logged at warn). Other content rejects with `OrderContentMismatchError`.
@@ -159,7 +159,11 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
159
159
  storedCommandId: inDb.commandId, recordedCommandId: posOrder.commandId });
160
160
  }
161
161
  }
162
- if (current.current === opened) void opened.outbox.flush();
162
+ if (current.current === opened) {
163
+ // Publish the stored order in state.pending before resolving: a caller that renders on resolve must see it (vendurepos/app#470).
164
+ try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
165
+ if (current.current === opened) void opened.outbox.flush(); // the store can switch or unmount during the refresh: a stopped outbox is never flushed again
166
+ }
163
167
  } finally {
164
168
  savesInFlight.current--;
165
169
  setSavesInFlightCount(savesInFlight.current);
@@ -246,6 +246,9 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
246
246
  subtotalMinor: order.subtotalMinor,
247
247
  ...(discountMinor > 0 ? { discountMinor } : {}),
248
248
  taxMinor: order.taxMinor, totalMinor: order.totalMinor,
249
+ // ADR-094: a rounded sale's entries ride at its content version; finalize refuses them unless the store declares cashRounding.
250
+ ...(order.cashRoundings?.length
251
+ ? { cashRoundings: order.cashRoundings.map(({ paymentId, minor }) => ({ paymentId, minor })) } : {}),
249
252
  ...(base >= 3 ? {
250
253
  display: { ...storedDisplay, lines: order.display!.lines.map(({ lineId, amountMinor, discounts }) => ({
251
254
  clientLineId: lineId, amountMinor, discounts,
@@ -2,6 +2,7 @@ import { minorUnitDigits, ORDER_LINE_SKU_MAX, ORDER_META_KEY_MAX, ORDER_NOTE_MAX
2
2
  type woocommerceTax } from '@tallyui/core';
3
3
  import { chargeOrderModeMinor } from '../order/order-builder';
4
4
  import { cleanTaxIds, TAX_IDS_INVALID } from '../order/tax-ids';
5
+ import { isTakenAt } from '../order/taken-at';
5
6
  import type { ChargeLine, Order, SentOrder } from '../order/types';
6
7
  import { legStatus } from '../tender/payment-legs';
7
8
  import { DEFAULT_TAX_ROUNDING, taxLinesByRate } from '../tax/exact';
@@ -208,6 +209,9 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
208
209
  if (order.lineItems.some((line) => line.anyAttributes?.length) && (options.capabilities?.orderCreate ?? 1) < 6) {
209
210
  throw new Error("finalize: picked options need the store to accept order.create version 6; update the store's TallyUI plugin");
210
211
  }
212
+ if (order.cashRoundings?.length && options.capabilities?.cashRounding !== true) {
213
+ throw new Error('finalize: cash rounding needs a store whose connector declares the cashRounding capability');
214
+ }
211
215
  if (!order.lineItems.length) throw new Error('finalize: no lines');
212
216
  // Defence in depth: the builder already clamps every discount to >= 0, so this should never fire.
213
217
  if (order.discountMinor < 0
@@ -304,6 +308,8 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
304
308
  ...(payment.tenderedMinor !== undefined ? { tenderedMinor: payment.tenderedMinor } : {}),
305
309
  ...(payment.changeMinor !== undefined ? { changeMinor: payment.changeMinor } : {}),
306
310
  ...(payment.reference !== undefined ? { reference: payment.reference } : {}),
311
+ ...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
312
+ ...(payment.sessionId !== undefined ? { sessionId: payment.sessionId } : {}),
307
313
  }));
308
314
  // A warning naming a payment the order no longer has is dropped and logged, never thrown: this runs at sale completion.
309
315
  const localWarnings = options.localWarnings?.flatMap((warning): PosOrderLocalWarning[] => {
@@ -375,6 +381,11 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
375
381
  return freezeSentForm({
376
382
  id, saleId: order.id, createdAt: afterClose?.createdAt ?? now, updatedAt: now, commandId: newId(), syncStatus: 'pending',
377
383
  currency: order.currency, pricesIncludeTax: order.pricesIncludeTax, lines, payments,
384
+ ...(order.cashRoundings?.length ? { cashRoundings: order.cashRoundings.map((entry) => {
385
+ const index = order.payments.findIndex((payment) => payment.id === entry.paymentId);
386
+ if (index === -1) throw new Error('finalize: a cash rounding names no payment on the order');
387
+ return { paymentId: payments[index].id, minor: entry.minor };
388
+ }) } : {}),
378
389
  ...(fees?.length ? { fees } : {}), ...(shipping?.length ? { shipping } : {}),
379
390
  subtotalMinor: order.subtotalMinor, discountMinor: order.discountMinor,
380
391
  taxMinor: order.taxMinor, totalMinor: order.totalMinor, taxRounding,
@@ -2,6 +2,7 @@ import type { ServerCapabilities } from '@tallyui/core';
2
2
  import type { RxCollection } from 'rxdb';
3
3
  import { couponPricingBasis, createOrderBuilder, type StorePricedCoupon } from '../order/order-builder';
4
4
  import { writeOrderDraft } from '../order/order-drafts';
5
+ import { isTakenAt } from '../order/taken-at';
5
6
  import type { Order } from '../order/types';
6
7
  import { readSession, type ClosureCollection, type RegisterSessionCollection } from '../register/session-store';
7
8
  import { readFresh } from '../rxdb';
@@ -123,12 +124,20 @@ export async function reopenRefusedOrder(orderId: string, deps: {
123
124
  ...(shipping.taxStatus !== undefined ? { taxStatus: shipping.taxStatus } : {}),
124
125
  ...(shipping.methodId !== undefined ? { methodId: shipping.methodId } : {}),
125
126
  });
126
- 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({
127
129
  // After close each leg keeps the refused order's id, so finalize knows it for the leg that closure counted.
128
130
  ...(afterClose ? { id: payment.id } : {}), method: payment.method, amountMinor: payment.amountMinor, reopened: true,
129
131
  ...(payment.reference !== undefined ? { reference: payment.reference } : {}),
130
132
  ...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
131
- });
133
+ ...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
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
+ }
132
141
  if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
133
142
  builder.setCustomer({ id: order.customer.id, name: order.customer.name,
134
143
  ...(order.customer.email !== undefined ? { email: order.customer.email } : {}),
@@ -38,6 +38,8 @@ import type { PosOrder } from './types';
38
38
  * Version 17 lets sentVersion and downgradedFrom be 11 (order.create version 11, ADR-086 d2 amended 2026-11-19), and changes nothing else. Its migration is the identity. It is one-way like version 16.
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
+ * 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.
41
43
  */
42
44
  /** A customer's address on an order (#722, OrderAddress): ten optional strings. */
43
45
  const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
@@ -47,7 +49,7 @@ const orderAddressSchema = { type: 'object', additionalProperties: false, proper
47
49
  } } as const;
48
50
 
49
51
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
50
- version: 19, primaryKey: 'id', type: 'object', additionalProperties: false,
52
+ version: 21, primaryKey: 'id', type: 'object', additionalProperties: false,
51
53
  properties: {
52
54
  id: { type: 'string', maxLength: 36 },
53
55
  saleId: { type: 'string', maxLength: 36 },
@@ -127,8 +129,11 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
127
129
  methodId: { type: 'string', minLength: 1, maxLength: 64 },
128
130
  storePaymentId: { type: 'string', minLength: 1, maxLength: 64 },
129
131
  amountMinor: { type: 'integer' }, tenderedMinor: { type: 'integer' }, changeMinor: { type: 'integer' }, reference: { type: 'string' },
132
+ takenAt: { type: 'string', maxLength: 40 },
130
133
  }, required: ['id', 'method', 'amountMinor'],
131
134
  } },
135
+ cashRoundings: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
136
+ paymentId: { type: 'string', maxLength: 36 }, minor: { type: 'integer' } }, required: ['paymentId', 'minor'] } },
132
137
  customer: { type: ['object', 'null'], properties: { id: { type: 'string' }, name: { type: 'string' }, email: { type: 'string' },
133
138
  billing: orderAddressSchema, shipping: orderAddressSchema, taxIds: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
134
139
  type: { type: 'string' }, value: { type: 'string' }, country: { type: 'string' }, label: { type: 'string' } }, required: ['type', 'value'] } } } },
@@ -218,5 +223,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
218
223
  // it means no older sale is ever re-rounded (#287).
219
224
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
220
225
  return { schema: posOrderSchema,
221
- 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 } };
226
+ migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity, 12: identity, 13: identity, 14: identity, 15: identity, 16: identity, 17: identity, 18: identity, 19: identity, 20: identity, 21: identity } };
222
227
  }
@@ -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
 
@@ -74,6 +74,10 @@ export interface PosOrderPayment {
74
74
  tenderedMinor?: number;
75
75
  changeMinor?: number;
76
76
  reference?: string;
77
+ /** When the till recorded the leg (`Payment.takenAt`); absent on store-held and older legs. */
78
+ takenAt?: string;
79
+ /** The session the leg was taken in (`Payment.sessionId`, S3); absent means the order's session. */
80
+ sessionId?: string;
77
81
  }
78
82
 
79
83
  export interface PosOrder {
@@ -105,6 +109,8 @@ export interface PosOrder {
105
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. */
106
110
  refundDueMinor?: number;
107
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[];
108
114
  /** `billing` and `shipping` (#722) are frozen copies of the customer's addresses, stored only with `taxAddress`. */
109
115
  customer: { id?: string; name?: string; email?: string; billing?: OrderAddress; shipping?: OrderAddress;
110
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. */
@@ -0,0 +1,114 @@
1
+ /**
2
+ * A Web Bluetooth sink for `createEscPosTransport`. The app supplies the `BluetoothDevice` from
3
+ * `navigator.bluetooth.requestDevice` (which needs a user gesture), with `BLUETOOTH_PRINT_SERVICES` in
4
+ * `optionalServices` so the sink may reach them, and keeps it between jobs. The sink holds no vendor code (ADR-084
5
+ * decision 2). It connects GATT if it is not connected and never disconnects: the app decides when to. The sink sets
6
+ * no timeout on a write.
7
+ */
8
+ import { PrintError } from '../types';
9
+ import type { EscPosSink } from './transport';
10
+
11
+ // Each print profile's GATT service and its write characteristic, in probe order. Source: WCPOS v2
12
+ // packages/printer/src/transport/ble-profiles.ts (found on a Netum NT-1809).
13
+ const PRINT_PROFILES = [
14
+ ['000018f0-0000-1000-8000-00805f9b34fb', '00002af1-0000-1000-8000-00805f9b34fb'],
15
+ ['0000ff00-0000-1000-8000-00805f9b34fb', '0000ff02-0000-1000-8000-00805f9b34fb'],
16
+ ['49535343-fe7d-4ae5-8fa9-9fafd205e455', '49535343-8841-43f4-a8d4-ecbe34729bb3'],
17
+ ['e7810a71-73ae-499d-8c15-faa9aef0c3f2', 'bef8d6c9-9c21-4c9e-b632-bd58c1009f9f'],
18
+ ] as const;
19
+
20
+ /** The print services the sink probes, in order. The app passes them to `requestDevice` as `optionalServices`. */
21
+ export const BLUETOOTH_PRINT_SERVICES: readonly string[] = PRINT_PROFILES.map(([service]) => service);
22
+
23
+ interface WebBluetoothCharacteristic {
24
+ readonly properties: { readonly write: boolean; readonly writeWithoutResponse: boolean };
25
+ writeValueWithResponse(value: Uint8Array<ArrayBuffer>): Promise<void>;
26
+ writeValueWithoutResponse(value: Uint8Array<ArrayBuffer>): Promise<void>;
27
+ }
28
+
29
+ interface WebBluetoothGattService {
30
+ getCharacteristic(characteristic: string): Promise<WebBluetoothCharacteristic>;
31
+ }
32
+
33
+ interface WebBluetoothGattServer {
34
+ readonly connected: boolean;
35
+ connect(): Promise<unknown>;
36
+ getPrimaryService(service: string): Promise<WebBluetoothGattService>;
37
+ }
38
+
39
+ /** Shaped on the DOM `BluetoothDevice`; e2e/web/webbluetooth-sink.spec.ts checks these member names in Chromium. */
40
+ export interface WebBluetoothDevice {
41
+ readonly name?: string | null;
42
+ readonly gatt?: WebBluetoothGattServer | null;
43
+ }
44
+
45
+ export interface WebBluetoothSinkOptions {
46
+ device: WebBluetoothDevice;
47
+ /** Bytes per GATT write: a positive integer, default 20. */
48
+ chunkSize?: number;
49
+ }
50
+
51
+ // v2's chunk size: 20 bytes is the payload of one write at BLE's default ATT MTU of 23 (3 bytes go to the header).
52
+ const BLE_CHUNK_SIZE = 20;
53
+ // v2's pause between chunks, found on a Netum NT-1809; the sink paces writes itself.
54
+ const BLE_CHUNK_PAUSE_MS = 20;
55
+ // v2's settle, found on a Netum NT-1809: the sink gives the printer 300 ms after the last chunk before resolving.
56
+ const BLE_SETTLE_MS = 300;
57
+
58
+ const pause = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
59
+
60
+ /**
61
+ * The first known print profile's characteristic that takes writes; each probe that rejects moves on to the next. A
62
+ * characteristic with `writeWithoutResponse` but not `write` is skipped, because the last chunk always goes with
63
+ * response.
64
+ */
65
+ async function printCharacteristic(gatt: WebBluetoothGattServer) {
66
+ for (const [service, characteristic] of PRINT_PROFILES) {
67
+ try {
68
+ const found = await (await gatt.getPrimaryService(service)).getCharacteristic(characteristic);
69
+ if (found.properties.write) return found;
70
+ } catch {
71
+ // The device lacks this service or characteristic: try the next profile.
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+
77
+ export function createWebBluetoothSink({ device, chunkSize = BLE_CHUNK_SIZE }: WebBluetoothSinkOptions): EscPosSink {
78
+ if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(`chunkSize must be a positive integer, not ${chunkSize}`);
79
+ const name = () => device.name || 'Bluetooth printer';
80
+ async function step<T>(label: string, run: () => Promise<T>): Promise<T> {
81
+ try {
82
+ return await run();
83
+ } catch (error) {
84
+ throw new PrintError('failed', `${name()}: ${label} failed: ${error instanceof Error ? error.message : error}`, { cause: error });
85
+ }
86
+ }
87
+ return {
88
+ async write(bytes) {
89
+ const { gatt } = device;
90
+ if (!gatt) throw new PrintError('unsupported', `${name()} has no GATT server to print to`);
91
+ // Read the link and probe on every write, so a write after the link drops reconnects and finds the service again.
92
+ if (!gatt.connected) await step('connect', () => gatt.connect());
93
+ const target = await printCharacteristic(gatt);
94
+ if (!target && !gatt.connected) {
95
+ throw new PrintError('failed', `${name()}: the link dropped while finding the print service; nothing was written`);
96
+ }
97
+ if (!target) {
98
+ throw new PrintError('unsupported', `${name()}: no known print service was found; nothing was written; is BLUETOOTH_PRINT_SERVICES in optionalServices?`);
99
+ }
100
+ for (let i = 0; i < bytes.length; i += chunkSize) {
101
+ // slice, not subarray: each write gets its own ArrayBuffer-backed copy.
102
+ const chunk = bytes.slice(i, i + chunkSize);
103
+ const last = i + chunkSize >= bytes.length;
104
+ const chunkLabel = `chunk ${i / chunkSize + 1}`;
105
+ if (last || !target.properties.writeWithoutResponse) {
106
+ await step(`writeValueWithResponse (${chunkLabel})`, () => target.writeValueWithResponse(chunk));
107
+ } else {
108
+ await step(`writeValueWithoutResponse (${chunkLabel})`, () => target.writeValueWithoutResponse(chunk));
109
+ }
110
+ await pause(last ? BLE_SETTLE_MS : BLE_CHUNK_PAUSE_MS);
111
+ }
112
+ },
113
+ };
114
+ }
@@ -7,6 +7,10 @@ export { createEscPosTransport } from './transport';
7
7
  export type { EscPosSink, EscPosTransportOptions } from './transport';
8
8
  export { createEpsonEposSink, createStarWebPrntSink, networkSinkFor } from './network-sinks';
9
9
  export type { NetworkSinkOptions } from './network-sinks';
10
+ export { createWebUsbSink } from './usb-sink';
11
+ export type { WebUsbDevice, WebUsbSinkOptions } from './usb-sink';
12
+ export { BLUETOOTH_PRINT_SERVICES, createWebBluetoothSink } from './bluetooth-sink';
13
+ export type { WebBluetoothDevice, WebBluetoothSinkOptions } from './bluetooth-sink';
10
14
  export { canOpenDrawer, openDrawerJob } from './drawer';
11
15
  export { renderEscpos, encodeThermalTemplate } from './render-escpos';
12
16
  export type { RenderEscposOptions } from './render-escpos';
@@ -6,9 +6,10 @@
6
6
  */
7
7
  import type { ReceiptTemplateOptions } from '../../receipt-template/template-data';
8
8
  import type { PrinterProfile } from '../printer-profiles';
9
- import { PrintError, type PrintJob, type PrintTransport } from '../types';
9
+ import { PrintError, toPrintError, type PrintJob, type PrintTransport } from '../types';
10
10
  import { encodeEscPos } from './encode';
11
11
 
12
+ /** Where the ESC/POS bytes go. A `write` that rejects with a `PrintError` keeps its code (`unsupported` for a device it cannot print to); any other rejection is a `failed` PrintError. */
12
13
  export interface EscPosSink {
13
14
  write(bytes: Uint8Array): Promise<void>;
14
15
  }
@@ -39,7 +40,7 @@ export function createEscPosTransport({ sink, profile, format }: EscPosTransport
39
40
  try {
40
41
  await sink.write(bytes);
41
42
  } catch (error) {
42
- throw new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error });
43
+ throw toPrintError(error);
43
44
  }
44
45
  },
45
46
  };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * A WebUSB sink for `createEscPosTransport`. The app supplies the `USBDevice` from `navigator.usb.requestDevice` (which
3
+ * needs a user gesture) or `navigator.usb.getDevices`, and keeps it between jobs. The sink holds no vendor code
4
+ * (ADR-084 decision 2) and never closes the device: the app releases it when it is done. The sink sets no timeout on a
5
+ * transfer.
6
+ */
7
+ import { PrintError } from '../types';
8
+ import type { EscPosSink } from './transport';
9
+
10
+ interface WebUsbEndpoint { readonly endpointNumber: number; readonly direction: 'in' | 'out'; readonly type: 'bulk' | 'interrupt' | 'isochronous' }
11
+
12
+ /** Shaped on the DOM `USBDevice`; e2e/web/webusb-sink.spec.ts checks these member names in Chromium. */
13
+ export interface WebUsbDevice {
14
+ readonly opened: boolean;
15
+ readonly configuration?: {
16
+ readonly interfaces: readonly {
17
+ readonly interfaceNumber: number;
18
+ readonly claimed: boolean;
19
+ readonly alternate: { readonly interfaceClass: number; readonly endpoints: readonly WebUsbEndpoint[] };
20
+ }[];
21
+ } | null;
22
+ readonly productName?: string | null;
23
+ open(): Promise<void>;
24
+ selectConfiguration(configurationValue: number): Promise<void>;
25
+ claimInterface(interfaceNumber: number): Promise<void>;
26
+ clearHalt(direction: 'in' | 'out', endpointNumber: number): Promise<void>;
27
+ transferOut(endpointNumber: number, data: Uint8Array<ArrayBuffer>): Promise<{ status: 'ok' | 'stall' | 'babble'; bytesWritten: number }>;
28
+ }
29
+
30
+ export interface WebUsbSinkOptions {
31
+ device: WebUsbDevice;
32
+ /** Bytes per `transferOut`: a positive integer, default 4096. */
33
+ chunkSize?: number;
34
+ }
35
+
36
+ // Keeps a single transfer bounded; it is not a pacing control (each transfer is awaited, so the device sets the pace).
37
+ const USB_CHUNK_SIZE = 4096;
38
+
39
+ // The USB printer class code (bInterfaceClass 7).
40
+ const USB_PRINTER_CLASS = 7;
41
+
42
+ /**
43
+ * The interface to print to, and its bulk OUT endpoint's number: the first printer-class interface with a bulk OUT
44
+ * endpoint, or, when there is none, the first interface of any class with a bulk OUT endpoint.
45
+ */
46
+ function bulkOut(device: WebUsbDevice) {
47
+ const candidates = (device.configuration?.interfaces ?? []).flatMap((usbInterface) => {
48
+ const endpoint = usbInterface.alternate.endpoints.find(({ direction, type }) => direction === 'out' && type === 'bulk');
49
+ return endpoint ? [{ usbInterface, endpointNumber: endpoint.endpointNumber }] : [];
50
+ });
51
+ return candidates.find(({ usbInterface }) => usbInterface.alternate.interfaceClass === USB_PRINTER_CLASS) ?? candidates[0] ?? null;
52
+ }
53
+
54
+ export function createWebUsbSink({ device, chunkSize = USB_CHUNK_SIZE }: WebUsbSinkOptions): EscPosSink {
55
+ if (!Number.isInteger(chunkSize) || chunkSize < 1) throw new RangeError(`chunkSize must be a positive integer, not ${chunkSize}`);
56
+ const name = () => device.productName || 'USB printer';
57
+ async function step<T>(label: string, run: () => Promise<T>): Promise<T> {
58
+ try {
59
+ return await run();
60
+ } catch (error) {
61
+ throw new PrintError('failed', `${name()}: ${label} failed: ${error instanceof Error ? error.message : error}`, { cause: error });
62
+ }
63
+ }
64
+ return {
65
+ async write(bytes) {
66
+ // Read the device's state on every write, so a write after the app reopens the device works.
67
+ if (!device.opened) await step('open', () => device.open());
68
+ if (device.configuration == null) await step('selectConfiguration(1)', () => device.selectConfiguration(1));
69
+ const target = bulkOut(device);
70
+ if (!target) throw new PrintError('unsupported', `${name()} has no bulk OUT endpoint to print to`);
71
+ const { usbInterface: { interfaceNumber, claimed }, endpointNumber } = target;
72
+ if (!claimed) await step(`claimInterface(${interfaceNumber})`, () => device.claimInterface(interfaceNumber));
73
+ for (let i = 0; i < bytes.length; i += chunkSize) {
74
+ // slice, not subarray: each transfer gets its own ArrayBuffer-backed copy.
75
+ const chunk = bytes.slice(i, i + chunkSize);
76
+ const result = await step(`transferOut(${endpointNumber})`, () => device.transferOut(endpointNumber, chunk));
77
+ if (result.status === 'ok') continue;
78
+ // A stalled endpoint stays halted until cleared, so clear it for the next job; this job still fails.
79
+ if (result.status === 'stall') await device.clearHalt('out', endpointNumber).catch(() => undefined);
80
+ throw new PrintError('failed', `${name()}: transferOut(${endpointNumber}) ended with status ${result.status}`);
81
+ }
82
+ },
83
+ };
84
+ }
@@ -11,5 +11,5 @@ export type { ResolvePrinterOptions } from './resolve-printer';
11
11
  export { createSystemPrintTransport, SYSTEM_PRINT_TIMING } from './system-transport';
12
12
  export type { SystemPrintTransportOptions } from './system-transport';
13
13
  export { escpos, encodeEscPos, createEscPosTransport, ESCPOS_CODE_PAGES, renderEscpos, encodeThermalTemplate } from './escpos';
14
- export { createEpsonEposSink, createStarWebPrntSink, networkSinkFor, canOpenDrawer, openDrawerJob } from './escpos';
15
- export type { EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, RenderEscposOptions } from './escpos';
14
+ export { createEpsonEposSink, createStarWebPrntSink, networkSinkFor, createWebUsbSink, createWebBluetoothSink, BLUETOOTH_PRINT_SERVICES, canOpenDrawer, openDrawerJob } from './escpos';
15
+ export type { EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, WebUsbDevice, WebUsbSinkOptions, WebBluetoothDevice, WebBluetoothSinkOptions, RenderEscposOptions } from './escpos';