@classytic/pos 0.5.0 → 0.7.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/CHANGELOG.md +115 -0
- package/dist/commands/index.d.mts +2 -0
- package/dist/commands/index.mjs +1 -0
- package/dist/commands/pos-commands.d.mts +228 -0
- package/dist/commands/pos-commands.mjs +355 -0
- package/dist/domain/enums/cash-movement-reason.enum.d.mts +3 -4
- package/dist/domain/enums/closed-by.enum.d.mts +3 -4
- package/dist/domain/enums/payment-method.enum.d.mts +6 -7
- package/dist/domain/enums/shift-state.enum.d.mts +7 -8
- package/dist/domain/errors/pos.errors.d.mts +82 -13
- package/dist/domain/errors/pos.errors.mjs +111 -1
- package/dist/domain/index.d.mts +11 -3
- package/dist/domain/index.mjs +10 -3
- package/dist/domain/ports/common.d.mts +2 -3
- package/dist/domain/ports/ledger.bridge.d.mts +6 -7
- package/dist/domain/ports/notification.bridge.d.mts +5 -6
- package/dist/domain/ports/policy.bridge.d.mts +2 -3
- package/dist/domain/sale/discount.d.mts +62 -0
- package/dist/domain/sale/discount.mjs +58 -0
- package/dist/domain/sale/price-override.d.mts +51 -0
- package/dist/domain/sale/price-override.mjs +51 -0
- package/dist/domain/sale/quick-cash.d.mts +10 -0
- package/dist/domain/sale/quick-cash.mjs +27 -0
- package/dist/domain/sale/service-line.d.mts +7 -0
- package/dist/domain/sale/service-line.mjs +10 -0
- package/dist/domain/sale/tender.d.mts +256 -0
- package/dist/domain/sale/tender.mjs +242 -0
- package/dist/domain/shift/shift-decisions.d.mts +52 -0
- package/dist/domain/shift/shift-decisions.mjs +93 -0
- package/dist/domain/shift/shift-report.d.mts +127 -0
- package/dist/domain/shift/shift-report.mjs +95 -0
- package/dist/domain/shift/shift.types.d.mts +109 -0
- package/dist/domain/state-machines/shift.fsm.d.mts +6 -7
- package/dist/domain/value-objects/cash-movement.vo.d.mts +7 -3
- package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -5
- package/dist/domain/value-objects/shift-policy.vo.d.mts +11 -7
- package/dist/domain/value-objects/shift-policy.vo.mjs +12 -1
- package/dist/engine/define-pos.d.mts +2 -3
- package/dist/engine/define-pos.mjs +13 -2
- package/dist/engine/engine-types.d.mts +24 -9
- package/dist/engine/index.mjs +1 -2
- package/dist/events/event-catalog.d.mts +18 -14
- package/dist/events/event-catalog.mjs +10 -4
- package/dist/events/event-constants.d.mts +3 -4
- package/dist/events/event-payloads.d.mts +9 -10
- package/dist/events/helpers.d.mts +6 -3
- package/dist/events/helpers.mjs +12 -2
- package/dist/events/in-process-bus.d.mts +3 -4
- package/dist/events/index.mjs +1 -1
- package/dist/grant/till-grant.d.mts +50 -0
- package/dist/grant/till-grant.mjs +47 -0
- package/dist/index.d.mts +14 -4
- package/dist/index.mjs +12 -4
- package/dist/models/create-models.d.mts +10 -6
- package/dist/models/create-models.mjs +16 -3
- package/dist/models/register.model.d.mts +7 -6
- package/dist/models/shift-sale-dedupe.model.d.mts +4 -5
- package/dist/models/shift.model.d.mts +4 -111
- package/dist/models/shift.model.mjs +26 -2
- package/dist/models/till-grant.model.d.mts +19 -0
- package/dist/models/till-grant.model.mjs +52 -0
- package/dist/repositories/register.repository.d.mts +3 -4
- package/dist/repositories/shift.repository.d.mts +77 -30
- package/dist/repositories/shift.repository.mjs +307 -108
- package/dist/repositories/till-grant.repository.d.mts +22 -0
- package/dist/repositories/till-grant.repository.mjs +41 -0
- package/dist/schemas/index.mjs +1 -2
- package/dist/schemas/shift.d.mts +9 -10
- package/dist/testing/fixtures.d.mts +4 -5
- package/dist/testing/index.mjs +1 -2
- package/package.json +50 -19
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { ShiftState } from "../enums/shift-state.enum.mjs";
|
|
2
|
+
import { CountableRow } from "./shift-decisions.mjs";
|
|
3
|
+
import { OrderStatusValue } from "@classytic/order/enums/order-status";
|
|
4
|
+
import { DocumentTaxBreakdown } from "@classytic/tax-core/document";
|
|
5
|
+
//#region src/domain/shift/shift-report.d.ts
|
|
6
|
+
/** The parts of a shift the report reads. */
|
|
7
|
+
export interface ReportShift {
|
|
8
|
+
_id: string;
|
|
9
|
+
registerId: string;
|
|
10
|
+
state: ShiftState;
|
|
11
|
+
openedAt: string | Date;
|
|
12
|
+
closedAt?: string | Date | null;
|
|
13
|
+
openingCashierName: string;
|
|
14
|
+
closingCashierName?: string | null;
|
|
15
|
+
paymentBreakdown: readonly (CountableRow & {
|
|
16
|
+
method: string;
|
|
17
|
+
})[];
|
|
18
|
+
cashMovements?: readonly {
|
|
19
|
+
type: 'in' | 'out';
|
|
20
|
+
amount: number;
|
|
21
|
+
reasonCode: string;
|
|
22
|
+
}[];
|
|
23
|
+
refundCount: number;
|
|
24
|
+
refundTotal: number;
|
|
25
|
+
}
|
|
26
|
+
/** The parts of an order the report reads. Money is integer minor units. */
|
|
27
|
+
export interface ReportOrder {
|
|
28
|
+
status?: OrderStatusValue;
|
|
29
|
+
/** Who rang the sale up: the order's verified actor, named by the till when it knows the name. */
|
|
30
|
+
actorRef?: string;
|
|
31
|
+
metadata?: {
|
|
32
|
+
cashierName?: string;
|
|
33
|
+
};
|
|
34
|
+
lines: readonly {
|
|
35
|
+
quantity: number;
|
|
36
|
+
snapshot?: {
|
|
37
|
+
name?: string;
|
|
38
|
+
sku?: string;
|
|
39
|
+
};
|
|
40
|
+
lineTotal?: {
|
|
41
|
+
amount: number;
|
|
42
|
+
};
|
|
43
|
+
}[];
|
|
44
|
+
totals: {
|
|
45
|
+
subtotal: {
|
|
46
|
+
amount: number;
|
|
47
|
+
};
|
|
48
|
+
discount?: {
|
|
49
|
+
amount: number;
|
|
50
|
+
};
|
|
51
|
+
tax?: {
|
|
52
|
+
amount: number;
|
|
53
|
+
};
|
|
54
|
+
grandTotal: {
|
|
55
|
+
amount: number;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
/** The sale's tax fact. Absent on an order written before it existed: counted as `unrated`. */
|
|
59
|
+
taxBreakdown?: (Pick<DocumentTaxBreakdown, 'priceBasis'> & {
|
|
60
|
+
totals: Pick<DocumentTaxBreakdown['totals'], 'taxMinor'>;
|
|
61
|
+
}) | null;
|
|
62
|
+
}
|
|
63
|
+
export interface ShiftReport {
|
|
64
|
+
kind: 'X' | 'Z';
|
|
65
|
+
shiftId: string;
|
|
66
|
+
registerId: string;
|
|
67
|
+
openedAt: string;
|
|
68
|
+
closedAt: string | null;
|
|
69
|
+
openedBy: string;
|
|
70
|
+
closedBy: string | null;
|
|
71
|
+
sales: {
|
|
72
|
+
count: number;
|
|
73
|
+
/** Before discounts. */
|
|
74
|
+
gross: number;
|
|
75
|
+
discounts: number;
|
|
76
|
+
/** Tax added on top of prices (and an unrated order's stated tax). */
|
|
77
|
+
taxAdded: number;
|
|
78
|
+
/** Tax already inside prices. */
|
|
79
|
+
taxIncluded: number;
|
|
80
|
+
/** Sales with no tax breakdown: their VAT was never computed and must be reviewed. */
|
|
81
|
+
unrated: number;
|
|
82
|
+
/** What the sales came to: gross − discounts + tax added. */
|
|
83
|
+
net: number;
|
|
84
|
+
};
|
|
85
|
+
refunds: {
|
|
86
|
+
count: number;
|
|
87
|
+
total: number;
|
|
88
|
+
};
|
|
89
|
+
/** From the drawer's breakdown: what each method took, net of refunds. */
|
|
90
|
+
payments: Array<{
|
|
91
|
+
method: string;
|
|
92
|
+
sales: number;
|
|
93
|
+
refunds: number;
|
|
94
|
+
net: number;
|
|
95
|
+
}>;
|
|
96
|
+
cash: {
|
|
97
|
+
opening: number;
|
|
98
|
+
sales: number;
|
|
99
|
+
refunds: number;
|
|
100
|
+
paidIn: number;
|
|
101
|
+
paidOut: number;
|
|
102
|
+
expected: number;
|
|
103
|
+
counted: number | null;
|
|
104
|
+
difference: number | null;
|
|
105
|
+
};
|
|
106
|
+
/** Cash moved in or out, by reason. */
|
|
107
|
+
cashMoves: Array<{
|
|
108
|
+
type: 'in' | 'out';
|
|
109
|
+
reasonCode: string;
|
|
110
|
+
count: number;
|
|
111
|
+
total: number;
|
|
112
|
+
}>;
|
|
113
|
+
topItems: Array<{
|
|
114
|
+
name: string;
|
|
115
|
+
quantity: number;
|
|
116
|
+
total: number;
|
|
117
|
+
}>;
|
|
118
|
+
byCashier: Array<{
|
|
119
|
+
cashier: string;
|
|
120
|
+
count: number;
|
|
121
|
+
net: number;
|
|
122
|
+
}>;
|
|
123
|
+
}
|
|
124
|
+
export declare function buildShiftReport(shift: ReportShift, orders: readonly ReportOrder[], options?: {
|
|
125
|
+
topItems?: number;
|
|
126
|
+
}): ShiftReport;
|
|
127
|
+
//#endregion
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { isFinalShiftState } from "../enums/shift-state.enum.mjs";
|
|
2
|
+
import { computeExpected } from "../value-objects/payment-breakdown.vo.mjs";
|
|
3
|
+
import { isCashRow } from "./shift-decisions.mjs";
|
|
4
|
+
//#region src/domain/shift/shift-report.ts
|
|
5
|
+
const iso = (value) => value == null ? null : new Date(value).toISOString();
|
|
6
|
+
/** Orders that count as sales: everything except cancelled/voided ones. */
|
|
7
|
+
/** Typed against the order kernel's statuses, so a misspelt status is a compile error, not a sale. */
|
|
8
|
+
const NOT_A_SALE = /* @__PURE__ */ new Set(["canceled"]);
|
|
9
|
+
const counts = (order) => !order.status || !NOT_A_SALE.has(order.status);
|
|
10
|
+
function buildShiftReport(shift, orders, options = {}) {
|
|
11
|
+
const sold = orders.filter(counts);
|
|
12
|
+
const sum = (pick) => sold.reduce((total, o) => total + pick(o), 0);
|
|
13
|
+
const items = /* @__PURE__ */ new Map();
|
|
14
|
+
for (const order of sold) for (const line of order.lines) {
|
|
15
|
+
const name = line.snapshot?.name ?? line.snapshot?.sku ?? "Item";
|
|
16
|
+
const key = line.snapshot?.sku ?? name;
|
|
17
|
+
const item = items.get(key) ?? {
|
|
18
|
+
name,
|
|
19
|
+
quantity: 0,
|
|
20
|
+
total: 0
|
|
21
|
+
};
|
|
22
|
+
item.quantity += line.quantity;
|
|
23
|
+
item.total += line.lineTotal?.amount ?? 0;
|
|
24
|
+
items.set(key, item);
|
|
25
|
+
}
|
|
26
|
+
const cashiers = /* @__PURE__ */ new Map();
|
|
27
|
+
for (const order of sold) {
|
|
28
|
+
const cashier = order.metadata?.cashierName ?? order.actorRef ?? "Unknown";
|
|
29
|
+
const entry = cashiers.get(cashier) ?? {
|
|
30
|
+
cashier,
|
|
31
|
+
count: 0,
|
|
32
|
+
net: 0
|
|
33
|
+
};
|
|
34
|
+
entry.count += 1;
|
|
35
|
+
entry.net += order.totals.grandTotal.amount;
|
|
36
|
+
cashiers.set(cashier, entry);
|
|
37
|
+
}
|
|
38
|
+
const moves = /* @__PURE__ */ new Map();
|
|
39
|
+
for (const move of shift.cashMovements ?? []) {
|
|
40
|
+
const key = `${move.type}:${move.reasonCode}`;
|
|
41
|
+
const entry = moves.get(key) ?? {
|
|
42
|
+
type: move.type,
|
|
43
|
+
reasonCode: move.reasonCode,
|
|
44
|
+
count: 0,
|
|
45
|
+
total: 0
|
|
46
|
+
};
|
|
47
|
+
entry.count += 1;
|
|
48
|
+
entry.total += move.amount;
|
|
49
|
+
moves.set(key, entry);
|
|
50
|
+
}
|
|
51
|
+
const cashRow = shift.paymentBreakdown.find(isCashRow);
|
|
52
|
+
return {
|
|
53
|
+
kind: isFinalShiftState(shift.state) ? "Z" : "X",
|
|
54
|
+
shiftId: shift._id,
|
|
55
|
+
registerId: shift.registerId,
|
|
56
|
+
openedAt: iso(shift.openedAt),
|
|
57
|
+
closedAt: iso(shift.closedAt),
|
|
58
|
+
openedBy: shift.openingCashierName,
|
|
59
|
+
closedBy: shift.closingCashierName ?? null,
|
|
60
|
+
sales: {
|
|
61
|
+
count: sold.length,
|
|
62
|
+
gross: sum((o) => o.totals.subtotal.amount),
|
|
63
|
+
discounts: sum((o) => o.totals.discount?.amount ?? 0),
|
|
64
|
+
taxAdded: sum((o) => o.taxBreakdown?.priceBasis === "inclusive" ? 0 : o.totals.tax?.amount ?? 0),
|
|
65
|
+
taxIncluded: sum((o) => o.taxBreakdown?.priceBasis === "inclusive" ? o.taxBreakdown.totals.taxMinor : 0),
|
|
66
|
+
unrated: sold.filter((o) => !o.taxBreakdown).length,
|
|
67
|
+
net: sum((o) => o.totals.grandTotal.amount)
|
|
68
|
+
},
|
|
69
|
+
refunds: {
|
|
70
|
+
count: shift.refundCount,
|
|
71
|
+
total: shift.refundTotal
|
|
72
|
+
},
|
|
73
|
+
payments: shift.paymentBreakdown.filter((row) => row.salesAmount !== 0 || row.refundAmount !== 0).map((row) => ({
|
|
74
|
+
method: row.method,
|
|
75
|
+
sales: row.salesAmount,
|
|
76
|
+
refunds: row.refundAmount,
|
|
77
|
+
net: row.salesAmount - row.refundAmount
|
|
78
|
+
})),
|
|
79
|
+
cash: {
|
|
80
|
+
opening: cashRow?.openingAmount ?? 0,
|
|
81
|
+
sales: cashRow?.salesAmount ?? 0,
|
|
82
|
+
refunds: cashRow?.refundAmount ?? 0,
|
|
83
|
+
paidIn: cashRow?.cashInAmount ?? 0,
|
|
84
|
+
paidOut: cashRow?.cashOutAmount ?? 0,
|
|
85
|
+
expected: cashRow ? cashRow.expectedAmount ?? computeExpected(cashRow) : 0,
|
|
86
|
+
counted: cashRow?.countedAmount ?? null,
|
|
87
|
+
difference: cashRow?.difference ?? null
|
|
88
|
+
},
|
|
89
|
+
cashMoves: [...moves.values()],
|
|
90
|
+
topItems: [...items.values()].sort((a, b) => b.total - a.total || b.quantity - a.quantity).slice(0, options.topItems ?? 10),
|
|
91
|
+
byCashier: [...cashiers.values()].sort((a, b) => b.net - a.net)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
//#endregion
|
|
95
|
+
export { buildShiftReport };
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { ShiftState } from "../enums/shift-state.enum.mjs";
|
|
2
|
+
import { ClosedBy } from "../enums/closed-by.enum.mjs";
|
|
3
|
+
import { CashMovement } from "../value-objects/cash-movement.vo.mjs";
|
|
4
|
+
import { PaymentBreakdown } from "../value-objects/payment-breakdown.vo.mjs";
|
|
5
|
+
import { ShiftPolicy } from "../value-objects/shift-policy.vo.mjs";
|
|
6
|
+
import { ApprovalChain } from "@classytic/primitives/approval";
|
|
7
|
+
//#region src/domain/shift/shift.types.d.ts
|
|
8
|
+
export type PendingLedgerPostTrigger = 'close' | 'forceClose';
|
|
9
|
+
/**
|
|
10
|
+
* The ledger post a close OWES: stamped in the CAS that ends the shift, before the bridge runs, and
|
|
11
|
+
* cleared when its `journalEntryId` is recorded. Present ⇒ a retried close re-posts with the same
|
|
12
|
+
* key instead of posting twice.
|
|
13
|
+
*/
|
|
14
|
+
export interface PendingLedgerPost {
|
|
15
|
+
/** Deterministic — `pos:shift:<shiftId>:close`. Never regenerated. */
|
|
16
|
+
idempotencyKey: string;
|
|
17
|
+
trigger: PendingLedgerPostTrigger;
|
|
18
|
+
/**
|
|
19
|
+
* Post attempts started. Incremented by a guarded CAS on the resume path,
|
|
20
|
+
* so two concurrent resumers cannot both enter the bridge for the same
|
|
21
|
+
* attempt (the deterministic key is the second line of defence).
|
|
22
|
+
*/
|
|
23
|
+
attempts: number;
|
|
24
|
+
stampedAt: Date;
|
|
25
|
+
lastAttemptAt: Date | null;
|
|
26
|
+
/**
|
|
27
|
+
* True once the pipeline emitted the shift's lifecycle event
|
|
28
|
+
* (`pos:shift.closed` / `pos:shift.force_closed`). The resume path checks
|
|
29
|
+
* it so converging a crashed close re-emits the event the crashed run
|
|
30
|
+
* never sent, without double-emitting for a `forceClose` whose orphan
|
|
31
|
+
* already landed and announced itself.
|
|
32
|
+
*/
|
|
33
|
+
announced: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* True when the close committed together with its durable `pos:shift.closed` row (`ledgerPost: 'deferred'`):
|
|
36
|
+
* that row's delivery posts the entry, so a retried close reports it pending instead of posting inline.
|
|
37
|
+
*/
|
|
38
|
+
durable?: boolean;
|
|
39
|
+
}
|
|
40
|
+
export interface IShift {
|
|
41
|
+
/** Tenant scope (organizationId / branchId). Type set by tenant config. */
|
|
42
|
+
organizationId: unknown;
|
|
43
|
+
/**
|
|
44
|
+
* Register / terminal id within the branch. Hosts that have only one
|
|
45
|
+
* register per branch can pass a constant string. Unique-active-shift is
|
|
46
|
+
* enforced per (organizationId, registerId).
|
|
47
|
+
*/
|
|
48
|
+
registerId: string;
|
|
49
|
+
/** Business day this shift belongs to (host's local TZ; YYYY-MM-DD UTC midnight). */
|
|
50
|
+
businessDate: Date;
|
|
51
|
+
state: ShiftState;
|
|
52
|
+
openingCashierId: string;
|
|
53
|
+
openingCashierName: string;
|
|
54
|
+
endingCashierId: string | null;
|
|
55
|
+
endingCashierName: string | null;
|
|
56
|
+
closingCashierId: string | null;
|
|
57
|
+
closingCashierName: string | null;
|
|
58
|
+
teamMemberIds: string[];
|
|
59
|
+
openedAt: Date;
|
|
60
|
+
pausedAt: Date | null;
|
|
61
|
+
resumedAt: Date | null;
|
|
62
|
+
blindClosedAt: Date | null;
|
|
63
|
+
closedAt: Date | null;
|
|
64
|
+
openingCash: number;
|
|
65
|
+
expectedCash: number | null;
|
|
66
|
+
countedCash: number | null;
|
|
67
|
+
cashDifference: number | null;
|
|
68
|
+
paymentBreakdown: PaymentBreakdown[];
|
|
69
|
+
salesCount: number;
|
|
70
|
+
salesTotal: number;
|
|
71
|
+
refundCount: number;
|
|
72
|
+
refundTotal: number;
|
|
73
|
+
cashMovements: CashMovement[];
|
|
74
|
+
/**
|
|
75
|
+
* Approval chain — primitives' `ApprovalChain` (PACKAGE_RULES §P7:
|
|
76
|
+
* canonical field name is `approvals`; never build a parallel
|
|
77
|
+
* review-workflow shape). On a Shift document this carries the
|
|
78
|
+
* **variance approval** — the single-step `ApprovalChain` constructed
|
|
79
|
+
* when a manager overrides a variance during close, or any multi-step
|
|
80
|
+
* chain a host attaches via a future `approvals` input on
|
|
81
|
+
* `CloseShiftInput`. Null when no variance override / no chain attached.
|
|
82
|
+
*
|
|
83
|
+
* Renamed from `varianceApproval` (2026-05-06) to align with P7.
|
|
84
|
+
*/
|
|
85
|
+
approvals: ApprovalChain | null;
|
|
86
|
+
/** Policy frozen at open time. Reconciliation reads from here, never live. */
|
|
87
|
+
policySnapshot: ShiftPolicy;
|
|
88
|
+
closedBy: ClosedBy | null;
|
|
89
|
+
notes: string;
|
|
90
|
+
/** Set by the close pipeline after the ledger bridge returns the JE id. */
|
|
91
|
+
journalEntryId: string | null;
|
|
92
|
+
/**
|
|
93
|
+
* Non-null ⇒ a close won the CAS and the ledger post is not yet recorded.
|
|
94
|
+
* See {@link PendingLedgerPost}. Null on every shift that never had a
|
|
95
|
+
* ledger bridge wired, and on every close whose post completed.
|
|
96
|
+
*/
|
|
97
|
+
pendingLedgerPost: PendingLedgerPost | null;
|
|
98
|
+
/** Soft-delete tombstone (softDeletePlugin). Null when live. */
|
|
99
|
+
deletedAt?: Date | null;
|
|
100
|
+
createdAt?: Date;
|
|
101
|
+
updatedAt?: Date;
|
|
102
|
+
}
|
|
103
|
+
/** A stored shift as a port receives it — its fields and its id, never a database document. */
|
|
104
|
+
export type ShiftRecord = IShift & {
|
|
105
|
+
readonly _id: {
|
|
106
|
+
toString(): string;
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
//#endregion
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { ShiftState } from "../enums/shift-state.enum.mjs";
|
|
2
2
|
//#region src/domain/state-machines/shift.fsm.d.ts
|
|
3
3
|
/** Domain verbs that drive transitions. */
|
|
4
|
-
declare const SHIFT_VERBS: readonly ['pause', 'resume', 'blindClose', 'close', 'forceClose'];
|
|
5
|
-
type ShiftVerb = (typeof SHIFT_VERBS)[number];
|
|
4
|
+
export declare const SHIFT_VERBS: readonly ['pause', 'resume', 'blindClose', 'close', 'forceClose'];
|
|
5
|
+
export type ShiftVerb = (typeof SHIFT_VERBS)[number];
|
|
6
6
|
/** Resolve the target state for a verb from a given state, or `null` if disallowed. */
|
|
7
|
-
declare function nextState(from: ShiftState, verb: ShiftVerb): ShiftState | null;
|
|
7
|
+
export declare function nextState(from: ShiftState, verb: ShiftVerb): ShiftState | null;
|
|
8
8
|
/** Predicate for guards. */
|
|
9
|
-
declare function canTransition(from: ShiftState, verb: ShiftVerb): boolean;
|
|
9
|
+
export declare function canTransition(from: ShiftState, verb: ShiftVerb): boolean;
|
|
10
10
|
/** All verbs valid from the given state — useful for UI affordance. */
|
|
11
|
-
declare function allowedVerbs(from: ShiftState): readonly ShiftVerb[];
|
|
12
|
-
//#endregion
|
|
13
|
-
export { SHIFT_VERBS, ShiftVerb, allowedVerbs, canTransition, nextState };
|
|
11
|
+
export declare function allowedVerbs(from: ShiftState): readonly ShiftVerb[];
|
|
12
|
+
//#endregion
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CashMovementReasonCode } from "../enums/cash-movement-reason.enum.mjs";
|
|
2
2
|
//#region src/domain/value-objects/cash-movement.vo.d.ts
|
|
3
|
-
interface CashMovement {
|
|
3
|
+
export interface CashMovement {
|
|
4
4
|
/** in: money added to drawer (top-up, return); out: money removed (drop, withdrawal). */
|
|
5
5
|
type: 'in' | 'out';
|
|
6
6
|
/** Always positive minor units (e.g. paisa). Direction lives in `type`. */
|
|
@@ -13,6 +13,10 @@ interface CashMovement {
|
|
|
13
13
|
cashierName: string;
|
|
14
14
|
/** When the movement happened — set at construction. */
|
|
15
15
|
timestamp: Date;
|
|
16
|
+
/**
|
|
17
|
+
* The client's key for this movement (one per Cash In/Out action, re-sent on retry). In the
|
|
18
|
+
* write's FILTER: a movement under a booked key is never recorded — or counted in the drawer — twice.
|
|
19
|
+
*/
|
|
20
|
+
movementKey?: string;
|
|
16
21
|
}
|
|
17
|
-
//#endregion
|
|
18
|
-
export { CashMovement };
|
|
22
|
+
//#endregion
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ShiftPaymentMethod } from "../enums/payment-method.enum.mjs";
|
|
2
2
|
import { PaymentMethodKind } from "@classytic/primitives/payment-method-kind";
|
|
3
3
|
//#region src/domain/value-objects/payment-breakdown.vo.d.ts
|
|
4
|
-
interface PaymentBreakdown {
|
|
4
|
+
export interface PaymentBreakdown {
|
|
5
5
|
/** Deployment/provider-specific method code (open string). */
|
|
6
6
|
method: ShiftPaymentMethod;
|
|
7
7
|
/** Universal category for reconciliation/reporting (resolved from the code). */
|
|
@@ -20,8 +20,7 @@ interface PaymentBreakdown {
|
|
|
20
20
|
difference: number | null;
|
|
21
21
|
}
|
|
22
22
|
/** Pure compute — `expectedAmount` from inputs. Lives in VO so tests don't need a DB. */
|
|
23
|
-
declare function computeExpected(b: Pick<PaymentBreakdown, 'openingAmount' | 'salesAmount' | 'refundAmount' | 'cashInAmount' | 'cashOutAmount'>): number;
|
|
23
|
+
export declare function computeExpected(b: Pick<PaymentBreakdown, 'openingAmount' | 'salesAmount' | 'refundAmount' | 'cashInAmount' | 'cashOutAmount'>): number;
|
|
24
24
|
/** Pure compute — variance from a counted reading. Returns null if counted is null. */
|
|
25
|
-
declare function computeDifference(expected: number, counted: number | null): number | null;
|
|
26
|
-
//#endregion
|
|
27
|
-
export { PaymentBreakdown, computeDifference, computeExpected };
|
|
25
|
+
export declare function computeDifference(expected: number, counted: number | null): number | null;
|
|
26
|
+
//#endregion
|
|
@@ -2,7 +2,7 @@ import { ShiftPaymentMethod } from "../enums/payment-method.enum.mjs";
|
|
|
2
2
|
import { CashMovementReasonCode } from "../enums/cash-movement-reason.enum.mjs";
|
|
3
3
|
import { PaymentMethodKind } from "@classytic/primitives/payment-method-kind";
|
|
4
4
|
//#region src/domain/value-objects/shift-policy.vo.d.ts
|
|
5
|
-
interface ShiftPolicy {
|
|
5
|
+
export interface ShiftPolicy {
|
|
6
6
|
/** Null = cashier chooses opening float. Number = required exact match at open. */
|
|
7
7
|
requiredOpeningFloat: number | null;
|
|
8
8
|
/** Lightspeed-style — cashier blind-counts, manager reconciles. */
|
|
@@ -17,8 +17,8 @@ interface ShiftPolicy {
|
|
|
17
17
|
allowHandover: boolean;
|
|
18
18
|
/** Shopify 2025: require reason code on every cash-in / cash-out. */
|
|
19
19
|
requireReasonCode: boolean;
|
|
20
|
-
/**
|
|
21
|
-
allowedReasonCodes: readonly CashMovementReasonCode[];
|
|
20
|
+
/** Reason codes valid at this branch, or `'*'` for any. `[]` is refused, never read as "any". */
|
|
21
|
+
allowedReasonCodes: readonly CashMovementReasonCode[] | '*';
|
|
22
22
|
/**
|
|
23
23
|
* Method CODES accepted at this branch — the closed table for the shift. Any
|
|
24
24
|
* open string (baseline `cash`/`card`/… or provider codes `bkash`/`nagad`/…).
|
|
@@ -49,12 +49,16 @@ interface ShiftPolicy {
|
|
|
49
49
|
* Per-branch variation belongs in DATA, resolved through the policy bridge —
|
|
50
50
|
* not in a second literal.
|
|
51
51
|
*/
|
|
52
|
-
declare function defaultShiftPolicy(overrides?: Partial<ShiftPolicy>): ShiftPolicy;
|
|
52
|
+
export declare function defaultShiftPolicy(overrides?: Partial<ShiftPolicy>): ShiftPolicy;
|
|
53
53
|
/**
|
|
54
54
|
* Variance check — pure function so tests don't need a shift document.
|
|
55
55
|
* Returns `withinThreshold: true` if EITHER bound is satisfied (whichever is
|
|
56
56
|
* looser). Threshold semantics: a |diff| of exactly threshold is permitted.
|
|
57
57
|
*/
|
|
58
|
-
declare function isWithinVarianceThreshold(difference: number, expected: number, policy: Pick<ShiftPolicy, 'varianceThresholdAbs' | 'varianceThresholdPct'>): boolean;
|
|
59
|
-
|
|
60
|
-
|
|
58
|
+
export declare function isWithinVarianceThreshold(difference: number, expected: number, policy: Pick<ShiftPolicy, 'varianceThresholdAbs' | 'varianceThresholdPct'>): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* May a cash movement carry `code` under this policy? `'*'` allows any code; a
|
|
61
|
+
* list allows its members; an EMPTY list throws `ReasonCodePolicyInvalidError`.
|
|
62
|
+
*/
|
|
63
|
+
export declare function isReasonCodeAllowed(policy: Pick<ShiftPolicy, 'allowedReasonCodes'>, code: CashMovementReasonCode): boolean;
|
|
64
|
+
//#endregion
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ReasonCodePolicyInvalidError } from "../errors/pos.errors.mjs";
|
|
1
2
|
import { CASH_MOVEMENT_REASON_CODES } from "../enums/cash-movement-reason.enum.mjs";
|
|
2
3
|
import { SHIFT_PAYMENT_METHODS } from "../enums/payment-method.enum.mjs";
|
|
3
4
|
//#region src/domain/value-objects/shift-policy.vo.ts
|
|
@@ -44,5 +45,15 @@ function isWithinVarianceThreshold(difference, expected, policy) {
|
|
|
44
45
|
if (expected <= 0) return false;
|
|
45
46
|
return abs <= policy.varianceThresholdPct / 100 * expected;
|
|
46
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* May a cash movement carry `code` under this policy? `'*'` allows any code; a
|
|
50
|
+
* list allows its members; an EMPTY list throws `ReasonCodePolicyInvalidError`.
|
|
51
|
+
*/
|
|
52
|
+
function isReasonCodeAllowed(policy, code) {
|
|
53
|
+
const allowed = policy.allowedReasonCodes;
|
|
54
|
+
if (allowed === "*") return true;
|
|
55
|
+
if (allowed.length === 0) throw new ReasonCodePolicyInvalidError();
|
|
56
|
+
return allowed.includes(code);
|
|
57
|
+
}
|
|
47
58
|
//#endregion
|
|
48
|
-
export { defaultShiftPolicy, isWithinVarianceThreshold };
|
|
59
|
+
export { defaultShiftPolicy, isReasonCodeAllowed, isWithinVarianceThreshold };
|
|
@@ -4,6 +4,5 @@ import { PosBlueprint, PosShape } from "./engine-types.mjs";
|
|
|
4
4
|
* Describe the POS engine. Pure — registers no model, builds no schema,
|
|
5
5
|
* performs no I/O.
|
|
6
6
|
*/
|
|
7
|
-
declare function definePos(shape: PosShape): PosBlueprint;
|
|
8
|
-
//#endregion
|
|
9
|
-
export { definePos };
|
|
7
|
+
export declare function definePos(shape: PosShape): PosBlueprint;
|
|
8
|
+
//#endregion
|
|
@@ -4,6 +4,7 @@ import { resolvePosTenant } from "../models/inject-tenant.mjs";
|
|
|
4
4
|
import { definePosModels } from "../models/create-models.mjs";
|
|
5
5
|
import { RegisterRepository } from "../repositories/register.repository.mjs";
|
|
6
6
|
import { ShiftRepository } from "../repositories/shift.repository.mjs";
|
|
7
|
+
import { TillGrantRepository } from "../repositories/till-grant.repository.mjs";
|
|
7
8
|
import { multiTenantPlugin, transactionResolutionOf } from "@classytic/mongokit";
|
|
8
9
|
import { assertNoLegacyTenantKeys } from "@classytic/repo-core/tenant";
|
|
9
10
|
//#region src/engine/define-pos.ts
|
|
@@ -49,6 +50,9 @@ function definePos(shape) {
|
|
|
49
50
|
* — it is about the STORE's contract, and `allowNonTransactional` does not waive it.
|
|
50
51
|
*/
|
|
51
52
|
if (runtime.outbox && runtime.outbox.transactionalSave !== true) throw new PosCapabilityError(["outbox.transactionalSave (the configured OutboxStore does not declare that save() enlists ctx.session — see @classytic/primitives/outbox)"]);
|
|
53
|
+
const ledgerPost = runtime.ledgerPost ?? "inline";
|
|
54
|
+
if (ledgerPost !== "inline" && ledgerPost !== "deferred") throw new PosCapabilityError([`ledgerPost must be 'inline' or 'deferred', got ${String(ledgerPost)}`]);
|
|
55
|
+
if (ledgerPost === "deferred" && !runtime.outbox) throw new PosCapabilityError(["an outbox (ledgerPost: 'deferred' commits the close with a durable event row; without an outbox the owed post has no delivery)"]);
|
|
52
56
|
const models = modelBlueprint.bind(connection);
|
|
53
57
|
const logger = runtime.logger ?? console;
|
|
54
58
|
const bridges = runtime.bridges ?? {};
|
|
@@ -72,6 +76,8 @@ function definePos(shape) {
|
|
|
72
76
|
...bridges.notification ? { notificationBridge: bridges.notification } : {},
|
|
73
77
|
eventTransport: events,
|
|
74
78
|
...runtime.outbox ? { outbox: runtime.outbox } : {},
|
|
79
|
+
ledgerPost,
|
|
80
|
+
allowNonTransactional,
|
|
75
81
|
logger
|
|
76
82
|
});
|
|
77
83
|
const registerRepo = new RegisterRepository({
|
|
@@ -96,7 +102,8 @@ function definePos(shape) {
|
|
|
96
102
|
collectionPrefix: shape.collectionPrefix,
|
|
97
103
|
autoIndex: shape.autoIndex,
|
|
98
104
|
forceRecreate: shape.forceRecreate ?? false,
|
|
99
|
-
allowNonTransactional
|
|
105
|
+
allowNonTransactional,
|
|
106
|
+
ledgerPost
|
|
100
107
|
});
|
|
101
108
|
let closed = false;
|
|
102
109
|
return Object.freeze({
|
|
@@ -107,7 +114,11 @@ function definePos(shape) {
|
|
|
107
114
|
models,
|
|
108
115
|
repositories: {
|
|
109
116
|
shift: shiftRepo,
|
|
110
|
-
register: registerRepo
|
|
117
|
+
register: registerRepo,
|
|
118
|
+
tillGrant: new TillGrantRepository({
|
|
119
|
+
model: models.TillGrant,
|
|
120
|
+
plugins: tenantPlugins
|
|
121
|
+
})
|
|
111
122
|
},
|
|
112
123
|
defaultPolicy,
|
|
113
124
|
async syncIndexes() {
|
|
@@ -5,12 +5,13 @@ import { NotificationBridge } from "../domain/ports/notification.bridge.mjs";
|
|
|
5
5
|
import { PosModels } from "../models/create-models.mjs";
|
|
6
6
|
import { RegisterRepository } from "../repositories/register.repository.mjs";
|
|
7
7
|
import { ShiftRepository } from "../repositories/shift.repository.mjs";
|
|
8
|
+
import { TillGrantRepository } from "../repositories/till-grant.repository.mjs";
|
|
8
9
|
import { TenantConfig } from "@classytic/repo-core/tenant";
|
|
9
10
|
import { Connection } from "mongoose";
|
|
10
11
|
import { EventTransport } from "@classytic/primitives/events";
|
|
11
12
|
import { OutboxStore } from "@classytic/primitives/outbox";
|
|
12
13
|
//#region src/engine/engine-types.d.ts
|
|
13
|
-
interface PosBridges {
|
|
14
|
+
export interface PosBridges {
|
|
14
15
|
/**
|
|
15
16
|
* Ledger bridge — host implements `onShiftClosed(shift, ctx)` to emit a
|
|
16
17
|
* JournalEntry and return the resulting `journalEntryId`. Without this
|
|
@@ -23,7 +24,7 @@ interface PosBridges {
|
|
|
23
24
|
/** Variance + orphan-close notifications. Best-effort; failures don't block state. */
|
|
24
25
|
notification?: NotificationBridge;
|
|
25
26
|
}
|
|
26
|
-
interface PosLogger {
|
|
27
|
+
export interface PosLogger {
|
|
27
28
|
error(message: string, ...args: unknown[]): void;
|
|
28
29
|
}
|
|
29
30
|
/**
|
|
@@ -31,7 +32,7 @@ interface PosLogger {
|
|
|
31
32
|
* no connection or I/O to inspect. Nothing here opens a socket or reads a
|
|
32
33
|
* secret — safe to call at import / module-composition time.
|
|
33
34
|
*/
|
|
34
|
-
interface PosShape {
|
|
35
|
+
export interface PosShape {
|
|
35
36
|
/** Default shift policy when neither `bridges.policy` nor a per-call override is supplied. */
|
|
36
37
|
defaultPolicy: ShiftPolicy;
|
|
37
38
|
/** Canonical persistence tenancy. Default `true`. */
|
|
@@ -58,7 +59,7 @@ interface PosShape {
|
|
|
58
59
|
* outbox, logger or host bridge belongs here, not in the shape — each is a
|
|
59
60
|
* runtime collaborator (may perform I/O, may be shared infrastructure).
|
|
60
61
|
*/
|
|
61
|
-
interface PosRuntime {
|
|
62
|
+
export interface PosRuntime {
|
|
62
63
|
/** Bridges — every method is opt-in; the package degrades gracefully without them. */
|
|
63
64
|
bridges?: PosBridges | undefined;
|
|
64
65
|
/** Inject your own event bus; otherwise an in-process bus is created (and owned). */
|
|
@@ -83,6 +84,17 @@ interface PosRuntime {
|
|
|
83
84
|
* standalone-Mongo local dev where transactions are absent.
|
|
84
85
|
*/
|
|
85
86
|
allowNonTransactional?: boolean | undefined;
|
|
87
|
+
/**
|
|
88
|
+
* Where a close's journal entry posts.
|
|
89
|
+
*
|
|
90
|
+
* - `'inline'` (default): the ledger bridge runs inside `close` / `forceClose`; a bridge failure rolls the close
|
|
91
|
+
* back (`close`) or keeps the marker (`forceClose`).
|
|
92
|
+
* - `'deferred'`: the close commits the shift, its `pendingLedgerPost` marker and a DURABLE `pos:shift.closed` /
|
|
93
|
+
* `pos:shift.force_closed` row (fixed id per shift) in ONE unit of work and answers; the host's subscriber to
|
|
94
|
+
* that event calls `shift.postPendingLedger(shiftId)`, which posts under the same idempotency key. A failed post
|
|
95
|
+
* is the subscriber's failure (the outbox failure policy), never a rolled-back close. Requires `outbox`.
|
|
96
|
+
*/
|
|
97
|
+
ledgerPost?: 'inline' | 'deferred' | undefined;
|
|
86
98
|
/** Custom logger; defaults to `console`. */
|
|
87
99
|
logger?: PosLogger | undefined;
|
|
88
100
|
}
|
|
@@ -90,7 +102,7 @@ interface PosRuntime {
|
|
|
90
102
|
* The immutable, resolved describe+bind configuration surfaced on the engine
|
|
91
103
|
* (`engine.config`). Excludes the live connection and secrets.
|
|
92
104
|
*/
|
|
93
|
-
interface ResolvedPosConfig {
|
|
105
|
+
export interface ResolvedPosConfig {
|
|
94
106
|
readonly defaultPolicy: ShiftPolicy;
|
|
95
107
|
readonly tenant: import('@classytic/repo-core/tenant').ResolvedTenantConfig;
|
|
96
108
|
readonly softDelete: false | {
|
|
@@ -100,12 +112,15 @@ interface ResolvedPosConfig {
|
|
|
100
112
|
readonly autoIndex: boolean | undefined;
|
|
101
113
|
readonly forceRecreate: boolean;
|
|
102
114
|
readonly allowNonTransactional: boolean;
|
|
115
|
+
readonly ledgerPost: 'inline' | 'deferred';
|
|
103
116
|
}
|
|
104
|
-
interface PosRepositories {
|
|
117
|
+
export interface PosRepositories {
|
|
105
118
|
shift: ShiftRepository;
|
|
106
119
|
register: RegisterRepository;
|
|
120
|
+
/** Grants issued to paired tills. */
|
|
121
|
+
tillGrant: TillGrantRepository;
|
|
107
122
|
}
|
|
108
|
-
interface PosEngine {
|
|
123
|
+
export interface PosEngine {
|
|
109
124
|
readonly config: ResolvedPosConfig;
|
|
110
125
|
readonly bridges: Readonly<PosBridges>;
|
|
111
126
|
readonly events: EventTransport;
|
|
@@ -125,7 +140,7 @@ interface PosEngine {
|
|
|
125
140
|
*/
|
|
126
141
|
close(): Promise<void>;
|
|
127
142
|
}
|
|
128
|
-
interface PosBlueprint {
|
|
143
|
+
export interface PosBlueprint {
|
|
129
144
|
readonly id: 'pos';
|
|
130
145
|
/** The model names this blueprint registers — known without a connection. */
|
|
131
146
|
readonly modelNames: readonly string[];
|
|
@@ -137,4 +152,4 @@ interface PosBlueprint {
|
|
|
137
152
|
bind(connection: Connection, runtime?: PosRuntime): PosEngine;
|
|
138
153
|
}
|
|
139
154
|
//#endregion
|
|
140
|
-
export {
|
|
155
|
+
export type { PosModels };
|
package/dist/engine/index.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { definePos };
|
|
1
|
+
export { definePos } from "./define-pos.mjs";
|