@tallyui/pos 3.12.0 → 3.14.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 +1844 -359
- package/dist/index.js +4620 -2211
- package/package.json +12 -6
- package/src/app-settings/app-settings.ts +108 -0
- package/src/app-settings/index.ts +8 -0
- package/src/app-settings/use-app-settings.ts +23 -0
- package/src/cashier/can.ts +12 -0
- package/src/cashier/index.ts +2 -0
- package/src/cashier/use-cashier.ts +81 -0
- package/src/csv/csv.ts +33 -0
- package/src/csv/index.ts +2 -0
- package/src/customer-display/display-link.ts +72 -0
- package/src/customer-display/display-state.ts +30 -0
- package/src/customer-display/index.ts +13 -0
- package/src/customer-display/protocol.ts +87 -0
- package/src/customer-display/snapshot.ts +65 -0
- package/src/customer-display/transport.ts +54 -0
- package/src/customer-display/use-customer-display.ts +36 -0
- package/src/index.ts +73 -10
- package/src/order/order-builder.ts +11 -1
- package/src/order/order-drafts.ts +16 -0
- package/src/order/types.ts +6 -3
- package/src/outbox/index.ts +5 -1
- package/src/outbox/outbox-health.ts +40 -0
- package/src/outbox/register-outbox.ts +59 -6
- package/src/outbox/safe-error.ts +11 -0
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-outbox-health.ts +22 -0
- package/src/outbox/use-register-outbox.ts +6 -0
- package/src/payment-driver/index.ts +8 -0
- package/src/payment-driver/registry.ts +39 -0
- package/src/payment-driver/simulated-driver.ts +104 -0
- package/src/payment-driver/types.ts +73 -0
- package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
- package/src/pos-order/command.ts +36 -16
- package/src/pos-order/finalize.ts +7 -3
- package/src/pos-order/index.ts +1 -0
- package/src/pos-order/note-delivery.ts +13 -0
- package/src/pos-order/reopen.ts +3 -2
- package/src/pos-order/schema.ts +5 -4
- package/src/pos-order/types.ts +3 -2
- package/src/print/escpos/code-page.ts +48 -0
- package/src/print/escpos/commands.ts +53 -0
- package/src/print/escpos/encode.ts +127 -0
- package/src/print/escpos/index.ts +7 -0
- package/src/print/escpos/transport.ts +45 -0
- package/src/print/index.ts +12 -0
- package/src/print/print-queue.ts +67 -0
- package/src/print/printer-profiles.ts +71 -0
- package/src/print/system-transport.ts +101 -0
- package/src/print/types.ts +44 -0
- package/src/receipt/reprint.ts +2 -1
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/default-templates.ts +78 -0
- package/src/receipt-template/index.ts +15 -0
- package/src/receipt-template/parse-xml.ts +175 -0
- package/src/receipt-template/render-html.ts +152 -0
- package/src/receipt-template/render-receipt.ts +19 -0
- package/src/receipt-template/render-template.ts +35 -0
- package/src/receipt-template/sanitize-html.ts +146 -0
- package/src/receipt-template/template-data.ts +97 -0
- package/src/receipt-template/types.ts +49 -0
- package/src/refund/index.ts +2 -0
- package/src/refund/refundable-lines.ts +91 -0
- package/src/register/export-csv.ts +24 -35
- package/src/register/float-suggestion.ts +22 -0
- package/src/register/handover.ts +103 -0
- package/src/register/index.ts +10 -3
- package/src/register/register-adoption.ts +71 -2
- package/src/register/register-commands.ts +7 -4
- package/src/register/register-count.helpers.ts +4 -0
- package/src/register/session-store.ts +4 -1
- package/src/register/use-register-session.ts +112 -28
- package/src/reports/adapters.ts +67 -0
- package/src/reports/index.ts +5 -0
- package/src/reports/presets.ts +27 -0
- package/src/reports/sales-figures.ts +187 -0
- package/src/reports/types.ts +63 -0
- package/src/sale/in-cart.ts +18 -0
- package/src/sale/index.ts +5 -1
- package/src/sale/open-sales.ts +40 -0
- package/src/sale/use-sale.ts +72 -8
- package/src/scanner/index.ts +6 -0
- package/src/scanner/scan-session.ts +84 -0
- package/src/scanner/use-barcode-scanner.ts +61 -0
- package/src/scanner/wedge-detector.ts +137 -0
- package/src/tender/cash-rounding.ts +74 -0
- package/src/tender/index.ts +4 -0
- package/src/tender/payment-legs.ts +48 -0
|
@@ -12,20 +12,24 @@
|
|
|
12
12
|
* - Refund parents and the close-time wait: a refund's record is the app's optional `refunds` collection, and one still pending at close is listed on the Z instead (ADR-080 amendment 1).
|
|
13
13
|
* - Anchor invalidation, `server_expected` and `server_sales_count`: no server figures (c2).
|
|
14
14
|
* - `unsyncedCount` and the `sync_status` filters: nothing is sent (c2).
|
|
15
|
-
* - The binding (`useRegisterBinding`)
|
|
15
|
+
* - The binding (`useRegisterBinding`): an app input. `blind` is an app input too: `useCashier(...).blind`.
|
|
16
16
|
*/
|
|
17
17
|
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
|
18
18
|
import { combineLatest, map, of, switchMap } from 'rxjs';
|
|
19
19
|
import type { RxCollection } from 'rxdb';
|
|
20
20
|
import type { RegisterSessionAlreadyOpenData, ServerCapabilities } from '@tallyui/core';
|
|
21
|
+
import { CLOSURE_HOLDING_REJECTIONS } from '../outbox/register-outbox';
|
|
22
|
+
import { safeErrorString } from '../outbox/safe-error';
|
|
21
23
|
import type { PosOrder } from '../pos-order/types';
|
|
22
24
|
import { replacedOrderIds } from '../pos-order/reopened';
|
|
23
25
|
import type { PosRefund, PosRefundCollection } from '../refund/pos-refund';
|
|
24
26
|
import { readFresh, watchFresh } from '../rxdb';
|
|
25
27
|
import { deriveExpected, type LedgerRow } from './expected';
|
|
26
28
|
import { recordRegisterFact, registerFactsLogger, type Actor } from './facts';
|
|
27
|
-
import { closeNeedsApproval } from './register-count.helpers';
|
|
28
|
-
import {
|
|
29
|
+
import { closeNeedsApproval, closureVariance } from './register-count.helpers';
|
|
30
|
+
import {
|
|
31
|
+
abandonSession, adoptRegisterResults, closureApprovalStatus, isLiveAtStore, reapproveClosure, takeOverSession, type ClosureApprovalStatus,
|
|
32
|
+
} from './register-adoption';
|
|
29
33
|
import { reconcileRegisterCommands, registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
|
|
30
34
|
import { observeRegister$, readRegister, type RegisterBucket, type RegisterDocument, type RegisterHost } from './register-document';
|
|
31
35
|
import type { CashMovement, Closure, RegisterSession } from './schemas';
|
|
@@ -109,11 +113,11 @@ export interface UseRegisterSessionOptions {
|
|
|
109
113
|
softwareVersion: string;
|
|
110
114
|
/** A sale is at tender (`sale.stage.kind === 'tender'`): counting and closing refuse. */
|
|
111
115
|
tenderInProgress: boolean;
|
|
112
|
-
/** The count variance, in minor units, over which the app asks for approval. */
|
|
116
|
+
/** The count variance, in minor units, over which the app asks for approval. The store's `capabilities.registerApproval.thresholdMinor` wins over it (ADR-082). */
|
|
113
117
|
varianceThreshold?: number;
|
|
114
118
|
/** `'HH:mm'` on the device's clock; an open session after it is `overdue`. */
|
|
115
119
|
expectedCloseTime?: string;
|
|
116
|
-
/** The cashier may not see expected figures while counting. */
|
|
120
|
+
/** The cashier may not see expected figures while counting: pass `useCashier(connector, context).blind` (no `viewReports`). */
|
|
117
121
|
blind?: boolean;
|
|
118
122
|
/** The closure's register name, and a person id's display name. */
|
|
119
123
|
labels?: { registerName?: string; resolveCashierName?: (id: string) => string };
|
|
@@ -123,9 +127,41 @@ type Reservation = RegisterBucket['closure_reservation'];
|
|
|
123
127
|
type Snapshot = {
|
|
124
128
|
rows: RegisterSession[]; closureRows: Closure[]; reservation: Reservation;
|
|
125
129
|
entries: CashMovement[]; sales: PosOrder[]; refundRows: PosRefund[];
|
|
126
|
-
open
|
|
130
|
+
/** The register's open and closure command rows (ADR-082 d4, d7, d9). */
|
|
131
|
+
commandRows: RegisterCommand[];
|
|
127
132
|
};
|
|
128
133
|
|
|
134
|
+
/** ADR-082 d7: a closure the store refused with either approval code, for the app's "Manager approval needed again" card. */
|
|
135
|
+
export interface ApprovalNeeded {
|
|
136
|
+
closureId: string; sessionId: string;
|
|
137
|
+
/** The variance to send to the approval route: the refusal's, else counted minus tillExpected from the row. */
|
|
138
|
+
variance: Record<string, number>;
|
|
139
|
+
code: 'register_approval_required' | 'register_approval_invalid';
|
|
140
|
+
reason?: string;
|
|
141
|
+
/** `isLiveAtStore` for the refused closure's session: the approval route can be used for it. */
|
|
142
|
+
liveAtStore: boolean;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const isTenderMap = (value: unknown): value is Record<string, number> => typeof value === 'object' && value !== null
|
|
146
|
+
&& !Array.isArray(value) && Object.values(value).every((figure) => typeof figure === 'number');
|
|
147
|
+
|
|
148
|
+
/** The lowest-`seq` closure row refused with either approval code; the outbox holds every later closure behind it. */
|
|
149
|
+
function approvalNeededOf(commandRows: readonly RegisterCommand[], sessions: readonly RegisterSession[]): ApprovalNeeded | null {
|
|
150
|
+
const row = commandRows.filter((command) => command.type === 'register.closure.submit' && command.syncStatus === 'rejected'
|
|
151
|
+
&& CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? '')).sort((a, b) => a.seq - b.seq)[0];
|
|
152
|
+
if (!row) return null;
|
|
153
|
+
const { closureId, sessionId, counted, tillExpected } = row.payload as { closureId: string; sessionId: string; counted?: unknown; tillExpected?: unknown };
|
|
154
|
+
const data = row.error?.data;
|
|
155
|
+
return {
|
|
156
|
+
closureId, sessionId, code: row.error!.code as ApprovalNeeded['code'],
|
|
157
|
+
variance: isTenderMap(data?.variance) ? data.variance
|
|
158
|
+
: closureVariance(isTenderMap(counted) ? counted : {}, isTenderMap(tillExpected) ? tillExpected : {}),
|
|
159
|
+
...(typeof data?.reason === 'string' ? { reason: data.reason } : {}),
|
|
160
|
+
liveAtStore: isLiveAtStore(sessions.find((session) => session.id === sessionId),
|
|
161
|
+
commandRows.find((command) => command.key === `session.open:${sessionId}`)),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
129
165
|
const reservationOf = (register: RegisterDocument | null, storeKey: string, registerId: string) =>
|
|
130
166
|
register?.stores[storeKey]?.registers?.[registerId]?.closure_reservation;
|
|
131
167
|
|
|
@@ -155,9 +191,17 @@ function ledgerRows(orders: readonly PosOrder[], replaced = replacedOrderIds(ord
|
|
|
155
191
|
})));
|
|
156
192
|
}
|
|
157
193
|
|
|
194
|
+
/** The closure's counted map, as `closeSession` hands it to `writeClosure`: cash is always present. */
|
|
195
|
+
const closedCount = (counted: Record<string, number>) => ({ ...counted, cash: counted.cash ?? 0 });
|
|
196
|
+
/** The store's match (ADR-082 d5): the same keys, and each the same figure. */
|
|
197
|
+
const sameVariance = (a: Record<string, number>, b: Record<string, number>) =>
|
|
198
|
+
Object.keys(a).length === Object.keys(b).length && Object.entries(b).every(([method, value]) => a[method] === value);
|
|
199
|
+
|
|
158
200
|
export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
159
201
|
const { sessions, movements, closures, orders, register, storeKey, registerId, enabled, actor, timezone, tenderInProgress, expectedCloseTime, labels } = options;
|
|
160
202
|
const { commands, refunds } = options;
|
|
203
|
+
// ADR-082 d3: the store's threshold wins over the app's; the gate and RegisterCount use this one.
|
|
204
|
+
const varianceThreshold = options.capabilities?.registerApproval?.thresholdMinor ?? options.varianceThreshold;
|
|
161
205
|
const commandEnabled = (options.capabilities?.register ?? 0) >= 1;
|
|
162
206
|
const commandTarget = useMemo(() => enabled && commandEnabled && commands && sessions && movements && closures && register && registerId
|
|
163
207
|
? { commands, sessions, movements, closures, host: register, storeKey, registerId, registerContract: options.capabilities?.register, deviceName: options.deviceName } : null,
|
|
@@ -169,7 +213,7 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
169
213
|
if (!target) return;
|
|
170
214
|
void reconcileRegisterCommands({ ...target, observed: row ? [row] : undefined }).catch((error: unknown) => {
|
|
171
215
|
try {
|
|
172
|
-
registerCommandsLogger.error('Register command reconcile failed', { context: { registerId: target.registerId, error:
|
|
216
|
+
registerCommandsLogger.error('Register command reconcile failed', { context: { registerId: target.registerId, error: safeErrorString(error) } });
|
|
173
217
|
} catch {
|
|
174
218
|
// A failing log sink must not affect a register action either.
|
|
175
219
|
}
|
|
@@ -189,15 +233,17 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
189
233
|
watchFresh(sessions, { selector: { register_id: registerId } }),
|
|
190
234
|
watchFresh(closures, { selector: { register_id: registerId } }),
|
|
191
235
|
observeRegister$(register).pipe(map((document) => reservationOf(document, storeKey, registerId))),
|
|
192
|
-
|
|
236
|
+
commandTarget ? watchFresh(commandTarget.commands, { selector: {
|
|
237
|
+
registerId, type: { $in: ['register.session.open', 'register.closure.submit'] },
|
|
238
|
+
} }) : of([] as RegisterCommand[]),
|
|
239
|
+
]).pipe(switchMap(([rows, closureRows, reservation, commandRows]) => {
|
|
193
240
|
const current = currentSession(rows, closureRows, reservation);
|
|
194
|
-
if (!current) return of({ rows, closureRows, reservation, entries: [], sales: [], refundRows: [] } as Snapshot);
|
|
241
|
+
if (!current) return of({ rows, closureRows, reservation, entries: [], sales: [], refundRows: [], commandRows } as Snapshot);
|
|
195
242
|
return combineLatest([
|
|
196
243
|
watchFresh(movements, { selector: { session_id: current.id } }),
|
|
197
244
|
watchFresh(orders, { selector: { sessionId: current.id } }),
|
|
198
|
-
commandTarget ? watchFresh(commandTarget.commands, { selector: { key: `session.open:${current.id}` } }) : of([]),
|
|
199
245
|
refunds ? watchFresh(refunds, { selector: { sessionId: current.id } }) : of([]),
|
|
200
|
-
]).pipe(map(([entries, sales,
|
|
246
|
+
]).pipe(map(([entries, sales, refundRows]) => ({ rows, closureRows, reservation, entries, sales, refundRows, commandRows })));
|
|
201
247
|
}));
|
|
202
248
|
}, [enabled, sessions, movements, closures, orders, register, storeKey, registerId, commandTarget, refunds]);
|
|
203
249
|
// A latest-value ref: an `actions` object from an earlier render still sees the current flag.
|
|
@@ -269,11 +315,13 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
269
315
|
}
|
|
270
316
|
}, [data, source]);
|
|
271
317
|
const session = data ? currentSession(data.rows, data.closureRows, data.reservation) : null;
|
|
272
|
-
const
|
|
318
|
+
const commandRows = data?.commandRows ?? [];
|
|
319
|
+
const open = session ? commandRows.find((row) => row.key === `session.open:${session.id}`) : undefined;
|
|
320
|
+
const refusal = open?.error?.data as RegisterSessionAlreadyOpenData | undefined;
|
|
273
321
|
const conflict = session?.status !== 'conflict' || !commandTarget ? undefined
|
|
274
|
-
:
|
|
275
|
-
? { sessionId:
|
|
276
|
-
:
|
|
322
|
+
: open?.syncStatus === 'pending' && typeof open.payload.supersedes === 'string'
|
|
323
|
+
? { sessionId: open.payload.supersedes, takingOver: true }
|
|
324
|
+
: open?.syncStatus === 'rejected' && refusal
|
|
277
325
|
? { sessionId: refusal.sessionId, openedAt: refusal.openedAt, openedBy: refusal.openedBy, deviceName: refusal.deviceName, takingOver: false } : undefined;
|
|
278
326
|
const entries = data?.entries ?? [];
|
|
279
327
|
const sales = data?.sales ?? [];
|
|
@@ -300,6 +348,16 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
300
348
|
if (!session) throw new RegisterSessionRequiredError();
|
|
301
349
|
return session;
|
|
302
350
|
};
|
|
351
|
+
// As `writeClosure` derives the Z's expected figures, from the same rows, past the query cache.
|
|
352
|
+
const freshExpected = async (row: RegisterSession) => {
|
|
353
|
+
const { movements, orders, refunds } = live();
|
|
354
|
+
return deriveExpected({
|
|
355
|
+
session: { id: row.id, countedFloatMinor: row.counted_float_minor },
|
|
356
|
+
movements: await readFresh(movements, { selector: { session_id: row.id } }),
|
|
357
|
+
ledgerRowsBySession: ledgerRows(await readFresh(orders, { selector: { sessionId: row.id } })),
|
|
358
|
+
refunds: refunds ? await readFresh(refunds, { selector: { sessionId: row.id } }) : undefined,
|
|
359
|
+
});
|
|
360
|
+
};
|
|
303
361
|
const refuseDuringTender = () => {
|
|
304
362
|
if (tender.current) throw new RegisterTenderInProgressError();
|
|
305
363
|
};
|
|
@@ -320,7 +378,14 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
320
378
|
lastClosure: [...(data?.closureRows ?? [])].sort((a, b) => b.closed_at.localeCompare(a.closed_at))[0] ?? null,
|
|
321
379
|
lastClosed: (data?.rows ?? []).filter((row) => row.status === 'closed')
|
|
322
380
|
.sort((a, b) => (b.closed_at_gmt ?? '').localeCompare(a.closed_at_gmt ?? ''))[0] ?? null,
|
|
323
|
-
varianceThreshold
|
|
381
|
+
varianceThreshold,
|
|
382
|
+
/** ADR-082 d4: the store holds the current session (`isLiveAtStore`), so the app's approval route can be used. */
|
|
383
|
+
liveAtStore: isLiveAtStore(session, open),
|
|
384
|
+
/** ADR-082 d7: a closure the store refused with either approval code, or `null`; recover it with `actions.reapproveClosure`. */
|
|
385
|
+
approvalNeeded: approvalNeededOf(commandRows, data?.rows ?? []),
|
|
386
|
+
/** ADR-082 d9: each listed closure's approval status by closure id; show `unverified` beside the approver's name. */
|
|
387
|
+
closureApprovalStatus: Object.fromEntries((data?.closureRows ?? []).map((closure) => [closure.id, closureApprovalStatus(closure,
|
|
388
|
+
commandRows.find((row) => row.key === `closure.submit:${closure.id}`), options.capabilities)])) as Record<string, ClosureApprovalStatus>,
|
|
324
389
|
enabled,
|
|
325
390
|
blind: options.blind ?? false,
|
|
326
391
|
/** Pass straight to useSale's `session` option: `complete()` then stamps through `stampSession`. */
|
|
@@ -346,6 +411,11 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
346
411
|
if (row?.status !== 'conflict') throw new RegisterSessionRequiredError();
|
|
347
412
|
await abandonSession({ ...commandTarget, sessionId: row.id });
|
|
348
413
|
},
|
|
414
|
+
/** ADR-082 d7: sends `approvalNeeded`'s closure again with a new proof and approver; `RegisterReapproveError` unless it is refused with either approval code at contract 3. */
|
|
415
|
+
reapproveClosure: async (input: { closureId: string; approval: string; approvedBy: string }) => {
|
|
416
|
+
if (!commandTarget) throw new RegisterSessionRequiredError();
|
|
417
|
+
await reapproveClosure({ ...input, commands: commandTarget.commands, registerContract: options.capabilities?.register });
|
|
418
|
+
},
|
|
349
419
|
/**
|
|
350
420
|
* Refuses with `RegisterSessionAlreadyOpenError` while the register has a live session or
|
|
351
421
|
* another open is running (in any hook instance), and with `RegisterCloseIncompleteError`
|
|
@@ -414,13 +484,18 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
414
484
|
* `counted` maps each tender to its counted minor units. An interrupted close resumes with
|
|
415
485
|
* the count persisted on the session, not the one passed to the retry (WCPOS uses the retry's).
|
|
416
486
|
* Over `varianceThreshold` (`closeNeedsApproval`, as `RegisterCount`), a close without
|
|
417
|
-
* `approvedBy` throws `RegisterApprovalRequiredError` before any write, blind or not;
|
|
487
|
+
* `approvedBy` throws `RegisterApprovalRequiredError` before any write, blind or not; so does one without
|
|
488
|
+
* `approval` at contract 3 with the store's `registerApproval` while the session is `liveAtStore` (ADR-082 d5); a
|
|
418
489
|
* resumed close (the stored session already closed) isn't gated again. `approvedBy` reaches the Z
|
|
419
490
|
* (`breakdowns.approved_by`), and `approvedByName` its `approved_by_name`.
|
|
491
|
+
* `approval` is the store's opaque proof (ADR-082): it goes to the session's
|
|
492
|
+
* `approver_token` and from there only onto a version 3 closure command, never onto the Z, a fact or a log. With
|
|
493
|
+
* `approvedVariance` (the variance the app sent to its approval route), a close whose `closureVariance` differs
|
|
494
|
+
* throws `RegisterApprovalRequiredError` before any write. A resumed close checks neither.
|
|
420
495
|
* One close per register runs at a time, in any hook instance: a call while one is in flight joins
|
|
421
496
|
* it, getting its closure or error, and its own `counted`, `approvedBy` and `approvedByName` are ignored.
|
|
422
497
|
*/
|
|
423
|
-
closeSession: async (input: { counted: Record<string, number>; approvedBy?: string; approvedByName?: string }) => {
|
|
498
|
+
closeSession: async (input: { counted: Record<string, number>; approvedBy?: string; approvedByName?: string; approval?: string; approvedVariance?: Record<string, number> }) => {
|
|
424
499
|
refuseDuringTender();
|
|
425
500
|
const key = registerId ?? '';
|
|
426
501
|
if (closingByRegister.has(key)) return closingByRegister.get(key)!;
|
|
@@ -431,19 +506,22 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
431
506
|
// render's snapshot, which can lag a sale or a close that already landed (#168 review).
|
|
432
507
|
const stored = await store.readSession(sessions, open.id);
|
|
433
508
|
if (!stored) throw new RegisterSessionRequiredError();
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
if (
|
|
509
|
+
// ADR-082 d5: at contract 3 with the store's threshold, a close without the store's proof may still need one.
|
|
510
|
+
const proofChecked = (options.capabilities?.register ?? 0) >= 3 && options.capabilities?.registerApproval != null && !input.approval;
|
|
511
|
+
if (stored.status !== 'closed' && (!input.approvedBy || input.approvedVariance || proofChecked)) {
|
|
512
|
+
const fresh = await freshExpected(stored);
|
|
513
|
+
const over = closeNeedsApproval(input.counted.cash ?? 0, fresh.cash ?? 0, varianceThreshold);
|
|
514
|
+
if (over && !input.approvedBy) throw new RegisterApprovalRequiredError();
|
|
515
|
+
// Live at the store, the route can be used, so `approvedBy` alone is not enough. Offline, or before the store
|
|
516
|
+
// applies the open, it closes with `approvedBy` and the store's refusal is recovered later (decision 7).
|
|
517
|
+
if (over && proofChecked && commandTarget && isLiveAtStore(stored,
|
|
518
|
+
(await readFresh(commandTarget.commands, { selector: { key: `session.open:${stored.id}` } }))[0])) throw new RegisterApprovalRequiredError();
|
|
519
|
+
// ADR-082 d5: a sale or a movement since the approval moved the variance the proof is bound to; ask again.
|
|
520
|
+
if (input.approvedVariance && !sameVariance(input.approvedVariance, closureVariance(closedCount(input.counted), fresh))) throw new RegisterApprovalRequiredError();
|
|
443
521
|
}
|
|
444
522
|
// By id, not `open` (plain data): `store.closeSession`'s guard runs again inside
|
|
445
523
|
// `incrementalModify` on the stored document, so a close that already landed keeps its count, time, actor and approver.
|
|
446
|
-
const closed = await store.closeSession(sessions, open.id, { counted: input.counted, closedBy: actor.id, approvedBy: input.approvedBy, timezone });
|
|
524
|
+
const closed = await store.closeSession(sessions, open.id, { counted: input.counted, closedBy: actor.id, approvedBy: input.approvedBy, approval: input.approval, timezone });
|
|
447
525
|
// The session stores no approver name, so a close resumed without this call's name (after
|
|
448
526
|
// a restart, say) falls back to `nameOf`.
|
|
449
527
|
const approvedByName = (input.approvedBy && closed.approved_by === input.approvedBy && input.approvedByName) || nameOf(closed.approved_by);
|
|
@@ -487,6 +565,12 @@ export function useRegisterSession(options: UseRegisterSessionOptions) {
|
|
|
487
565
|
reconcile();
|
|
488
566
|
}
|
|
489
567
|
},
|
|
568
|
+
/** ADR-082 d3: the variance this count would close with, read as the gate reads it; the app sends it to its approval route and back as `approvedVariance`. */
|
|
569
|
+
closureVariance: async (counted: Record<string, number>) => {
|
|
570
|
+
const stored = await store.readSession(live().sessions, current().id);
|
|
571
|
+
if (!stored) throw new RegisterSessionRequiredError();
|
|
572
|
+
return closureVariance(closedCount(counted), await freshExpected(stored));
|
|
573
|
+
},
|
|
490
574
|
recordMovement: async (input: { type: 'paid_in' | 'paid_out' | 'no_sale'; amountMinor: number; reason: string }) => {
|
|
491
575
|
try {
|
|
492
576
|
// `live()` first: missing collections or host refuse before `requireOpen` writes anything.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { StoreOrder } from '@tallyui/core';
|
|
2
|
+
import type { PosOrder } from '../pos-order/types';
|
|
3
|
+
import type { PosRefund } from '../refund/pos-refund';
|
|
4
|
+
import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
|
|
5
|
+
import type { LineJoin, ReportLine, ReportOrder, ReportRefund } from './types';
|
|
6
|
+
|
|
7
|
+
function joinedLine(line: { productId?: string; variantId?: string; quantity: number }, join?: LineJoin): Pick<ReportLine, 'costMinor' | 'category'> {
|
|
8
|
+
const answer = join?.({
|
|
9
|
+
...(line.productId !== undefined ? { productId: line.productId } : {}),
|
|
10
|
+
...(line.variantId !== undefined ? { variantId: line.variantId } : {}),
|
|
11
|
+
});
|
|
12
|
+
return {
|
|
13
|
+
...(typeof answer?.unitCostMinor === 'number' && Number.isFinite(answer.unitCostMinor)
|
|
14
|
+
? { costMinor: Math.round(answer.unitCostMinor * line.quantity) } : {}),
|
|
15
|
+
...(answer?.category ? { category: answer.category } : {}),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin): ReportOrder {
|
|
20
|
+
const taxedLines = [...order.lines.map((line) => ({ ...line, taxInclusive: order.taxRounding.granularity === 'woocommerce'
|
|
21
|
+
&& line.netMicros !== undefined ? order.pricesIncludeTax : line.taxInclusive ?? order.pricesIncludeTax })),
|
|
22
|
+
...[...(order.fees ?? []), ...(order.shipping ?? [])].map((charge) => ({ ...charge, taxInclusive: order.pricesIncludeTax }))];
|
|
23
|
+
const taxes = order.taxByRate ?? taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding);
|
|
24
|
+
return {
|
|
25
|
+
id: order.id, at: order.createdAt, totalMinor: order.totalMinor, taxMinor: order.taxMinor,
|
|
26
|
+
discountMinor: order.discountMinor, needsPayment: false, refunds: [],
|
|
27
|
+
lines: order.lines.map((line) => {
|
|
28
|
+
const taxMinor = roundMicrosToMinor(line.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n));
|
|
29
|
+
return {
|
|
30
|
+
key: line.variantId || line.productId || line.name, name: line.name, quantity: line.quantity,
|
|
31
|
+
netMinor: order.taxRounding.granularity === 'woocommerce' && line.netMicros !== undefined
|
|
32
|
+
? line.netMinor
|
|
33
|
+
: (line.taxInclusive ?? order.pricesIncludeTax) ? line.netMinor - taxMinor : line.netMinor,
|
|
34
|
+
taxMinor, ...joinedLine(line, join),
|
|
35
|
+
};
|
|
36
|
+
}),
|
|
37
|
+
payments: order.payments.map(({ method, amountMinor }) => ({ method, amountMinor })),
|
|
38
|
+
taxes: taxes.map((row) => ({
|
|
39
|
+
ratePpm: row.ratePpm, ...(row.code !== undefined ? { code: row.code } : {}),
|
|
40
|
+
label: row.label ?? `Tax ${row.ratePpm / 10000}%`, taxMinor: row.amountMinor, netMinor: row.netMinor,
|
|
41
|
+
})),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function reportOrderFromStoreOrder(order: StoreOrder, join?: LineJoin): ReportOrder {
|
|
46
|
+
return {
|
|
47
|
+
id: order.id, at: order.placedAt, totalMinor: order.totalMinor, taxMinor: order.taxMinor, discountMinor: order.discountMinor,
|
|
48
|
+
lines: order.lines.map((line) => ({
|
|
49
|
+
key: line.variantId || line.productId || line.name, name: line.name, quantity: line.quantity,
|
|
50
|
+
netMinor: line.totalMinor, taxMinor: line.taxMinor, ...joinedLine(line, join),
|
|
51
|
+
})),
|
|
52
|
+
payments: order.payments.map(({ method, title, amountMinor }) => ({ method, ...(title !== undefined ? { label: title } : {}), amountMinor })),
|
|
53
|
+
taxes: order.taxLines.map(({ ratePpm, code, label, amountMinor }) => ({
|
|
54
|
+
ratePpm, ...(code !== undefined ? { code } : {}), label, taxMinor: amountMinor, netMinor: null,
|
|
55
|
+
})),
|
|
56
|
+
refunds: order.refunds.map(({ id, amountMinor }) => ({ id, amountMinor })),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function reportRefundFromPosRefund(refund: PosRefund): ReportRefund | undefined {
|
|
61
|
+
if (refund.status !== 'applied') return undefined;
|
|
62
|
+
return {
|
|
63
|
+
id: refund.id, orderId: refund.orderId, at: refund.envelope.payload.createdAt || refund.createdAt,
|
|
64
|
+
amountMinor: refund.result && Number.isSafeInteger(refund.result.totalMinor)
|
|
65
|
+
? refund.result.totalMinor : refund.envelope.payload.totalMinor,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { salesFigures, marginOf, comparisonRange, daysOf, inRange } from './sales-figures';
|
|
2
|
+
export { presetRange, DATE_PRESETS, type DatePreset } from './presets';
|
|
3
|
+
export { reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund } from './adapters';
|
|
4
|
+
export type { StoreDay, DayRange, ReportCategory, ReportLine, ReportPayment, ReportTax, ReportOrder, ReportRefund, LineJoin } from './types';
|
|
5
|
+
export type { Margin, SalesTotals, PaymentRow, GroupRow, TaxRow, DayPoint, SalesFiguresInput, SalesFigures } from './sales-figures';
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { businessDayOf } from '../register/session-store';
|
|
2
|
+
import type { DayRange, StoreDay } from './types';
|
|
3
|
+
|
|
4
|
+
export type DatePreset = 'today' | 'yesterday' | 'thisWeek' | 'lastWeek' | 'thisMonth' | 'lastMonth';
|
|
5
|
+
export const DATE_PRESETS: readonly DatePreset[] = ['today', 'yesterday', 'thisWeek', 'lastWeek', 'thisMonth', 'lastMonth'];
|
|
6
|
+
|
|
7
|
+
const DAY_MS = 86_400_000;
|
|
8
|
+
const iso = (at: number): StoreDay => new Date(at).toISOString().slice(0, 10);
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The preset's store days at `now` in `timezone` (IANA or 'device'). Weeks start Monday;
|
|
12
|
+
* this week and this month end today, as WCPOS v2's date button clamps a preset to today.
|
|
13
|
+
*/
|
|
14
|
+
export function presetRange(preset: DatePreset, now: Date, timezone: string): DayRange {
|
|
15
|
+
const today = businessDayOf(now.toISOString(), timezone);
|
|
16
|
+
const [year, month, day] = today.split('-').map(Number);
|
|
17
|
+
const at = Date.UTC(year, month - 1, day);
|
|
18
|
+
const monday = at - ((new Date(at).getUTCDay() + 6) % 7) * DAY_MS;
|
|
19
|
+
switch (preset) {
|
|
20
|
+
case 'today': return { from: today, to: today };
|
|
21
|
+
case 'yesterday': return { from: iso(at - DAY_MS), to: iso(at - DAY_MS) };
|
|
22
|
+
case 'thisWeek': return { from: iso(monday), to: today };
|
|
23
|
+
case 'lastWeek': return { from: iso(monday - 7 * DAY_MS), to: iso(monday - DAY_MS) };
|
|
24
|
+
case 'thisMonth': return { from: iso(Date.UTC(year, month - 1, 1)), to: today };
|
|
25
|
+
case 'lastMonth': return { from: iso(Date.UTC(year, month - 2, 1)), to: iso(Date.UTC(year, month - 1, 0)) };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { businessDayOf } from '../register/session-store';
|
|
2
|
+
import type { DatePreset } from './presets';
|
|
3
|
+
import type { DayRange, ReportLine, ReportOrder, ReportRefund, StoreDay } from './types';
|
|
4
|
+
|
|
5
|
+
const DAY_MS = 86_400_000;
|
|
6
|
+
|
|
7
|
+
export interface Margin {
|
|
8
|
+
costedNetMinor: number;
|
|
9
|
+
costMinor: number;
|
|
10
|
+
profitMinor: number;
|
|
11
|
+
marginPct: number | null;
|
|
12
|
+
missingLines: number;
|
|
13
|
+
missingQuantity: number;
|
|
14
|
+
}
|
|
15
|
+
export interface SalesTotals {
|
|
16
|
+
grossMinor: number; netMinor: number; taxMinor: number; discountMinor: number;
|
|
17
|
+
refundsMinor: number; embeddedRefundsMinor: number;
|
|
18
|
+
orderCount: number; averageMinor: number; items: number;
|
|
19
|
+
margin: Margin;
|
|
20
|
+
}
|
|
21
|
+
export interface PaymentRow { method: string; label: string; amountMinor: number; orders: number }
|
|
22
|
+
export interface GroupRow { key: string; name: string; quantity: number; netMinor: number; margin: Margin }
|
|
23
|
+
export interface TaxRow { key: string; ratePpm: number; code?: string; label: string; taxMinor: number; netMinor: number | null }
|
|
24
|
+
export interface DayPoint { day: StoreDay; grossMinor: number; orderCount: number; refundsMinor: number }
|
|
25
|
+
export interface SalesFiguresInput {
|
|
26
|
+
orders: readonly ReportOrder[];
|
|
27
|
+
refunds?: readonly ReportRefund[];
|
|
28
|
+
range: DayRange;
|
|
29
|
+
compare?: DayRange;
|
|
30
|
+
/** IANA zone of the store, or 'device'. */
|
|
31
|
+
timezone: string;
|
|
32
|
+
}
|
|
33
|
+
export interface SalesFigures {
|
|
34
|
+
range: DayRange;
|
|
35
|
+
totals: SalesTotals;
|
|
36
|
+
payments: { rows: PaymentRow[]; takenMinor: number };
|
|
37
|
+
products: GroupRow[];
|
|
38
|
+
categories: GroupRow[];
|
|
39
|
+
taxes: TaxRow[];
|
|
40
|
+
refunds: { count: number; amountMinor: number; orders: number };
|
|
41
|
+
series: DayPoint[];
|
|
42
|
+
comparison?: { range: DayRange; totals: SalesTotals; series: DayPoint[] };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function inRange(at: string, range: DayRange, timezone: string): boolean {
|
|
46
|
+
const day = businessDayOf(at, timezone);
|
|
47
|
+
return range.from <= day && day <= range.to;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function daysOf(range: DayRange): StoreDay[] {
|
|
51
|
+
const [year, month, day] = range.from.split('-').map(Number);
|
|
52
|
+
const days: StoreDay[] = [];
|
|
53
|
+
for (let at = Date.UTC(year, month - 1, day); ; at += 86_400_000) {
|
|
54
|
+
const next = new Date(at).toISOString().slice(0, 10);
|
|
55
|
+
if (next > range.to) return days;
|
|
56
|
+
days.push(next);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The range a report is compared with, period to date. Port of WCPOS v2 `useReportsPeriod`
|
|
62
|
+
* (`screens/main/reports/context.tsx`). A week or month preset is a week or a month; any other
|
|
63
|
+
* range is a day (one day), a week (up to seven) or a month (longer). A day goes back one day
|
|
64
|
+
* (`previous`) or seven (`week`), and a week seven, so Monday to today meets the same weekdays of
|
|
65
|
+
* the week before. A month starts a month earlier, a 31st clamped to a shorter month's last day:
|
|
66
|
+
* a whole calendar month meets the whole month before, and any other range keeps its day count,
|
|
67
|
+
* so 1–10 Nov meets 1–10 Oct.
|
|
68
|
+
*/
|
|
69
|
+
export function comparisonRange(range: DayRange, mode: 'previous' | 'week', preset?: DatePreset): DayRange {
|
|
70
|
+
const iso = (at: number): StoreDay => new Date(at).toISOString().slice(0, 10);
|
|
71
|
+
const [year, month, day] = range.from.split('-').map(Number);
|
|
72
|
+
const from = Date.UTC(year, month - 1, day);
|
|
73
|
+
const [toYear, toMonth, toDay] = range.to.split('-').map(Number);
|
|
74
|
+
const to = Date.UTC(toYear, toMonth - 1, toDay);
|
|
75
|
+
const days = daysOf(range).length;
|
|
76
|
+
const period = preset?.endsWith('Month') ? 'month' : preset?.endsWith('Week') ? 'week' : days === 1 ? 'day' : days <= 7 ? 'week' : 'month';
|
|
77
|
+
if (period !== 'month') {
|
|
78
|
+
const shift = (period === 'day' && mode === 'previous' ? 1 : 7) * DAY_MS;
|
|
79
|
+
return { from: iso(from - shift), to: iso(to - shift) };
|
|
80
|
+
}
|
|
81
|
+
const start = Date.UTC(year, month - 2, Math.min(day, new Date(Date.UTC(year, month - 1, 0)).getUTCDate()));
|
|
82
|
+
const wholeMonth = day === 1 && to === Date.UTC(year, month, 0);
|
|
83
|
+
return { from: iso(start), to: iso(wholeMonth ? Date.UTC(year, month - 1, 0) : start + (days - 1) * DAY_MS) };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function marginOf(lines: readonly ReportLine[]): Margin {
|
|
87
|
+
const margin: Margin = { costedNetMinor: 0, costMinor: 0, profitMinor: 0, marginPct: null, missingLines: 0, missingQuantity: 0 };
|
|
88
|
+
let costed = false;
|
|
89
|
+
for (const line of lines) {
|
|
90
|
+
if (typeof line.costMinor === 'number' && Number.isFinite(line.costMinor)) {
|
|
91
|
+
costed = true;
|
|
92
|
+
margin.costMinor += line.costMinor;
|
|
93
|
+
margin.costedNetMinor += line.netMinor;
|
|
94
|
+
} else {
|
|
95
|
+
margin.missingLines += 1;
|
|
96
|
+
margin.missingQuantity += Number.isFinite(line.quantity) ? Math.abs(line.quantity) : 0;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
margin.profitMinor = margin.costedNetMinor - margin.costMinor;
|
|
100
|
+
margin.marginPct = costed && margin.costedNetMinor !== 0 ? margin.profitMinor / margin.costedNetMinor : null;
|
|
101
|
+
return margin;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function periodFigures(input: SalesFiguresInput, range: DayRange) {
|
|
105
|
+
const orders = input.orders.filter((order) => inRange(order.at, range, input.timezone));
|
|
106
|
+
const refunds = (input.refunds ?? []).filter((refund) => inRange(refund.at, range, input.timezone));
|
|
107
|
+
const lines = orders.flatMap((order) => order.lines);
|
|
108
|
+
const totals: SalesTotals = {
|
|
109
|
+
grossMinor: 0, netMinor: 0, taxMinor: 0, discountMinor: 0, refundsMinor: 0, embeddedRefundsMinor: 0,
|
|
110
|
+
orderCount: orders.length, averageMinor: 0,
|
|
111
|
+
items: lines.reduce((sum, line) => sum + (Number.isFinite(line.quantity) ? line.quantity : 0), 0),
|
|
112
|
+
margin: marginOf(lines),
|
|
113
|
+
};
|
|
114
|
+
const series: DayPoint[] = daysOf(range).map((day) => ({ day, grossMinor: 0, orderCount: 0, refundsMinor: 0 }));
|
|
115
|
+
const byDay = new Map(series.map((point) => [point.day, point]));
|
|
116
|
+
for (const order of orders) {
|
|
117
|
+
totals.grossMinor += order.totalMinor;
|
|
118
|
+
totals.taxMinor += order.taxMinor;
|
|
119
|
+
totals.discountMinor += order.discountMinor;
|
|
120
|
+
totals.embeddedRefundsMinor += order.refunds.reduce((sum, refund) => sum + Math.abs(refund.amountMinor), 0);
|
|
121
|
+
const point = byDay.get(businessDayOf(order.at, input.timezone))!;
|
|
122
|
+
point.grossMinor += order.totalMinor;
|
|
123
|
+
point.orderCount += 1;
|
|
124
|
+
}
|
|
125
|
+
for (const refund of refunds) {
|
|
126
|
+
totals.refundsMinor += Math.abs(refund.amountMinor);
|
|
127
|
+
byDay.get(businessDayOf(refund.at, input.timezone))!.refundsMinor += Math.abs(refund.amountMinor);
|
|
128
|
+
}
|
|
129
|
+
totals.netMinor = totals.grossMinor - totals.taxMinor;
|
|
130
|
+
totals.averageMinor = orders.length ? Math.round(totals.grossMinor / orders.length) : 0;
|
|
131
|
+
return { orders, refunds, totals, series };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function salesFigures(input: SalesFiguresInput): SalesFigures {
|
|
135
|
+
const { orders, refunds, totals, series } = periodFigures(input, input.range);
|
|
136
|
+
const payments = new Map<string, PaymentRow>();
|
|
137
|
+
const products = new Map<string, { name: string; lines: ReportLine[] }>();
|
|
138
|
+
const categories = new Map<string, { name: string; lines: ReportLine[] }>();
|
|
139
|
+
const taxes = new Map<string, TaxRow>();
|
|
140
|
+
for (const order of orders) {
|
|
141
|
+
const contributions = [...order.payments];
|
|
142
|
+
const remainder = order.totalMinor - order.payments.reduce((sum, payment) => sum + payment.amountMinor, 0);
|
|
143
|
+
if (remainder > 0) contributions.push({ method: order.needsPayment ? 'unpaid' : 'unknown', amountMinor: remainder });
|
|
144
|
+
const methods = new Set<string>();
|
|
145
|
+
for (const payment of contributions) {
|
|
146
|
+
const row = payments.get(payment.method) ?? { method: payment.method, label: '', amountMinor: 0, orders: 0 };
|
|
147
|
+
row.amountMinor += payment.amountMinor;
|
|
148
|
+
if (!row.label && payment.label) row.label = payment.label;
|
|
149
|
+
if (!methods.has(payment.method)) row.orders += 1;
|
|
150
|
+
methods.add(payment.method);
|
|
151
|
+
payments.set(payment.method, row);
|
|
152
|
+
}
|
|
153
|
+
for (const line of order.lines) {
|
|
154
|
+
const product = products.get(line.key) ?? { name: line.name, lines: [] };
|
|
155
|
+
product.lines.push(line);
|
|
156
|
+
products.set(line.key, product);
|
|
157
|
+
const key = line.category?.id ?? '';
|
|
158
|
+
const category = categories.get(key) ?? { name: line.category?.name ?? '', lines: [] };
|
|
159
|
+
category.lines.push(line);
|
|
160
|
+
categories.set(key, category);
|
|
161
|
+
}
|
|
162
|
+
for (const tax of order.taxes) {
|
|
163
|
+
const key = JSON.stringify([tax.ratePpm, tax.code ?? tax.label]);
|
|
164
|
+
const row = taxes.get(key) ?? { ...tax, key, taxMinor: 0, netMinor: 0 };
|
|
165
|
+
row.taxMinor += tax.taxMinor;
|
|
166
|
+
row.netMinor = row.netMinor === null || tax.netMinor === null ? null : row.netMinor + tax.netMinor;
|
|
167
|
+
taxes.set(key, row);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const groups = [products, categories].map((group) => Array.from(group, ([key, { name, lines }]): GroupRow => ({
|
|
171
|
+
key, name, quantity: lines.reduce((sum, line) => sum + (Number.isFinite(line.quantity) ? line.quantity : 0), 0),
|
|
172
|
+
netMinor: lines.reduce((sum, line) => sum + line.netMinor, 0), margin: marginOf(lines),
|
|
173
|
+
})).sort((a, b) => b.netMinor - a.netMinor || b.quantity - a.quantity || a.name.localeCompare(b.name)));
|
|
174
|
+
const rows = [...payments.values()].sort((a, b) => b.amountMinor - a.amountMinor || a.method.localeCompare(b.method));
|
|
175
|
+
const result: SalesFigures = {
|
|
176
|
+
range: input.range, totals,
|
|
177
|
+
payments: { rows, takenMinor: rows.reduce((sum, row) => sum + (row.method === 'unpaid' ? 0 : row.amountMinor), 0) },
|
|
178
|
+
products: groups[0], categories: groups[1], taxes: [...taxes.values()].sort((a, b) => b.taxMinor - a.taxMinor),
|
|
179
|
+
refunds: { count: refunds.length, amountMinor: totals.refundsMinor, orders: new Set(refunds.map((refund) => refund.orderId)).size },
|
|
180
|
+
series,
|
|
181
|
+
};
|
|
182
|
+
if (input.compare) {
|
|
183
|
+
const comparison = periodFigures(input, input.compare);
|
|
184
|
+
result.comparison = { range: input.compare, totals: comparison.totals, series: comparison.series };
|
|
185
|
+
}
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** A store day, `yyyy-MM-dd` in the store's timezone. */
|
|
2
|
+
export type StoreDay = string;
|
|
3
|
+
/** Inclusive range of store days. */
|
|
4
|
+
export interface DayRange { from: StoreDay; to: StoreDay }
|
|
5
|
+
|
|
6
|
+
export interface ReportCategory { id: string; name: string }
|
|
7
|
+
|
|
8
|
+
export interface ReportLine {
|
|
9
|
+
/** Grouping identity: variant, else product, else name. */
|
|
10
|
+
key: string;
|
|
11
|
+
name: string;
|
|
12
|
+
quantity: number;
|
|
13
|
+
/** After discounts, excluding tax. */
|
|
14
|
+
netMinor: number;
|
|
15
|
+
taxMinor: number;
|
|
16
|
+
/** Cost of goods for the whole line (quantity × unit cost). Absent or null means the cost is missing, never 0. */
|
|
17
|
+
costMinor?: number | null;
|
|
18
|
+
/** The line's first category, when the caller joined one. */
|
|
19
|
+
category?: ReportCategory;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ReportPayment { method: string; label?: string; amountMinor: number }
|
|
23
|
+
|
|
24
|
+
export interface ReportTax {
|
|
25
|
+
ratePpm: number;
|
|
26
|
+
code?: string;
|
|
27
|
+
label: string;
|
|
28
|
+
taxMinor: number;
|
|
29
|
+
/** The net this rate taxed; null when the source does not carry it. */
|
|
30
|
+
netMinor: number | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** An order as the reports read it. Money in integer minor units. */
|
|
34
|
+
export interface ReportOrder {
|
|
35
|
+
id: string;
|
|
36
|
+
/** ISO 8601 UTC instant the sale was made. */
|
|
37
|
+
at: string;
|
|
38
|
+
/** Gross, including tax. */
|
|
39
|
+
totalMinor: number;
|
|
40
|
+
taxMinor: number;
|
|
41
|
+
discountMinor: number;
|
|
42
|
+
/** True when the order still owes money: its unpaid remainder is `unpaid`, not `unknown`. */
|
|
43
|
+
needsPayment?: boolean;
|
|
44
|
+
lines: ReportLine[];
|
|
45
|
+
payments: ReportPayment[];
|
|
46
|
+
taxes: ReportTax[];
|
|
47
|
+
/** Refunds embedded on the order, undated (a store order's own list). Positive. */
|
|
48
|
+
refunds: Array<{ id: string; amountMinor: number }>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A refund dated by when it was made, counted on that store day. */
|
|
52
|
+
export interface ReportRefund {
|
|
53
|
+
id: string;
|
|
54
|
+
orderId: string;
|
|
55
|
+
/** ISO 8601 UTC instant the refund was made. */
|
|
56
|
+
at: string;
|
|
57
|
+
/** Positive. */
|
|
58
|
+
amountMinor: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The caller's product directory: a line's unit cost and first category. */
|
|
62
|
+
export type LineJoin = (line: { productId?: string; variantId?: string }) =>
|
|
63
|
+
{ unitCostMinor?: number | null; category?: ReportCategory } | undefined;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** The part of a cart line the in-cart count reads (`LineItem` has all three). */
|
|
2
|
+
export type CartQuantityLine = { productId: string; quantity: number; custom?: true };
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Quantity per product id, summed across the product's lines, so a product with variants counts every
|
|
6
|
+
* variant's lines; a custom line belongs to no catalogue product and counts for none.
|
|
7
|
+
*
|
|
8
|
+
* Ported from WCPOS v2 `useProductCount`, packages/core/src/screens/main/pos/products/rows/product-row.tsx
|
|
9
|
+
* (MIT, WCPOS): the cashier reads how many are in the cart, not how many lines.
|
|
10
|
+
*/
|
|
11
|
+
export function cartQuantities(lines: readonly CartQuantityLine[]): Map<string, number> {
|
|
12
|
+
const quantities = new Map<string, number>();
|
|
13
|
+
for (const line of lines) {
|
|
14
|
+
if (line.custom) continue;
|
|
15
|
+
quantities.set(line.productId, (quantities.get(line.productId) ?? 0) + line.quantity);
|
|
16
|
+
}
|
|
17
|
+
return quantities;
|
|
18
|
+
}
|