@tallyui/pos 4.1.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +584 -161
- package/dist/index.js +1908 -1077
- package/package.json +7 -6
- package/src/index.ts +17 -10
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +65 -21
- package/src/order/order-drafts.ts +78 -24
- package/src/order/taken-at.ts +5 -0
- package/src/order/types.ts +11 -2
- package/src/order/woocommerce-tax.ts +9 -12
- package/src/outbox/http-transport.ts +16 -1
- package/src/outbox/index.ts +2 -1
- package/src/outbox/needs-admin-reason.ts +10 -0
- package/src/outbox/order-outbox.ts +14 -5
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-order-outbox.ts +7 -3
- package/src/pos-order/command.ts +3 -0
- package/src/pos-order/finalize.ts +11 -0
- package/src/pos-order/reopen.ts +11 -2
- package/src/pos-order/schema.ts +7 -2
- package/src/pos-order/types.ts +7 -1
- package/src/print/escpos/bluetooth-sink.ts +114 -0
- package/src/print/escpos/index.ts +4 -0
- package/src/print/escpos/transport.ts +3 -2
- package/src/print/escpos/usb-sink.ts +84 -0
- package/src/print/index.ts +2 -2
- package/src/receipt/build-receipt-data.ts +8 -1
- package/src/receipt/reprint.ts +2 -0
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/template-data.ts +1 -1
- package/src/receipt-template/wcpos/from-orders.ts +5 -1
- package/src/refund/index.ts +1 -0
- package/src/refund/needs-admin-line.ts +6 -0
- package/src/refund/refundable-lines.ts +2 -91
- package/src/refund/send-order-refund.ts +6 -1
- package/src/refund/submit-order-refund.ts +33 -1
- package/src/register/closing.ts +15 -0
- package/src/register/closure-document.ts +13 -5
- package/src/register/closure-figures.ts +83 -0
- package/src/register/document-labels.ts +5 -3
- package/src/register/expected.ts +30 -9
- package/src/register/index.ts +3 -1
- package/src/register/register-adoption.ts +42 -4
- package/src/register/register-document.ts +17 -0
- package/src/register/session-store.ts +48 -12
- package/src/register/use-register-session.ts +53 -20
- package/src/reports/adapters.ts +5 -1
- package/src/reports/index.ts +1 -1
- package/src/reports/sales-figures.ts +33 -6
- package/src/reports/types.ts +3 -1
- package/src/sale/index.ts +1 -1
- package/src/sale/use-sale.ts +321 -135
- package/src/store-orders/index.ts +5 -0
- package/src/store-orders/sales-range-query.ts +18 -0
- package/src/store-orders/use-store-orders-in-range.ts +127 -0
- package/src/store-orders/use-store-refunds-in-range.ts +179 -0
- package/src/tax/exact.ts +2 -10
- package/src/tax/index.ts +1 -0
- package/src/tender/cash-rounding.ts +49 -6
- package/src/tender/index.ts +1 -1
- package/src/tender/payment-legs.ts +5 -0
- package/src/tender/tender-figures.ts +3 -1
- package/src/outbox/types.test-d.ts +0 -27
|
@@ -1,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: {
|
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';
|