@tallyui/pos 4.2.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.d.ts +620 -166
  2. package/dist/index.js +1970 -1091
  3. package/package.json +7 -6
  4. package/src/index.ts +15 -12
  5. package/src/order/index.ts +1 -0
  6. package/src/order/order-builder.ts +64 -22
  7. package/src/order/order-drafts.ts +77 -25
  8. package/src/order/types.ts +9 -2
  9. package/src/order/woocommerce-tax.ts +9 -12
  10. package/src/outbox/http-transport.ts +16 -1
  11. package/src/outbox/index.ts +3 -1
  12. package/src/outbox/needs-admin-reason.ts +10 -0
  13. package/src/outbox/order-outbox.ts +27 -11
  14. package/src/outbox/register-outbox.ts +4 -3
  15. package/src/outbox/store-settlement.ts +136 -0
  16. package/src/outbox/types.ts +3 -1
  17. package/src/outbox/use-order-outbox.ts +54 -4
  18. package/src/pos-order/attention-handled.ts +2 -0
  19. package/src/pos-order/command.ts +31 -9
  20. package/src/pos-order/finalize.ts +9 -0
  21. package/src/pos-order/index.ts +3 -1
  22. package/src/pos-order/needs-attention.ts +8 -3
  23. package/src/pos-order/reopen.ts +9 -2
  24. package/src/pos-order/schema.ts +20 -2
  25. package/src/pos-order/store-order-left.ts +21 -0
  26. package/src/pos-order/store-settlement.ts +51 -0
  27. package/src/pos-order/types.ts +27 -1
  28. package/src/receipt/build-receipt-data.ts +8 -1
  29. package/src/receipt/reprint.ts +2 -0
  30. package/src/receipt/types.ts +2 -0
  31. package/src/receipt-template/template-data.ts +1 -1
  32. package/src/receipt-template/wcpos/from-orders.ts +5 -1
  33. package/src/refund/index.ts +1 -0
  34. package/src/refund/needs-admin-line.ts +6 -0
  35. package/src/refund/refundable-lines.ts +2 -91
  36. package/src/refund/send-order-refund.ts +6 -1
  37. package/src/refund/submit-order-refund.ts +33 -1
  38. package/src/register/closing.ts +15 -0
  39. package/src/register/closure-document.ts +13 -5
  40. package/src/register/closure-figures.ts +83 -0
  41. package/src/register/document-labels.ts +5 -3
  42. package/src/register/expected.ts +30 -9
  43. package/src/register/index.ts +3 -1
  44. package/src/register/register-adoption.ts +42 -4
  45. package/src/register/register-document.ts +17 -0
  46. package/src/register/session-store.ts +48 -12
  47. package/src/register/use-register-session.ts +53 -20
  48. package/src/reports/adapters.ts +5 -1
  49. package/src/reports/index.ts +1 -1
  50. package/src/reports/sales-figures.ts +33 -6
  51. package/src/reports/types.ts +3 -1
  52. package/src/sale/index.ts +1 -1
  53. package/src/sale/use-sale.ts +320 -134
  54. package/src/store-orders/index.ts +3 -0
  55. package/src/store-orders/sales-range-query.ts +18 -0
  56. package/src/store-orders/use-store-refunds-in-range.ts +179 -0
  57. package/src/tax/exact.ts +2 -10
  58. package/src/tender/cash-rounding.ts +57 -6
  59. package/src/tender/index.ts +1 -1
  60. package/src/tender/payment-legs.ts +5 -0
  61. package/src/tender/tender-figures.ts +3 -1
  62. package/src/outbox/types.test-d.ts +0 -27
  63. package/src/print/escpos/sinks.test-d.ts +0 -77
@@ -1,5 +1,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 {
@@ -1,12 +1,14 @@
1
1
  export { createHttpCommandTransport } from './http-transport';
2
2
  export type { HttpTransportOptions } from './http-transport';
3
3
  export { createOrderOutbox, isRequeueable, isRequeueableOrder } from './order-outbox';
4
+ export { cancelOnStore, payRestOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './store-settlement';
4
5
  export type { OrderOutboxOptions, OrderOutbox } from './order-outbox';
5
6
  export { createRegisterOutbox, isRegisterRequeueable } from './register-outbox';
6
7
  export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';
7
8
  export { useRegisterOutbox } from './use-register-outbox';
8
9
  export type { UseRegisterOutboxOptions, UseRegisterOutboxResult } from './use-register-outbox';
9
- export type { TransportOutcome, CommandTransport, OrderTransportContext, OutboxState } from './types';
10
+ export type { TransportOutcome, NeedsAdminAnswer, CommandTransport, OrderTransportContext, OutboxState } from './types';
11
+ export { needsAdminReasonOf, NEEDS_ADMIN_RETRY_PREFIX } from './needs-admin-reason';
10
12
  export { useOrderOutbox, outboxLogger } from './use-order-outbox';
11
13
  export type { UseOrderOutboxOptions, UseOrderOutboxResult } from './use-order-outbox';
12
14
  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
+ }
@@ -3,7 +3,7 @@ import { deepEqual, type RxCollection, type RxDocumentData } from 'rxdb';
3
3
  import { BehaviorSubject, type Observable, type Subscription } from 'rxjs';
4
4
  import { outboxLogger } from './logger';
5
5
  import type { LogSyncRecord, SyncRecordOutcome } from '../logging';
6
- import { toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, uuidv7, replacedOrderIds, type PosOrder, type PosOrderServerFailures } from '../pos-order';
6
+ import { toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, uuidv7, replacedOrderIds, settledOnStore, storeOrderLeft, type PosOrder, type PosOrderServerFailures } from '../pos-order';
7
7
  import { freezeSentForm } from '../pos-order/finalize';
8
8
  import { countFresh, readFresh } from '../rxdb';
9
9
  import { createBackendNotFound, type BackendNotFound } from './backend-not-found';
@@ -26,8 +26,10 @@ export function isRequeueable(code: string | undefined): boolean {
26
26
  * Whether `requeue()` will send this order again. A rejected order: its code is requeueable, except that a reopened
27
27
  * sale (`storeOrderId`) refused with `reopen_required` or `revision_conflict` needs a fresh reopen, not a resend
28
28
  * (ADR-090 gate 5). A pending order the outbox could not build as an update (`UPDATE_UNSENDABLE`): yes, it is tried again.
29
+ * An order with a `storeSettlement` (#1101): never; the till is settling its store order instead.
29
30
  */
30
- export function isRequeueableOrder(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error'>): boolean {
31
+ export function isRequeueableOrder(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error' | 'storeSettlement'>): boolean {
32
+ if (order.storeSettlement !== undefined) return false;
31
33
  return order.syncStatus === 'pending' ? order.error?.code === UPDATE_UNSENDABLE
32
34
  : order.syncStatus === 'rejected' && isRequeueable(order.error?.code)
33
35
  && !(order.storeOrderId !== undefined && ['reopen_required', 'revision_conflict'].includes(order.error?.code ?? ''));
@@ -78,7 +80,8 @@ export interface OrderOutbox {
78
80
  * Orders isRequeueableOrder refuses are left alone. Resolves to the number requeued. */
79
81
  requeue(orderIds?: string[]): Promise<number>;
80
82
  /** Removes the rejected order `orderId` from the collection, after any running flush ends. Resolves to true when
81
- * removed; false, with nothing changed, when the id is unknown or the order is not rejected. */
83
+ * removed; false, with nothing changed, when the id is unknown, the order is not rejected, or the store created its
84
+ * order before refusing it (`storeOrderLeft`, #1101). */
82
85
  discard(orderId: string): Promise<boolean>;
83
86
  /** Watches for pending orders and sends them. */
84
87
  start(): void;
@@ -87,6 +90,11 @@ export interface OrderOutbox {
87
90
  state$: Observable<OutboxState>;
88
91
  }
89
92
 
93
+ // The hook's record() awaits this so a recorded order is in state.pending before it resolves (vendurepos/app#470).
94
+ const stateRefreshers = new WeakMap<OrderOutbox, () => Promise<void>>();
95
+ /** Recounts and publishes the outbox's state; internal to @tallyui/pos (not exported from the package). */
96
+ export const refreshOutboxState = (outbox: OrderOutbox): Promise<void> => stateRefreshers.get(outbox)?.() ?? Promise.resolve();
97
+
90
98
  export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
91
99
  const { collection, transport, deviceId } = options;
92
100
  // A reopened sale goes as order.update, never order.create (ADR-090 decision 4).
@@ -211,7 +219,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
211
219
  const refused = await readFresh(collection, { selector: { syncStatus: 'rejected' } });
212
220
  const successors = refused.length ? await readFresh(collection, { selector: { saleId: { $in: refused.map((order) => order.id) } } }) : [];
213
221
  const replaced = replacedOrderIds([...refused, ...successors]);
214
- const rejected = refused.filter((order) => !replaced.has(order.id)).length;
222
+ // A refused sale whose store order is settled on the store (#1101) no longer counts.
223
+ const rejected = refused.filter((order) => !replaced.has(order.id) && !settledOnStore(order)).length;
215
224
  state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
216
225
  }
217
226
 
@@ -223,9 +232,10 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
223
232
 
224
233
  // A failure the store answered (not offline). Returns undefined when the run goes on at once, or the
225
234
  // 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) {
235
+ function serverFailed(orders: PosOrder[], alone: 'probe' | 'isolated' | undefined, reason: string, retryAfterMs?: number, needsAdminId?: string) {
227
236
  const at = now();
228
- for (const { commandId } of orders) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq, reason });
237
+ for (const { commandId } of orders) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq,
238
+ reason: needsAdminId === undefined || commandId === needsAdminId ? reason : 'status_409' });
229
239
  const id = orders[0].commandId;
230
240
  if (alone === 'isolated') {
231
241
  isolate(id, reason, retryAfterMs);
@@ -234,7 +244,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
234
244
  if (runProgressed && retryAfterMs === undefined && reason !== 'status_429') return undefined;
235
245
  return Math.max(retryAfterMs ?? 0, isolated.get(id)!.nextAt - now());
236
246
  }
237
- if (alone === 'probe') walk?.failed.set(id, { orderId: orders[0].id, reason });
247
+ if (alone === 'probe') walk?.failed.set(id, { orderId: orders[0].id,
248
+ reason: needsAdminId === undefined || id === needsAdminId ? reason : 'status_409' });
238
249
  else {
239
250
  head = { id, count: head?.id === id ? head.count + 1 : 1 };
240
251
  if (head.count >= isolateAfter) walk ??= { failed: new Map() };
@@ -390,7 +401,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
390
401
  // no answer in time) is not offline: it counts like a 503 and never pauses a clock.
391
402
  for (const clock of clocks.values()) clock.pausedAt ??= now();
392
403
  walk = undefined;
393
- } else if ((floor = serverFailed(orders, alone, outcome.reason, outcome.retryAfterMs)) === undefined) continue;
404
+ } else if ((floor = serverFailed(orders, alone, outcome.reason, outcome.retryAfterMs, outcome.needsAdmin?.id)) === undefined) continue;
394
405
  return scheduleRetry(outcome.reason, floor);
395
406
  }
396
407
  if (outcome.kind === 'unauthorized') {
@@ -549,7 +560,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
549
560
  }
550
561
 
551
562
  updateState().catch(() => {});
552
- return {
563
+ const outbox: OrderOutbox = {
553
564
  state$,
554
565
  flush,
555
566
  async requeue(orderIds) {
@@ -577,7 +588,9 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
577
588
  delete data.sentVersion;
578
589
  delete data.downgradedFrom;
579
590
  // The server ledger stored the rejection under the old id; replaying it returns that rejection.
580
- // For the codes requeue() accepts, the server created no order, so a fresh id cannot duplicate one.
591
+ // The create push keys on the order's id (the transport's recordId is clientOrderId), which a requeue leaves
592
+ // unchanged; so the resend of a row whose order the store created (storeOrderLeft, #1101) carries that order's
593
+ // clientOrderId again.
581
594
  data.commandId = uuidv7();
582
595
  data.updatedAt = new Date(now()).toISOString();
583
596
  return data;
@@ -598,7 +611,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
598
611
  // requeue that won the race leaves its pending order in place.
599
612
  await (await collection.findOne(orderId).exec())?.incrementalModify((data) => {
600
613
  // The modifier runs again on a write conflict, so it decides on each run.
601
- commandId = data.syncStatus === 'rejected' ? data.commandId : undefined;
614
+ // A refused sale whose order the store created (storeOrderLeft, #1101) stays: the till settles that order instead.
615
+ commandId = data.syncStatus === 'rejected' && storeOrderLeft(data) === undefined ? data.commandId : undefined;
602
616
  if (commandId === undefined) return data;
603
617
  data._deleted = true;
604
618
  return data;
@@ -633,4 +647,6 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
633
647
  state$.next({ ...state$.value, nextAttemptAt: undefined });
634
648
  },
635
649
  };
650
+ stateRefreshers.set(outbox, () => updateState());
651
+ return outbox;
636
652
  }
@@ -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') {
@@ -0,0 +1,136 @@
1
+ import type { SettleCancelRequest, SettleOutcome, SettlePayment, SettlePayRequest, SettlePayResult } from '@tallyui/core';
2
+ import type { RxCollection } from 'rxdb';
3
+ import { outboxLogger } from './logger';
4
+ import { canCancelOnStore, canPayRestOnStore, storeOrderLeft, unrecordedLegs, uuidv7, type PosOrder, type PosOrderStoreSettlement } from '../pos-order';
5
+
6
+ export interface CancelOnStoreDeps {
7
+ orders: RxCollection<PosOrder>;
8
+ /** The connector's cancel, bound to the open store (`RefusedOrderSettlement.cancel`). */
9
+ cancel(request: SettleCancelRequest): Promise<SettleOutcome>;
10
+ now?: () => Date;
11
+ }
12
+
13
+ /**
14
+ * Cancels on the store the order a refused sale left behind (#1101), when `canCancelOnStore` allows it on the stored
15
+ * row; otherwise resolves to `not_offered` and never calls `cancel`. It first stores the attempt as `sending` (keeping
16
+ * the stored `attemptId` of a cancel still `sending`, so a repeat is the same attempt), and only once that write has
17
+ * resolved calls `cancel`. The outcome is written only while the stored settlement is still this attempt's `sending`
18
+ * one; `retry` writes nothing, and a rejected `cancel` leaves the row `sending` and rejects with the same error.
19
+ * `syncStatus`, `error`, `commandId`, `payments` and the totals are never changed. pos_orders is till-local, never
20
+ * pulled from a store, so these writes break no replication rule.
21
+ */
22
+ export async function cancelOnStore(deps: CancelOnStoreDeps, orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
23
+ const stamp = () => (deps.now?.() ?? new Date()).toISOString();
24
+ let request: SettleCancelRequest | undefined;
25
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
26
+ // The modifier runs again on a write conflict, so it decides on the stored state each run.
27
+ request = undefined;
28
+ if (data._deleted || !canCancelOnStore(data)) return data;
29
+ const stored = data.storeSettlement;
30
+ const attemptId = stored?.kind === 'cancel' && stored.state === 'sending' ? stored.attemptId : uuidv7();
31
+ const at = stamp();
32
+ data.storeSettlement = { kind: 'cancel', state: 'sending', attemptId, at };
33
+ data.updatedAt = at;
34
+ request = { storeOrderId: storeOrderLeft(data)!.orderId, clientOrderId: data.id, attemptId };
35
+ return data;
36
+ });
37
+ if (!request) return { kind: 'not_offered' };
38
+ const sent: SettleCancelRequest = request;
39
+ const outcome = await deps.cancel(sent);
40
+ if (outcome.kind === 'retry') {
41
+ outboxLogger.info('Cancelling the store order got no definite answer; it stays sending', { orderId, reason: outcome.reason });
42
+ return outcome;
43
+ }
44
+ if (outcome.kind === 'refused') outboxLogger.warn('The store refused to cancel the order', { orderId, code: outcome.code, message: outcome.message });
45
+ if (outcome.kind === 'changed') {
46
+ outboxLogger.warn('The store order changed; nothing was cancelled', { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
47
+ }
48
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
49
+ const stored = data.storeSettlement;
50
+ // A newer attempt, or an answer already written, wins over this one.
51
+ if (stored?.attemptId !== sent.attemptId || stored.state !== 'sending') return data;
52
+ const at = stamp();
53
+ const base = { kind: 'cancel' as const, attemptId: sent.attemptId, at };
54
+ const settled: PosOrderStoreSettlement = outcome.kind === 'done' ? { ...base, state: 'done', storeStatus: outcome.status }
55
+ : outcome.kind === 'changed' ? { ...base, state: 'changed', storeStatus: outcome.status, capturedMinor: outcome.capturedMinor }
56
+ : outcome.kind === 'refused' ? { ...base, state: 'refused', code: outcome.code, message: outcome.message }
57
+ : { ...base, state: 'gone' };
58
+ data.storeSettlement = settled;
59
+ data.updatedAt = at;
60
+ return data;
61
+ });
62
+ return outcome;
63
+ }
64
+
65
+ export interface PayRestOnStoreDeps {
66
+ orders: RxCollection<PosOrder>;
67
+ /** The connector's pay, bound to the open store (`RefusedOrderSettlement.pay`). */
68
+ pay(request: SettlePayRequest): Promise<SettlePayResult>;
69
+ now?: () => Date;
70
+ }
71
+
72
+ type StoredPayment = NonNullable<PosOrderStoreSettlement['payments']>[number];
73
+
74
+ /**
75
+ * Records on the store the legs of a refused sale its part-paid store order is missing (#1101 slice 3), when
76
+ * `canPayRestOnStore` allows it on the stored row; otherwise resolves to `not_offered` and never calls `pay`. No money is
77
+ * taken: each leg of `unrecordedLegs` is sent under a new id (method, amount, and `tenderedMinor` for cash only, never
78
+ * the change), except that a stored pay with one payment per leg keeps its ids, amounts and `done` flags, so the store
79
+ * skips a leg it already holds. It first stores the attempt as `sending` with those ids (a pay still `sending` also keeps
80
+ * its `attemptId`, so a repeat is the same attempt; any other mints a new one), and only once that write has resolved
81
+ * calls `pay`. The answer is written only while the stored settlement is still this attempt's `sending` one: every id in
82
+ * `recorded` is marked `done` whatever the outcome, `retry` keeps `sending`, and a rejected `pay` leaves the row
83
+ * `sending` and rejects with the same error.
84
+ * `syncStatus`, `error`, `commandId`, `payments` and the totals are never changed.
85
+ */
86
+ export async function payRestOnStore(deps: PayRestOnStoreDeps, orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }> {
87
+ const stamp = () => (deps.now?.() ?? new Date()).toISOString();
88
+ let request: SettlePayRequest | undefined;
89
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
90
+ // The modifier runs again on a write conflict, so it decides on the stored state each run.
91
+ request = undefined;
92
+ if (data._deleted || !canPayRestOnStore(data)) return data;
93
+ const stored = data.storeSettlement;
94
+ const legs = unrecordedLegs(data);
95
+ const again = stored?.kind === 'pay' && stored.payments?.length === legs.length ? stored : undefined;
96
+ const attemptId = again?.state === 'sending' ? again.attemptId : uuidv7();
97
+ const payments: StoredPayment[] = again?.payments ?? legs.map((leg) => ({
98
+ id: uuidv7(), method: leg.method, amountMinor: leg.amountMinor,
99
+ ...(leg.method === 'cash' && leg.tenderedMinor !== undefined ? { tenderedMinor: leg.tenderedMinor } : {}),
100
+ }));
101
+ const at = stamp();
102
+ data.storeSettlement = { kind: 'pay', state: 'sending', attemptId, at, payments };
103
+ data.updatedAt = at;
104
+ request = { storeOrderId: storeOrderLeft(data)!.orderId, clientOrderId: data.id, attemptId, currency: data.currency,
105
+ payments: payments.map(({ done: _done, ...payment }) => payment as SettlePayment) };
106
+ return data;
107
+ });
108
+ if (!request) return { kind: 'not_offered' };
109
+ const sent: SettlePayRequest = request;
110
+ const { outcome, recorded } = await deps.pay(sent);
111
+ if (outcome.kind === 'retry') {
112
+ outboxLogger.info('Recording the rest on the store got no definite answer; it stays sending', { orderId, reason: outcome.reason, recorded: recorded.length });
113
+ }
114
+ if (outcome.kind === 'refused') outboxLogger.warn('The store refused to record the rest of the order', { orderId, code: outcome.code, message: outcome.message });
115
+ if (outcome.kind === 'changed') {
116
+ outboxLogger.warn('The store order changed; nothing more was recorded', { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
117
+ }
118
+ const done = new Set(recorded);
119
+ await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
120
+ const stored = data.storeSettlement;
121
+ // A newer attempt, or an answer already written, wins over this one.
122
+ if (stored?.attemptId !== sent.attemptId || stored.state !== 'sending') return data;
123
+ const payments = (stored.payments ?? []).map((payment) => (done.has(payment.id) ? { ...payment, done: true } : payment));
124
+ if (outcome.kind === 'retry' && payments.every((payment, index) => payment.done === stored.payments?.[index]?.done)) return data;
125
+ const at = stamp();
126
+ const base = { kind: 'pay' as const, attemptId: sent.attemptId, at, payments };
127
+ data.storeSettlement = outcome.kind === 'retry' ? { ...stored, payments }
128
+ : outcome.kind === 'done' ? { ...base, state: 'done', storeStatus: outcome.status }
129
+ : outcome.kind === 'changed' ? { ...base, state: 'changed', storeStatus: outcome.status, capturedMinor: outcome.capturedMinor }
130
+ : outcome.kind === 'refused' ? { ...base, state: 'refused', code: outcome.code, message: outcome.message }
131
+ : { ...base, state: 'gone' };
132
+ data.updatedAt = outcome.kind === 'retry' ? data.updatedAt : at;
133
+ return data;
134
+ });
135
+ return outcome;
136
+ }
@@ -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>;
@@ -1,10 +1,11 @@
1
- import type { OrderCreateEnvelope, OrderUpdateEnvelope } from '@tallyui/core';
1
+ import type { OrderCreateEnvelope, OrderUpdateEnvelope, SettleCancelRequest, SettleOutcome, SettlePayRequest, SettlePayResult } from '@tallyui/core';
2
2
  import { useEffect, useMemo, useRef, useState } from 'react';
3
3
  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
+ import { cancelOnStore as cancelStoreOrder, payRestOnStore as payStoreRest } from './store-settlement';
8
9
  import type { CommandTransport, OutboxState } from './types';
9
10
 
10
11
  const idle: OutboxState = { pending: 0, sending: false };
@@ -28,6 +29,12 @@ export interface UseOrderOutboxOptions {
28
29
  onBusy?(busy: boolean): void;
29
30
  /** Called when `open` rejects, even if the key has changed since (medusapos: reports storage worker failures). */
30
31
  onOpenError?(error: unknown): void;
32
+ /** The settlement of a refused sale's store order (#1101) for `storeKey`: the connector's `cancel` and `pay`, bound to
33
+ * that store. Read on each call, for the open store. */
34
+ storeSettlement?(storeKey: string): {
35
+ cancel?(request: SettleCancelRequest): Promise<SettleOutcome>;
36
+ pay?(request: SettlePayRequest): Promise<SettlePayResult>;
37
+ } | undefined;
31
38
  }
32
39
 
33
40
  export interface UseOrderOutboxResult {
@@ -38,7 +45,7 @@ export interface UseOrderOutboxResult {
38
45
  /** The newest 50 orders, newest first; empty until the current store is ready. */
39
46
  recent: PosOrder[];
40
47
  /**
41
- * Stores a finalized order, then flushes. Throws the opening error, or "Orders are not ready.", before the store is ready.
48
+ * 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
49
  * Recording an order whose `id` is already stored, not deleted, with the same money-bearing content (`sameSale`;
43
50
  * a retried `complete()`) counts as stored, never overwrites it, and still flushes, whatever the stored `commandId`
44
51
  * (a requeue mints a new one; the difference is logged at warn). Other content rejects with `OrderContentMismatchError`.
@@ -56,6 +63,19 @@ export interface UseOrderOutboxResult {
56
63
  requeue(orderIds?: string[]): Promise<number>;
57
64
  /** Removes one rejected order (see `OrderOutbox.discard`); resolves to false before the current store is ready. */
58
65
  discard(orderId: string): Promise<boolean>;
66
+ /**
67
+ * Cancels on the store the order a refused sale left behind (`cancelOnStore`, #1101), with the `cancel` of
68
+ * `storeSettlement` for the open store, then recounts the outbox state, whether the cancel resolved or rejected.
69
+ * Resolves to `not_offered` before the current store is ready, or when there is no `storeSettlement` or no `cancel`.
70
+ */
71
+ cancelOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
72
+ /**
73
+ * Records on the store the till's legs a refused sale's part-paid store order is missing (`payRestOnStore`, #1101
74
+ * slice 3), with the `pay` of `storeSettlement` for the open store, then recounts the outbox state, whether the pay
75
+ * resolved or rejected. Resolves to `not_offered` before the current store is ready, or when there is no
76
+ * `storeSettlement` or no `pay`.
77
+ */
78
+ payRestOnStore(orderId: string): Promise<SettleOutcome | { kind: 'not_offered' }>;
59
79
  /**
60
80
  * The count of `record()` calls not yet settled (resolved or rejected). An app holds sign-out
61
81
  * (closing the store) while this is above 0, because a close that lands under a write stuck in
@@ -135,6 +155,32 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
135
155
  const opened = current.current;
136
156
  return opened && opened.storeKey === storeKey ? opened.outbox.discard(orderId) : false;
137
157
  },
158
+ async cancelOnStore(orderId) {
159
+ const opened = current.current;
160
+ if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
161
+ const settlement = latest.current.storeSettlement?.(opened.storeKey);
162
+ const cancel = settlement?.cancel?.bind(settlement);
163
+ if (!cancel) return { kind: 'not_offered' };
164
+ try {
165
+ return await cancelStoreOrder({ orders: opened.orders, cancel }, orderId);
166
+ } finally {
167
+ // A settled row leaves state.rejected: publish it before resolving.
168
+ try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
169
+ }
170
+ },
171
+ async payRestOnStore(orderId) {
172
+ const opened = current.current;
173
+ if (!opened || opened.storeKey !== storeKey) return { kind: 'not_offered' };
174
+ const settlement = latest.current.storeSettlement?.(opened.storeKey);
175
+ const pay = settlement?.pay?.bind(settlement);
176
+ if (!pay) return { kind: 'not_offered' };
177
+ try {
178
+ return await payStoreRest({ orders: opened.orders, pay }, orderId);
179
+ } finally {
180
+ // A settled row leaves state.rejected: publish it before resolving.
181
+ try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
182
+ }
183
+ },
138
184
  savesInFlight: savesInFlightCount,
139
185
  stuckCommandIds,
140
186
  async record(posOrder) {
@@ -159,7 +205,11 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
159
205
  storedCommandId: inDb.commandId, recordedCommandId: posOrder.commandId });
160
206
  }
161
207
  }
162
- if (current.current === opened) void opened.outbox.flush();
208
+ if (current.current === opened) {
209
+ // Publish the stored order in state.pending before resolving: a caller that renders on resolve must see it (vendurepos/app#470).
210
+ try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
211
+ if (current.current === opened) void opened.outbox.flush(); // the store can switch or unmount during the refresh: a stopped outbox is never flushed again
212
+ }
163
213
  } finally {
164
214
  savesInFlight.current--;
165
215
  setSavesInFlightCount(savesInFlight.current);
@@ -5,6 +5,8 @@ import type { PosOrder } from './types';
5
5
  * Marks the order `orderId` handled for its current `commandId`, so `needsAttention` leaves it out until a requeue
6
6
  * mints a new one (ADR-092 6f, tally-woo 03). Resolves to true when the order is stamped (or already was, for this
7
7
  * commandId); false, with nothing changed, when the id is unknown or the order is pending (still the outbox's to settle).
8
+ * The stamp does not hide a refused sale whose order the store created (`storeOrderLeft`, #1101): it is still written
9
+ * and the call still resolves to true, but `needsAttention` keeps that sale.
8
10
  */
9
11
  export async function markAttentionHandled(orders: RxCollection<PosOrder>, orderId: string, now?: () => Date): Promise<boolean> {
10
12
  const doc = await orders.findOne(orderId).exec();
@@ -1,7 +1,8 @@
1
1
  import { ORDER_META_KEY_MAX, ORDER_META_MAX, ORDER_NOTE_MAX, ORDER_TAX_ID_TYPE_MAX, ORDER_TAX_ID_VALUE_MAX, ORDER_TAX_IDS_MAX } from '@tallyui/core';
2
2
  import type { OrderCreateEnvelope, OrderCreateMeta, OrderCreatePayload, OrderCreateTaxId, OrderUpdateEnvelope, OrderUpdatePayload } from '@tallyui/core';
3
3
  import { MICROS_PER_MINOR, roundMicrosToMinor, taxMicros } from '../tax/exact';
4
- import { woocommerceChargeTaxMinor } from '../order/woocommerce-tax';
4
+ import { woocommerceChargeTaxMinor, woocommerceLine } from '../order/woocommerce-tax';
5
+ import type { LineTaxLine } from '../order/types';
5
6
  import type { PosOrder, PosOrderLine } from './types';
6
7
 
7
8
  /** The highest order.create version this till sends; pos_orders' sentVersion and downgradedFrom maxima must equal it. */
@@ -82,12 +83,22 @@ export const editedSku = (line: PosOrderLine) => !line.custom && line.catalogueS
82
83
  /**
83
84
  * Version 4 (#286): a line's discount made tax-exclusive. An exclusive line's is unchanged; an inclusive line's
84
85
  * gross discount D on its amount A becomes `net(A) − net(A − D)`, exact in millionths, rounded half away from zero.
85
- * Tax comes from stored taxLines after D, recomputed before a store-priced coupon, and from `taxMicros` before D.
86
+ * A Woo-rounded line with a coupon or a compound rate takes both nets from `woocommerceLine` at its stored rates (#1342):
87
+ * its stored taxLines are after the coupon. Otherwise tax comes from stored taxLines after D, recomputed before a
88
+ * store-priced coupon, and from `taxMicros` before D.
86
89
  */
87
- function netDiscountMinor(line: PosOrderLine, pricesIncludeTax: boolean, woocommerce: boolean): number {
88
- if (!(line.taxInclusive ?? pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
89
- const ratePpm = line.taxLines.reduce((sum, tax) => sum + tax.ratePpm, 0);
90
+ function netDiscountMinor(line: PosOrderLine, order: Pick<PosOrder, 'pricesIncludeTax' | 'taxRounding' | 'coupons' | 'currency'>): number {
91
+ if (!(line.taxInclusive ?? order.pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
92
+ const woocommerce = order.taxRounding?.granularity === 'woocommerce', stored: readonly LineTaxLine[] = line.taxLines;
90
93
  const afterDiscount = line.unitPriceMinor * line.quantity - line.discountMinor;
94
+ if (woocommerce && (order.coupons?.length || stored.some((tax) => tax.compound))) {
95
+ const rates = stored.map((tax, i) => ({ id: i, code: tax.code ?? '', label: '', rate: (tax.ratePpm / 10000).toFixed(4),
96
+ priority: i, compound: tax.compound ?? false, shipping: true }));
97
+ // Only netMicros is read: the net before any coupon, which roundAtSubtotal does not change.
98
+ const net = (minor: number) => BigInt(woocommerceLine(minor, rates, true, order.currency, false).netMicros);
99
+ return roundMicrosToMinor(net(line.unitPriceMinor * line.quantity) - net(afterDiscount));
100
+ }
101
+ const ratePpm = line.taxLines.reduce((sum, tax) => sum + tax.ratePpm, 0);
91
102
  // A store-priced coupon leaves stored taxLines after the coupon; the line discount needs tax before it.
92
103
  const taxAfter = !woocommerce && line.netMinor < afterDiscount ? taxMicros(afterDiscount, ratePpm, true)
93
104
  : line.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n);
@@ -120,9 +131,17 @@ function wireNote(note: string | undefined): string | undefined {
120
131
  return newline === -1 ? undefined : note.slice(newline + 1) || undefined;
121
132
  }
122
133
 
134
+ /** #1341 (ADR-075/076): in Woo rounding a charge goes on the wire at its display row, found by id (the server checks the
135
+ * two are equal); with no such row it goes at its stored amount. Any other rounding sends the stored amount. */
136
+ function wireChargeMinor(order: PosOrder, charge: { id: string; amountMinor: number }, rows?: readonly { id: string; amountMinor: number }[]): number {
137
+ if (order.taxRounding?.granularity !== 'woocommerce') return charge.amountMinor;
138
+ return rows?.find(({ id }) => id === charge.id)?.amountMinor ?? charge.amountMinor;
139
+ }
140
+
123
141
  /**
124
142
  * Builds the ADR-038 order.create envelope for a PosOrder. It sends the stored order unchanged, so every resend of
125
- * an order is byte-identical, and an order stored by an older till goes out exactly as that till sent it:
143
+ * an order is byte-identical, except that a Woo-rounded order with charge display rows sends each charge at its row
144
+ * (`wireChargeMinor`, #1341) and everything else as stored:
126
145
  * `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
127
146
  * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
128
147
  * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
@@ -184,7 +203,7 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
184
203
  const withTaxAddress = version === 8 || (version >= 9 && taxAddress !== undefined);
185
204
  const withAddresses = withTaxAddress || version >= UNTAXED_ADDRESS_ORDER_CREATE_VERSION;
186
205
  const taxIds = version >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && sentTaxIds.length ? { taxIds: sentTaxIds } : undefined;
187
- const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order.pricesIncludeTax, order.taxRounding?.granularity === 'woocommerce') : line.discountMinor);
206
+ const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order) : line.discountMinor);
188
207
  for (const coupon of carried) {
189
208
  if (!coupon.lines) throw new Error(`Order ${order.id}: a carried coupon has no line shares`);
190
209
  for (const [i, line] of order.lines.entries()) lineDiscounts[i] += coupon.lines.find(({ lineId }) => lineId === line.id)?.discountMinor ?? 0;
@@ -215,7 +234,7 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
215
234
  ...(base === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
216
235
  })),
217
236
  ...(base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
218
- clientFeeId: fee.id, name: fee.name, amountMinor: fee.amountMinor, taxStatus: fee.taxStatus,
237
+ clientFeeId: fee.id, name: fee.name, amountMinor: wireChargeMinor(order, fee, order.display?.fees), taxStatus: fee.taxStatus,
219
238
  ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
220
239
  // #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
221
240
  taxMinor: order.taxRounding?.granularity === 'woocommerce'
@@ -224,7 +243,7 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
224
243
  })) } : {}),
225
244
  ...(base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
226
245
  clientShippingId: charge.id, name: charge.name, ...(charge.methodId !== undefined ? { methodId: charge.methodId } : {}),
227
- amountMinor: charge.amountMinor, taxStatus: charge.taxStatus,
246
+ amountMinor: wireChargeMinor(order, charge, order.display?.shipping), taxStatus: charge.taxStatus,
228
247
  ...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}),
229
248
  // #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
230
249
  taxMinor: order.taxRounding?.granularity === 'woocommerce'
@@ -246,6 +265,9 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
246
265
  subtotalMinor: order.subtotalMinor,
247
266
  ...(discountMinor > 0 ? { discountMinor } : {}),
248
267
  taxMinor: order.taxMinor, totalMinor: order.totalMinor,
268
+ // ADR-094: a rounded sale's entries ride at its content version; finalize refuses them unless the store declares cashRounding.
269
+ ...(order.cashRoundings?.length
270
+ ? { cashRoundings: order.cashRoundings.map(({ paymentId, minor }) => ({ paymentId, minor })) } : {}),
249
271
  ...(base >= 3 ? {
250
272
  display: { ...storedDisplay, lines: order.display!.lines.map(({ lineId, amountMinor, discounts }) => ({
251
273
  clientLineId: lineId, amountMinor, discounts,
@@ -209,6 +209,9 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
209
209
  if (order.lineItems.some((line) => line.anyAttributes?.length) && (options.capabilities?.orderCreate ?? 1) < 6) {
210
210
  throw new Error("finalize: picked options need the store to accept order.create version 6; update the store's TallyUI plugin");
211
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
+ }
212
215
  if (!order.lineItems.length) throw new Error('finalize: no lines');
213
216
  // Defence in depth: the builder already clamps every discount to >= 0, so this should never fire.
214
217
  if (order.discountMinor < 0
@@ -306,6 +309,7 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
306
309
  ...(payment.changeMinor !== undefined ? { changeMinor: payment.changeMinor } : {}),
307
310
  ...(payment.reference !== undefined ? { reference: payment.reference } : {}),
308
311
  ...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
312
+ ...(payment.sessionId !== undefined ? { sessionId: payment.sessionId } : {}),
309
313
  }));
310
314
  // A warning naming a payment the order no longer has is dropped and logged, never thrown: this runs at sale completion.
311
315
  const localWarnings = options.localWarnings?.flatMap((warning): PosOrderLocalWarning[] => {
@@ -377,6 +381,11 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
377
381
  return freezeSentForm({
378
382
  id, saleId: order.id, createdAt: afterClose?.createdAt ?? now, updatedAt: now, commandId: newId(), syncStatus: 'pending',
379
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
+ }) } : {}),
380
389
  ...(fees?.length ? { fees } : {}), ...(shipping?.length ? { shipping } : {}),
381
390
  subtotalMinor: order.subtotalMinor, discountMinor: order.discountMinor,
382
391
  taxMinor: order.taxMinor, totalMinor: order.totalMinor, taxRounding,
@@ -1,4 +1,4 @@
1
- export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder } from './types';
1
+ export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, PosOrderStoreSettlement } from './types';
2
2
  export { uuidv7 } from './uuidv7';
3
3
  export { AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder } from './finalize';
4
4
  export type { FinalizeOptions } from './finalize';
@@ -7,6 +7,8 @@ export { posOrderSchema, posOrderCollection } from './schema';
7
7
  export { addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger } from './open';
8
8
  export { getDeviceId } from './device-id';
9
9
  export { needsAttention, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE } from './needs-attention';
10
+ export { storeOrderLeft } from './store-order-left';
11
+ export { canCancelOnStore, canPayRestOnStore, settledOnStore, unrecordedLegs } from './store-settlement';
10
12
  export { markAttentionHandled } from './attention-handled';
11
13
  export { moneyDivergence, type MoneyDivergence } from './money-divergence';
12
14
  export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './reopen';