@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,29 +1,32 @@
1
1
  import {
2
2
  DisplaySignallingError, type DisplayAdvertisement, type DisplayRecord, type DisplaySignalling, type SignalMessage,
3
- type SyncContext,
3
+ type SyncContext, type TillDevice,
4
4
  } from '@tallyui/core';
5
- import type { ReceiptData } from '../receipt/types';
6
- import { createDisplayLink, type DisplayLink } from './display-link';
7
- import type { DisplayConfig, DisplayEnvelope, DisplayPayment } from './protocol';
8
- import { createSnapshotSender, quietly, type ServiceClock, type SnapshotSender } from './snapshot-fallback';
5
+ import { createDisplayLink, callDisplay, type DisplayCall, type DisplayLink } from './display-link';
6
+ import type { DisplayConfig, DisplayEnvelope } from './protocol';
7
+ import { createSnapshotSender, quietly, systemClock, SALE_ACTIONS, type ServiceClock, type SnapshotSender } from './snapshot-fallback';
8
+ import { withTillDevice, type TillDeviceHandle } from './till-device';
9
9
  import type { DisplayTransport } from './transport';
10
10
  import { createTillPeerLink, type PeerFactory, type PeerLink, type PeerLinkState, type SignalPort } from './webrtc';
11
11
 
12
12
  export type { ServiceClock } from './snapshot-fallback';
13
13
 
14
- /** How often the till drains its signal inbox while a link is connecting; TallyUI's choice. */
14
+ /** How often the till drains its signal inbox while a link is connecting; TallyUI's choice.
15
+ * @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
15
16
  export const SIGNAL_POLL_MS = 1000;
16
- /** How often the till lists its displays; TallyUI's choice. */
17
+ /** How often the till lists its displays; TallyUI's choice.
18
+ * @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
17
19
  export const LIST_POLL_MS = 10_000;
18
- /** How long a link may stay connecting before it counts as a drop; TallyUI's choice. */
20
+ /** How long a link may stay connecting before it counts as a drop; TallyUI's choice.
21
+ * @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
19
22
  export const CONNECT_TIMEOUT_MS = 30_000;
20
23
 
21
24
  export interface TillDisplayServiceOptions {
22
25
  signalling: DisplaySignalling;
23
26
  /** The cashier session; null while nobody is logged in, which stops every server call (d5). */
24
27
  context: () => SyncContext | null;
25
- /** The till's own device id (d5); U8 stores it. */
26
- deviceId: string;
28
+ /** The till's device (d5, TallyUI#754), from `createTillDevice`; its key is never logged or reported. */
29
+ device: TillDeviceHandle;
27
30
  advertisement: DisplayAdvertisement;
28
31
  /** One display's config: the store, i18n and idle settings, with `display` from its record. */
29
32
  configFor: (display: DisplayRecord) => DisplayConfig;
@@ -33,9 +36,12 @@ export interface TillDisplayServiceOptions {
33
36
  onError?: (error: unknown) => void;
34
37
  }
35
38
  export type TillDisplayStatus = 'online' | 'offline' | 'paused' | 'closed';
39
+ export type TillDisplayPauseReason = 'signed_out' | 'forbidden' | 'device_refused';
36
40
  export interface TillDisplayEntry { display: DisplayRecord; link: PeerLinkState }
37
41
  export interface TillDisplayService extends DisplayLink {
38
42
  readonly status: TillDisplayStatus;
43
+ /** Why the service is `paused`; null in every other status. */
44
+ readonly pauseReason: TillDisplayPauseReason | null;
39
45
  /** The owned displays from the last successful list, each with its current link's state. */
40
46
  readonly displays: readonly TillDisplayEntry[];
41
47
  /** Called after any change to `status` or `displays`; returns the unsubscribe. */
@@ -44,19 +50,9 @@ export interface TillDisplayService extends DisplayLink {
44
50
  refresh(): Promise<void>;
45
51
  }
46
52
 
47
- const systemClock: ServiceClock = {
48
- now: () => Date.now(),
49
- setTimeout: (run, ms) => setTimeout(run, ms),
50
- clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
51
- };
52
-
53
- /** The sale states a display shows: its current event, which the snapshot carries. */
54
- const SALE_ACTIONS: ReadonlySet<string> = new Set(['cart.updated', 'payment.state', 'display.idle']);
55
53
  /** Handed to a snapshot sender in place of a POST while the server is lost or paused; retried, never logged. */
56
54
  const NOT_SENT = new DisplaySignallingError('network', 'not sent: the display service is offline or paused');
57
55
 
58
- type Call = ['cart', ReceiptData | null] | ['payment', ReceiptData, DisplayPayment];
59
-
60
56
  interface Slot {
61
57
  id: string;
62
58
  record: DisplayRecord;
@@ -80,14 +76,15 @@ interface Slot {
80
76
  * server is lost. It is a `DisplayLink`, so `createSaleDisplayPublisher` drives it.
81
77
  */
82
78
  export function createTillDisplayService(options: TillDisplayServiceOptions): TillDisplayService {
83
- const { signalling, deviceId, advertisement, configFor, createPeer, clock = systemClock } = options;
79
+ const { signalling, device, advertisement, configFor, createPeer, clock = systemClock } = options;
84
80
  const slots = new Map<string, Slot>();
85
81
  const listeners = new Set<() => void>();
86
82
  let status: TillDisplayStatus = 'online';
87
- // A `forbidden` pause stops every call until refresh(); a null context pauses without one, and the list timer
83
+ // A `forbidden` or `device_refused` pause stops every call until refresh(); a null context pauses without one, and the list timer
88
84
  // keeps reading context() so the till picks its displays up again when a cashier logs in (d5).
89
85
  let forbidden = false;
90
- let latest: Call | null = null;
86
+ let pauseReason: TillDisplayPauseReason | null = null;
87
+ let latest: DisplayCall | null = null;
91
88
  let entries: readonly TillDisplayEntry[] = [];
92
89
  const timers: { list: unknown; signal: unknown } = { list: null, signal: null };
93
90
  let signalBusy = false;
@@ -106,11 +103,16 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
106
103
  active: advertisement.snapshot && status === 'online' && slot.record.connected && slot.link?.state !== 'open',
107
104
  seq: slot.seq, config: slot.config, event: slot.event,
108
105
  });
109
- const setStatus = (next: TillDisplayStatus) => {
110
- if (status === next || status === 'closed') return;
111
- status = next;
112
- slots.forEach(push);
113
- if (next === 'online') ensureSignalPoll();
106
+ const setStatus = (next: TillDisplayStatus, reason: TillDisplayPauseReason | null = null) => {
107
+ const nextReason = next === 'paused' ? reason : null;
108
+ if (status === 'closed' || (status === next && pauseReason === nextReason)) return;
109
+ pauseReason = nextReason;
110
+ // A same-status pause with a new reason only emits; the slots and the signal poll stay as they are.
111
+ if (status !== next) {
112
+ status = next;
113
+ slots.forEach(push);
114
+ if (next === 'online') ensureSignalPoll();
115
+ }
114
116
  emit();
115
117
  };
116
118
 
@@ -118,7 +120,7 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
118
120
  const contextNow = (): SyncContext | null => {
119
121
  if (status === 'closed' || forbidden) return null;
120
122
  const ctx = options.context();
121
- if (!ctx) setStatus('paused');
123
+ if (!ctx) setStatus('paused', 'signed_out');
122
124
  return ctx;
123
125
  };
124
126
  /** The service's reading of a failed call: d11 for a lost server, a pause, or a display that is gone. */
@@ -126,20 +128,20 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
126
128
  if (status === 'closed' || !(error instanceof DisplaySignallingError)) return;
127
129
  if (error.code === 'network' || error.code === 'server') {
128
130
  if (!forbidden) setStatus('offline');
129
- } else if (error.code === 'forbidden') {
131
+ } else if (error.code === 'forbidden' || error.code === 'device_refused') {
130
132
  forbidden = true;
131
133
  stopTimer('list');
132
- setStatus('paused');
134
+ setStatus('paused', error.code);
133
135
  } else if (error.code === 'not_found' && displayId !== undefined) {
134
136
  remove(displayId);
135
137
  emit();
136
138
  }
137
139
  };
138
140
  /** A server call whose failure is logged and handled, never thrown; `null` when it failed or was not made. */
139
- const call = async <T>(work: (ctx: SyncContext) => Promise<T>, displayId?: string): Promise<{ value: T } | null> => {
141
+ const call = async <T>(work: (ctx: SyncContext, till: TillDevice) => Promise<T>, displayId?: string): Promise<{ value: T } | null> => {
140
142
  try {
141
143
  const ctx = contextNow();
142
- return ctx ? { value: await work(ctx) } : null;
144
+ return ctx ? { value: await withTillDevice(device, ctx, (till) => work(ctx, till)) } : null;
143
145
  } catch (error) {
144
146
  report(error);
145
147
  handle(error, displayId);
@@ -153,7 +155,7 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
153
155
  timers.signal = clock.setTimeout(async () => {
154
156
  timers.signal = null;
155
157
  signalBusy = true;
156
- const result = await call((ctx) => signalling.receiveSignals(ctx, deviceId));
158
+ const result = await call((ctx, till) => signalling.receiveSignals(ctx, till));
157
159
  signalBusy = false;
158
160
  for (const { displayId, type, payload } of result?.value ?? []) slots.get(displayId)?.deliver?.({ type, payload });
159
161
  ensureSignalPoll();
@@ -181,7 +183,7 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
181
183
  if (status !== 'online' || slot.link) return;
182
184
  slot.seq += 1;
183
185
  const port: SignalPort = {
184
- send: (message) => void call((ctx) => signalling.sendSignal(ctx, deviceId, slot.id, message), slot.id),
186
+ send: (message) => void call((ctx, till) => signalling.sendSignal(ctx, till, slot.id, message), slot.id),
185
187
  onSignal: (listener) => {
186
188
  slot.deliver = listener;
187
189
  return () => void (slot.deliver === listener && (slot.deliver = null));
@@ -211,8 +213,7 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
211
213
  push(slot);
212
214
  emit();
213
215
  });
214
- if (latest?.[0] === 'cart') slot.view.showCart(latest[1]);
215
- else if (latest) slot.view.showPayment(latest[1], latest[2]);
216
+ if (latest) callDisplay(slot.view, latest);
216
217
  ensureSignalPoll();
217
218
  };
218
219
 
@@ -224,7 +225,7 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
224
225
  post: async (body) => {
225
226
  const ctx = status === 'online' ? contextNow() : null;
226
227
  if (!ctx) throw NOT_SENT;
227
- await signalling.postSnapshot(ctx, deviceId, id, body).catch((error: unknown) => {
228
+ await withTillDevice(device, ctx, (till) => signalling.postSnapshot(ctx, till, id, body)).catch((error: unknown) => {
228
229
  handle(error, id);
229
230
  throw error;
230
231
  });
@@ -253,7 +254,7 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
253
254
  async function listNow(): Promise<void> {
254
255
  stopTimer('list');
255
256
  const generation = ++listGeneration;
256
- const result = await call((ctx) => signalling.list(ctx, deviceId));
257
+ const result = await call((ctx, till) => signalling.list(ctx, till));
257
258
  if (status === 'closed' || generation !== listGeneration) return;
258
259
  if (result) {
259
260
  setStatus('online');
@@ -268,17 +269,17 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
268
269
  }
269
270
  void listNow();
270
271
 
271
- const fanOut = (next: Call) => {
272
+ const fanOut = (next: DisplayCall) => {
272
273
  if (status === 'closed') return;
273
274
  latest = next;
274
275
  for (const { view } of slots.values()) {
275
- if (next[0] === 'cart') view?.showCart(next[1]);
276
- else view?.showPayment(next[1], next[2]);
276
+ if (view) callDisplay(view, next);
277
277
  }
278
278
  };
279
279
 
280
280
  return {
281
281
  get status() { return status; },
282
+ get pauseReason() { return pauseReason; },
282
283
  get displays() { return entries; },
283
284
  onChange(listener) {
284
285
  listeners.add(listener);
@@ -297,6 +298,7 @@ export function createTillDisplayService(options: TillDisplayServiceOptions): Ti
297
298
  stopTimer('signal');
298
299
  for (const id of [...slots.keys()]) remove(id);
299
300
  status = 'closed';
301
+ pauseReason = null;
300
302
  emit();
301
303
  listeners.clear();
302
304
  },
@@ -1,11 +1,13 @@
1
- import { DisplaySignallingError, type DisplaySignalling, type PendingPairing, type SyncContext } from '@tallyui/core';
2
- import { quietly, type ServiceClock } from './snapshot-fallback';
1
+ import { DisplaySignallingError, type DisplaySignalling, type PendingPairing, type SyncContext, type TillDevice } from '@tallyui/core';
2
+ import { quietly, systemClock, type ServiceClock } from './snapshot-fallback';
3
3
  import type { TillDisplayService } from './till-display-service';
4
+ import { withTillDevice, type TillDeviceHandle } from './till-device';
4
5
 
5
- /** How often the till lists the claims on its code while it shows one; TallyUI's choice. */
6
+ /** How often the till lists the claims on its code while it shows one; TallyUI's choice.
7
+ * @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
6
8
  export const PENDING_POLL_MS = 2000;
7
9
 
8
- export type PairingError = 'forbidden' | 'limit' | 'expired' | 'not_found' | 'network' | 'server';
10
+ export type PairingError = 'forbidden' | 'limit' | 'expired' | 'not_found' | 'device_refused' | 'network' | 'server';
9
11
  export type PairingPhase =
10
12
  | { phase: 'idle'; error?: PairingError }
11
13
  | { phase: 'minting' }
@@ -15,8 +17,8 @@ export interface TillPairingOptions {
15
17
  signalling: DisplaySignalling;
16
18
  /** The cashier session; null while nobody is logged in, which refuses every call as `forbidden` (d5). */
17
19
  context: () => SyncContext | null;
18
- /** The till's own device id (d5). */
19
- deviceId: string;
20
+ /** The till's device (d5, TallyUI#754), from `createTillDevice`; its key is never logged or reported. */
21
+ device: TillDeviceHandle;
20
22
  /** U4's service, refreshed after a confirm or a forget. */
21
23
  service?: Pick<TillDisplayService, 'refresh'>;
22
24
  clock?: ServiceClock;
@@ -38,13 +40,7 @@ export interface TillPairing {
38
40
  close(): void;
39
41
  }
40
42
 
41
- const systemClock: ServiceClock = {
42
- now: () => Date.now(),
43
- setTimeout: (run, ms) => setTimeout(run, ms),
44
- clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
45
- };
46
-
47
- const NAMED: ReadonlySet<string> = new Set<PairingError>(['forbidden', 'limit', 'expired', 'not_found', 'network', 'server']);
43
+ const NAMED: ReadonlySet<string> = new Set<PairingError>(['forbidden', 'limit', 'expired', 'not_found', 'device_refused', 'network', 'server']);
48
44
  /** A signalling refusal keeps its code; anything else is `server`. */
49
45
  const nameOf = (error: unknown): PairingError =>
50
46
  error instanceof DisplaySignallingError && NAMED.has(error.code) ? (error.code as PairingError) : 'server';
@@ -54,7 +50,7 @@ const nameOf = (error: unknown): PairingError =>
54
50
  * confirm or decline one, and forget a paired display. Framework-free; `useTillPairing` renders it.
55
51
  */
56
52
  export function createTillPairing(options: TillPairingOptions): TillPairing {
57
- const { signalling, deviceId, service, clock = systemClock } = options;
53
+ const { signalling, device, service, clock = systemClock } = options;
58
54
  const listeners = new Set<() => void>();
59
55
  let phase: PairingPhase = { phase: 'idle' };
60
56
  let forgetError: PairingError | null = null;
@@ -75,10 +71,10 @@ export function createTillPairing(options: TillPairingOptions): TillPairing {
75
71
  emit();
76
72
  };
77
73
  const idle = (error?: PairingError) => setPhase(error ? { phase: 'idle', error } : { phase: 'idle' });
78
- /** Runs one signalling call with the cashier session; a missing session is a `forbidden` refusal, with no call. */
79
- const run = <T>(work: (ctx: SyncContext) => Promise<T>): Promise<T> => {
74
+ /** Runs one signalling call with the cashier session and the device; a missing session is a `forbidden` refusal, with no call. */
75
+ const run = <T>(work: (ctx: SyncContext, till: TillDevice) => Promise<T>): Promise<T> => {
80
76
  const ctx = options.context();
81
- return ctx ? work(ctx) : Promise.reject(new DisplaySignallingError('forbidden', 'no cashier session'));
77
+ return ctx ? withTillDevice(device, ctx, (till) => work(ctx, till)) : Promise.reject(new DisplaySignallingError('forbidden', 'no cashier session'));
82
78
  };
83
79
  const refresh = async () => {
84
80
  if (!closed) await (async () => service?.refresh())().catch(report);
@@ -94,11 +90,12 @@ export function createTillPairing(options: TillPairingOptions): TillPairing {
94
90
  const poll = async (mine: number) => {
95
91
  timer = null;
96
92
  try {
97
- const claims = await run((ctx) => signalling.pending(ctx, deviceId));
93
+ const claims = await run((ctx, till) => signalling.pending(ctx, till));
98
94
  if (mine === epoch && phase.phase === 'code') setPhase({ ...phase, claims });
99
95
  } catch (error) {
100
96
  report(error);
101
- if (mine === epoch && phase.phase === 'code' && nameOf(error) === 'forbidden') idle('forbidden');
97
+ const named = nameOf(error);
98
+ if (mine === epoch && phase.phase === 'code' && (named === 'forbidden' || named === 'device_refused')) idle(named);
102
99
  }
103
100
  tick(mine);
104
101
  };
@@ -115,7 +112,7 @@ export function createTillPairing(options: TillPairingOptions): TillPairing {
115
112
  const mine = ++epoch;
116
113
  setPhase({ phase: 'minting' });
117
114
  try {
118
- const { code, expiresAt } = await run((ctx) => signalling.mint(ctx, deviceId));
115
+ const { code, expiresAt } = await run((ctx, till) => signalling.mint(ctx, till));
119
116
  if (mine !== epoch) return;
120
117
  setPhase({ phase: 'code', code, expiresAt, claims: [] });
121
118
  tick(mine);
@@ -129,7 +126,7 @@ export function createTillPairing(options: TillPairingOptions): TillPairing {
129
126
  const mine = ++epoch;
130
127
  setPhase({ phase: 'confirming', claimId });
131
128
  try {
132
- await run((ctx) => signalling.confirm(ctx, deviceId, claimId));
129
+ await run((ctx, till) => signalling.confirm(ctx, till, claimId));
133
130
  } catch (error) {
134
131
  report(error);
135
132
  if (mine === epoch) idle(nameOf(error));
@@ -142,7 +139,7 @@ export function createTillPairing(options: TillPairingOptions): TillPairing {
142
139
  if (closed || phase.phase !== 'code') return;
143
140
  const mine = epoch;
144
141
  try {
145
- await run((ctx) => signalling.decline(ctx, deviceId, claimId));
142
+ await run((ctx, till) => signalling.decline(ctx, till, claimId));
146
143
  } catch (error) {
147
144
  return report(error);
148
145
  }
@@ -157,7 +154,7 @@ export function createTillPairing(options: TillPairingOptions): TillPairing {
157
154
  if (closed) return;
158
155
  if (forgetError !== null) { forgetError = null; emit(); }
159
156
  try {
160
- await run((ctx) => signalling.forget(ctx, deviceId, displayId));
157
+ await run((ctx, till) => signalling.forget(ctx, till, displayId));
161
158
  } catch (error) {
162
159
  report(error);
163
160
  if (closed) return;
@@ -4,7 +4,8 @@ import { makeEnvelope, type DisplayTemplate } from './protocol';
4
4
  import type { DisplayTransport } from './transport';
5
5
 
6
6
  export const DISPLAY_TEMPLATE: DisplayTemplate = { id: 'default', version: 1 };
7
- /** The hello is re-sent until a config answers it, so a till opened after the display still finds it. */
7
+ /** The hello is re-sent until a config answers it, so a till opened after the display still finds it.
8
+ * @deprecated Internal tuning value, not supported API; leaves the public entry at the next major. */
8
9
  export const HELLO_RETRY_MS = 2000;
9
10
 
10
11
  /**
@@ -1,12 +1,12 @@
1
1
  import { useCallback, useRef, useSyncExternalStore } from 'react';
2
- import type { TillDisplayService, TillDisplayEntry, TillDisplayStatus } from './till-display-service';
2
+ import type { TillDisplayService, TillDisplayEntry, TillDisplayPauseReason, TillDisplayStatus } from './till-display-service';
3
3
  import type { PairingError, PairingPhase, TillPairing } from './till-pairing';
4
4
 
5
5
  export interface TillPairingView { phase: PairingPhase; forgetError: PairingError | null }
6
- export interface TillDisplaysView { status: TillDisplayStatus; displays: readonly TillDisplayEntry[] }
6
+ export interface TillDisplaysView { status: TillDisplayStatus; displays: readonly TillDisplayEntry[]; pauseReason: TillDisplayPauseReason | null }
7
7
 
8
8
  const NO_PAIRING: TillPairingView = { phase: { phase: 'idle' }, forgetError: null };
9
- const NO_DISPLAYS: TillDisplaysView = { status: 'closed', displays: [] };
9
+ const NO_DISPLAYS: TillDisplaysView = { status: 'closed', displays: [], pauseReason: null };
10
10
 
11
11
  /** A store over `source.onChange` whose snapshot is a new object only when one of its parts changed. */
12
12
  function useView<S extends { onChange(listener: () => void): () => void }, V extends object>(
@@ -31,5 +31,5 @@ export function useTillPairing(pairing: TillPairing | null): TillPairingView {
31
31
 
32
32
  /** The till display service's status and displays, re-rendered on each change; null gives `closed` with none. */
33
33
  export function useTillDisplays(service: TillDisplayService | null): TillDisplaysView {
34
- return useView(service, NO_DISPLAYS, (s) => ({ status: s.status, displays: s.displays }));
34
+ return useView(service, NO_DISPLAYS, (s) => ({ status: s.status, displays: s.displays, pauseReason: s.pauseReason }));
35
35
  }
package/src/index.ts CHANGED
@@ -32,9 +32,11 @@ export type { CashierState } from './cashier';
32
32
  export {
33
33
  UI_SCALES, UI_THEMES, APP_SETTING_DEFINITIONS, DEFAULT_APP_SETTINGS, appSettingSchema,
34
34
  appSettingCollection, resolveAppSettings, readAppSettings, appSettings$, writeAppSetting, useAppSettings,
35
+ CART_COLUMN_IDS, OPEN_ORDERS_POSITIONS,
35
36
  } from './app-settings';
36
37
  export type {
37
38
  UiScale, UiTheme, AppSettings, AppSettingKey, AppSettingDefinition, AppSettingDoc, AppSettingCollection,
39
+ CartColumnId, CartColumnsSetting, OpenOrdersPosition,
38
40
  } from './app-settings';
39
41
 
40
42
  // RxDB reads past the query cache, and live lists that can't leave it stale (RxDB 16.21.1 bug 4)
@@ -55,6 +57,7 @@ export type { OrderManager, OrderManagerOptions, ParkedOrderSummary } from './or
55
57
  export type {
56
58
  Order,
57
59
  OrderCoupon,
60
+ OrderCouponLine,
58
61
  SentOrder,
59
62
  LineItem,
60
63
  LineTaxLine,
@@ -73,7 +76,7 @@ export type {
73
76
  } from './order';
74
77
 
75
78
  // Receipt
76
- export { buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, RECEIPT_SCHEMA_VERSION } from './receipt';
79
+ export { buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, RECEIPT_SCHEMA_VERSION, isCarriedCouponLabel } from './receipt';
77
80
  export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, ReceiptRegister, ReceiptFiscal } from './receipt';
78
81
 
79
82
  // Receipt templates
@@ -96,17 +99,23 @@ export type { SignalPort, PeerLink, PeerLinkState, PeerLinkOptions, PeerFactory,
96
99
  export { createDisplayClient, COLLECT_POLL_MS, DISPLAY_SIGNAL_POLL_MS, OPEN_SIGNAL_POLL_MS, SNAPSHOT_POLL_MS, useDisplayClient } from './customer-display';
97
100
  export type { DisplayClient, DisplayClientOptions, DisplayClientPhase, DisplayClientError, DisplayTokenStore, DisplayClientView } from './customer-display';
98
101
  export { createTillDisplayService, SIGNAL_POLL_MS, LIST_POLL_MS, CONNECT_TIMEOUT_MS, createSnapshotSender, SNAPSHOT_MIN_INTERVAL_MS, SNAPSHOT_RESEND_MS, SNAPSHOT_LIFETIME_MS } from './customer-display';
99
- export type { TillDisplayService, TillDisplayServiceOptions, TillDisplayStatus, TillDisplayEntry, ServiceClock, SnapshotSender, SnapshotSenderOptions, SnapshotBody } from './customer-display';
102
+ export type { TillDisplayService, TillDisplayServiceOptions, TillDisplayStatus, TillDisplayPauseReason, TillDisplayEntry, ServiceClock, SnapshotSender, SnapshotSenderOptions, SnapshotBody } from './customer-display';
100
103
  export { createTillPairing, PENDING_POLL_MS, useTillPairing, useTillDisplays } from './customer-display';
101
104
  export type { TillPairing, TillPairingOptions, PairingPhase, PairingError, TillPairingView, TillDisplaysView } from './customer-display';
105
+ export { createTillDevice } from './customer-display';
106
+ export type { TillDeviceHandle, TillDeviceKeyStore, TillDeviceOptions } from './customer-display';
107
+
108
+ // Customer form values to a create input or an update patch
109
+ export { shipsToBilling, toCustomerInput, toCustomerPatch } from './customer/customer-patch';
110
+ export type { CustomerEditValues } from './customer/customer-patch';
102
111
 
103
112
  // Product
104
- export { searchProducts, sortProducts, productSortValue, PRODUCT_SORT_FIELDS, type ProductSort, type ProductSortValue, catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE, type CatalogueView, type CatalogueGridColumns, type CatalogueViewState, type CatalogueViewAction, withStockOverlay, getProductStock, stockOverlay$, stockOverlayAsOf$, productCategories, listCategories, inCategory } from './product';
113
+ export { searchProducts, sortProducts, productSortValue, PRODUCT_SORT_FIELDS, type ProductSort, type ProductSortValue, catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE, type CatalogueView, type CatalogueGridColumns, type CatalogueViewState, type CatalogueViewAction, withStockOverlay, getProductStock, stockOverlay$, stockOverlayAsOf$, productCategories, listCategories, inCategory, productTerms, listTermGroups, hasTerm, type ProductTermGroup, TILE_FIELDS, DEFAULT_TILE_FIELDS, normalizeTileFields, type TileField, type TileFields } from './product';
105
114
 
106
115
  // Scanner
107
- export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector, DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession, useBarcodeScanner, SCANNER_DEVICE_KEY_MAX_LENGTH, normalizeUuid, isCanonicalUuid, scannerDeviceKey, scannerTransport, createSerialLineDecoder, decodeHidPosReport, isWebSerialSupported, isWebHidSupported, isChooserCancel, SCANNER_PROFILES_COLLECTION, scannerProfileSchema, scannerProfileCollection, addScannerProfileCollection, scannerProfiles$, readScannerProfiles, saveScannerProfile, removeScannerProfile, createScanHub, createScanBus, inertScanHub, dedupeScans, SCAN_DEDUP_WINDOW_MS } from './scanner';
116
+ export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector, DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession, useBarcodeScanner, SCANNER_DEVICE_KEY_MAX_LENGTH, normalizeUuid, isCanonicalUuid, scannerDeviceKey, scannerTransport, createSerialLineDecoder, decodeHidPosReport, isWebSerialSupported, isWebHidSupported, isChooserCancel, SCANNER_PROFILES_COLLECTION, scannerProfileSchema, scannerProfileCollection, addScannerProfileCollection, scannerProfiles$, readScannerProfiles, saveScannerProfile, removeScannerProfile, createScanHub, createScanBus, inertScanHub, dedupeScans, SCAN_DEDUP_WINDOW_MS, analyzeScanTrace } from './scanner';
108
117
  export { scannerProfileStore, createDeviceScannerStateCell, createSerialScanner, serialPortIdentity, DEFAULT_SERIAL_BAUD_RATE, STANDARD_SPP_SERVICE_CLASS_ID } from './scanner';
109
- export type { WedgeSettings, WedgeState, TraceKey, WedgeReplayResult, WedgeDetectorOptions, WedgeDetector, ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession, UseBarcodeScannerOptions, ScannerConnectionType, ScannerIdentity, ScannerTransport, SerialLineDecoderOptions, SerialLineDecoder, HidPosDecodeOptions, HidPosResult, ScannerProfile, ScannerProfileCollection, ScanSourceKind, ScanSource, ScanEvent, ScanBus, ScanHub, WedgeScanMeta } from './scanner';
118
+ export type { WedgeSettings, WedgeState, TraceKey, WedgeReplayResult, WedgeDetectorOptions, WedgeDetector, ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession, UseBarcodeScannerOptions, ScannerConnectionType, ScannerIdentity, ScannerTransport, SerialLineDecoderOptions, SerialLineDecoder, HidPosDecodeOptions, HidPosResult, ScannerProfile, ScannerProfileCollection, ScanSourceKind, ScanSource, ScanEvent, ScanBus, ScanHub, WedgeScanMeta, ScanTraceSettings, TraceSuggestion, TraceAnalysis } from './scanner';
110
119
  export type { ScannerProfileStore, DeviceScannerSettings, DeviceScannerState, DeviceScannerErrorPhase, DeviceScannerErrorHandler, DeviceScannerStateCell, DeviceScanner, SerialPortInfoLike, SerialPortLike, SerialLike, SerialScannerOptions } from './scanner';
111
120
  export { createHidScanner, HID_POS_USAGE_PAGE } from './scanner';
112
121
  export type { HidInputReportEventLike, HidDeviceLike, HidLike, HidScannerOptions } from './scanner';
@@ -127,25 +136,30 @@ export type {
127
136
  export {
128
137
  PrintError, toPrintError, createPrintQueue, SYSTEM_PRINTER_ID, PRINTER_PROFILES_COLLECTION, printerProfileSchema,
129
138
  printerProfileCollection, addPrinterProfileCollection, createSystemPrintTransport, SYSTEM_PRINT_TIMING,
130
- escpos, encodeEscPos, createEscPosTransport, ESCPOS_CODE_PAGES,
139
+ escpos, encodeEscPos, createEscPosTransport, createEpsonEposSink, createStarWebPrntSink, networkSinkFor, canOpenDrawer,
140
+ openDrawerJob, ESCPOS_CODE_PAGES, resolvePrinter, templateColumns, renderEscpos, encodeThermalTemplate,
131
141
  } from './print';
132
142
  export type {
133
143
  PrintJob, PrintJobKind, PrintErrorCode, PrintTransport, PrintQueue, PrintQueueOptions, PrintQueueState,
134
144
  PrinterProfile, PrinterProfileCollection, SystemPrintTransportOptions,
135
- EscPosBuilder, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions,
145
+ EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, ResolvePrinterOptions, RenderEscposOptions,
136
146
  } from './print';
137
147
 
138
148
  // Sale
139
- export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED, COUPONS_NEED_CONNECTION, COUPONS_REPRICING, createStorePricedDiscountCodes, cartQuantities, SPLIT_FIXED_DISCOUNT, variantFits, matchVariant, disabledOptions, orderFiltersQuery } from './sale';
149
+ export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, SALE_HAS_PAYMENT, SALE_FINISHED, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED, COUPONS_NEED_CONNECTION, COUPONS_REPRICING, COUPON_CARRIED, COUPON_CARRY_STALE, TENDER_GATE_FAILED, TENDER_SALE_CHANGED, createStorePricedDiscountCodes, cartQuantities, SPLIT_FIXED_DISCOUNT, variantFits, matchVariant, disabledOptions, orderFiltersQuery } from './sale';
140
150
  export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, StorePricedAccepted, StorePricedCodePricing, StorePricedDiscountCodesOptions, CartQuantityLine, OptionPicks, OrderFilterValue } from './sale';
141
151
 
142
- export { uuidv7, finalizeOrder, toOrderCreateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
152
+ export { uuidv7, AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder, toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, markAttentionHandled, moneyDivergence, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
143
153
  export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
144
154
  export { noteDelivery, type NoteDelivery } from './pos-order';
145
- export { TAX_ADDRESS_ORDER_CREATE_VERSION } from './pos-order/command';
146
- export { CUSTOMER_RETAX_REFUSED } from './sale/use-sale';
147
- export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions } from './pos-order';
148
- export { createHttpCommandTransport, createOrderOutbox, isRequeueable, useOrderOutbox, outboxLogger } from './outbox';
155
+ export { extrasNotSent, type ExtrasNotSent } from './pos-order';
156
+ export { refundDueOf } from './pos-order';
157
+ export { lockedRefundDueMinor, tillLegsTheStoreRefuses } from './pos-order/refund-due';
158
+ export { ADDRESS_CHANGE_REFUSED, CUSTOMER_RETAX_REFUSED, LINE_EDIT_REFUSED, META_CHANGE_REFUSED, META_INVALID, RESTORE_STALE, TAX_IDS_CHANGE_REFUSED, TAX_IDS_INVALID, type SaleRemoval } from './sale/use-sale';
159
+ export { INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION, TAX_ADDRESS_ORDER_CREATE_VERSION, UNTAXED_ADDRESS_ORDER_CREATE_VERSION } from './pos-order/command';
160
+ export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions, MoneyDivergence } from './pos-order';
161
+ export type { PosOrderCouponLine } from './pos-order/types';
162
+ export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger } from './outbox';
149
163
  export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
150
164
  export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
151
165
  export type { OutboxCounts, OutboxHealth, UseOutboxHealthOptions, UseOutboxHealthResult } from './outbox';
@@ -153,12 +167,14 @@ export { createBackendNotFound } from './outbox/backend-not-found';
153
167
  export type { BackendNotFound } from './outbox/backend-not-found';
154
168
  export type { HttpTransportOptions, OrderOutboxOptions, OrderOutbox, TransportOutcome, CommandTransport, OrderTransportContext, OutboxState, UseOrderOutboxOptions, UseOrderOutboxResult } from './outbox';
155
169
  export { sendOrderRefund, type OrderRefundOutcome, posRefundSchema, posRefundCollection, submitOrderRefund, RefundAnswerPendingError, type PosRefund, type PosRefundStatus, type PosRefundCollection, refundableLines, priceRefund } from './refund';
170
+ export { sendOrderReopen, isOrderReopenInFlight, isReopenOffered, type OrderReopenOutcome, storeOrderForReopen, ReopenEntryError, REOPEN_REFUSED_STATUSES, type ReopenEntryReason, reopenStoreOrder, REOPENED_NOT_LOADED, STORE_ORDER_OPEN_HERE, type ReopenStoreOrderOutcome } from './reopen';
156
171
  export type { RefundableOrderLine, EarlierRefund, RefundableLine, PricedRefundLine, PricedRefund } from './refund';
157
- export { tenderReducer, initTenderState, initialTenderState, appliedMinor, changeMinor, quickTenderedAmounts, evenSplitShareMinor, activePlan, planLegs, MAX_TENDER_MINOR, tenderVoidSchema, tenderVoidCollection, legStatus, countsTowardPaid, isInMotion, capturedMinor, inMotionMinor, canMoveLeg, canVoidLeg } from './tender';
158
- export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg, TenderVoid, PaymentLegStatus } from './tender';
172
+ export { tenderReducer, initTenderState, initialTenderState, appliedMinor, changeMinor, quickTenderedAmounts, evenSplitShareMinor, percentOfMinor, activePlan, planLegs, MAX_TENDER_MINOR, tenderFigures, runsWholeOrder, tenderVoidSchema, tenderVoidCollection, legStatus, countsTowardPaid, isInMotion, capturedMinor, inMotionMinor, canMoveLeg, canVoidLeg, splitUnitLines, unitsMinor, unitAllocationsFromLegs, paidUnitsByLine, unpaidUnitsByLine, pickedUnitsMinor } from './tender';
173
+ export { heldUnitsByLine } from './tender';
174
+ export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg, TenderVoid, PaymentLegStatus, TenderFacts, TenderFigures, SplitUnitLine, UnitAllocations } from './tender';
159
175
 
160
176
  // Register
161
- export { normalizeAmount, isServerDecimal, movementFieldError, deriveExpected, deriveDrawerTerms, parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText, denominations } from './register';
177
+ export { normalizeAmount, isServerDecimal, movementFieldError, deriveExpected, deriveDrawerTerms, takingsByMethod, parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText, denominations } from './register';
162
178
  export type { MovementType, LedgerRow, Movement, DrawerTerm, DrawerTerms } from './register';
163
179
  export { registerSessionSchema, registerSessionCollection, cashMovementSchema, closureSchema } from './register';
164
180
  export { addRegisterSessionCollection, RegisterSessionOpenClosedError, registerSessionsLogger, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS } from './register';
@@ -169,9 +185,12 @@ export { mintUuid, readRegister, ensureRegister, observeRegister$, getBoundRegis
169
185
  export type { RegisterHost, RegisterCounters, RegisterBucket, RegisterStore, RegisterDocument } from './register';
170
186
  export { RegisterSessionRequiredError, RegisterSessionClosedError, RegisterNeedsUpgradeError, RegisterSessionConflictError, RegisterTakeOverError, isKnownSessionStatus, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, openSessionSelector, requireOpenSession, stampSession, openSession, startCounting, backToSelling, closeSession, recordMovement, voidMovement, writeClosure } from './register';
171
187
  export type { RegisterSessionCollection, CashMovementCollection, ClosureCollection } from './register';
172
- export { deriveSettled, exportCsv, labelKeys, clampClosureScope, selectClosureRows } from './register';
188
+ export { deriveSettled, exportCsv, labelKeys, clampClosureScope, selectClosureRows, ENGLISH_CLOSURE_LABELS } from './register';
173
189
  export type { Correction, RecordedFigures, ClosureScope } from './register';
174
- export { minorToDecimal, formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUNDING_MIXED_NOTE, registerFactsLogger, recordRegisterFact, type ClosureContext, type Actor, type RegisterFact } from './register';
190
+ export { formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUNDING_MIXED_NOTE, TAX_STORE_PAID_NOTE, registerFactsLogger, recordRegisterFact, type ClosureContext, type Actor, type RegisterFact, createClosureContext, formatDecimalMoney, type CreateClosureContextOptions } from './register';
191
+ import { minorToDecimal as registerMinorToDecimal } from './register';
192
+ /** @deprecated Use `minorToMajor(minor, digits)` from `@tallyui/core`, which also rejects an amount that is not a safe integer. */
193
+ export const minorToDecimal: (minor: number, exponent: number) => string = registerMinorToDecimal;
175
194
  export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type ApprovalNeeded, type UseRegisterSessionOptions } from './register';
176
195
  export { roundedDue, tenderRounding } from './tender';
177
196
  export type { TenderRounding } from './tender';
@@ -1,3 +1,5 @@
1
+ import { apportionLargestRemainders } from './apportion';
2
+
1
3
  /**
2
4
  * Splits an order discount across lines in proportion to each line's pre-order-discount amount,
3
5
  * in its own tax mode (ADR-062), with largest-remainder rounding to the minor unit.
@@ -14,21 +16,7 @@ export function allocateOrderDiscount(lineAmountsMinor: readonly number[], total
14
16
  }
15
17
  const weights = lineAmountsMinor.map((amount) => BigInt(Math.max(0, amount)));
16
18
  const weightTotal = weights.reduce((sum, weight) => sum + weight, 0n);
17
- const total = BigInt(totalMinor);
18
- if (total > weightTotal) throw new RangeError('Order discount exceeds the lines it applies to');
19
- if (total === 0n) return weights.map(() => 0);
20
-
21
- // BigInt keeps total × weight exact however large the order is.
22
- const shares = weights.map((weight) => (total * weight) / weightTotal);
23
- const remainders = weights.map((weight) => (total * weight) % weightTotal);
24
- let leftover = total - shares.reduce((sum, share) => sum + share, 0n);
25
- const ranked = remainders.map((_, index) => index)
26
- .sort((a, b) => remainders[a] === remainders[b] ? a - b : remainders[a] > remainders[b] ? -1 : 1);
27
- // Each leftover unit goes to a line with a non-zero remainder, whose share is still below its amount.
28
- for (const index of ranked) {
29
- if (leftover === 0n) break;
30
- shares[index] += 1n;
31
- leftover -= 1n;
32
- }
33
- return shares.map(Number);
19
+ if (BigInt(totalMinor) > weightTotal) throw new RangeError('Order discount exceeds the lines it applies to');
20
+ // totalMinor > 0 implies weightTotal > 0 here, so the fallback index is never used.
21
+ return apportionLargestRemainders(weights, totalMinor, 0);
34
22
  }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Splits `totalMinor` (a safe integer >= 0) over `weights` by largest remainders (docs/contract/order-create-v9.md):
3
+ * take each share's floor of totalMinor × w / Σw, then give the leftover units, one each, to the largest fractional parts.
4
+ * Ties go to the lower index. A negative weight counts as 0. When every weight is 0 and totalMinor is not,
5
+ * the whole total goes to `fallbackIndex`. Exact BigInt arithmetic throughout.
6
+ */
7
+ export function apportionLargestRemainders(weights: readonly bigint[], totalMinor: number, fallbackIndex: number): number[] {
8
+ if (!Number.isSafeInteger(totalMinor) || totalMinor < 0) throw new RangeError('Total must be a safe integer >= 0');
9
+ if (totalMinor === 0) return weights.map(() => 0);
10
+ const positive = weights.map((weight) => weight < 0n ? 0n : weight);
11
+ const sum = positive.reduce((total, weight) => total + weight, 0n);
12
+ if (sum === 0n) {
13
+ if (!Number.isInteger(fallbackIndex) || fallbackIndex < 0 || fallbackIndex >= weights.length)
14
+ throw new RangeError('Fallback index is out of range');
15
+ return weights.map((_, index) => index === fallbackIndex ? totalMinor : 0);
16
+ }
17
+ const total = BigInt(totalMinor);
18
+ const shares = positive.map((weight) => total * weight / sum);
19
+ const remainders = positive.map((weight) => total * weight % sum);
20
+ let leftover = total - shares.reduce((amount, share) => amount + share, 0n);
21
+ const ranked = remainders.map((_, index) => index)
22
+ .sort((a, b) => remainders[a] === remainders[b] ? a - b : remainders[a] > remainders[b] ? -1 : 1);
23
+ for (const index of ranked) {
24
+ if (leftover === 0n) break;
25
+ shares[index] += 1n;
26
+ leftover -= 1n;
27
+ }
28
+ return shares.map(Number);
29
+ }