@tallyui/pos 4.2.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +465 -162
- package/dist/index.js +1752 -1104
- package/package.json +7 -6
- package/src/index.ts +12 -9
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +64 -22
- package/src/order/order-drafts.ts +77 -25
- package/src/order/types.ts +9 -2
- package/src/order/woocommerce-tax.ts +9 -12
- package/src/outbox/http-transport.ts +16 -1
- package/src/outbox/index.ts +2 -1
- package/src/outbox/needs-admin-reason.ts +10 -0
- package/src/outbox/order-outbox.ts +14 -5
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-order-outbox.ts +7 -3
- package/src/pos-order/command.ts +3 -0
- package/src/pos-order/finalize.ts +9 -0
- package/src/pos-order/reopen.ts +9 -2
- package/src/pos-order/schema.ts +5 -2
- package/src/pos-order/types.ts +5 -1
- package/src/receipt/build-receipt-data.ts +8 -1
- package/src/receipt/reprint.ts +2 -0
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/template-data.ts +1 -1
- package/src/receipt-template/wcpos/from-orders.ts +5 -1
- package/src/refund/index.ts +1 -0
- package/src/refund/needs-admin-line.ts +6 -0
- package/src/refund/refundable-lines.ts +2 -91
- package/src/refund/send-order-refund.ts +6 -1
- package/src/refund/submit-order-refund.ts +33 -1
- package/src/register/closing.ts +15 -0
- package/src/register/closure-document.ts +13 -5
- package/src/register/closure-figures.ts +83 -0
- package/src/register/document-labels.ts +5 -3
- package/src/register/expected.ts +30 -9
- package/src/register/index.ts +3 -1
- package/src/register/register-adoption.ts +42 -4
- package/src/register/register-document.ts +17 -0
- package/src/register/session-store.ts +48 -12
- package/src/register/use-register-session.ts +53 -20
- package/src/reports/adapters.ts +5 -1
- package/src/reports/index.ts +1 -1
- package/src/reports/sales-figures.ts +33 -6
- package/src/reports/types.ts +3 -1
- package/src/sale/index.ts +1 -1
- package/src/sale/use-sale.ts +313 -134
- package/src/store-orders/index.ts +3 -0
- package/src/store-orders/sales-range-query.ts +18 -0
- package/src/store-orders/use-store-refunds-in-range.ts +179 -0
- package/src/tax/exact.ts +2 -10
- package/src/tender/cash-rounding.ts +49 -6
- package/src/tender/index.ts +1 -1
- package/src/tender/payment-legs.ts +5 -0
- package/src/tender/tender-figures.ts +3 -1
- package/src/outbox/types.test-d.ts +0 -27
- package/src/print/escpos/sinks.test-d.ts +0 -77
|
@@ -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: {
|
package/src/reports/adapters.ts
CHANGED
|
@@ -23,6 +23,7 @@ export function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin, method
|
|
|
23
23
|
const taxes = recordedTaxByRate(order) ?? taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding);
|
|
24
24
|
const till = tillPayments(order.payments);
|
|
25
25
|
const amountOf = (payments: readonly { amountMinor: number }[]) => payments.reduce((total, payment) => total + payment.amountMinor, 0);
|
|
26
|
+
const roundingMinor = (order.cashRoundings ?? []).reduce((total, entry) => total + entry.minor, 0);
|
|
26
27
|
return {
|
|
27
28
|
id: order.id, at: order.createdAt, totalMinor: order.totalMinor, taxMinor: order.taxMinor,
|
|
28
29
|
discountMinor: order.discountMinor, needsPayment: false, refunds: [],
|
|
@@ -43,6 +44,7 @@ export function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin, method
|
|
|
43
44
|
return { method, ...(label ? { label } : {}), amountMinor: payment.amountMinor };
|
|
44
45
|
}),
|
|
45
46
|
...(order.storeOrderId !== undefined ? { paidEarlierMinor: amountOf(order.payments) - amountOf(till) } : {}),
|
|
47
|
+
...(roundingMinor !== 0 ? { roundingMinor } : {}),
|
|
46
48
|
taxes: taxes.map((row) => ({
|
|
47
49
|
ratePpm: row.ratePpm, ...(row.code !== undefined ? { code: row.code } : {}),
|
|
48
50
|
label: row.label ?? `Tax ${row.ratePpm / 10000}%`, taxMinor: row.amountMinor, netMinor: row.netMinor,
|
|
@@ -50,9 +52,10 @@ export function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin, method
|
|
|
50
52
|
};
|
|
51
53
|
}
|
|
52
54
|
|
|
55
|
+
/** A store order as a report row, on its paid day (`paidAt`); an order with no `paidAt` (unpaid, or a store that records none) stays on its placed day. */
|
|
53
56
|
export function reportOrderFromStoreOrder(order: StoreOrder, join?: LineJoin): ReportOrder {
|
|
54
57
|
return {
|
|
55
|
-
id: order.id, at: order.placedAt, totalMinor: order.totalMinor, taxMinor: order.taxMinor, discountMinor: order.discountMinor,
|
|
58
|
+
id: order.id, at: order.paidAt ?? order.placedAt, totalMinor: order.totalMinor, taxMinor: order.taxMinor, discountMinor: order.discountMinor,
|
|
56
59
|
lines: order.lines.map((line) => ({
|
|
57
60
|
key: line.variantId || line.productId || line.name, name: line.name, quantity: line.quantity,
|
|
58
61
|
netMinor: line.totalMinor, taxMinor: line.taxMinor, ...joinedLine(line, join),
|
|
@@ -62,6 +65,7 @@ export function reportOrderFromStoreOrder(order: StoreOrder, join?: LineJoin): R
|
|
|
62
65
|
ratePpm, ...(code !== undefined ? { code } : {}), label, taxMinor: amountMinor, netMinor: null,
|
|
63
66
|
})),
|
|
64
67
|
refunds: order.refunds.map(({ id, amountMinor }) => ({ id, amountMinor })),
|
|
68
|
+
...(order.needsPayment !== undefined ? { needsPayment: order.needsPayment } : {}),
|
|
65
69
|
};
|
|
66
70
|
}
|
|
67
71
|
|
package/src/reports/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { salesFigures, marginOf, comparisonRange, daysOf, inRange } from './sales-figures';
|
|
1
|
+
export { salesFigures, marginOf, medianMinor, comparisonRange, daysOf, inRange } from './sales-figures';
|
|
2
2
|
export { presetRange, DATE_PRESETS, type DatePreset } from './presets';
|
|
3
3
|
export { reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund } from './adapters';
|
|
4
4
|
export type { StoreDay, DayRange, ReportCategory, ReportLine, ReportPayment, ReportTax, ReportOrder, ReportRefund, LineJoin } from './types';
|
|
@@ -15,12 +15,25 @@ export interface Margin {
|
|
|
15
15
|
export interface SalesTotals {
|
|
16
16
|
grossMinor: number; netMinor: number; taxMinor: number; discountMinor: number;
|
|
17
17
|
refundsMinor: number; embeddedRefundsMinor: number;
|
|
18
|
+
/**
|
|
19
|
+
* Σ cash roundings in gross; gross = net + tax + rounding (front desk, 22 Nov, Q3).
|
|
20
|
+
* Only orders built by `reportOrderFromPosOrder` carry one. A store-sourced order (`reportOrderFromStoreOrder`) carries no rounding figure:
|
|
21
|
+
* Woo stores its rounding as a plain fee line, so that order's rounding stays inside net (#1282, a documented limit).
|
|
22
|
+
*/
|
|
23
|
+
roundingMinor: number;
|
|
18
24
|
orderCount: number; averageMinor: number; items: number;
|
|
19
25
|
/** v2 ordersSummary: the middle order total, the mean of the two middles for an even count (rounded half up to the minor unit); 0 with no orders. */
|
|
20
26
|
medianMinor?: number;
|
|
21
27
|
/** v2 ordersSummary: the largest order total; null with no orders. */
|
|
22
28
|
largestMinor?: number | null;
|
|
23
29
|
margin: Margin;
|
|
30
|
+
/** Which refund figure `grossAfterRefundsMinor` subtracts: `refundsMinor` or `embeddedRefundsMinor`. A report never subtracts both. */
|
|
31
|
+
refundBasis: 'dated' | 'embedded';
|
|
32
|
+
/**
|
|
33
|
+
* `grossMinor` less the basis figure; negative when refunds exceed gross. Gross refunds come off gross only, never
|
|
34
|
+
* off `netMinor` or any row.
|
|
35
|
+
*/
|
|
36
|
+
grossAfterRefundsMinor: number;
|
|
24
37
|
}
|
|
25
38
|
export interface PaymentRow { method: string; label: string; amountMinor: number; orders: number }
|
|
26
39
|
export interface GroupRow { key: string; name: string; quantity: number; netMinor: number; margin: Margin }
|
|
@@ -28,6 +41,11 @@ export interface TaxRow { key: string; ratePpm: number; code?: string; label: st
|
|
|
28
41
|
export interface DayPoint { day: StoreDay; grossMinor: number; orderCount: number; refundsMinor: number }
|
|
29
42
|
export interface SalesFiguresInput {
|
|
30
43
|
orders: readonly ReportOrder[];
|
|
44
|
+
/**
|
|
45
|
+
* Dated refunds, for every period the report shows. Pass `undefined` (not `[]`) when the store has no dated refunds
|
|
46
|
+
* (no `listRefunds`, or the store does not support it), so the report uses its orders' embedded refunds.
|
|
47
|
+
* `useStoreRefundsInRange().refunds` is already in that shape; pass it only once the read is `complete`.
|
|
48
|
+
*/
|
|
31
49
|
refunds?: readonly ReportRefund[];
|
|
32
50
|
range: DayRange;
|
|
33
51
|
compare?: DayRange;
|
|
@@ -105,13 +123,18 @@ export function marginOf(lines: readonly ReportLine[]): Margin {
|
|
|
105
123
|
return margin;
|
|
106
124
|
}
|
|
107
125
|
|
|
126
|
+
/** The median of minor-unit values: 0 for none; an even count rounds the mean of the middle two (`Math.round`). */
|
|
127
|
+
export function medianMinor(values: readonly number[]): number {
|
|
128
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
129
|
+
const middle = Math.floor(sorted.length / 2);
|
|
130
|
+
if (!sorted.length) return 0;
|
|
131
|
+
return sorted.length % 2 ? sorted[middle] : Math.round((sorted[middle - 1] + sorted[middle]) / 2);
|
|
132
|
+
}
|
|
133
|
+
|
|
108
134
|
/** Median and largest order total. Port of WCPOS v2 `ordersSummary` (`screens/main/reports/cards/aggregate.ts`). */
|
|
109
135
|
function orderSpread(totals: number[]): { medianMinor: number; largestMinor: number | null } {
|
|
110
136
|
const values = [...totals].sort((a, b) => a - b);
|
|
111
|
-
|
|
112
|
-
if (!values.length) return { medianMinor: 0, largestMinor: null };
|
|
113
|
-
const medianMinor = values.length % 2 ? values[middle] : Math.round((values[middle - 1] + values[middle]) / 2);
|
|
114
|
-
return { medianMinor, largestMinor: values[values.length - 1] };
|
|
137
|
+
return { medianMinor: medianMinor(values), largestMinor: values.length ? values[values.length - 1] : null };
|
|
115
138
|
}
|
|
116
139
|
|
|
117
140
|
function periodFigures(input: SalesFiguresInput, range: DayRange) {
|
|
@@ -119,16 +142,18 @@ function periodFigures(input: SalesFiguresInput, range: DayRange) {
|
|
|
119
142
|
const refunds = (input.refunds ?? []).filter((refund) => inRange(refund.at, range, input.timezone));
|
|
120
143
|
const lines = orders.flatMap((order) => order.lines);
|
|
121
144
|
const totals: SalesTotals = {
|
|
122
|
-
grossMinor: 0, netMinor: 0, taxMinor: 0, discountMinor: 0, refundsMinor: 0, embeddedRefundsMinor: 0,
|
|
145
|
+
grossMinor: 0, netMinor: 0, taxMinor: 0, discountMinor: 0, refundsMinor: 0, embeddedRefundsMinor: 0, roundingMinor: 0,
|
|
123
146
|
orderCount: orders.length, averageMinor: 0,
|
|
124
147
|
items: lines.reduce((sum, line) => sum + (Number.isFinite(line.quantity) ? line.quantity : 0), 0),
|
|
125
148
|
margin: marginOf(lines),
|
|
149
|
+
refundBasis: input.refunds !== undefined ? 'dated' : 'embedded', grossAfterRefundsMinor: 0,
|
|
126
150
|
};
|
|
127
151
|
const series: DayPoint[] = daysOf(range).map((day) => ({ day, grossMinor: 0, orderCount: 0, refundsMinor: 0 }));
|
|
128
152
|
const byDay = new Map(series.map((point) => [point.day, point]));
|
|
129
153
|
for (const order of orders) {
|
|
130
154
|
totals.grossMinor += order.totalMinor;
|
|
131
155
|
totals.taxMinor += order.taxMinor;
|
|
156
|
+
totals.roundingMinor += order.roundingMinor ?? 0;
|
|
132
157
|
totals.discountMinor += order.discountMinor;
|
|
133
158
|
totals.embeddedRefundsMinor += order.refunds.reduce((sum, refund) => sum + Math.abs(refund.amountMinor), 0);
|
|
134
159
|
const point = byDay.get(businessDayOf(order.at, input.timezone))!;
|
|
@@ -139,7 +164,9 @@ function periodFigures(input: SalesFiguresInput, range: DayRange) {
|
|
|
139
164
|
totals.refundsMinor += Math.abs(refund.amountMinor);
|
|
140
165
|
byDay.get(businessDayOf(refund.at, input.timezone))!.refundsMinor += Math.abs(refund.amountMinor);
|
|
141
166
|
}
|
|
142
|
-
totals.netMinor = totals.grossMinor - totals.taxMinor;
|
|
167
|
+
totals.netMinor = totals.grossMinor - totals.taxMinor - totals.roundingMinor;
|
|
168
|
+
totals.grossAfterRefundsMinor =
|
|
169
|
+
totals.grossMinor - (totals.refundBasis === 'dated' ? totals.refundsMinor : totals.embeddedRefundsMinor);
|
|
143
170
|
totals.averageMinor = orders.length ? Math.round(totals.grossMinor / orders.length) : 0;
|
|
144
171
|
Object.assign(totals, orderSpread(orders.map((order) => order.totalMinor)));
|
|
145
172
|
return { orders, refunds, totals, series };
|
package/src/reports/types.ts
CHANGED
|
@@ -48,6 +48,8 @@ export interface ReportOrder {
|
|
|
48
48
|
taxes: ReportTax[];
|
|
49
49
|
/** Refunds embedded on the order, undated (a store order's own list). Positive. */
|
|
50
50
|
refunds: Array<{ id: string; amountMinor: number }>;
|
|
51
|
+
/** Σ the order's cash roundings, signed (ADR-094); absent when none. Always absent on a store-sourced order: its rounding is a plain fee, kept inside net (#1282). */
|
|
52
|
+
roundingMinor?: number;
|
|
51
53
|
}
|
|
52
54
|
|
|
53
55
|
/** A refund dated by when it was made, counted on that store day. */
|
|
@@ -56,7 +58,7 @@ export interface ReportRefund {
|
|
|
56
58
|
orderId: string;
|
|
57
59
|
/** ISO 8601 UTC instant the refund was made. */
|
|
58
60
|
at: string;
|
|
59
|
-
/**
|
|
61
|
+
/** Zero or more. Gross, tax included. */
|
|
60
62
|
amountMinor: number;
|
|
61
63
|
}
|
|
62
64
|
|
package/src/sale/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, SALE_HAS_PAYMENT, SALE_FINISHED, COUPONS_REPRICING, COUPON_CARRIED, COUPON_CARRY_STALE, TENDER_GATE_FAILED, TENDER_SALE_CHANGED, saleLogger } from './use-sale';
|
|
1
|
+
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, REGISTER_CLOSING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_CARD_IN_PROGRESS, SALE_IN_TENDER, SALE_HAS_PAYMENT, SALE_FINISHED, COUPONS_REPRICING, COUPON_CARRIED, COUPON_CARRY_STALE, TENDER_GATE_FAILED, TENDER_SALE_CHANGED, saleLogger } from './use-sale';
|
|
2
2
|
export { openSales, isPartlyPaid } from './open-sales';
|
|
3
3
|
export type { OpenSale } from './open-sales';
|
|
4
4
|
export type { SaleStage } from './use-sale';
|