@tallyui/pos 4.2.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +465 -162
- package/dist/index.js +1752 -1104
- package/package.json +7 -6
- package/src/index.ts +12 -9
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +64 -22
- package/src/order/order-drafts.ts +77 -25
- package/src/order/types.ts +9 -2
- package/src/order/woocommerce-tax.ts +9 -12
- package/src/outbox/http-transport.ts +16 -1
- package/src/outbox/index.ts +2 -1
- package/src/outbox/needs-admin-reason.ts +10 -0
- package/src/outbox/order-outbox.ts +14 -5
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-order-outbox.ts +7 -3
- package/src/pos-order/command.ts +3 -0
- package/src/pos-order/finalize.ts +9 -0
- package/src/pos-order/reopen.ts +9 -2
- package/src/pos-order/schema.ts +5 -2
- package/src/pos-order/types.ts +5 -1
- package/src/receipt/build-receipt-data.ts +8 -1
- package/src/receipt/reprint.ts +2 -0
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/template-data.ts +1 -1
- package/src/receipt-template/wcpos/from-orders.ts +5 -1
- package/src/refund/index.ts +1 -0
- package/src/refund/needs-admin-line.ts +6 -0
- package/src/refund/refundable-lines.ts +2 -91
- package/src/refund/send-order-refund.ts +6 -1
- package/src/refund/submit-order-refund.ts +33 -1
- package/src/register/closing.ts +15 -0
- package/src/register/closure-document.ts +13 -5
- package/src/register/closure-figures.ts +83 -0
- package/src/register/document-labels.ts +5 -3
- package/src/register/expected.ts +30 -9
- package/src/register/index.ts +3 -1
- package/src/register/register-adoption.ts +42 -4
- package/src/register/register-document.ts +17 -0
- package/src/register/session-store.ts +48 -12
- package/src/register/use-register-session.ts +53 -20
- package/src/reports/adapters.ts +5 -1
- package/src/reports/index.ts +1 -1
- package/src/reports/sales-figures.ts +33 -6
- package/src/reports/types.ts +3 -1
- package/src/sale/index.ts +1 -1
- package/src/sale/use-sale.ts +313 -134
- package/src/store-orders/index.ts +3 -0
- package/src/store-orders/sales-range-query.ts +18 -0
- package/src/store-orders/use-store-refunds-in-range.ts +179 -0
- package/src/tax/exact.ts +2 -10
- package/src/tender/cash-rounding.ts +49 -6
- package/src/tender/index.ts +1 -1
- package/src/tender/payment-legs.ts +5 -0
- package/src/tender/tender-figures.ts +3 -1
- package/src/outbox/types.test-d.ts +0 -27
- 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 {
|
package/src/outbox/index.ts
CHANGED
|
@@ -6,7 +6,8 @@ export { createRegisterOutbox, isRegisterRequeueable } from './register-outbox';
|
|
|
6
6
|
export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';
|
|
7
7
|
export { useRegisterOutbox } from './use-register-outbox';
|
|
8
8
|
export type { UseRegisterOutboxOptions, UseRegisterOutboxResult } from './use-register-outbox';
|
|
9
|
-
export type { TransportOutcome, CommandTransport, OrderTransportContext, OutboxState } from './types';
|
|
9
|
+
export type { TransportOutcome, NeedsAdminAnswer, CommandTransport, OrderTransportContext, OutboxState } from './types';
|
|
10
|
+
export { needsAdminReasonOf, NEEDS_ADMIN_RETRY_PREFIX } from './needs-admin-reason';
|
|
10
11
|
export { useOrderOutbox, outboxLogger } from './use-order-outbox';
|
|
11
12
|
export type { UseOrderOutboxOptions, UseOrderOutboxResult } from './use-order-outbox';
|
|
12
13
|
export { summarizeOutboxHealth, watchOutboxHealth } from './outbox-health';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** The retry reason prefix the transport gives a 409 needs_admin answer; the server's reason follows it. */
|
|
2
|
+
export const NEEDS_ADMIN_RETRY_PREFIX = 'needs_admin:';
|
|
3
|
+
/** A needs_admin reason the till accepts: snake_case, 1–40 characters, so the prefixed retry reason fits the 64 the order keeps. */
|
|
4
|
+
export const NEEDS_ADMIN_REASON = /^[a-z][a-z0-9_]{0,39}$/;
|
|
5
|
+
/** The server's needs_admin reason inside an outbox retry reason, or undefined when the reason is anything else. */
|
|
6
|
+
export function needsAdminReasonOf(retryReason: string): string | undefined {
|
|
7
|
+
if (!retryReason.startsWith(NEEDS_ADMIN_RETRY_PREFIX)) return undefined;
|
|
8
|
+
const reason = retryReason.slice(NEEDS_ADMIN_RETRY_PREFIX.length);
|
|
9
|
+
return NEEDS_ADMIN_REASON.test(reason) ? reason : undefined;
|
|
10
|
+
}
|
|
@@ -87,6 +87,11 @@ export interface OrderOutbox {
|
|
|
87
87
|
state$: Observable<OutboxState>;
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
// The hook's record() awaits this so a recorded order is in state.pending before it resolves (vendurepos/app#470).
|
|
91
|
+
const stateRefreshers = new WeakMap<OrderOutbox, () => Promise<void>>();
|
|
92
|
+
/** Recounts and publishes the outbox's state; internal to @tallyui/pos (not exported from the package). */
|
|
93
|
+
export const refreshOutboxState = (outbox: OrderOutbox): Promise<void> => stateRefreshers.get(outbox)?.() ?? Promise.resolve();
|
|
94
|
+
|
|
90
95
|
export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
91
96
|
const { collection, transport, deviceId } = options;
|
|
92
97
|
// A reopened sale goes as order.update, never order.create (ADR-090 decision 4).
|
|
@@ -223,9 +228,10 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
223
228
|
|
|
224
229
|
// A failure the store answered (not offline). Returns undefined when the run goes on at once, or the
|
|
225
230
|
// floor for the retry: the store's Retry-After, or an isolated order's own backoff.
|
|
226
|
-
function serverFailed(orders: PosOrder[], alone: 'probe' | 'isolated' | undefined, reason: string, retryAfterMs?: number) {
|
|
231
|
+
function serverFailed(orders: PosOrder[], alone: 'probe' | 'isolated' | undefined, reason: string, retryAfterMs?: number, needsAdminId?: string) {
|
|
227
232
|
const at = now();
|
|
228
|
-
for (const { commandId } of orders) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq,
|
|
233
|
+
for (const { commandId } of orders) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq,
|
|
234
|
+
reason: needsAdminId === undefined || commandId === needsAdminId ? reason : 'status_409' });
|
|
229
235
|
const id = orders[0].commandId;
|
|
230
236
|
if (alone === 'isolated') {
|
|
231
237
|
isolate(id, reason, retryAfterMs);
|
|
@@ -234,7 +240,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
234
240
|
if (runProgressed && retryAfterMs === undefined && reason !== 'status_429') return undefined;
|
|
235
241
|
return Math.max(retryAfterMs ?? 0, isolated.get(id)!.nextAt - now());
|
|
236
242
|
}
|
|
237
|
-
if (alone === 'probe') walk?.failed.set(id, { orderId: orders[0].id,
|
|
243
|
+
if (alone === 'probe') walk?.failed.set(id, { orderId: orders[0].id,
|
|
244
|
+
reason: needsAdminId === undefined || id === needsAdminId ? reason : 'status_409' });
|
|
238
245
|
else {
|
|
239
246
|
head = { id, count: head?.id === id ? head.count + 1 : 1 };
|
|
240
247
|
if (head.count >= isolateAfter) walk ??= { failed: new Map() };
|
|
@@ -390,7 +397,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
390
397
|
// no answer in time) is not offline: it counts like a 503 and never pauses a clock.
|
|
391
398
|
for (const clock of clocks.values()) clock.pausedAt ??= now();
|
|
392
399
|
walk = undefined;
|
|
393
|
-
} else if ((floor = serverFailed(orders, alone, outcome.reason, outcome.retryAfterMs)) === undefined) continue;
|
|
400
|
+
} else if ((floor = serverFailed(orders, alone, outcome.reason, outcome.retryAfterMs, outcome.needsAdmin?.id)) === undefined) continue;
|
|
394
401
|
return scheduleRetry(outcome.reason, floor);
|
|
395
402
|
}
|
|
396
403
|
if (outcome.kind === 'unauthorized') {
|
|
@@ -549,7 +556,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
549
556
|
}
|
|
550
557
|
|
|
551
558
|
updateState().catch(() => {});
|
|
552
|
-
|
|
559
|
+
const outbox: OrderOutbox = {
|
|
553
560
|
state$,
|
|
554
561
|
flush,
|
|
555
562
|
async requeue(orderIds) {
|
|
@@ -633,4 +640,6 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
633
640
|
state$.next({ ...state$.value, nextAttemptAt: undefined });
|
|
634
641
|
},
|
|
635
642
|
};
|
|
643
|
+
stateRefreshers.set(outbox, () => updateState());
|
|
644
|
+
return outbox;
|
|
636
645
|
}
|
|
@@ -116,9 +116,10 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
116
116
|
reason: stuck.reduce((latest, entry) => (entry[1].seq > latest[1].seq ? entry : latest))[1].reason,
|
|
117
117
|
orders: stuck.map(([commandId, { since, firstFailedAt, reason }]) => ({ commandId, since, firstFailedAt, reason })) };
|
|
118
118
|
}
|
|
119
|
-
function serverFailed(commands: RegisterCommand[], reason: string) {
|
|
119
|
+
function serverFailed(commands: RegisterCommand[], reason: string, needsAdminId?: string) {
|
|
120
120
|
const at = now();
|
|
121
|
-
for (const { commandId } of commands) clocks.set(commandId, { ...(clocks.get(commandId) ?? { since: at, firstFailedAt: at }), seq: ++failureSeq,
|
|
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') {
|
package/src/outbox/types.ts
CHANGED
|
@@ -7,13 +7,15 @@ export interface OrderTransportContext {
|
|
|
7
7
|
local: { orders: ReadonlyMap<string, PosOrder> };
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
export type NeedsAdminAnswer = { id: string; reason: string; message: string };
|
|
11
|
+
|
|
10
12
|
export type TransportOutcome =
|
|
11
13
|
| { kind: 'results'; results: CommandResult[] }
|
|
12
14
|
| { kind: 'unauthorized' }
|
|
13
15
|
| { kind: 'refused'; status: number; reason: string }
|
|
14
16
|
/** `reason` is `network` when the store could not be reached, `timeout` when a sent request got no answer in time,
|
|
15
17
|
* else what the store answered (`status_503`, `bad_body`, ...). The order outbox counts every reason but `network`. */
|
|
16
|
-
| { kind: 'retry'; reason: string; retryAfterMs?: number };
|
|
18
|
+
| { kind: 'retry'; reason: string; retryAfterMs?: number; needsAdmin?: NeedsAdminAnswer };
|
|
17
19
|
|
|
18
20
|
export interface CommandTransport<E extends AnyCommandEnvelope = CommandEnvelope<OrderCreatePayload>> {
|
|
19
21
|
send(batch: E[], context?: OrderTransportContext): Promise<TransportOutcome>;
|
|
@@ -4,7 +4,7 @@ import type { RxCollection, RxError } from 'rxdb';
|
|
|
4
4
|
import { outboxLogger } from './logger';
|
|
5
5
|
import { OrderContentMismatchError, sameSale, type PosOrder } from '../pos-order';
|
|
6
6
|
import { watchFresh } from '../rxdb';
|
|
7
|
-
import { createOrderOutbox } from './order-outbox';
|
|
7
|
+
import { createOrderOutbox, refreshOutboxState } from './order-outbox';
|
|
8
8
|
import type { CommandTransport, OutboxState } from './types';
|
|
9
9
|
|
|
10
10
|
const idle: OutboxState = { pending: 0, sending: false };
|
|
@@ -38,7 +38,7 @@ export interface UseOrderOutboxResult {
|
|
|
38
38
|
/** The newest 50 orders, newest first; empty until the current store is ready. */
|
|
39
39
|
recent: PosOrder[];
|
|
40
40
|
/**
|
|
41
|
-
* Stores a finalized order, then flushes. Throws the opening error, or "Orders are not ready.", before the store is ready.
|
|
41
|
+
* Stores a finalized order, then flushes. It resolves only once `state.pending` counts the order. Throws the opening error, or "Orders are not ready.", before the store is ready.
|
|
42
42
|
* Recording an order whose `id` is already stored, not deleted, with the same money-bearing content (`sameSale`;
|
|
43
43
|
* a retried `complete()`) counts as stored, never overwrites it, and still flushes, whatever the stored `commandId`
|
|
44
44
|
* (a requeue mints a new one; the difference is logged at warn). Other content rejects with `OrderContentMismatchError`.
|
|
@@ -159,7 +159,11 @@ export function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxRe
|
|
|
159
159
|
storedCommandId: inDb.commandId, recordedCommandId: posOrder.commandId });
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
|
-
if (current.current === opened)
|
|
162
|
+
if (current.current === opened) {
|
|
163
|
+
// Publish the stored order in state.pending before resolving: a caller that renders on resolve must see it (vendurepos/app#470).
|
|
164
|
+
try { await refreshOutboxState(opened.outbox); } catch (cause) { outboxLogger.warn('Failed to refresh the outbox state', { cause }); }
|
|
165
|
+
if (current.current === opened) void opened.outbox.flush(); // the store can switch or unmount during the refresh: a stopped outbox is never flushed again
|
|
166
|
+
}
|
|
163
167
|
} finally {
|
|
164
168
|
savesInFlight.current--;
|
|
165
169
|
setSavesInFlightCount(savesInFlight.current);
|
package/src/pos-order/command.ts
CHANGED
|
@@ -246,6 +246,9 @@ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, opti
|
|
|
246
246
|
subtotalMinor: order.subtotalMinor,
|
|
247
247
|
...(discountMinor > 0 ? { discountMinor } : {}),
|
|
248
248
|
taxMinor: order.taxMinor, totalMinor: order.totalMinor,
|
|
249
|
+
// ADR-094: a rounded sale's entries ride at its content version; finalize refuses them unless the store declares cashRounding.
|
|
250
|
+
...(order.cashRoundings?.length
|
|
251
|
+
? { cashRoundings: order.cashRoundings.map(({ paymentId, minor }) => ({ paymentId, minor })) } : {}),
|
|
249
252
|
...(base >= 3 ? {
|
|
250
253
|
display: { ...storedDisplay, lines: order.display!.lines.map(({ lineId, amountMinor, discounts }) => ({
|
|
251
254
|
clientLineId: lineId, amountMinor, discounts,
|
|
@@ -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,
|
package/src/pos-order/reopen.ts
CHANGED
|
@@ -124,13 +124,20 @@ export async function reopenRefusedOrder(orderId: string, deps: {
|
|
|
124
124
|
...(shipping.taxStatus !== undefined ? { taxStatus: shipping.taxStatus } : {}),
|
|
125
125
|
...(shipping.methodId !== undefined ? { methodId: shipping.methodId } : {}),
|
|
126
126
|
});
|
|
127
|
-
|
|
127
|
+
const legIds = new Map<string, string>();
|
|
128
|
+
for (const payment of order.payments) legIds.set(payment.id, builder.addPayment({
|
|
128
129
|
// After close each leg keeps the refused order's id, so finalize knows it for the leg that closure counted.
|
|
129
130
|
...(afterClose ? { id: payment.id } : {}), method: payment.method, amountMinor: payment.amountMinor, reopened: true,
|
|
130
131
|
...(payment.reference !== undefined ? { reference: payment.reference } : {}),
|
|
131
132
|
...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
|
|
132
133
|
...(isTakenAt(payment.takenAt) ? { takenAt: payment.takenAt } : {}),
|
|
133
|
-
|
|
134
|
+
...(payment.sessionId !== undefined ? { sessionId: payment.sessionId } : {}),
|
|
135
|
+
}));
|
|
136
|
+
// ADR-094: each entry follows its leg's new id; an entry whose stored leg is not found is dropped.
|
|
137
|
+
for (const entry of order.cashRoundings ?? []) {
|
|
138
|
+
const paymentId = legIds.get(entry.paymentId);
|
|
139
|
+
if (paymentId) builder.addCashRounding({ paymentId, minor: entry.minor });
|
|
140
|
+
}
|
|
134
141
|
if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
|
|
135
142
|
builder.setCustomer({ id: order.customer.id, name: order.customer.name,
|
|
136
143
|
...(order.customer.email !== undefined ? { email: order.customer.email } : {}),
|
package/src/pos-order/schema.ts
CHANGED
|
@@ -39,6 +39,7 @@ import type { PosOrder } from './types';
|
|
|
39
39
|
* Version 18 adds the customer's `taxIds`, the order's `meta`, a line's `catalogueSku` and `attentionHandledFor` (ADR-092), and lets sentVersion and downgradedFrom be 12 (order.create version 12), and changes nothing else. Its migration is the identity. It is one-way like version 17.
|
|
40
40
|
* Version 19 adds a store-priced coupon's `carried` flag and its lines' `amountMinor` (a coupon the store refused at send, carried at the amount charged), and the order's `countedInClosureOf`, and changes nothing else. Its migration is the identity. It is one-way like version 18.
|
|
41
41
|
* Version 20 adds a payment's optional `takenAt`, the instant the till recorded the leg; identity migration, one-way like version 19.
|
|
42
|
+
* Version 21 adds the order's optional `cashRoundings` (ADR-094); identity migration, one-way like version 20.
|
|
42
43
|
*/
|
|
43
44
|
/** A customer's address on an order (#722, OrderAddress): ten optional strings. */
|
|
44
45
|
const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
|
|
@@ -48,7 +49,7 @@ const orderAddressSchema = { type: 'object', additionalProperties: false, proper
|
|
|
48
49
|
} } as const;
|
|
49
50
|
|
|
50
51
|
export const posOrderSchema: RxJsonSchema<PosOrder> = {
|
|
51
|
-
version:
|
|
52
|
+
version: 21, primaryKey: 'id', type: 'object', additionalProperties: false,
|
|
52
53
|
properties: {
|
|
53
54
|
id: { type: 'string', maxLength: 36 },
|
|
54
55
|
saleId: { type: 'string', maxLength: 36 },
|
|
@@ -131,6 +132,8 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
|
|
|
131
132
|
takenAt: { type: 'string', maxLength: 40 },
|
|
132
133
|
}, required: ['id', 'method', 'amountMinor'],
|
|
133
134
|
} },
|
|
135
|
+
cashRoundings: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
136
|
+
paymentId: { type: 'string', maxLength: 36 }, minor: { type: 'integer' } }, required: ['paymentId', 'minor'] } },
|
|
134
137
|
customer: { type: ['object', 'null'], properties: { id: { type: 'string' }, name: { type: 'string' }, email: { type: 'string' },
|
|
135
138
|
billing: orderAddressSchema, shipping: orderAddressSchema, taxIds: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
136
139
|
type: { type: 'string' }, value: { type: 'string' }, country: { type: 'string' }, label: { type: 'string' } }, required: ['type', 'value'] } } } },
|
|
@@ -220,5 +223,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
|
|
|
220
223
|
// it means no older sale is ever re-rounded (#287).
|
|
221
224
|
const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
|
|
222
225
|
return { schema: posOrderSchema,
|
|
223
|
-
migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity, 12: identity, 13: identity, 14: identity, 15: identity, 16: identity, 17: identity, 18: identity, 19: identity, 20: identity } };
|
|
226
|
+
migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity, 12: identity, 13: identity, 14: identity, 15: identity, 16: identity, 17: identity, 18: identity, 19: identity, 20: identity, 21: identity } };
|
|
224
227
|
}
|
package/src/pos-order/types.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { CommandError, CommandServerRefs, CommandWarning, OrderAddress, OrderCreateLine, PaymentMethodKind, TaxRounding } from '@tallyui/core';
|
|
2
|
-
import type { DisplayTotals, FeeLine, ShippingLine } from '../order/types';
|
|
2
|
+
import type { CashRounding, DisplayTotals, FeeLine, ShippingLine } from '../order/types';
|
|
3
3
|
|
|
4
4
|
export type PosOrderSyncStatus = 'pending' | 'applied' | 'rejected';
|
|
5
5
|
|
|
@@ -76,6 +76,8 @@ export interface PosOrderPayment {
|
|
|
76
76
|
reference?: string;
|
|
77
77
|
/** When the till recorded the leg (`Payment.takenAt`); absent on store-held and older legs. */
|
|
78
78
|
takenAt?: string;
|
|
79
|
+
/** The session the leg was taken in (`Payment.sessionId`, S3); absent means the order's session. */
|
|
80
|
+
sessionId?: string;
|
|
79
81
|
}
|
|
80
82
|
|
|
81
83
|
export interface PosOrder {
|
|
@@ -107,6 +109,8 @@ export interface PosOrder {
|
|
|
107
109
|
/** What the store owes back on a reopened sale whose locked payments exceed its new total, in minor units (pos_orders v15, ADR-090). `finalizeOrder` writes it on every reopened sale, 0 when nothing is due; absent on a till sale. */
|
|
108
110
|
refundDueMinor?: number;
|
|
109
111
|
payments: PosOrderPayment[];
|
|
112
|
+
/** ADR-094: the cash rounding entries, keyed by this order's payment ids and counted in totalMinor. Absent when empty. */
|
|
113
|
+
cashRoundings?: CashRounding[];
|
|
110
114
|
/** `billing` and `shipping` (#722) are frozen copies of the customer's addresses, stored only with `taxAddress`. */
|
|
111
115
|
customer: { id?: string; name?: string; email?: string; billing?: OrderAddress; shipping?: OrderAddress;
|
|
112
116
|
/** The sale's tax ids (pos_orders v18, ADR-092), sent at order.create 12; `label` is kept on the till and is not sent. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Discount, SentOrder } from '../order/types';
|
|
1
|
+
import type { Discount, Order, SentOrder } from '../order/types';
|
|
2
2
|
import { lockedRefundDueMinor } from '../pos-order/refund-due';
|
|
3
3
|
import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
|
|
4
4
|
import { taxedLinesFor } from '../tax/taxed-lines';
|
|
@@ -6,6 +6,12 @@ import { carriedRows } from './carried-rows';
|
|
|
6
6
|
import type { ReceiptConfig, ReceiptData } from './types';
|
|
7
7
|
import { RECEIPT_SCHEMA_VERSION } from './types';
|
|
8
8
|
|
|
9
|
+
/** ADR-094: the receipt's Rounding row, the sum of the order's cash roundings; none when the sum is 0. */
|
|
10
|
+
export function receiptRounding(order: Pick<Order, 'cashRoundings'>): Pick<ReceiptData, 'rounding'> {
|
|
11
|
+
const amountMinor = (order.cashRoundings ?? []).reduce((sum, entry) => sum + entry.minor, 0);
|
|
12
|
+
return amountMinor !== 0 ? { rounding: { name: 'Rounding', amountMinor } } : {};
|
|
13
|
+
}
|
|
14
|
+
|
|
9
15
|
export function buildReceiptData(order: SentOrder, config: ReceiptConfig): ReceiptData {
|
|
10
16
|
// Drops the shared helper's `netMinor` (the Z report's own use): the receipt's tax summary
|
|
11
17
|
// never showed it, and an exact-shape test elsewhere in this package pins that.
|
|
@@ -68,6 +74,7 @@ export function buildReceiptData(order: SentOrder, config: ReceiptConfig): Recei
|
|
|
68
74
|
})),
|
|
69
75
|
fees: (order.display.fees ?? []).map(({ name, amountMinor }) => ({ name, amountMinor })),
|
|
70
76
|
shipping: (order.display.shipping ?? []).map(({ name, amountMinor }) => ({ name, amountMinor })),
|
|
77
|
+
...receiptRounding(order),
|
|
71
78
|
orderDiscountMinor: order.display.orderDiscountMinor,
|
|
72
79
|
totals: {
|
|
73
80
|
taxInclusive: order.display.taxInclusive,
|
package/src/receipt/reprint.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { refundDueOf } from '../pos-order/refund-due';
|
|
|
4
4
|
import type { PosOrder } from '../pos-order/types';
|
|
5
5
|
import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
|
|
6
6
|
import { recordedTaxByRate, taxedLinesFor } from '../tax/taxed-lines';
|
|
7
|
+
import { receiptRounding } from './build-receipt-data';
|
|
7
8
|
import { carriedRows } from './carried-rows';
|
|
8
9
|
import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
|
|
9
10
|
import { RECEIPT_SCHEMA_VERSION } from './types';
|
|
@@ -84,6 +85,7 @@ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCon
|
|
|
84
85
|
discounts: display && display.orderDiscountMinor > 0 ? [{ label: 'Order discount', amountMinor: display.orderDiscountMinor }] : [],
|
|
85
86
|
fees: charges(display ? display.fees : order.fees),
|
|
86
87
|
shipping: charges(display ? display.shipping : order.shipping),
|
|
88
|
+
...receiptRounding(order),
|
|
87
89
|
orderDiscountMinor: display ? display.orderDiscountMinor : 0,
|
|
88
90
|
totals: display
|
|
89
91
|
? {
|
package/src/receipt/types.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface ReceiptData {
|
|
|
44
44
|
lineItems: ReceiptLineItem[];
|
|
45
45
|
fees: Array<{ name: string; amountMinor: number }>;
|
|
46
46
|
shipping: Array<{ name: string; amountMinor: number }>;
|
|
47
|
+
/** ADR-094: the sum of the order's cash roundings, signed; present only when non-zero. Counted in totals.totalMinor. */
|
|
48
|
+
rounding?: { name: string; amountMinor: number };
|
|
47
49
|
discounts: { label: string; amountMinor: number }[];
|
|
48
50
|
orderDiscountMinor: number; // the order discounts as one row, in the display mode; + Σ displayDiscounts = totals.discountMinor
|
|
49
51
|
totals: {
|
|
@@ -82,7 +82,7 @@ export function receiptTemplateData(receipt: ReceiptData, options: ReceiptTempla
|
|
|
82
82
|
subtotal: money(totals.subtotalMinor),
|
|
83
83
|
lineDiscount: lineDiscountMinor > 0 ? `−${money(lineDiscountMinor)}` : '',
|
|
84
84
|
orderDiscount: receipt.orderDiscountMinor > 0 ? `−${money(receipt.orderDiscountMinor)}` : '',
|
|
85
|
-
charges: [...receipt.fees, ...receipt.shipping].map((charge) => ({
|
|
85
|
+
charges: [...receipt.fees, ...receipt.shipping, ...(receipt.rounding ? [receipt.rounding] : [])].map((charge) => ({
|
|
86
86
|
label: charge.name, amount: money(charge.amountMinor),
|
|
87
87
|
})),
|
|
88
88
|
taxes: totals.taxLines.map((tax) => ({
|
|
@@ -110,7 +110,11 @@ function tillSource(order: TillOrder, receipt: ReceiptData, lines: TillLine[]) {
|
|
|
110
110
|
status: 'completed', currency: order.currency, pricesIncludeTax: order.pricesIncludeTax,
|
|
111
111
|
customer: order.customer && { id: order.customer.id, firstName: order.customer.name, email: order.customer.email },
|
|
112
112
|
lines: lines.map((line) => tillLine(line, key)),
|
|
113
|
-
fees:
|
|
113
|
+
fees: [
|
|
114
|
+
...(order.fees ?? []).map((fee) => ({ name: fee.name, ...tillCharge(fee, context, key) })),
|
|
115
|
+
// ADR-094 detail 5: the rounding prints as WooCommerce carries it, a tax-free fee row named 'Rounding'.
|
|
116
|
+
...(receipt.rounding ? [{ name: receipt.rounding.name, totalMinor: receipt.rounding.amountMinor, totalTaxMinor: 0 }] : []),
|
|
117
|
+
],
|
|
114
118
|
shipping: (order.shipping ?? []).map((row) => ({
|
|
115
119
|
methodTitle: row.name, ...(row.methodId !== undefined ? { methodId: row.methodId } : {}), ...tillCharge(row, context, key),
|
|
116
120
|
})),
|
package/src/refund/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { sendOrderRefund, type OrderRefundOutcome } from './send-order-refund';
|
|
2
|
+
export { refundNeedsAdminLine } from './needs-admin-line';
|
|
2
3
|
export { posRefundSchema, posRefundCollection, type PosRefund, type PosRefundStatus, type PosRefundCollection } from './pos-refund';
|
|
3
4
|
export { submitOrderRefund, RefundAnswerPendingError } from './submit-order-refund';
|
|
4
5
|
export { refundableLines, priceRefund } from './refundable-lines';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** The till's lead line for a refund parked needs_admin, by reason (TallyUI #1280). Only session_closed guarantees no money moved. */
|
|
2
|
+
export function refundNeedsAdminLine(reason: string): string {
|
|
3
|
+
return reason === 'session_closed'
|
|
4
|
+
? 'Not paid. This refund needs a manager to finish it in the store admin.'
|
|
5
|
+
: 'Not finished. A manager must check this refund in the store admin before any money is handed over.';
|
|
6
|
+
}
|
|
@@ -1,91 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Amounts follow ADR-080 amendment 2's cumulative-share rule.
|
|
4
|
-
*/
|
|
5
|
-
import type { StoreOrderLine, OrderRefundLine } from '@tallyui/core';
|
|
6
|
-
import { roundRatio } from '../tax/exact';
|
|
7
|
-
|
|
8
|
-
/** The fields of an order line this needs; a StoreOrderLine fits. */
|
|
9
|
-
export type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
|
|
10
|
-
/** Earlier refund lines; negative quantities count by magnitude. */
|
|
11
|
-
export interface EarlierRefund { lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>> }
|
|
12
|
-
|
|
13
|
-
/** Remaining quantities and amounts, with earlier refund magnitudes capped at the line quantity. */
|
|
14
|
-
export interface RefundableLine {
|
|
15
|
-
orderLineId: string;
|
|
16
|
-
refundedQuantity: number;
|
|
17
|
-
refundableQuantity: number;
|
|
18
|
-
netMinor: number;
|
|
19
|
-
taxMinor: number;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** A selected quantity's cumulative shares of net and tax, and their sum. */
|
|
23
|
-
export interface PricedRefundLine {
|
|
24
|
-
orderLineId: string; quantity: number; netMinor: number; taxMinor: number;
|
|
25
|
-
totalMinor: number;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** Payload-ready lines and their amounts; the caller adds shipping and adjustment to totalMinor. */
|
|
29
|
-
export interface PricedRefund {
|
|
30
|
-
/** Exactly orderLineId, quantity (>= 1), and restock. */
|
|
31
|
-
lines: OrderRefundLine[];
|
|
32
|
-
/** Amounts in the same order as lines. */
|
|
33
|
-
priced: PricedRefundLine[];
|
|
34
|
-
/** Requests cut to availability, including unknown lines cut to zero. */
|
|
35
|
-
clamped: Array<{ orderLineId: string; requestedQuantity: number; quantity: number }>;
|
|
36
|
-
netMinor: number; taxMinor: number; totalMinor: number;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Returns the quantities and amounts still refundable, in order-line order. */
|
|
40
|
-
export function refundableLines(
|
|
41
|
-
lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[],
|
|
42
|
-
): RefundableLine[] {
|
|
43
|
-
const earlier = refunds.flatMap((refund) => refund.lines);
|
|
44
|
-
for (const refund of earlier) {
|
|
45
|
-
if (!Number.isSafeInteger(refund.quantity)) throw new RangeError('Earlier refund quantity must be a safe integer');
|
|
46
|
-
}
|
|
47
|
-
return lines.map((line) => {
|
|
48
|
-
if (!Number.isSafeInteger(line.quantity) || line.quantity < 0
|
|
49
|
-
|| !Number.isSafeInteger(line.totalMinor) || !Number.isSafeInteger(line.taxMinor)) {
|
|
50
|
-
throw new RangeError('Order line values must be safe integers and quantity non-negative');
|
|
51
|
-
}
|
|
52
|
-
const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id
|
|
53
|
-
? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
|
|
54
|
-
const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => line.quantity === 0 ? 0
|
|
55
|
-
: total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
|
|
56
|
-
return {
|
|
57
|
-
orderLineId: line.id, refundedQuantity, refundableQuantity: line.quantity - refundedQuantity, netMinor, taxMinor,
|
|
58
|
-
};
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** Prices requested quantities with cumulative shares, clamping them to what remains refundable. */
|
|
63
|
-
export function priceRefund(
|
|
64
|
-
lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[], request: readonly OrderRefundLine[],
|
|
65
|
-
): PricedRefund {
|
|
66
|
-
const available = refundableLines(lines, refunds);
|
|
67
|
-
const seen = new Set<string>();
|
|
68
|
-
const result: PricedRefund = { lines: [], priced: [], clamped: [], netMinor: 0, taxMinor: 0, totalMinor: 0 };
|
|
69
|
-
for (const { orderLineId, quantity: requestedQuantity, restock } of request) {
|
|
70
|
-
if (!Number.isSafeInteger(requestedQuantity) || requestedQuantity < 0 || seen.has(orderLineId)) {
|
|
71
|
-
throw new RangeError('Request quantities must be non-negative safe integers and line ids unique');
|
|
72
|
-
}
|
|
73
|
-
seen.add(orderLineId);
|
|
74
|
-
const index = lines.findIndex((line) => line.id === orderLineId);
|
|
75
|
-
const quantity = Math.min(requestedQuantity, available[index]?.refundableQuantity ?? 0);
|
|
76
|
-
if (quantity < requestedQuantity) result.clamped.push({ orderLineId, requestedQuantity, quantity });
|
|
77
|
-
if (quantity < 1) continue;
|
|
78
|
-
const line = lines[index];
|
|
79
|
-
const refundedQuantity = available[index].refundedQuantity;
|
|
80
|
-
const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) =>
|
|
81
|
-
Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), 'half_up'))
|
|
82
|
-
- Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
|
|
83
|
-
const totalMinor = netMinor + taxMinor;
|
|
84
|
-
result.lines.push({ orderLineId, quantity, restock });
|
|
85
|
-
result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
|
|
86
|
-
result.netMinor += netMinor;
|
|
87
|
-
result.taxMinor += taxMinor;
|
|
88
|
-
result.totalMinor += totalMinor;
|
|
89
|
-
}
|
|
90
|
-
return result;
|
|
91
|
-
}
|
|
1
|
+
// Moved to @tallyui/core (arch 1a); re-exported so the till's names stay.
|
|
2
|
+
export { refundableLines, priceRefund, type RefundableOrderLine, type EarlierRefund, type RefundableLine, type PricedRefundLine, type PricedRefund } from '@tallyui/core';
|
|
@@ -5,11 +5,12 @@ import type { CommandTransport } from '../outbox/types';
|
|
|
5
5
|
export type OrderRefundOutcome =
|
|
6
6
|
| { kind: 'applied'; refund: OrderRefundResult; duplicate: boolean }
|
|
7
7
|
| { kind: 'rejected'; error: CommandError }
|
|
8
|
+
| { kind: 'needs_admin'; reason: string; message: string }
|
|
8
9
|
| { kind: 'unknown'; reason: string; retryAfterMs?: number }
|
|
9
10
|
| { kind: 'refused'; status: number; reason: string }
|
|
10
11
|
| { kind: 'unauthorized' };
|
|
11
12
|
|
|
12
|
-
/** Online only, never queued (ADR-080). On unknown, resend the same envelope (same id).
|
|
13
|
+
/** Online only, never queued (ADR-080). On unknown or needs_admin, resend the same envelope (same id; Check again).
|
|
13
14
|
* After rejected, a new attempt needs a new id. Refused and unauthorized mean the store did not take the batch. */
|
|
14
15
|
export async function sendOrderRefund(
|
|
15
16
|
transport: CommandTransport<OrderRefundEnvelope>, envelope: OrderRefundEnvelope,
|
|
@@ -21,6 +22,10 @@ export async function sendOrderRefund(
|
|
|
21
22
|
return { kind: 'unknown', reason: 'transport_error' };
|
|
22
23
|
}
|
|
23
24
|
if (outcome.kind === 'retry') {
|
|
25
|
+
const { needsAdmin } = outcome;
|
|
26
|
+
if (needsAdmin?.id === envelope.id) {
|
|
27
|
+
return { kind: 'needs_admin', reason: needsAdmin.reason, message: needsAdmin.message };
|
|
28
|
+
}
|
|
24
29
|
return {
|
|
25
30
|
kind: 'unknown', reason: outcome.reason,
|
|
26
31
|
...(outcome.retryAfterMs !== undefined ? { retryAfterMs: outcome.retryAfterMs } : {}),
|
|
@@ -12,14 +12,36 @@ export class RefundAnswerPendingError extends Error {
|
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
// Calls for one refund envelope run one at a time in this process, because the till is single-instance (#1290).
|
|
16
|
+
const inFlight = new WeakMap<PosRefundCollection, Map<string, Promise<unknown>>>();
|
|
17
|
+
|
|
15
18
|
/** Online only, never queued; the record is written before the send.
|
|
16
19
|
* An applied record is final; a pending one is resent only with its own envelope
|
|
17
20
|
* (ADR-080 amendment 1). */
|
|
18
|
-
export async function submitOrderRefund(
|
|
21
|
+
export async function submitOrderRefund(args: {
|
|
22
|
+
refunds: PosRefundCollection; transport: CommandTransport<OrderRefundEnvelope>;
|
|
23
|
+
envelope: OrderRefundEnvelope; now?: () => string;
|
|
24
|
+
}): Promise<{ outcome: OrderRefundOutcome; record: PosRefund }> {
|
|
25
|
+
const { refunds, envelope } = args;
|
|
26
|
+
let calls = inFlight.get(refunds);
|
|
27
|
+
if (!calls) { calls = new Map(); inFlight.set(refunds, calls); }
|
|
28
|
+
const key = `${envelope.payload.clientRefundId} ${envelope.id}`;
|
|
29
|
+
const run = (calls.get(key) ?? Promise.resolve()).catch(() => undefined).then(() => submitOnce(args));
|
|
30
|
+
calls.set(key, run);
|
|
31
|
+
try {
|
|
32
|
+
return await run;
|
|
33
|
+
} finally {
|
|
34
|
+
if (calls.get(key) === run) calls.delete(key);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function submitOnce({ refunds, transport, envelope, now = () => new Date().toISOString() }: {
|
|
19
39
|
refunds: PosRefundCollection; transport: CommandTransport<OrderRefundEnvelope>;
|
|
20
40
|
envelope: OrderRefundEnvelope; now?: () => string;
|
|
21
41
|
}): Promise<{ outcome: OrderRefundOutcome; record: PosRefund }> {
|
|
22
42
|
const id = envelope.payload.clientRefundId;
|
|
43
|
+
// The record may already be held by the store unless this call wrote its pending attempt (#1285).
|
|
44
|
+
let mayBeHeld = true;
|
|
23
45
|
let doc = await refunds.findOne(id).exec();
|
|
24
46
|
if (!doc) {
|
|
25
47
|
const at = now();
|
|
@@ -29,6 +51,7 @@ export async function submitOrderRefund({ refunds, transport, envelope, now = ()
|
|
|
29
51
|
id, commandId: envelope.id, orderId, sessionId, registerId, envelope,
|
|
30
52
|
status: 'pending', createdAt: at, updatedAt: at,
|
|
31
53
|
});
|
|
54
|
+
mayBeHeld = false;
|
|
32
55
|
} catch (error) {
|
|
33
56
|
if (!(error instanceof RxError) || error.code !== 'CONFLICT') throw error;
|
|
34
57
|
doc = (await refunds.findOne(id).exec())!;
|
|
@@ -50,16 +73,20 @@ export async function submitOrderRefund({ refunds, transport, envelope, now = ()
|
|
|
50
73
|
}
|
|
51
74
|
if (record.status === 'unsent' && record.commandId === envelope.id) {
|
|
52
75
|
doc = await doc.incrementalModify((stored) => {
|
|
76
|
+
mayBeHeld = true;
|
|
53
77
|
if (stored.status !== 'unsent' || stored.commandId !== envelope.id) return stored;
|
|
54
78
|
const { error, ...rest } = stored;
|
|
79
|
+
mayBeHeld = false;
|
|
55
80
|
return { ...rest, status: 'pending', updatedAt: now() };
|
|
56
81
|
});
|
|
57
82
|
record = doc.toJSON() as PosRefund;
|
|
58
83
|
continue;
|
|
59
84
|
}
|
|
60
85
|
doc = await doc.incrementalModify((stored) => {
|
|
86
|
+
mayBeHeld = true;
|
|
61
87
|
if (stored.status !== 'rejected' && stored.status !== 'unsent') return stored;
|
|
62
88
|
const { result, duplicate, error, ...rest } = stored;
|
|
89
|
+
mayBeHeld = false;
|
|
63
90
|
return { ...rest, commandId: envelope.id, envelope, status: 'pending', updatedAt: now() };
|
|
64
91
|
});
|
|
65
92
|
record = doc.toJSON() as PosRefund;
|
|
@@ -69,7 +96,12 @@ export async function submitOrderRefund({ refunds, transport, envelope, now = ()
|
|
|
69
96
|
if (outcome.kind !== 'unknown') {
|
|
70
97
|
doc = await doc.incrementalModify((stored) => {
|
|
71
98
|
if (stored.status !== 'pending' || stored.commandId !== envelope.id) return stored;
|
|
99
|
+
if ((outcome.kind === 'refused' || outcome.kind === 'unauthorized') && (mayBeHeld || stored.error?.code === 'needs_admin')) return stored;
|
|
72
100
|
const updatedAt = now();
|
|
101
|
+
if (outcome.kind === 'needs_admin') {
|
|
102
|
+
return { ...stored, error: { code: 'needs_admin', message: outcome.message,
|
|
103
|
+
data: { reason: outcome.reason, at: updatedAt } }, updatedAt };
|
|
104
|
+
}
|
|
73
105
|
if (outcome.kind === 'applied') {
|
|
74
106
|
const { error, ...rest } = stored;
|
|
75
107
|
return { ...rest, status: 'applied', result: outcome.refund, duplicate: outcome.duplicate, updatedAt };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type * as store from './session-store';
|
|
2
|
+
|
|
3
|
+
// The close in flight per register, which a second close joins; its listeners re-render `closing`.
|
|
4
|
+
export const closingByRegister = new Map<string, ReturnType<typeof store.writeClosure>>();
|
|
5
|
+
const closingListeners = new Set<() => void>();
|
|
6
|
+
export const notifyClosing = () => closingListeners.forEach((listener) => listener());
|
|
7
|
+
export const subscribeClosing = (listener: () => void) => {
|
|
8
|
+
closingListeners.add(listener);
|
|
9
|
+
return () => { closingListeners.delete(listener); };
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/** A `closeSession` for this register is in flight, in any hook instance. */
|
|
13
|
+
export function isRegisterClosing(registerId: string): boolean {
|
|
14
|
+
return closingByRegister.has(registerId);
|
|
15
|
+
}
|