@tallyui/pos 3.12.0 → 3.13.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 +1545 -300
- package/dist/index.js +4259 -2218
- package/package.json +12 -6
- package/src/app-settings/app-settings.ts +93 -0
- package/src/app-settings/index.ts +8 -0
- package/src/app-settings/use-app-settings.ts +23 -0
- package/src/cashier/can.ts +12 -0
- package/src/cashier/index.ts +2 -0
- package/src/cashier/use-cashier.ts +81 -0
- package/src/csv/csv.ts +33 -0
- package/src/csv/index.ts +2 -0
- package/src/customer-display/display-state.ts +30 -0
- package/src/customer-display/index.ts +8 -0
- package/src/customer-display/protocol.ts +87 -0
- package/src/customer-display/snapshot.ts +65 -0
- package/src/index.ts +67 -10
- package/src/order/order-builder.ts +11 -1
- package/src/order/order-drafts.ts +16 -0
- package/src/order/types.ts +6 -3
- package/src/outbox/index.ts +5 -1
- package/src/outbox/outbox-health.ts +40 -0
- package/src/outbox/register-outbox.ts +59 -6
- package/src/outbox/safe-error.ts +11 -0
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-outbox-health.ts +22 -0
- package/src/outbox/use-register-outbox.ts +6 -0
- package/src/payment-driver/index.ts +8 -0
- package/src/payment-driver/registry.ts +39 -0
- package/src/payment-driver/simulated-driver.ts +104 -0
- package/src/payment-driver/types.ts +73 -0
- package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
- package/src/pos-order/command.ts +36 -16
- package/src/pos-order/finalize.ts +7 -3
- package/src/pos-order/index.ts +1 -0
- package/src/pos-order/note-delivery.ts +13 -0
- package/src/pos-order/reopen.ts +3 -2
- package/src/pos-order/schema.ts +5 -4
- package/src/pos-order/types.ts +3 -2
- package/src/print/index.ts +10 -0
- package/src/print/print-queue.ts +67 -0
- package/src/print/printer-profiles.ts +71 -0
- package/src/print/system-transport.ts +101 -0
- package/src/print/types.ts +40 -0
- package/src/receipt/reprint.ts +2 -1
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/default-templates.ts +78 -0
- package/src/receipt-template/index.ts +15 -0
- package/src/receipt-template/parse-xml.ts +175 -0
- package/src/receipt-template/render-html.ts +152 -0
- package/src/receipt-template/render-receipt.ts +19 -0
- package/src/receipt-template/render-template.ts +35 -0
- package/src/receipt-template/sanitize-html.ts +146 -0
- package/src/receipt-template/template-data.ts +97 -0
- package/src/receipt-template/types.ts +49 -0
- package/src/refund/index.ts +2 -0
- package/src/refund/refundable-lines.ts +91 -0
- package/src/register/export-csv.ts +24 -35
- package/src/register/float-suggestion.ts +22 -0
- package/src/register/index.ts +8 -3
- package/src/register/register-adoption.ts +71 -2
- package/src/register/register-commands.ts +7 -4
- package/src/register/register-count.helpers.ts +4 -0
- package/src/register/session-store.ts +4 -1
- package/src/register/use-register-session.ts +112 -28
- package/src/reports/adapters.ts +67 -0
- package/src/reports/index.ts +5 -0
- package/src/reports/presets.ts +27 -0
- package/src/reports/sales-figures.ts +173 -0
- package/src/reports/types.ts +63 -0
- package/src/sale/index.ts +3 -1
- package/src/sale/open-sales.ts +40 -0
- package/src/sale/use-sale.ts +72 -8
- package/src/scanner/index.ts +6 -0
- package/src/scanner/scan-session.ts +84 -0
- package/src/scanner/use-barcode-scanner.ts +61 -0
- package/src/scanner/wedge-detector.ts +137 -0
- package/src/tender/cash-rounding.ts +74 -0
- package/src/tender/index.ts +4 -0
- package/src/tender/payment-legs.ts +48 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { formatMoney } from '@tallyui/core';
|
|
2
|
+
import type { ReceiptData } from '../receipt/types';
|
|
3
|
+
|
|
4
|
+
export interface ReceiptTemplateRow { label: string; amount: string }
|
|
5
|
+
export interface ReceiptTemplateLine {
|
|
6
|
+
name: string;
|
|
7
|
+
/** `Name: value` per variant option, in `attributes` order. */
|
|
8
|
+
options: { text: string }[];
|
|
9
|
+
/** `<quantity> × <unit price>`. */
|
|
10
|
+
detail: string;
|
|
11
|
+
/** displayAmountMinor, before any discount. */
|
|
12
|
+
amount: string;
|
|
13
|
+
/** The line's own displayDiscounts; amount carries a leading `−`. */
|
|
14
|
+
discounts: ReceiptTemplateRow[];
|
|
15
|
+
}
|
|
16
|
+
export interface ReceiptTemplateData {
|
|
17
|
+
store: { name: string; addressLines: { line: string }[] };
|
|
18
|
+
document: { title: string; isReprint: boolean; reprintCount: number };
|
|
19
|
+
order: { number: string; date: string };
|
|
20
|
+
cashier: string;
|
|
21
|
+
register: string;
|
|
22
|
+
customer: string;
|
|
23
|
+
lines: ReceiptTemplateLine[];
|
|
24
|
+
subtotal: string;
|
|
25
|
+
lineDiscount: string;
|
|
26
|
+
orderDiscount: string;
|
|
27
|
+
charges: ReceiptTemplateRow[];
|
|
28
|
+
taxes: ReceiptTemplateRow[];
|
|
29
|
+
total: string;
|
|
30
|
+
payments: { method: string; amount: string; reference: string }[];
|
|
31
|
+
change: string;
|
|
32
|
+
note: string;
|
|
33
|
+
qrPayload: string;
|
|
34
|
+
}
|
|
35
|
+
export interface ReceiptTemplateOptions {
|
|
36
|
+
/** Default: formatMoney({ amount: minor, currency }) ?? ''. */
|
|
37
|
+
formatMoney?: (minor: number, currency: string) => string;
|
|
38
|
+
/** Default: Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' });
|
|
39
|
+
* an unparseable date is returned as given. */
|
|
40
|
+
formatDate?: (iso: string) => string;
|
|
41
|
+
/** Default: 'cash' → 'Cash', 'external' → 'Card terminal', anything else as given. */
|
|
42
|
+
paymentLabel?: (method: string) => string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function receiptTemplateData(receipt: ReceiptData, options: ReceiptTemplateOptions = {}): ReceiptTemplateData {
|
|
46
|
+
const money = (minor: number) => options.formatMoney
|
|
47
|
+
? options.formatMoney(minor, receipt.currency) : formatMoney({ amount: minor, currency: receipt.currency }) ?? '';
|
|
48
|
+
const date = options.formatDate ?? ((iso: string) => {
|
|
49
|
+
const parsed = new Date(iso);
|
|
50
|
+
return Number.isNaN(parsed.getTime()) ? iso
|
|
51
|
+
: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(parsed);
|
|
52
|
+
});
|
|
53
|
+
const paymentLabel = options.paymentLabel ?? ((method: string) =>
|
|
54
|
+
method === 'cash' ? 'Cash' : method === 'external' ? 'Card terminal' : method);
|
|
55
|
+
const titles = {
|
|
56
|
+
sale: 'Receipt', refund: 'Refund', void: 'Void', cancellation: 'Cancellation', closure: 'Z report', x_report: 'X report',
|
|
57
|
+
};
|
|
58
|
+
const { header, fiscal, totals } = receipt;
|
|
59
|
+
const lineDiscountMinor = totals.discountMinor - receipt.orderDiscountMinor;
|
|
60
|
+
return {
|
|
61
|
+
store: {
|
|
62
|
+
name: header.storeName,
|
|
63
|
+
addressLines: (header.storeAddress ?? '').split('\n').map((line) => line.trim())
|
|
64
|
+
.filter((line) => line !== '').map((line) => ({ line })),
|
|
65
|
+
},
|
|
66
|
+
document: { title: titles[fiscal.document_type], isReprint: fiscal.is_reprint, reprintCount: fiscal.reprint_count },
|
|
67
|
+
order: { number: header.orderNumber, date: date(header.date) },
|
|
68
|
+
cashier: header.cashier ?? '',
|
|
69
|
+
register: receipt.register.name,
|
|
70
|
+
customer: header.customer ?? '',
|
|
71
|
+
lines: receipt.lineItems.map((line) => ({
|
|
72
|
+
name: line.name,
|
|
73
|
+
options: Object.entries(line.attributes ?? {}).map(([name, value]) => ({ text: `${name}: ${value}` })),
|
|
74
|
+
detail: `${line.quantity} × ${money(line.unitPriceMinor)}`,
|
|
75
|
+
amount: money(line.displayAmountMinor),
|
|
76
|
+
discounts: line.displayDiscounts.map((discount) => ({
|
|
77
|
+
label: discount.label, amount: `−${money(discount.amountMinor)}`,
|
|
78
|
+
})),
|
|
79
|
+
})),
|
|
80
|
+
subtotal: money(totals.subtotalMinor),
|
|
81
|
+
lineDiscount: lineDiscountMinor > 0 ? `−${money(lineDiscountMinor)}` : '',
|
|
82
|
+
orderDiscount: receipt.orderDiscountMinor > 0 ? `−${money(receipt.orderDiscountMinor)}` : '',
|
|
83
|
+
charges: [...receipt.fees, ...receipt.shipping].map((charge) => ({
|
|
84
|
+
label: charge.name, amount: money(charge.amountMinor),
|
|
85
|
+
})),
|
|
86
|
+
taxes: totals.taxLines.map((tax) => ({
|
|
87
|
+
label: (totals.taxInclusive ? 'incl. ' : '') + tax.label, amount: money(tax.amountMinor),
|
|
88
|
+
})),
|
|
89
|
+
total: money(totals.totalMinor),
|
|
90
|
+
payments: receipt.payments.map((payment) => ({
|
|
91
|
+
method: paymentLabel(payment.method), amount: money(payment.amountMinor), reference: payment.reference ?? '',
|
|
92
|
+
})),
|
|
93
|
+
change: receipt.changeDueMinor > 0 ? money(receipt.changeDueMinor) : '',
|
|
94
|
+
note: receipt.footer.note ?? '',
|
|
95
|
+
qrPayload: fiscal.qr_payload,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Ported from WCPOS v2 packages/receipt-renderer/src/types.ts (monorepo main 5ac185b0, MIT).
|
|
2
|
+
// AST shapes unchanged; ESC/POS image and barcode encoding types omitted.
|
|
3
|
+
export type DrawerConnector = 'pin2' | 'pin5';
|
|
4
|
+
|
|
5
|
+
export type ThermalNode =
|
|
6
|
+
| ReceiptNode | TextNode | RawTextNode | BoldNode | UnderlineNode | InvertNode
|
|
7
|
+
| SizeNode | AlignNode | RowNode | ColNode | LineNode | BarcodeNode | QrcodeNode
|
|
8
|
+
| ImageNode | CutNode | FeedNode | DrawerNode;
|
|
9
|
+
|
|
10
|
+
export interface ReceiptNode {
|
|
11
|
+
type: 'receipt';
|
|
12
|
+
paperWidth: number;
|
|
13
|
+
children: ThermalNode[];
|
|
14
|
+
}
|
|
15
|
+
export interface RawTextNode { type: 'raw-text'; value: string }
|
|
16
|
+
export interface TextNode { type: 'text'; children: ThermalNode[] }
|
|
17
|
+
export interface BoldNode { type: 'bold'; children: ThermalNode[] }
|
|
18
|
+
export interface UnderlineNode { type: 'underline'; children: ThermalNode[] }
|
|
19
|
+
export interface InvertNode { type: 'invert'; children: ThermalNode[] }
|
|
20
|
+
export interface SizeNode {
|
|
21
|
+
type: 'size';
|
|
22
|
+
width: number;
|
|
23
|
+
height: number;
|
|
24
|
+
children: ThermalNode[];
|
|
25
|
+
}
|
|
26
|
+
export interface AlignNode {
|
|
27
|
+
type: 'align';
|
|
28
|
+
mode: 'left' | 'center' | 'right';
|
|
29
|
+
children: ThermalNode[];
|
|
30
|
+
}
|
|
31
|
+
export interface RowNode { type: 'row'; children: ColNode[] }
|
|
32
|
+
export interface ColNode {
|
|
33
|
+
type: 'col';
|
|
34
|
+
width: number | '*';
|
|
35
|
+
align: 'left' | 'right';
|
|
36
|
+
children: ThermalNode[];
|
|
37
|
+
}
|
|
38
|
+
export interface LineNode { type: 'line'; style: 'single' | 'double' | 'dashed' | 'dotted' }
|
|
39
|
+
export interface BarcodeNode {
|
|
40
|
+
type: 'barcode';
|
|
41
|
+
barcodeType: string;
|
|
42
|
+
height: number;
|
|
43
|
+
value: string;
|
|
44
|
+
}
|
|
45
|
+
export interface QrcodeNode { type: 'qrcode'; size: number; value: string }
|
|
46
|
+
export interface ImageNode { type: 'image'; src: string; width: number }
|
|
47
|
+
export interface CutNode { type: 'cut'; cutType: 'full' | 'partial' }
|
|
48
|
+
export interface FeedNode { type: 'feed'; lines: number }
|
|
49
|
+
export interface DrawerNode { type: 'drawer'; connector?: DrawerConnector }
|
package/src/refund/index.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { sendOrderRefund, type OrderRefundOutcome } from './send-order-refund';
|
|
2
2
|
export { posRefundSchema, posRefundCollection, type PosRefund, type PosRefundStatus, type PosRefundCollection } from './pos-refund';
|
|
3
3
|
export { submitOrderRefund, RefundAnswerPendingError } from './submit-order-refund';
|
|
4
|
+
export { refundableLines, priceRefund } from './refundable-lines';
|
|
5
|
+
export type { RefundableOrderLine, EarlierRefund, RefundableLine, PricedRefundLine, PricedRefund } from './refundable-lines';
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ports v2 calculate-refund.ts (calculateLineItemRefund, computeRemainingRefundQuantity).
|
|
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,12 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* A CSV export of the closures currently shown: one column per tender the visible rows use, an
|
|
3
|
-
* expected-only tender kept as a zero-counted shortage,
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* expected-only tender kept as a zero-counted shortage, quoting and formula guarding from
|
|
4
|
+
* `../csv`, and CRLF between lines (LEDGER.md #26, #27).
|
|
5
|
+
* Port provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`
|
|
6
6
|
* `export-csv.ts`. Money is a2's integer minor units: an `exponent` parameter (as in a1's
|
|
7
7
|
* `parseMinor`/`varianceText`) formats each cell back to the decimal string WCPOS's server sent,
|
|
8
8
|
* e.g. `1250` at exponent 2 becomes `'12.50'`.
|
|
9
9
|
*/
|
|
10
|
+
import { toCsv, type CsvColumn } from '../csv';
|
|
10
11
|
import { minorToDecimal } from './money';
|
|
11
12
|
import type { Closure } from './schemas';
|
|
12
13
|
|
|
@@ -29,32 +30,16 @@ export function exportCsv(
|
|
|
29
30
|
]),
|
|
30
31
|
),
|
|
31
32
|
];
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
t(
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
...tenders.flatMap((method) =>
|
|
41
|
-
|
|
42
|
-
`${t('register.counted')} (${method})`,
|
|
43
|
-
`${t('register.variance')} (${method})`,
|
|
44
|
-
]),
|
|
45
|
-
t('reports.csv_status'),
|
|
46
|
-
);
|
|
47
|
-
return [
|
|
48
|
-
header,
|
|
49
|
-
...rows.map((row) => [
|
|
50
|
-
row.business_day,
|
|
51
|
-
row.number,
|
|
52
|
-
row.breakdowns.register_name || names[row.register_id] || row.register_id.slice(0, 8),
|
|
53
|
-
row.breakdowns.store_name || storeName || row.store_key,
|
|
54
|
-
row.opened_at,
|
|
55
|
-
row.closed_at,
|
|
56
|
-
row.breakdowns.closed_by_name || t('register.unknown_cashier'),
|
|
57
|
-
...tenders.flatMap((method) => {
|
|
33
|
+
const columns: CsvColumn<Closure>[] = [
|
|
34
|
+
{ header: t('reports.csv_business_day'), value: (row) => row.business_day },
|
|
35
|
+
{ header: t('reports.csv_closure'), value: (row) => row.number },
|
|
36
|
+
{ header: t('reports.csv_register'), value: (row) => row.breakdowns.register_name || names[row.register_id] || row.register_id.slice(0, 8) },
|
|
37
|
+
{ header: t('reports.csv_store'), value: (row) => row.breakdowns.store_name || storeName || row.store_key },
|
|
38
|
+
{ header: t('reports.csv_opened'), value: (row) => row.opened_at },
|
|
39
|
+
{ header: t('reports.csv_closed'), value: (row) => row.closed_at },
|
|
40
|
+
{ header: t('reports.csv_closer'), value: (row) => row.breakdowns.closed_by_name || t('register.unknown_cashier') },
|
|
41
|
+
...tenders.flatMap((method): CsvColumn<Closure>[] => {
|
|
42
|
+
const values = (row: Closure) => {
|
|
58
43
|
const expected = at(row.expected, method);
|
|
59
44
|
const counted = at(row.counted, method) ?? (expected === undefined ? undefined : 0);
|
|
60
45
|
const value = at(row.variance, method) ?? (expected === undefined ? undefined : (counted ?? 0) - expected);
|
|
@@ -65,10 +50,14 @@ export function exportCsv(
|
|
|
65
50
|
? ''
|
|
66
51
|
: `${minorToDecimal(Math.abs(value), exponent)} ${t(value < 0 ? 'register.short' : value > 0 ? 'register.over' : 'reports.exact')}`,
|
|
67
52
|
];
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
53
|
+
};
|
|
54
|
+
return [
|
|
55
|
+
{ header: `${t('reports.document.expected')} (${method})`, value: (row) => values(row)[0] },
|
|
56
|
+
{ header: `${t('register.counted')} (${method})`, value: (row) => values(row)[1] },
|
|
57
|
+
{ header: `${t('register.variance')} (${method})`, value: (row) => values(row)[2] },
|
|
58
|
+
];
|
|
59
|
+
}),
|
|
60
|
+
{ header: t('reports.csv_status'), value: (row) => row.unsynced_count > 0 ? t('register.unsynced') : row.corrections_count ? t('reports.corrected') : '' },
|
|
61
|
+
];
|
|
62
|
+
return toCsv(rows, columns);
|
|
74
63
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The opening float the open-register card suggests (v2 parity A4): the register's default float, else the cash
|
|
3
|
+
* counted at the last close, else none. Port provenance: WCPOS v2 monorepo `main` `5ac185b0e`,
|
|
4
|
+
* `packages/core/src/screens/main/pos/cart/open-register-card.tsx:40-50` (`defaultFloat ?? lastCount ?? null`), with
|
|
5
|
+
* `seedAmount` from `packages/core/src/services/register-session/count-money.ts`. Money is TallyUI's integer
|
|
6
|
+
* minor-units convention, so `seedAmount`'s rounding of four-decimal server strings has no counterpart here.
|
|
7
|
+
*/
|
|
8
|
+
import type { RegisterInfo } from '@tallyui/core';
|
|
9
|
+
|
|
10
|
+
export type FloatSuggestion =
|
|
11
|
+
| { amountMinor: number; source: 'default' | 'last_count' }
|
|
12
|
+
| { amountMinor: null; source: null };
|
|
13
|
+
|
|
14
|
+
/** A default float of zero is still the default, as in v2 (`??`, not `||`). */
|
|
15
|
+
export function suggestFloat({ register, lastCountedCashMinor }: {
|
|
16
|
+
register?: Pick<RegisterInfo, 'defaultFloatMinor'> | null;
|
|
17
|
+
lastCountedCashMinor?: number | null;
|
|
18
|
+
}): FloatSuggestion {
|
|
19
|
+
if (register?.defaultFloatMinor != null) return { amountMinor: register.defaultFloatMinor, source: 'default' };
|
|
20
|
+
if (lastCountedCashMinor != null) return { amountMinor: lastCountedCashMinor, source: 'last_count' };
|
|
21
|
+
return { amountMinor: null, source: null };
|
|
22
|
+
}
|
package/src/register/index.ts
CHANGED
|
@@ -2,7 +2,7 @@ export { normalizeAmount, isServerDecimal, movementFieldError } from './movement
|
|
|
2
2
|
export type { MovementType } from './movement-input';
|
|
3
3
|
export { deriveExpected } from './expected';
|
|
4
4
|
export type { LedgerRow, Movement } from './expected';
|
|
5
|
-
export { parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, denominationTotal, varianceText } from './register-count.helpers';
|
|
5
|
+
export { parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText } from './register-count.helpers';
|
|
6
6
|
export { denominations } from './register-count.denominations';
|
|
7
7
|
export { registerSessionSchema, registerSessionCollection, cashMovementSchema, closureSchema } from './schemas';
|
|
8
8
|
export { addRegisterSessionCollection, RegisterSessionOpenClosedError, registerSessionsLogger, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS } from './open';
|
|
@@ -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 { suggestFloat } from './float-suggestion';
|
|
22
|
+
export type { FloatSuggestion } from './float-suggestion';
|
|
21
23
|
export type { Correction, RecordedFigures } from './settled-figures';
|
|
22
24
|
export { exportCsv } from './export-csv';
|
|
23
25
|
export { labelKeys } from './document-labels';
|
|
@@ -28,7 +30,10 @@ export { formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUN
|
|
|
28
30
|
export type { ClosureContext } from './closure-document';
|
|
29
31
|
export { registerFactsLogger, recordRegisterFact, type Actor, type RegisterFact } from './facts';
|
|
30
32
|
export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError } from './use-register-session';
|
|
31
|
-
export type { UseRegisterSessionOptions } from './use-register-session';
|
|
33
|
+
export type { ApprovalNeeded, UseRegisterSessionOptions } from './use-register-session';
|
|
32
34
|
export { registerCommandSchema, registerCommandCollection, registerCommandsLogger, sessionOpenCommand, sessionTransitionCommand, movementCommand, closureCommand, reconcileRegisterCommands } from './register-commands';
|
|
33
|
-
export {
|
|
35
|
+
export {
|
|
36
|
+
adoptRegisterResults, takeOverSession, abandonSession, isLiveAtStore, closureApprovalStatus, reapproveClosure, RegisterReapproveError,
|
|
37
|
+
} from './register-adoption';
|
|
38
|
+
export type { ClosureApprovalStatus } from './register-adoption';
|
|
34
39
|
export type { RegisterCommand, RegisterCommandCollection } from './register-commands';
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import type { ServerCapabilities } from '@tallyui/core';
|
|
2
|
+
import { CLOSURE_HOLDING_REJECTIONS } from '../outbox/register-outbox';
|
|
1
3
|
import { readFresh } from '../rxdb';
|
|
2
4
|
import { uuidv7 } from '../pos-order/uuidv7';
|
|
3
|
-
import {
|
|
4
|
-
import type
|
|
5
|
+
import { countVariance, overThreshold } from './register-count.helpers';
|
|
6
|
+
import { registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
|
|
7
|
+
import type { Closure, RegisterSession } from './schemas';
|
|
5
8
|
import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type RegisterSessionCollection } from './session-store';
|
|
6
9
|
|
|
7
10
|
const chains = new WeakMap<RegisterCommandCollection, Promise<void>>();
|
|
@@ -103,3 +106,69 @@ export async function abandonSession(input: SessionTarget): Promise<void> {
|
|
|
103
106
|
chains.set(commands, run.then(() => undefined, () => undefined));
|
|
104
107
|
return run;
|
|
105
108
|
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* ADR-082 d4: the store holds this session, so the app's approval route can be used for it. Its open row is applied (a
|
|
112
|
+
* resumed open and an error-free duplicate are recorded applied), and it is not conflict, superseded or abandoned. A
|
|
113
|
+
* closed session still counts: the route accepts it.
|
|
114
|
+
*/
|
|
115
|
+
export function isLiveAtStore(session: Pick<RegisterSession, 'id' | 'status'> | null | undefined,
|
|
116
|
+
openRow: Pick<RegisterCommand, 'key' | 'syncStatus'> | null | undefined): boolean {
|
|
117
|
+
return !!session && openRow?.key === `session.open:${session.id}` && openRow.syncStatus === 'applied'
|
|
118
|
+
&& session.status !== 'conflict' && session.status !== 'superseded' && session.status !== 'abandoned';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** `verified` once the store has applied a version 3 closure carrying a proof; `not_required` for a close the store does not check. */
|
|
122
|
+
export type ClosureApprovalStatus = 'verified' | 'unverified' | 'not_required';
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* ADR-082 d9, derived from the closure's `register.closure.submit` row; nothing is stored. A verified approval is
|
|
126
|
+
* needed at register contract 3 with the store's `registerApproval`, over its threshold on cash (the store's rule).
|
|
127
|
+
* Until the store applies a version 3 row with a proof, a recorded approver is `unverified`: no row yet, pending,
|
|
128
|
+
* refused, or a version 1 row the store recorded without checking.
|
|
129
|
+
*/
|
|
130
|
+
export function closureApprovalStatus(closure: Pick<Closure, 'counted' | 'till_expected'>,
|
|
131
|
+
row: Pick<RegisterCommand, 'syncStatus' | 'version' | 'payload'> | null | undefined,
|
|
132
|
+
capabilities: Pick<ServerCapabilities, 'register' | 'registerApproval'> | undefined): ClosureApprovalStatus {
|
|
133
|
+
const threshold = capabilities?.registerApproval?.thresholdMinor;
|
|
134
|
+
if ((capabilities?.register ?? 0) < 3 || threshold == null
|
|
135
|
+
|| !overThreshold(countVariance(closure.counted.cash ?? 0, closure.till_expected.cash ?? 0), threshold)) return 'not_required';
|
|
136
|
+
return row?.syncStatus === 'applied' && row.version >= 3 && typeof row.payload.approval === 'string' && row.payload.approval
|
|
137
|
+
? 'verified' : 'unverified';
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** `reapproveClosure` refused. Its message can be shown to a cashier as it is. */
|
|
141
|
+
export class RegisterReapproveError extends Error {
|
|
142
|
+
constructor(readonly code: 'REGISTER_REAPPROVE_UNSUPPORTED' | 'REGISTER_REAPPROVE_NOT_REFUSED' | 'REGISTER_REAPPROVE_PROOF_MISSING') {
|
|
143
|
+
super(code === 'REGISTER_REAPPROVE_UNSUPPORTED' ? 'This store cannot check a manager approval.'
|
|
144
|
+
: code === 'REGISTER_REAPPROVE_NOT_REFUSED' ? 'This closure is not waiting for a manager approval.'
|
|
145
|
+
: 'Manager approval needed. Ask a manager to approve.');
|
|
146
|
+
this.name = 'RegisterReapproveError';
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* ADR-082 d7: requeues a closure the store refused with either approval code, in its ledger place (the same key and
|
|
152
|
+
* `seq`), with a new command id (the store replays a stored refusal for the old one), version 3, the new proof and
|
|
153
|
+
* approver, and every other payload field as it was. The local closure, its Z and the session are not rewritten.
|
|
154
|
+
*/
|
|
155
|
+
export async function reapproveClosure({ commands, closureId, approval, approvedBy, registerContract, now }: {
|
|
156
|
+
commands: RegisterCommandCollection; closureId: string; approval: string; approvedBy: string; registerContract?: number; now?: string;
|
|
157
|
+
}): Promise<void> {
|
|
158
|
+
if ((registerContract ?? 0) < 3) throw new RegisterReapproveError('REGISTER_REAPPROVE_UNSUPPORTED');
|
|
159
|
+
if (typeof approval !== 'string' || !approval || typeof approvedBy !== 'string' || !approvedBy) {
|
|
160
|
+
throw new RegisterReapproveError('REGISTER_REAPPROVE_PROOF_MISSING');
|
|
161
|
+
}
|
|
162
|
+
const run = (chains.get(commands) ?? Promise.resolve()).then(async () => {
|
|
163
|
+
const row = await commands.findOne(`closure.submit:${closureId}`).exec();
|
|
164
|
+
if (!row) throw new RegisterReapproveError('REGISTER_REAPPROVE_NOT_REFUSED');
|
|
165
|
+
await row.incrementalModify((doc) => {
|
|
166
|
+
if (doc.syncStatus !== 'rejected' || !CLOSURE_HOLDING_REJECTIONS.has(doc.error?.code ?? '')) throw new RegisterReapproveError('REGISTER_REAPPROVE_NOT_REFUSED');
|
|
167
|
+
const { error: _refusal, ...rest } = doc;
|
|
168
|
+
return { ...rest, commandId: uuidv7(), version: 3, syncStatus: 'pending',
|
|
169
|
+
payload: { ...doc.payload, approval, approvedBy }, updatedAt: now ?? new Date().toISOString() };
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
chains.set(commands, run.then(() => undefined, () => undefined));
|
|
173
|
+
return run;
|
|
174
|
+
}
|
|
@@ -38,7 +38,7 @@ export const registerCommandSchema: RxJsonSchema<RegisterCommand> = {
|
|
|
38
38
|
};
|
|
39
39
|
export const registerCommandCollection = () => ({ schema: registerCommandSchema });
|
|
40
40
|
|
|
41
|
-
type BuiltCommand = Pick<RegisterCommand, 'key' | 'type' | 'payload'> & { version: 1 | 2 };
|
|
41
|
+
type BuiltCommand = Pick<RegisterCommand, 'key' | 'type' | 'payload'> & { version: 1 | 2 | 3 };
|
|
42
42
|
|
|
43
43
|
/** ADR-078: 1 to 64 characters after trim. */
|
|
44
44
|
export function deviceNameOf(name: string | null | undefined): string | undefined {
|
|
@@ -82,8 +82,10 @@ export function movementCommand(m: CashMovement): BuiltCommand {
|
|
|
82
82
|
payload: { ...common, type: m.type, amountMinor: m.amountMinor, reason: m.reason } satisfies RegisterMovementRecordPayload };
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
|
|
86
|
-
|
|
85
|
+
/** ADR-082 d1: version 3 with the store's opaque approval at register contract 3; below 3 or unknown, version 1 and today's bytes. */
|
|
86
|
+
export function closureCommand(c: Closure, v3: { registerContract?: number; approval?: string | null } = {}): BuiltCommand {
|
|
87
|
+
const at3 = (v3.registerContract ?? 0) >= 3;
|
|
88
|
+
return { key: `closure.submit:${c.id}`, type: 'register.closure.submit', version: at3 ? 3 : 1, payload: {
|
|
87
89
|
closureId: c.id, sessionId: c.session_id, registerId: c.register_id, number: c.number,
|
|
88
90
|
openedAt: c.opened_at, closedAt: c.closed_at,
|
|
89
91
|
...(c.business_day == null ? {} : { businessDay: c.business_day }),
|
|
@@ -94,6 +96,7 @@ export function closureCommand(c: Closure): BuiltCommand {
|
|
|
94
96
|
perpetualSalesTotalMinor: c.perpetual_sales_total_minor, perpetualRefundsTotalMinor: c.perpetual_refunds_total_minor,
|
|
95
97
|
unsyncedCount: c.unsynced_count, unsyncedTotalMinor: c.unsynced_total_minor, softwareVersion: c.software_version,
|
|
96
98
|
orderIds: c.order_ids, movementIds: c.movement_ids,
|
|
99
|
+
...(at3 && v3.approval ? { approval: v3.approval } : {}),
|
|
97
100
|
} satisfies RegisterClosureSubmitPayload };
|
|
98
101
|
}
|
|
99
102
|
|
|
@@ -133,7 +136,7 @@ export function reconcileRegisterCommands({ commands, sessions, movements, closu
|
|
|
133
136
|
...entries.filter((entry) => entry.type === 'void').map(movementCommand));
|
|
134
137
|
if (session.status_at != null && sentStatus(session)) events.push(sessionTransitionCommand({ ...session, status_at: session.status_at }));
|
|
135
138
|
return { session, number: closureRows[0]?.number, built: [(registerContract ?? 0) >= 2 ? sessionOpenCommand(session, { deviceName }) : sessionOpenCommand(session), ...events,
|
|
136
|
-
...closureRows.map((closure) => closureCommand(closure))] };
|
|
139
|
+
...closureRows.map((closure) => closureCommand(closure, { registerContract, approval: session.approver_token }))] };
|
|
137
140
|
}));
|
|
138
141
|
facts.sort((a, b) => Number(a.session.status !== 'closed') - Number(b.session.status !== 'closed')
|
|
139
142
|
|| (a.number ?? Infinity) - (b.number ?? Infinity)
|
|
@@ -40,6 +40,10 @@ export const overThreshold = (variance: number, thresholdMinor?: number | null)
|
|
|
40
40
|
export const closeNeedsApproval = (countedCashMinor: number, expectedCashMinor: number, thresholdMinor?: number | null) =>
|
|
41
41
|
overThreshold(countVariance(countedCashMinor, expectedCashMinor), thresholdMinor);
|
|
42
42
|
|
|
43
|
+
/** ADR-082 d3: counted minus till-expected for each key of `counted`, the variance a store approval is bound to. */
|
|
44
|
+
export const closureVariance = (counted: Record<string, number>, tillExpected: Record<string, number>) =>
|
|
45
|
+
Object.fromEntries(Object.entries(counted).map(([method, value]) => [method, countVariance(value, tillExpected[method] ?? 0)]));
|
|
46
|
+
|
|
43
47
|
/** Sums denomination face values (already minor units) by piece count. */
|
|
44
48
|
export const denominationTotal = (pieces: Record<number, number>) =>
|
|
45
49
|
Object.entries(pieces).reduce((sum, [value, count]) => sum + Number(value) * count, 0);
|
|
@@ -309,11 +309,13 @@ export const backToSelling = (sessions: RegisterSessionCollection, id: string) =
|
|
|
309
309
|
* Closes the session with its counted tenders (minor units); `timezone` dates a session opened
|
|
310
310
|
* without a business day. `approvedBy`, the manager who approved the count, is written in the same
|
|
311
311
|
* write as the close, and a repeat close keeps the first close's approver as it keeps its count.
|
|
312
|
+
* `approval`, the store's opaque proof (ADR-082), is written to `approver_token` in the same
|
|
313
|
+
* write; it never reaches the closure or its breakdowns.
|
|
312
314
|
*/
|
|
313
315
|
export async function closeSession(
|
|
314
316
|
sessions: RegisterSessionCollection,
|
|
315
317
|
id: string,
|
|
316
|
-
input: { counted: Record<string, number>; closedBy?: string; approvedBy?: string; timezone?: string },
|
|
318
|
+
input: { counted: Record<string, number>; closedBy?: string; approvedBy?: string; approval?: string; timezone?: string },
|
|
317
319
|
) {
|
|
318
320
|
const session = await sessions.findOne(id).exec();
|
|
319
321
|
if (!session) throw new RegisterSessionRequiredError();
|
|
@@ -322,6 +324,7 @@ export async function closeSession(
|
|
|
322
324
|
counted: input.counted,
|
|
323
325
|
closed_by: input.closedBy ?? null,
|
|
324
326
|
...(input.approvedBy ? { approved_by: input.approvedBy } : {}),
|
|
327
|
+
...(input.approval ? { approver_token: input.approval } : {}),
|
|
325
328
|
closure_id: id,
|
|
326
329
|
});
|
|
327
330
|
}
|