@tallyui/pos 4.2.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +620 -166
- package/dist/index.js +1970 -1091
- package/package.json +7 -6
- package/src/index.ts +15 -12
- 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 +3 -1
- package/src/outbox/needs-admin-reason.ts +10 -0
- package/src/outbox/order-outbox.ts +27 -11
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/store-settlement.ts +136 -0
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-order-outbox.ts +54 -4
- package/src/pos-order/attention-handled.ts +2 -0
- package/src/pos-order/command.ts +31 -9
- package/src/pos-order/finalize.ts +9 -0
- package/src/pos-order/index.ts +3 -1
- package/src/pos-order/needs-attention.ts +8 -3
- package/src/pos-order/reopen.ts +9 -2
- package/src/pos-order/schema.ts +20 -2
- package/src/pos-order/store-order-left.ts +21 -0
- package/src/pos-order/store-settlement.ts +51 -0
- package/src/pos-order/types.ts +27 -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 +320 -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 +57 -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
|
@@ -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 {
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { ServerCapabilities } from '@tallyui/core';
|
|
2
|
-
import { CLOSURE_HOLDING_REJECTIONS, NON_BLOCKING_REJECTIONS } from '../outbox/register-outbox';
|
|
2
|
+
import { CLOSURE_HOLDING_REJECTIONS, isRegisterRequeueable, NON_BLOCKING_REJECTIONS } from '../outbox/register-outbox';
|
|
3
3
|
import { readFresh } from '../rxdb';
|
|
4
4
|
import { uuidv7 } from '../pos-order/uuidv7';
|
|
5
5
|
import { countVariance, overThreshold } from './register-count.helpers';
|
|
6
|
-
import { adoptStoreCounters, renumberClosures, type RegisterHost } from './register-document';
|
|
6
|
+
import { adoptStoreCounters, renumberClosures, settleStoreRefunds, type RegisterHost } from './register-document';
|
|
7
7
|
import { registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
|
|
8
8
|
import type { Closure, RegisterSession } from './schemas';
|
|
9
9
|
import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type ClosureCollection,
|
|
@@ -69,14 +69,44 @@ async function renumberRefused(commands: RegisterCommandCollection, closures: Cl
|
|
|
69
69
|
});
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Rule R: the anchor N is the newest applied closure answer for a closure row of this store (another store's answer
|
|
75
|
+
* never anchors) whose `closure.number` is its counters' last number (a replayed older closure carries today's counters
|
|
76
|
+
* with its old number, so it never anchors), and S the largest refunds figure read at N. Nothing is written when any
|
|
77
|
+
* store figure is past N, while any closure of this store numbered above N exists, or when any closure submit of this
|
|
78
|
+
* register is pending (it may be in flight) or refused with a refusal that can still reach the store (refused for its
|
|
79
|
+
* number, held for its approval, or one the outbox resends); no row is rewritten.
|
|
80
|
+
*/
|
|
81
|
+
async function settleRefunds(answers: RegisterCommand[], commands: RegisterCommandCollection, closures: ClosureCollection,
|
|
82
|
+
host: RegisterHost, storeKey: string, registerId: string) {
|
|
83
|
+
const [submits, local] = await Promise.all([
|
|
84
|
+
readFresh(commands, { selector: { registerId, type: 'register.closure.submit' } }),
|
|
85
|
+
readFresh(closures, { selector: { register_id: registerId } }),
|
|
86
|
+
]);
|
|
87
|
+
const own = new Set(local.filter(({ store_key }) => (store_key ?? storeKey) === storeKey).map(({ id }) => id));
|
|
88
|
+
const store = answers.flatMap(({ type, syncStatus, result, payload }) => {
|
|
89
|
+
const [number, refunds] = [figure(result?.counters?.lastClosureNumber), figure(result?.counters?.perpetualRefundsTotalMinor)];
|
|
90
|
+
return syncStatus === 'applied' && number !== undefined && refunds !== undefined ? [{ number, refunds,
|
|
91
|
+
anchor: type === 'register.closure.submit' && result?.closure?.number === number && own.has(payload.closureId as string) }] : [];
|
|
92
|
+
});
|
|
93
|
+
const n = Math.max(-1, ...store.filter(({ anchor }) => anchor).map(({ number }) => number));
|
|
94
|
+
if (n < 0 || store.some(({ number }) => number > n)) return;
|
|
95
|
+
const blocks = (code = '') => code === 'register_closure_number_invalid' || CLOSURE_HOLDING_REJECTIONS.has(code) || isRegisterRequeueable(code);
|
|
96
|
+
if (local.some(({ number, store_key }) => (store_key ?? storeKey) === storeKey && number > n) || submits.some(({ syncStatus, error }) =>
|
|
97
|
+
syncStatus === 'pending' || (syncStatus === 'rejected' && blocks(error?.code)))) return;
|
|
98
|
+
await settleStoreRefunds(host, storeKey, registerId, { lastClosureNumber: n,
|
|
99
|
+
perpetualRefundsTotalMinor: Math.max(...store.filter(({ number }) => number === n).map(({ refunds }) => refunds)) });
|
|
100
|
+
}
|
|
72
101
|
type SessionTarget = { commands: RegisterCommandCollection; sessions: RegisterSessionCollection; sessionId: string; now?: string };
|
|
73
102
|
|
|
74
103
|
/**
|
|
75
104
|
* Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
|
|
76
105
|
* Superseded rejections make open/counting sessions terminal; a conflict session leaves only by an applied open or abandon (ADR-078 decision 9); terminal/unknown states stay untouched.
|
|
77
106
|
* Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
|
|
78
|
-
* Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters
|
|
107
|
+
* Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters`; refunds only from answers at the highest closure number among them),
|
|
79
108
|
* and given `closures` too, a closure refused for its number is renumbered once and requeued (#655, `renumberRefused`).
|
|
109
|
+
* Given `closures`, applied closure answers then set the register's perpetual refunds to the store's (`settleStoreRefunds`) when nothing of this till's is unsent.
|
|
80
110
|
* Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
|
|
81
111
|
*/
|
|
82
112
|
export async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }: {
|
|
@@ -119,7 +149,15 @@ export async function adoptRegisterResults({ commands, sessions, registerId, hos
|
|
|
119
149
|
if (row) await row.incrementalModify(modify);
|
|
120
150
|
}
|
|
121
151
|
const counters = answers.filter((answer) => answer.syncStatus === 'applied' && answer.result?.counters).map((answer) => answer.result?.counters);
|
|
122
|
-
|
|
152
|
+
// Refunds are raised only from the newest closure number's answers: an older one may echo the till's inflated figure.
|
|
153
|
+
const top = Math.max(-1, ...counters.map((entry) => figure(entry?.lastClosureNumber) ?? -1));
|
|
154
|
+
const raising = counters.map((entry) => {
|
|
155
|
+
if (!entry || figure(entry.lastClosureNumber) === top) return entry;
|
|
156
|
+
const { perpetualRefundsTotalMinor: _older, ...rest } = entry;
|
|
157
|
+
return rest;
|
|
158
|
+
});
|
|
159
|
+
if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, raising);
|
|
160
|
+
if (host && storeKey && closures) await settleRefunds(answers, commands, closures, host, storeKey, registerId);
|
|
123
161
|
if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
|
|
124
162
|
}).catch((error: unknown) => {
|
|
125
163
|
registerCommandsLogger.error('Register result adoption failed', { context: { registerId, error: String(error) } });
|
|
@@ -267,6 +267,23 @@ export function renumberClosures(host: RegisterHost, storeKey: string, registerI
|
|
|
267
267
|
});
|
|
268
268
|
}
|
|
269
269
|
|
|
270
|
+
/**
|
|
271
|
+
* Sets the register's perpetual refunds to the store's figure from its newest applied closure answer (rule R), so it
|
|
272
|
+
* lowers as well as raises: besides a number refusal (`renumberClosures`), the one exception to "never lowered".
|
|
273
|
+
* Nothing is written when the register's last number isn't `lastClosureNumber` (a mint has started since, or the till
|
|
274
|
+
* is behind), when a reserved closure is not yet applied, or when the figure is already the store's. Every other
|
|
275
|
+
* field stays, sales included, so a repeat changes nothing.
|
|
276
|
+
*/
|
|
277
|
+
export function settleStoreRefunds(host: RegisterHost, storeKey: string, registerId: string,
|
|
278
|
+
{ lastClosureNumber, perpetualRefundsTotalMinor }: Pick<StoreCounters, 'lastClosureNumber' | 'perpetualRefundsTotalMinor'>) {
|
|
279
|
+
return modifyStore(host, storeKey, (store) => {
|
|
280
|
+
const register = store?.registers?.[registerId] ?? {};
|
|
281
|
+
if (register.last_closure_number !== lastClosureNumber || register.closure_reservation?.applied === false
|
|
282
|
+
|| register.perpetual_refunds_total_minor === perpetualRefundsTotalMinor) return undefined;
|
|
283
|
+
return withRegister(store, registerId, { ...register, perpetual_refunds_total_minor: perpetualRefundsTotalMinor });
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
270
287
|
/**
|
|
271
288
|
* Adds a closed period to the register's perpetual totals. With `closureId`, it applies that
|
|
272
289
|
* reserved closure once: the totals become the reservation's, and a repeat does nothing.
|
|
@@ -18,7 +18,9 @@ import { replacedOrderIds } from '../pos-order/reopened';
|
|
|
18
18
|
import { tillPayments } from '../pos-order/till-payments';
|
|
19
19
|
import type { PosRefund } from '../refund/pos-refund';
|
|
20
20
|
import { readFresh } from '../rxdb';
|
|
21
|
-
import {
|
|
21
|
+
import { parkedCashRoundings, parkedTakenLegs } from '../order/order-drafts';
|
|
22
|
+
import type { CashRounding, Payment } from '../order/types';
|
|
23
|
+
import { deriveExpected, liveLedgerRows, parkedLedgerRows, paymentLedgerRows, refundAmounts } from './expected';
|
|
22
24
|
import { recordRegisterFact } from './facts';
|
|
23
25
|
import { MAX_REASON_LENGTH } from './movement-input';
|
|
24
26
|
import { countVariance } from './register-count.helpers';
|
|
@@ -482,6 +484,9 @@ export async function writeClosure({
|
|
|
482
484
|
otherTenders,
|
|
483
485
|
movements,
|
|
484
486
|
orders,
|
|
487
|
+
drafts,
|
|
488
|
+
liveLegs,
|
|
489
|
+
liveRoundings,
|
|
485
490
|
refunds,
|
|
486
491
|
tillExpected,
|
|
487
492
|
labels,
|
|
@@ -500,6 +505,16 @@ export async function writeClosure({
|
|
|
500
505
|
movements: readonly CashMovement[];
|
|
501
506
|
/** Any `pos_orders`; only those whose `sessionId` is this session's are counted. */
|
|
502
507
|
orders: readonly PosOrder[];
|
|
508
|
+
/**
|
|
509
|
+
* `order_drafts` documents: a parked sale's legs taken in this session count here (S3). Optional here only because
|
|
510
|
+
* `useRegisterSession`, the real caller, always passes it and `liveLegs`; any other caller must pass both, or cash taken
|
|
511
|
+
* in this session but not yet on an order is missing from its Z.
|
|
512
|
+
*/
|
|
513
|
+
drafts?: readonly { data?: unknown }[];
|
|
514
|
+
/** The live sale's taken legs (`useSale`'s `registerView().takenLegs`, S3): those taken in this session count here. See `drafts`. */
|
|
515
|
+
liveLegs?: readonly Payment[];
|
|
516
|
+
/** The live sale's cash rounding entries (`registerView().cashRoundings`, #1281): one on a `liveLegs` leg taken in this session counts here. */
|
|
517
|
+
liveRoundings?: readonly CashRounding[];
|
|
503
518
|
/** `pos_refunds` rows; only this session's applied ones are counted (ADR-080 amendment 1). */
|
|
504
519
|
refunds?: readonly PosRefund[];
|
|
505
520
|
tillExpected?: Record<string, number>;
|
|
@@ -523,7 +538,9 @@ export async function writeClosure({
|
|
|
523
538
|
const replaced = replacedOrderIds(orders);
|
|
524
539
|
const bound = orders.filter((order) => order.sessionId === session.id && !replaced.has(order.id));
|
|
525
540
|
const countedRefunds = (refunds ?? []).filter((refund) => refund.status === 'applied' && refund.sessionId === session.id);
|
|
526
|
-
|
|
541
|
+
// S3: a leg counts in the session that took it, here or on another session's Z, never on both.
|
|
542
|
+
const rows = [...paymentLedgerRows(bound), ...parkedLedgerRows(drafts ?? []), ...liveLedgerRows(liveLegs ?? [])]
|
|
543
|
+
.filter((row) => row.session_id === session.id);
|
|
527
544
|
const entries = movements.filter((row) => row.session_id === session.id);
|
|
528
545
|
const till_expected =
|
|
529
546
|
tillExpected ??
|
|
@@ -547,11 +564,14 @@ export async function writeClosure({
|
|
|
547
564
|
}
|
|
548
565
|
}
|
|
549
566
|
const payment_methods = Object.fromEntries(methodTotals);
|
|
550
|
-
//
|
|
551
|
-
//
|
|
567
|
+
// Rows are keyed by code plus rate (desk ruling: "name plus rate"), never merging taxes at the same rate; two WooCommerce
|
|
568
|
+
// rate ids that share a code and a rate, split on the receipt, are one row here. Each line is in the mode
|
|
552
569
|
// its receipt rounded it in (`taxedLinesFor`). Each order is split by the
|
|
553
|
-
// tax rounding it recorded (#287)
|
|
554
|
-
|
|
570
|
+
// tax rounding it recorded (#287); absent is the default, today's split.
|
|
571
|
+
// RxDB reads stored fields by dot path, so the key carries no '[', ']', '\\' or '.'; never integer-like, so row order is insertion order.
|
|
572
|
+
// One pass escapes '%' with the rest, so the key stays injective; it never throws (a lone surrogate is kept as is).
|
|
573
|
+
const taxRateKey = (code: string | undefined, ratePpm: number) => `${ratePpm}:${(code ?? '').replace(/[%.[\]\\]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`;
|
|
574
|
+
const taxRates = new Map<string, { ratePpm: number; code?: string; net_minor: number; tax_minor: number }>();
|
|
555
575
|
const roundings = new Set<string>();
|
|
556
576
|
for (const order of bound) {
|
|
557
577
|
// Grouped by the rule applied: a `custom` sale used the default figures, so it joins the default's group.
|
|
@@ -559,16 +579,30 @@ export async function writeClosure({
|
|
|
559
579
|
const rounding = recorded.granularity === 'custom' ? DEFAULT_TAX_ROUNDING : recorded;
|
|
560
580
|
roundings.add(rounding.granularity === 'woocommerce' ? `woocommerce ${rounding.roundAtSubtotal}` : `${rounding.granularity} ${rounding.mode}`);
|
|
561
581
|
const taxedLines = taxedLinesFor(order.lines, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
|
|
562
|
-
for (const { ratePpm, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding)) {
|
|
563
|
-
const existing = taxRates.get(
|
|
564
|
-
taxRates.set(
|
|
565
|
-
ratePpm,
|
|
582
|
+
for (const { ratePpm, code, netMinor, amountMinor } of taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding)) {
|
|
583
|
+
const existing = taxRates.get(taxRateKey(code, ratePpm));
|
|
584
|
+
taxRates.set(taxRateKey(code, ratePpm), {
|
|
585
|
+
ratePpm, code,
|
|
566
586
|
net_minor: (existing?.net_minor ?? 0) + netMinor,
|
|
567
587
|
tax_minor: (existing?.tax_minor ?? 0) + amountMinor,
|
|
568
588
|
});
|
|
569
589
|
}
|
|
570
590
|
}
|
|
571
591
|
const unsynced = bound.filter((order) => order.syncStatus === 'pending');
|
|
592
|
+
// ADR-094: a bound order's rounding counts as its leg's money does (S3): a till leg, in the session that took it.
|
|
593
|
+
// A parked or live sale's entries count by the same rule, against that sale's own taken legs (#1281).
|
|
594
|
+
const cashRoundingMinor = sum(bound.flatMap((order) => {
|
|
595
|
+
const legs = new Map(tillPayments(order.payments).map((payment) => [payment.id, payment]));
|
|
596
|
+
return (order.cashRoundings ?? []).filter((entry) => {
|
|
597
|
+
const leg = legs.get(entry.paymentId);
|
|
598
|
+
return leg !== undefined && (leg.sessionId ?? order.sessionId) === session.id;
|
|
599
|
+
}).map((entry) => entry.minor);
|
|
600
|
+
})) + sum([
|
|
601
|
+
...(drafts ?? []).map((row) => ({ legs: parkedTakenLegs(row.data), entries: parkedCashRoundings(row.data) })),
|
|
602
|
+
{ legs: liveLegs ?? [], entries: liveRoundings ?? [] },
|
|
603
|
+
].flatMap(({ legs, entries }) => entries
|
|
604
|
+
.filter((entry) => legs.some((leg) => leg.id === entry.paymentId && leg.sessionId === session.id))
|
|
605
|
+
.map((entry) => entry.minor)));
|
|
572
606
|
const draft: Closure = {
|
|
573
607
|
id: session.id,
|
|
574
608
|
session_id: session.id,
|
|
@@ -602,14 +636,16 @@ export async function writeClosure({
|
|
|
602
636
|
...(session.count_note?.trim() ? { variance_note: session.count_note } : {}),
|
|
603
637
|
payment_methods,
|
|
604
638
|
tax_rates: Object.fromEntries(
|
|
605
|
-
[...taxRates.values()].map(({ ratePpm, net_minor, tax_minor }) => [
|
|
606
|
-
ratePpm, { name: `Tax ${ratePpm / 10000}
|
|
639
|
+
[...taxRates.values()].sort((a, b) => a.ratePpm - b.ratePpm || ((a.code ?? '') < (b.code ?? '') ? -1 : (a.code ?? '') > (b.code ?? '') ? 1 : 0)).map(({ ratePpm, code, net_minor, tax_minor }) => [ // Numeric keys sorted automatically; identity keys need an explicit sort.
|
|
640
|
+
taxRateKey(code, ratePpm), { name: `Tax ${ratePpm / 10000}%${[...taxRates.values()].filter((row) => row.ratePpm === ratePpm).length > 1 && code ? ` (${code})` : ''}`, rate_ppm: ratePpm, ...(code ? { code } : {}), net_minor, tax_minor, gross_minor: net_minor + tax_minor },
|
|
607
641
|
]),
|
|
608
642
|
),
|
|
609
643
|
// The session's sales used more than one tax rounding (#287): the Z report says so.
|
|
610
644
|
...(roundings.size > 1 ? { tax_rounding_mixed: true } : {}),
|
|
611
645
|
// A reopened sale's tax rates are its whole order's, including tax on what was paid earlier in the store (ADR-090 ruling 38).
|
|
612
646
|
...(bound.some((order) => tillPayments(order.payments).length < order.payments.length) ? { tax_includes_store_paid: true } : {}),
|
|
647
|
+
// ADR-094: in period_sales_total_minor, in no tax_rates row.
|
|
648
|
+
...(cashRoundingMinor !== 0 ? { cash_rounding_minor: cashRoundingMinor } : {}),
|
|
613
649
|
opening_float: {
|
|
614
650
|
expected_minor: session.expected_float_minor ?? null,
|
|
615
651
|
counted_minor: session.counted_float_minor,
|
|
@@ -20,11 +20,13 @@ import type { RxCollection } from 'rxdb';
|
|
|
20
20
|
import type { RegisterSessionAlreadyOpenData, ServerCapabilities } from '@tallyui/core';
|
|
21
21
|
import { CLOSURE_HOLDING_REJECTIONS } from '../outbox/register-outbox';
|
|
22
22
|
import { safeErrorString } from '../outbox/safe-error';
|
|
23
|
+
import type { CashRounding, Payment } from '../order/types';
|
|
23
24
|
import type { PosOrder } from '../pos-order/types';
|
|
24
25
|
import { replacedOrderIds } from '../pos-order/reopened';
|
|
25
26
|
import type { PosRefund, PosRefundCollection } from '../refund/pos-refund';
|
|
26
27
|
import { readFresh, watchFresh } from '../rxdb';
|
|
27
|
-
import {
|
|
28
|
+
import { closingByRegister, notifyClosing, subscribeClosing } from './closing';
|
|
29
|
+
import { deriveDrawerTerms, deriveExpected, liveLedgerRows, parkedLedgerRows, paymentLedgerRows, type LedgerRow } from './expected';
|
|
28
30
|
import { recordRegisterFact, registerFactsLogger, type Actor } from './facts';
|
|
29
31
|
import { closeNeedsApproval, closureVariance } from './register-count.helpers';
|
|
30
32
|
import {
|
|
@@ -44,6 +46,14 @@ export class RegisterTenderInProgressError extends Error {
|
|
|
44
46
|
}
|
|
45
47
|
}
|
|
46
48
|
|
|
49
|
+
/** The live sale is still saving (or its save failed and was not retried), so the till can't count or close under it. Its message can be shown to a cashier as it is. */
|
|
50
|
+
export class RegisterSaleSavingError extends Error {
|
|
51
|
+
constructor() {
|
|
52
|
+
super('A sale is still being saved. Wait for it to finish, or retry it if it failed, then close the register.');
|
|
53
|
+
this.name = 'RegisterSaleSavingError';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
47
57
|
/** The register already has an `open` or `counting` session, or an open is in flight. Its message can be shown to a cashier as it is. */
|
|
48
58
|
export class RegisterSessionAlreadyOpenError extends Error {
|
|
49
59
|
constructor() {
|
|
@@ -70,14 +80,6 @@ export class RegisterApprovalRequiredError extends Error {
|
|
|
70
80
|
|
|
71
81
|
// Module-wide, so two hook instances for one register can't both open (keyed by `registerId`).
|
|
72
82
|
const openingByRegister = new Map<string, Promise<unknown>>();
|
|
73
|
-
// The close in flight per register, which a second close joins; its listeners re-render `closing`.
|
|
74
|
-
const closingByRegister = new Map<string, ReturnType<typeof store.writeClosure>>();
|
|
75
|
-
const closingListeners = new Set<() => void>();
|
|
76
|
-
const notifyClosing = () => closingListeners.forEach((listener) => listener());
|
|
77
|
-
const subscribeClosing = (listener: () => void) => {
|
|
78
|
-
closingListeners.add(listener);
|
|
79
|
-
return () => { closingListeners.delete(listener); };
|
|
80
|
-
};
|
|
81
83
|
// Closures whose `session-closed` fact is logged, so a double-tapped close logs it once.
|
|
82
84
|
const closedFacts = new Set<string>();
|
|
83
85
|
|
|
@@ -97,6 +99,23 @@ export interface UseRegisterSessionOptions {
|
|
|
97
99
|
deviceName?: string | null;
|
|
98
100
|
/** `pos_orders`: a session's sales are those whose `sessionId` is its id. */
|
|
99
101
|
orders: RxCollection<PosOrder> | null;
|
|
102
|
+
/**
|
|
103
|
+
* Required (S3): `order_drafts`, the sale's own, so a parked sale's taken legs count in the session that took them;
|
|
104
|
+
* `null` when the app never parks a sale. Left out, that cash would be missing from the session's Z.
|
|
105
|
+
*/
|
|
106
|
+
drafts: RxCollection | null;
|
|
107
|
+
/**
|
|
108
|
+
* Required (S3): the live sale's taken legs, read when the figures are derived, so a leg still in the cart (after
|
|
109
|
+
* `cancelTender`, say) counts on its session's Z; `null` when the app has no live sale. A getter, because the app
|
|
110
|
+
* creates the register before the sale (the sale takes `register.saleSession`). The usual wiring is a ref:
|
|
111
|
+
* ```ts
|
|
112
|
+
* const saleRef = useRef<ReturnType<typeof useSale> | null>(null)
|
|
113
|
+
* const register = useRegisterSession({ …, liveSale: () => saleRef.current?.registerView() ?? { takenLegs: [], saving: false } })
|
|
114
|
+
* const sale = useSale(…)
|
|
115
|
+
* saleRef.current = sale
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
liveSale: (() => { takenLegs: readonly Payment[]; saving: boolean; cashRoundings?: readonly CashRounding[] }) | null;
|
|
100
119
|
/** The register document's host, for the closure number and perpetual totals (`writeClosure`); `null` while it opens. */
|
|
101
120
|
register: RegisterHost | null;
|
|
102
121
|
/** The app's neutral store key (see `bindRegister`). */
|
|
@@ -126,7 +145,7 @@ export interface UseRegisterSessionOptions {
|
|
|
126
145
|
type Reservation = RegisterBucket['closure_reservation'];
|
|
127
146
|
type Snapshot = {
|
|
128
147
|
rows: RegisterSession[]; closureRows: Closure[]; reservation: Reservation;
|
|
129
|
-
entries: CashMovement[]; sales: PosOrder[]; refundRows: PosRefund[];
|
|
148
|
+
entries: CashMovement[]; sales: PosOrder[]; refundRows: PosRefund[]; parked: { data?: unknown }[];
|
|
130
149
|
/** The register's open and closure command rows (ADR-082 d4, d7, d9). */
|
|
131
150
|
commandRows: RegisterCommand[];
|
|
132
151
|
};
|
|
@@ -183,9 +202,9 @@ function currentSession(rows: RegisterSession[], closureRows: Closure[], reserva
|
|
|
183
202
|
?? null;
|
|
184
203
|
}
|
|
185
204
|
|
|
186
|
-
/** A session's ledger rows, built from its orders' payments the way `writeClosure` builds them. */
|
|
187
|
-
function ledgerRows(orders: readonly PosOrder[], replaced = replacedOrderIds(orders)): LedgerRow[] {
|
|
188
|
-
return paymentLedgerRows(orders.filter((order) => !replaced.has(order.id)));
|
|
205
|
+
/** A session's ledger rows, built from its orders' payments the way `writeClosure` builds them, plus `extra` (S3: parked and live legs). */
|
|
206
|
+
function ledgerRows(orders: readonly PosOrder[], extra: readonly LedgerRow[], replaced = replacedOrderIds(orders)): LedgerRow[] {
|
|
207
|
+
return [...paymentLedgerRows(orders.filter((order) => !replaced.has(order.id))), ...extra];
|
|
189
208
|
}
|
|
190
209
|
|
|
191
210
|
/** The closure's counted map, as `closeSession` hands it to `writeClosure`: cash is always present. */
|
|
@@ -196,7 +215,7 @@ const sameVariance = (a: Record<string, number>, b: Record<string, number>) =>
|
|
|
196
215
|
|
|
197
216
|
export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
198
217
|
const { sessions, movements, closures, orders, register, storeKey, registerId, enabled, actor, timezone, tenderInProgress, expectedCloseTime, labels } = options;
|
|
199
|
-
const { commands, refunds } = options;
|
|
218
|
+
const { commands, refunds, drafts } = options;
|
|
200
219
|
// ADR-082 d3: the store's threshold wins over the app's; the gate and RegisterCount use this one.
|
|
201
220
|
const varianceThreshold = options.capabilities?.registerApproval?.thresholdMinor ?? options.varianceThreshold;
|
|
202
221
|
const commandEnabled = (options.capabilities?.register ?? 0) >= 1;
|
|
@@ -235,14 +254,15 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
235
254
|
} }) : of([] as RegisterCommand[]),
|
|
236
255
|
]).pipe(switchMap(([rows, closureRows, reservation, commandRows]) => {
|
|
237
256
|
const current = currentSession(rows, closureRows, reservation);
|
|
238
|
-
if (!current) return of({ rows, closureRows, reservation, entries: [], sales: [], refundRows: [], commandRows } as Snapshot);
|
|
257
|
+
if (!current) return of({ rows, closureRows, reservation, entries: [], sales: [], refundRows: [], parked: [], commandRows } as Snapshot);
|
|
239
258
|
return combineLatest([
|
|
240
259
|
watchFresh(movements, { selector: { session_id: current.id } }),
|
|
241
260
|
watchFresh(orders, { selector: { sessionId: current.id } }),
|
|
242
261
|
refunds ? watchFresh(refunds, { selector: { sessionId: current.id } }) : of([]),
|
|
243
|
-
|
|
262
|
+
drafts ? watchFresh(drafts, { selector: {} }) : of([]),
|
|
263
|
+
]).pipe(map(([entries, sales, refundRows, parked]) => ({ rows, closureRows, reservation, entries, sales, refundRows, parked, commandRows })));
|
|
244
264
|
}));
|
|
245
|
-
}, [enabled, sessions, movements, closures, orders, register, storeKey, registerId, commandTarget, refunds]);
|
|
265
|
+
}, [enabled, sessions, movements, closures, orders, register, storeKey, registerId, commandTarget, refunds, drafts]);
|
|
246
266
|
// A latest-value ref: an `actions` object from an earlier render still sees the current flag.
|
|
247
267
|
const tender = useRef(tenderInProgress);
|
|
248
268
|
tender.current = tenderInProgress;
|
|
@@ -323,9 +343,12 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
323
343
|
const entries = data?.entries ?? [];
|
|
324
344
|
const sales = data?.sales ?? [];
|
|
325
345
|
const replaced = replacedOrderIds(sales);
|
|
346
|
+
const parked = data?.parked;
|
|
347
|
+
const parkedRows = useMemo(() => parkedLedgerRows(parked ?? []), [parked]);
|
|
326
348
|
// The drawer ledger's terms; their `expected` is `deriveExpected`'s own result for the same rows.
|
|
349
|
+
const sale = options.liveSale?.();
|
|
327
350
|
const terms = session
|
|
328
|
-
? deriveDrawerTerms({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales, replaced), refunds: data?.refundRows ?? [] })
|
|
351
|
+
? deriveDrawerTerms({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales, [...parkedRows, ...liveLedgerRows(sale?.saving ? [] : sale?.takenLegs ?? [])], replaced), refunds: data?.refundRows ?? [] })
|
|
329
352
|
: null;
|
|
330
353
|
const expected = terms ? terms.expected : {};
|
|
331
354
|
const now = new Date();
|
|
@@ -351,24 +374,33 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
351
374
|
};
|
|
352
375
|
const live = () => {
|
|
353
376
|
if (!enabled || !sessions || !movements || !closures || !orders || !registerId || !register || refunds === null) throw new RegisterSessionRequiredError();
|
|
354
|
-
return { sessions, movements, closures, orders, registerId, register, refunds };
|
|
377
|
+
return { sessions, movements, closures, orders, registerId, register, refunds, drafts, liveSale: options.liveSale };
|
|
355
378
|
};
|
|
356
379
|
const current = () => {
|
|
357
380
|
if (!session) throw new RegisterSessionRequiredError();
|
|
358
381
|
return session;
|
|
359
382
|
};
|
|
383
|
+
const parkedFresh = async () => { const { drafts } = live(); return drafts ? readFresh(drafts, { selector: {} }) : []; };
|
|
384
|
+
// One read of the live sale: its taken legs and their rounding entries (#1281), both empty while it saves.
|
|
385
|
+
const liveTaken = () => {
|
|
386
|
+
const sale = live().liveSale?.();
|
|
387
|
+
return sale?.saving ? { liveLegs: [], liveRoundings: [] } : { liveLegs: sale?.takenLegs ?? [], liveRoundings: sale?.cashRoundings ?? [] };
|
|
388
|
+
};
|
|
389
|
+
const liveLegs = () => liveTaken().liveLegs;
|
|
360
390
|
// As `writeClosure` derives the Z's expected figures, from the same rows, past the query cache.
|
|
361
391
|
const freshExpected = async (row: RegisterSession) => {
|
|
362
392
|
const { movements, orders, refunds } = live();
|
|
363
393
|
return deriveExpected({
|
|
364
394
|
session: { id: row.id, countedFloatMinor: row.counted_float_minor },
|
|
365
395
|
movements: await readFresh(movements, { selector: { session_id: row.id } }),
|
|
366
|
-
ledgerRowsBySession: ledgerRows(await readFresh(orders, { selector: { sessionId: row.id } })
|
|
396
|
+
ledgerRowsBySession: ledgerRows(await readFresh(orders, { selector: { sessionId: row.id } }),
|
|
397
|
+
[...parkedLedgerRows(await parkedFresh()), ...liveLedgerRows(liveLegs())]),
|
|
367
398
|
refunds: refunds ? await readFresh(refunds, { selector: { sessionId: row.id } }) : undefined,
|
|
368
399
|
});
|
|
369
400
|
};
|
|
370
401
|
const refuseDuringTender = () => {
|
|
371
402
|
if (tender.current) throw new RegisterTenderInProgressError();
|
|
403
|
+
if (live().liveSale?.().saving) throw new RegisterSaleSavingError();
|
|
372
404
|
};
|
|
373
405
|
const nameOf = (id: string | null | undefined) => !id ? '' : id === actor.id ? actor.name : labels?.resolveCashierName?.(id) ?? '';
|
|
374
406
|
|
|
@@ -535,6 +567,7 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
535
567
|
counted: cash, otherTenders, timezone, softwareVersion: options.softwareVersion,
|
|
536
568
|
movements: await readFresh(movements, { selector: { session_id: closed.id } }),
|
|
537
569
|
orders: await readFresh(orders, { selector: { sessionId: closed.id } }),
|
|
570
|
+
drafts: await parkedFresh(), ...liveTaken(),
|
|
538
571
|
refunds: refunds ? await readFresh(refunds, { selector: { sessionId: closed.id } }) : undefined,
|
|
539
572
|
resolveCashierName: labels?.resolveCashierName,
|
|
540
573
|
labels: {
|