@tallyui/pos 4.1.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +584 -161
- package/dist/index.js +1908 -1077
- package/package.json +7 -6
- package/src/index.ts +17 -10
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +65 -21
- package/src/order/order-drafts.ts +78 -24
- package/src/order/taken-at.ts +5 -0
- package/src/order/types.ts +11 -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 +11 -0
- package/src/pos-order/reopen.ts +11 -2
- package/src/pos-order/schema.ts +7 -2
- package/src/pos-order/types.ts +7 -1
- package/src/print/escpos/bluetooth-sink.ts +114 -0
- package/src/print/escpos/index.ts +4 -0
- package/src/print/escpos/transport.ts +3 -2
- package/src/print/escpos/usb-sink.ts +84 -0
- package/src/print/index.ts +2 -2
- 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 +321 -135
- package/src/store-orders/index.ts +5 -0
- package/src/store-orders/sales-range-query.ts +18 -0
- package/src/store-orders/use-store-orders-in-range.ts +127 -0
- package/src/store-orders/use-store-refunds-in-range.ts +179 -0
- package/src/tax/exact.ts +2 -10
- package/src/tax/index.ts +1 -0
- 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
|
@@ -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
|
+
}
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* string id (not WCPOS's numeric one).
|
|
15
15
|
*/
|
|
16
16
|
import { minorUnitDigits } from '@tallyui/core';
|
|
17
|
+
import { closureFigures } from './closure-figures';
|
|
17
18
|
import { ENGLISH_CLOSURE_LABELS } from './document-labels';
|
|
18
19
|
import { minorToDecimal, formatDecimalMoney } from './money';
|
|
19
20
|
import type { Closure, RegisterSession } from './schemas';
|
|
@@ -102,7 +103,9 @@ function decimalizeBreakdowns(breakdowns: Values, exponent: number): Values {
|
|
|
102
103
|
)
|
|
103
104
|
);
|
|
104
105
|
};
|
|
105
|
-
|
|
106
|
+
// The float's figures through closureFigures; an unknown one stays `null`, as writeClosure writes it.
|
|
107
|
+
const float = closureFigures({ breakdowns }).openingFloat;
|
|
108
|
+
const decOrNull = (m: number | undefined) => (m === undefined ? null : minorToDecimal(m, exponent));
|
|
106
109
|
return {
|
|
107
110
|
...breakdowns,
|
|
108
111
|
...(breakdowns.payment_methods
|
|
@@ -111,17 +114,19 @@ function decimalizeBreakdowns(breakdowns: Values, exponent: number): Values {
|
|
|
111
114
|
...(breakdowns.tax_rates
|
|
112
115
|
? { tax_rates: group('tax_rates', [['net_minor', 'net'], ['tax_minor', 'tax'], ['gross_minor', 'gross']]) }
|
|
113
116
|
: {}),
|
|
114
|
-
...(
|
|
117
|
+
...(breakdowns.opening_float
|
|
115
118
|
? {
|
|
116
119
|
opening_float: {
|
|
117
|
-
|
|
118
|
-
|
|
120
|
+
expected_minor: float.expectedMinor ?? null, counted_minor: float.countedMinor ?? null,
|
|
121
|
+
variance_minor: float.varianceMinor ?? null, expected: decOrNull(float.expectedMinor),
|
|
122
|
+
counted: decOrNull(float.countedMinor), variance: decOrNull(float.varianceMinor),
|
|
119
123
|
},
|
|
120
124
|
}
|
|
121
125
|
: {}),
|
|
122
126
|
...(breakdowns.movements
|
|
123
127
|
? { movements: (breakdowns.movements as BreakdownMovement[]).map((m) => ({ ...m, amount: dec(m.amountMinor) })) }
|
|
124
128
|
: {}),
|
|
129
|
+
...(breakdowns.cash_rounding_minor !== undefined ? { cash_rounding: dec(breakdowns.cash_rounding_minor) } : {}),
|
|
125
130
|
};
|
|
126
131
|
}
|
|
127
132
|
|
|
@@ -214,9 +219,12 @@ function envelope<R extends Values>(row: R, context: ClosureContext, xreport = f
|
|
|
214
219
|
...Object.fromEntries(
|
|
215
220
|
['payment_methods', 'tax_rates', 'movements'].map((key) => [`has_${key}`, Object.keys((breakdowns[key] as Values) ?? {}).length > 0]),
|
|
216
221
|
),
|
|
222
|
+
has_cash_rounding: breakdowns.cash_rounding !== undefined,
|
|
217
223
|
...(breakdowns.tax_rounding_mixed === true ? { tax_rounding_note: TAX_ROUNDING_MIXED_NOTE } : {}),
|
|
218
224
|
...(breakdowns.tax_includes_store_paid === true ? { tax_store_paid_note: TAX_STORE_PAID_NOTE } : {}),
|
|
219
225
|
...money(row, ['period_sales_total', 'period_refunds_total', 'perpetual_sales_total', 'perpetual_refunds_total', 'unsynced_total']),
|
|
226
|
+
...(breakdowns.cash_rounding !== undefined
|
|
227
|
+
? { cash_rounding: money({ name: context.i18n.cash_rounding, amount: breakdowns.cash_rounding }, ['amount']) } : {}),
|
|
220
228
|
opened_at_gmt: row.opened_at,
|
|
221
229
|
opened_by: breakdowns.opened_by ?? null,
|
|
222
230
|
closed_by: row.closed_by ?? null,
|
|
@@ -237,7 +245,7 @@ function envelope<R extends Values>(row: R, context: ClosureContext, xreport = f
|
|
|
237
245
|
type_label: context.i18n[String(m.type)] ?? m.type,
|
|
238
246
|
voided: !!m.voided_by,
|
|
239
247
|
})),
|
|
240
|
-
cashiers: (
|
|
248
|
+
cashiers: closureFigures({ breakdowns }).cashiers,
|
|
241
249
|
},
|
|
242
250
|
},
|
|
243
251
|
store: context.store,
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One typed read of a closure's figures (#1261). `writeClosure` (session-store.ts) freezes them in the untyped
|
|
3
|
+
* `Closure.breakdowns`, and a closure adopted from the store may lack any of them, so every reader goes through here.
|
|
4
|
+
*
|
|
5
|
+
* The one rule: a money or count value that is not a finite integer (absent, `null`, a string, NaN) is left out
|
|
6
|
+
* (undefined), never read as 0. A missing group is an empty list. A payment method, tax rate or movement whose money
|
|
7
|
+
* is not a finite integer is dropped from its list, and so is a movement without a string id. A cashier given as a
|
|
8
|
+
* bare string becomes `{ id, name: id }`; a nameless one is named by its id.
|
|
9
|
+
*/
|
|
10
|
+
import type { Closure } from './schemas';
|
|
11
|
+
|
|
12
|
+
export type ClosureFigures = {
|
|
13
|
+
openingFloat: { expectedMinor?: number; countedMinor?: number; varianceMinor?: number };
|
|
14
|
+
paymentMethods: { id: string; name?: string; salesMinor: number; refundsMinor: number }[];
|
|
15
|
+
taxRates: { key: string; name?: string; netMinor: number; taxMinor: number; grossMinor: number }[];
|
|
16
|
+
movements: { id: string; type: string; amountMinor: number; reason: string; voided: boolean; createdAtGmt?: string; createdBy?: string }[];
|
|
17
|
+
transactionCount?: number;
|
|
18
|
+
refundCount?: number;
|
|
19
|
+
cashiers: { id: string; name: string }[];
|
|
20
|
+
taxRoundingMixed: boolean;
|
|
21
|
+
taxIncludesStorePaid: boolean;
|
|
22
|
+
varianceNote?: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
type Values = Record<string, unknown>;
|
|
26
|
+
|
|
27
|
+
const integer = (value: unknown) => (typeof value === 'number' && Number.isInteger(value) ? value : undefined);
|
|
28
|
+
const text = (value: unknown) => (typeof value === 'string' ? value : undefined);
|
|
29
|
+
const record = (value: unknown) =>
|
|
30
|
+
(value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Values) : undefined);
|
|
31
|
+
const list = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
|
|
32
|
+
const entries = (value: unknown) =>
|
|
33
|
+
Object.entries(record(value) ?? {}).flatMap(([key, entry]) => {
|
|
34
|
+
const values = record(entry);
|
|
35
|
+
return values ? [[key, values] as const] : [];
|
|
36
|
+
});
|
|
37
|
+
/** The keys whose value is known, so a missing figure is absent rather than present as `undefined`. */
|
|
38
|
+
const known = <T extends Values>(values: T) =>
|
|
39
|
+
Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)) as Partial<T>;
|
|
40
|
+
|
|
41
|
+
export function closureFigures(closure: Pick<Closure, 'breakdowns'>): ClosureFigures {
|
|
42
|
+
const b = closure.breakdowns;
|
|
43
|
+
const float = record(b.opening_float) ?? {};
|
|
44
|
+
const paymentMethods = entries(b.payment_methods).flatMap(([id, entry]) => {
|
|
45
|
+
const salesMinor = integer(entry.sales_minor);
|
|
46
|
+
const refundsMinor = integer(entry.refunds_minor);
|
|
47
|
+
if (salesMinor === undefined || refundsMinor === undefined) return [];
|
|
48
|
+
return [{ id, ...known({ name: text(entry.name) }), salesMinor, refundsMinor }];
|
|
49
|
+
});
|
|
50
|
+
const taxRates = entries(b.tax_rates).flatMap(([key, entry]) => {
|
|
51
|
+
const [netMinor, taxMinor, grossMinor] = [integer(entry.net_minor), integer(entry.tax_minor), integer(entry.gross_minor)];
|
|
52
|
+
if (netMinor === undefined || taxMinor === undefined || grossMinor === undefined) return [];
|
|
53
|
+
return [{ key, ...known({ name: text(entry.name) }), netMinor, taxMinor, grossMinor }];
|
|
54
|
+
});
|
|
55
|
+
const movements = list(b.movements).flatMap((value) => {
|
|
56
|
+
const m = record(value);
|
|
57
|
+
const id = text(m?.id);
|
|
58
|
+
const amountMinor = integer(m?.amountMinor);
|
|
59
|
+
if (!m || id === undefined || amountMinor === undefined) return [];
|
|
60
|
+
return [{
|
|
61
|
+
id, type: text(m.type) ?? '', amountMinor, reason: text(m.reason) ?? '', voided: !!m.voided_by,
|
|
62
|
+
...known({ createdAtGmt: text(m.created_at_gmt), createdBy: text(m.created_by) }),
|
|
63
|
+
}];
|
|
64
|
+
});
|
|
65
|
+
const cashiers = list(b.cashiers).flatMap((value) => {
|
|
66
|
+
if (typeof value === 'string') return [{ id: value, name: value }];
|
|
67
|
+
const c = record(value) ?? {};
|
|
68
|
+
const id = text(c.id) ?? (Number.isFinite(c.id) ? String(c.id) : undefined);
|
|
69
|
+
return id === undefined ? [] : [{ id, name: text(c.name) || id }];
|
|
70
|
+
});
|
|
71
|
+
return {
|
|
72
|
+
openingFloat: known({
|
|
73
|
+
expectedMinor: integer(float.expected_minor), countedMinor: integer(float.counted_minor),
|
|
74
|
+
varianceMinor: integer(float.variance_minor),
|
|
75
|
+
}),
|
|
76
|
+
paymentMethods, taxRates, movements,
|
|
77
|
+
...known({ transactionCount: integer(b.transaction_count), refundCount: integer(b.refund_count) }),
|
|
78
|
+
cashiers,
|
|
79
|
+
taxRoundingMixed: b.tax_rounding_mixed === true,
|
|
80
|
+
taxIncludesStorePaid: b.tax_includes_store_paid === true,
|
|
81
|
+
...known({ varianceNote: text(b.variance_note) }),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Offline defaults use the same label keys as the shipped server closure template. Port
|
|
2
|
-
// provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c` `document-labels.ts`, unchanged
|
|
3
|
-
// no money, no imports.
|
|
2
|
+
// provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c` `document-labels.ts`, unchanged
|
|
3
|
+
// except `cash_rounding` — no money, no imports.
|
|
4
4
|
export const labelKeys = {
|
|
5
5
|
x_report: 'register.x_report',
|
|
6
6
|
closure: 'reports.document.closure',
|
|
@@ -43,6 +43,8 @@ export const labelKeys = {
|
|
|
43
43
|
no_sale: 'register.no_sale',
|
|
44
44
|
void: 'register.void',
|
|
45
45
|
copy: 'reports.document.copy',
|
|
46
|
+
// TallyUI's own key (ADR-094); the WCPOS server template has none.
|
|
47
|
+
cash_rounding: 'reports.document.cash_rounding',
|
|
46
48
|
};
|
|
47
49
|
|
|
48
50
|
// The English wording for offline documents, keyed like `ClosureContext.i18n`.
|
|
@@ -67,5 +69,5 @@ export const ENGLISH_CLOSURE_LABELS: Record<keyof typeof labelKeys, string> = {
|
|
|
67
69
|
exact: 'Exact', voided: 'Voided',
|
|
68
70
|
paid_in: 'Paid in', paid_out: 'Paid out',
|
|
69
71
|
no_sale: 'No sale', void: 'Void',
|
|
70
|
-
copy: 'Copy',
|
|
72
|
+
copy: 'Copy', cash_rounding: 'Rounding',
|
|
71
73
|
};
|
package/src/register/expected.ts
CHANGED
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
* `refunded_amount`) are not ported: the store attributes each refund to a tender in `byMethod`.
|
|
9
9
|
*/
|
|
10
10
|
import { legMethodId } from '@tallyui/core';
|
|
11
|
+
import { parkedTakenLegs } from '../order/order-drafts';
|
|
12
|
+
import type { Payment } from '../order/types';
|
|
11
13
|
import { tillPayments } from '../pos-order/till-payments';
|
|
12
|
-
import type { PosOrder } from '../pos-order/types';
|
|
13
14
|
import type { PosRefund } from '../refund/pos-refund';
|
|
14
15
|
|
|
15
16
|
export type RefundRow = Pick<PosRefund, 'id' | 'sessionId' | 'status' | 'result'>;
|
|
@@ -36,14 +37,27 @@ export type LedgerRow = {
|
|
|
36
37
|
/**
|
|
37
38
|
* The ledger rows of these orders' payments. Each payment is captured, and a cash payment's amount is already net of change.
|
|
38
39
|
* A locked store payment (storePaymentId set) is the store's earlier money, not this till's, and is left out (ADR-090 gate 11).
|
|
40
|
+
* A payment stamped with the session that took it counts there, else in its order's (S3).
|
|
39
41
|
*/
|
|
40
|
-
export function paymentLedgerRows
|
|
42
|
+
export function paymentLedgerRows<P extends { method: string; amountMinor: number; storePaymentId?: string; sessionId?: string }>(
|
|
43
|
+
orders: readonly { sessionId?: string; payments: readonly P[] }[],
|
|
44
|
+
): LedgerRow[] {
|
|
41
45
|
return orders.flatMap((order) => tillPayments(order.payments).map((payment) => ({
|
|
42
|
-
session_id: order.sessionId, kind: payment.method === 'cash' ? 'cash' : 'other', method_id: payment.method,
|
|
46
|
+
session_id: payment.sessionId ?? order.sessionId, kind: payment.method === 'cash' ? 'cash' : 'other', method_id: payment.method,
|
|
43
47
|
status: 'captured', amountMinor: payment.amountMinor,
|
|
44
48
|
})));
|
|
45
49
|
}
|
|
46
50
|
|
|
51
|
+
/** S3: the ledger rows of the live sale's taken legs (`useSale`'s `registerView().takenLegs`), each in the session that took it. */
|
|
52
|
+
export function liveLedgerRows(legs: readonly Payment[]): LedgerRow[] {
|
|
53
|
+
return paymentLedgerRows([{ payments: legs }]);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** S3: the ledger rows of parked drafts' taken legs (`order_drafts` documents), mapped as `liveLedgerRows` maps the live sale's. */
|
|
57
|
+
export function parkedLedgerRows(drafts: readonly { data?: unknown }[]): LedgerRow[] {
|
|
58
|
+
return liveLedgerRows(drafts.flatMap((draft) => parkedTakenLegs(draft.data)));
|
|
59
|
+
}
|
|
60
|
+
|
|
47
61
|
/** `type`, `voids` and `voided_by` are kept as WCPOS names them: neutral across backends. */
|
|
48
62
|
export type Movement = {
|
|
49
63
|
id: string;
|
|
@@ -160,19 +174,26 @@ export function deriveDrawerTerms(input: Parameters<typeof deriveExpected>[0]):
|
|
|
160
174
|
};
|
|
161
175
|
}
|
|
162
176
|
|
|
177
|
+
type TillLeg = { method: string; methodId?: string; amountMinor: number; storePaymentId?: string; sessionId?: string };
|
|
178
|
+
type TillOrder = { sessionId?: string; payments: readonly TillLeg[] };
|
|
179
|
+
|
|
163
180
|
/**
|
|
164
|
-
* Takings per payment method for one session, for the closure sheet: this till's captured payments (`tillPayments`)
|
|
165
|
-
*
|
|
181
|
+
* Takings per payment method for one session, for the closure sheet: this till's captured payments (`tillPayments`) in
|
|
182
|
+
* `sessionId`: a payment's own session, else its order's (S3), keyed by `legMethodId`'s kind plus id (`external:stripe`), with the number of
|
|
166
183
|
* payments behind each. Local only, never synced: register rows and payloads keep `method_id: payment.method` (#256, ADR-070
|
|
167
184
|
* decision 1). A leg with no methodId keys exactly as deriveDrawerTerms does (`cash` or its method); the figures sum to
|
|
168
|
-
* deriveDrawerTerms' cash sales plus other tenders for the same orders.
|
|
185
|
+
* deriveDrawerTerms' cash sales plus other tenders for the same orders. `extra` adds taken legs no order holds yet (S3: a
|
|
186
|
+
* parked draft's `parkedTakenLegs`, the live sale's `registerView().takenLegs`), each counted only in its own `sessionId`; they are legs,
|
|
187
|
+
* not `LedgerRow`s, because a row keeps no `methodId` to key by. Refunds and movements are not here: they are keyed
|
|
169
188
|
* by the wire method. The map has no prototype, so a platform id such as `__proto__` or `toString` is a key like any other.
|
|
170
189
|
*/
|
|
171
|
-
export function takingsByMethod(
|
|
190
|
+
export function takingsByMethod(
|
|
191
|
+
orders: readonly TillOrder[], sessionId: string, extra: readonly TillLeg[] = [],
|
|
192
|
+
): Record<string, DrawerTerm> {
|
|
172
193
|
const takings: Record<string, DrawerTerm> = Object.create(null);
|
|
173
|
-
for (const order of orders) {
|
|
174
|
-
if (order.sessionId !== sessionId) continue;
|
|
194
|
+
for (const order of [...orders, { payments: extra }] as readonly TillOrder[]) {
|
|
175
195
|
for (const payment of tillPayments(order.payments)) {
|
|
196
|
+
if ((payment.sessionId ?? order.sessionId) !== sessionId) continue;
|
|
176
197
|
const term = (takings[legMethodId(payment)] ??= { amountMinor: 0, count: 0 });
|
|
177
198
|
term.amountMinor += payment.amountMinor;
|
|
178
199
|
term.count += 1;
|
package/src/register/index.ts
CHANGED
|
@@ -18,6 +18,8 @@ export {
|
|
|
18
18
|
} from './session-store';
|
|
19
19
|
export type { RegisterSessionCollection, CashMovementCollection, ClosureCollection } from './session-store';
|
|
20
20
|
export { deriveSettled } from './settled-figures';
|
|
21
|
+
export { closureFigures } from './closure-figures';
|
|
22
|
+
export type { ClosureFigures } from './closure-figures';
|
|
21
23
|
export { suggestFloat } from './float-suggestion';
|
|
22
24
|
export type { FloatSuggestion } from './float-suggestion';
|
|
23
25
|
export type { Correction, RecordedFigures } from './settled-figures';
|
|
@@ -29,7 +31,7 @@ export { minorToDecimal, formatDecimalMoney } from './money';
|
|
|
29
31
|
export { formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUNDING_MIXED_NOTE, TAX_STORE_PAID_NOTE, createClosureContext } from './closure-document';
|
|
30
32
|
export type { ClosureContext, CreateClosureContextOptions } from './closure-document';
|
|
31
33
|
export { registerFactsLogger, recordRegisterFact, type Actor, type RegisterFact } from './facts';
|
|
32
|
-
export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError } from './use-register-session';
|
|
34
|
+
export { useRegisterSession, RegisterTenderInProgressError, RegisterSaleSavingError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError } from './use-register-session';
|
|
33
35
|
export type { ApprovalNeeded, UseRegisterSessionOptions } from './use-register-session';
|
|
34
36
|
export { registerCommandSchema, registerCommandCollection, registerCommandsLogger, sessionOpenCommand, sessionTransitionCommand, movementCommand, closureCommand, reconcileRegisterCommands } from './register-commands';
|
|
35
37
|
export {
|