@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.
Files changed (71) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/commands/index.d.mts +2 -0
  3. package/dist/commands/index.mjs +1 -0
  4. package/dist/commands/pos-commands.d.mts +228 -0
  5. package/dist/commands/pos-commands.mjs +355 -0
  6. package/dist/domain/enums/cash-movement-reason.enum.d.mts +3 -4
  7. package/dist/domain/enums/closed-by.enum.d.mts +3 -4
  8. package/dist/domain/enums/payment-method.enum.d.mts +6 -7
  9. package/dist/domain/enums/shift-state.enum.d.mts +7 -8
  10. package/dist/domain/errors/pos.errors.d.mts +82 -13
  11. package/dist/domain/errors/pos.errors.mjs +111 -1
  12. package/dist/domain/index.d.mts +11 -3
  13. package/dist/domain/index.mjs +10 -3
  14. package/dist/domain/ports/common.d.mts +2 -3
  15. package/dist/domain/ports/ledger.bridge.d.mts +6 -7
  16. package/dist/domain/ports/notification.bridge.d.mts +5 -6
  17. package/dist/domain/ports/policy.bridge.d.mts +2 -3
  18. package/dist/domain/sale/discount.d.mts +62 -0
  19. package/dist/domain/sale/discount.mjs +58 -0
  20. package/dist/domain/sale/price-override.d.mts +51 -0
  21. package/dist/domain/sale/price-override.mjs +51 -0
  22. package/dist/domain/sale/quick-cash.d.mts +10 -0
  23. package/dist/domain/sale/quick-cash.mjs +27 -0
  24. package/dist/domain/sale/service-line.d.mts +7 -0
  25. package/dist/domain/sale/service-line.mjs +10 -0
  26. package/dist/domain/sale/tender.d.mts +256 -0
  27. package/dist/domain/sale/tender.mjs +242 -0
  28. package/dist/domain/shift/shift-decisions.d.mts +52 -0
  29. package/dist/domain/shift/shift-decisions.mjs +93 -0
  30. package/dist/domain/shift/shift-report.d.mts +127 -0
  31. package/dist/domain/shift/shift-report.mjs +95 -0
  32. package/dist/domain/shift/shift.types.d.mts +109 -0
  33. package/dist/domain/state-machines/shift.fsm.d.mts +6 -7
  34. package/dist/domain/value-objects/cash-movement.vo.d.mts +7 -3
  35. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -5
  36. package/dist/domain/value-objects/shift-policy.vo.d.mts +11 -7
  37. package/dist/domain/value-objects/shift-policy.vo.mjs +12 -1
  38. package/dist/engine/define-pos.d.mts +2 -3
  39. package/dist/engine/define-pos.mjs +13 -2
  40. package/dist/engine/engine-types.d.mts +24 -9
  41. package/dist/engine/index.mjs +1 -2
  42. package/dist/events/event-catalog.d.mts +18 -14
  43. package/dist/events/event-catalog.mjs +10 -4
  44. package/dist/events/event-constants.d.mts +3 -4
  45. package/dist/events/event-payloads.d.mts +9 -10
  46. package/dist/events/helpers.d.mts +6 -3
  47. package/dist/events/helpers.mjs +12 -2
  48. package/dist/events/in-process-bus.d.mts +3 -4
  49. package/dist/events/index.mjs +1 -1
  50. package/dist/grant/till-grant.d.mts +50 -0
  51. package/dist/grant/till-grant.mjs +47 -0
  52. package/dist/index.d.mts +14 -4
  53. package/dist/index.mjs +12 -4
  54. package/dist/models/create-models.d.mts +10 -6
  55. package/dist/models/create-models.mjs +16 -3
  56. package/dist/models/register.model.d.mts +7 -6
  57. package/dist/models/shift-sale-dedupe.model.d.mts +4 -5
  58. package/dist/models/shift.model.d.mts +4 -111
  59. package/dist/models/shift.model.mjs +26 -2
  60. package/dist/models/till-grant.model.d.mts +19 -0
  61. package/dist/models/till-grant.model.mjs +52 -0
  62. package/dist/repositories/register.repository.d.mts +3 -4
  63. package/dist/repositories/shift.repository.d.mts +77 -30
  64. package/dist/repositories/shift.repository.mjs +307 -108
  65. package/dist/repositories/till-grant.repository.d.mts +22 -0
  66. package/dist/repositories/till-grant.repository.mjs +41 -0
  67. package/dist/schemas/index.mjs +1 -2
  68. package/dist/schemas/shift.d.mts +9 -10
  69. package/dist/testing/fixtures.d.mts +4 -5
  70. package/dist/testing/index.mjs +1 -2
  71. package/package.json +50 -19
package/CHANGELOG.md CHANGED
@@ -1,5 +1,120 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.7.0] — 2026-10-18
4
+
5
+ ### Added — `PosRuntime.ledgerPost: 'deferred'`: the Z-report's entry posts off the request
6
+ - `'inline'` (default) is unchanged. `'deferred'` makes `close` / `forceClose` commit the CAS, the `pendingLedgerPost`
7
+ marker (`durable: true`) and a DURABLE `pos:shift.closed` / `pos:shift.force_closed` row — fixed id
8
+ `${name}:v1:${shiftId}` — in ONE unit of work (`dispatchDomainEvent`, `@classytic/primitives/durable-events`), then answer
9
+ `ledgerPending: true`. Requires an `outbox` (refused at bind otherwise).
10
+ - `repositories.shift.postPendingLedger(shiftId)` is the delivery's verb: it posts under the marker's own key, records the
11
+ entry, and THROWS on a bridge failure so the outbox retries; a delivery with no marker does nothing.
12
+ - `CloseShiftResult.ledgerPending`. A retried `close` of a shift whose durable post is owed reports it and never posts inline.
13
+ - `shiftClosedEvent` / `shiftForceClosedEvent` are `durability: 'durable'` with `occurrence = shiftId`; inline mode writes the same fixed id.
14
+ - Peer `@classytic/primitives` is now `>=0.31.0` (`./durable-events`). Pinned by `tests/integration/deferred-ledger-post.scenario.test.ts`.
15
+
16
+ ### Added — `./grant`: the till's offline grant
17
+ `TillGrant` — branch, register, the branch's `ShiftPolicy`, `OrderDiscountLimits` and the counter-sale rule,
18
+ signed by the deployment; its `iat` is the signed checkpoint. `readTillGrant(token, keyOf, { sn })` reads only a
19
+ whole grant issued to that till. Browser-safe. `checkSaleAgainstGrant` names what a recorded sale did outside its
20
+ grant (discount over the ceiling, an unallowed full comp, made after expiry). The server records each grant it
21
+ issues (`repositories.tillGrant`, model `TillGrant` → `pos_till_grants`, kept 90 days past expiry). Pinned by `tests/unit/till-grant.test.ts` (the device check
22
+ is falsified).
23
+
24
+ ### ⚠ Changed — a sale takes stock from `stock/<productId>`, and keeps it until the server's count does
25
+ - Stock lives in its own document, `RecordableStock`: the shape a server publishes to tills, and
26
+ the till's own in free mode. A sale's writes go to `stock`, never to `products`.
27
+ `RecordedSale.stock` lists tracked goods only. `takeFromStock(current, productId, variantSku,
28
+ quantity)` starts from zero when there is no document. A count may go negative.
29
+ - `pos.sale` gains `pending`. Once the server has recorded the sale, its stock still leaves the
30
+ shelf on the device until the order's `metadata.stockIssue` is `posted`. A `failed` issue keeps
31
+ the subtraction.
32
+ - `RecordableProduct` is removed.
33
+
34
+ ### Added — a guard: `./domain` and `./commands` stay browser-safe
35
+
36
+ The offline till bundles these two subpaths. `tests/unit/browser-safe.arch.test.ts` fails on any
37
+ runtime import beyond each other and `@classytic/primitives` (no database, no Node built-ins, no
38
+ server folders). Type-only imports may also name repo-core contracts; no server type is allowed
39
+ (the debt list is empty and must stay so). Both checks were broken on purpose to prove them.
40
+
41
+ ### ⚠ Changed — the ledger and notification ports take a `ShiftRecord`, not a Mongoose document
42
+
43
+ `IShift`, `PendingLedgerPost` and `PendingLedgerPostTrigger` move into `domain/shift/shift.types.ts`
44
+ (exported from the root and from `./domain`, under the same names). `ShiftRecord` is the shift's
45
+ fields plus an id. `LedgerBridge` and `NotificationBridge` now receive it instead of
46
+ `ShiftDocument`, so the browser-safe declarations no longer reference Mongoose. An implementation
47
+ that called a document method on the shift must read its fields instead; none in this repo did.
48
+
49
+ ### Added — `pos.customer.upsert` in the command pack
50
+
51
+ A customer the till created or changed, under its device id. On the reference server, a phone that
52
+ already belongs to another customer keeps that record (a real server aliases the till's id to it).
53
+ Refused ⇒ suppressed; sales keep their customer snapshot. `RecordableCustomer` is exported.
54
+
55
+ ### Added — `shift.open` takes a caller-minted `id` and `openedAt`
56
+
57
+ A shift opened offline keeps the till's id and the time its drawer opened, so the device and the
58
+ server name one shift. The register's one-open-shift rule is unchanged. Pinned by
59
+ `tests/integration/open-offline-shift.scenario.test.ts` (id falsified).
60
+
61
+ ### Added — the shift report (`@classytic/pos/domain`)
62
+
63
+ `buildShiftReport(shift, orders)` — X while the shift is open, Z once it is final: sales (gross,
64
+ discounts, tax added, tax included, net), refunds, the payment split and cash figures from the
65
+ drawer's own breakdown, cash moves by reason, top items and sales by cashier. One function, so a
66
+ server's report route and an offline till give the same figures for the same sales.
67
+
68
+ ### Added — shift decisions (`@classytic/pos/domain`)
69
+
70
+ `seedBreakdown`, `applyCounts`, `isCashRow`, `decideShiftClose`, `decideBlindClose`: the opening
71
+ breakdown, a count's effect, and whether a close may proceed (state machine, counts required from
72
+ `open`, variance gate) as pure functions. The repository persists their result (CAS, ledger and
73
+ events unchanged), and an offline till decides through the same functions.
74
+
75
+ ### Added — the sale rules (`@classytic/pos/domain`)
76
+
77
+ Moved here from `@spinekit/pos` so every till decides a sale the same way — the server and an
78
+ offline device alike:
79
+
80
+ - **Tender:** `validateTenderLegs`, `allocateTender` (tendered → applied → change; only APPLIED is
81
+ money), `assertTenderSettles`, `tenderSummary`, `createTenderMethodResolver`,
82
+ `DEFAULT_TENDER_METHOD_RESOLVER`, and the types `TenderPolicy`, `TenderMethodDeclaration`,
83
+ `PosTenderSummary`, …
84
+ - **Order discount:** `decideOrderDiscount({ subtotalMinor, requestedMinor, reason, authorized,
85
+ approvedBy, limits })` — pure and sync; refuses (never clamps) naming `authority | reason |
86
+ limit | full-comp`. Also `discountCeilingMinor`, `OrderDiscountLimits`, `PosOrderDiscountRecord`.
87
+ - **Errors**, now `PosError` subclasses with unchanged codes and statuses: `TenderMismatchError`
88
+ (`pos.tender.mismatch`, now with `details`), `TenderMethodRefusedError`,
89
+ `OrderDiscountRefusedError`, `PriceOverrideRefusedError`.
90
+ - `mongoose`, `@classytic/mongokit` and `@classytic/validation` are now OPTIONAL peers: only the engine needs them, and a
91
+ browser till that imports `@classytic/pos/domain` should not have them installed.
92
+
93
+ ### Changed — `getActiveShift` refuses to guess the register (BREAKING for multi-register callers)
94
+
95
+ Without `registerId`, and with several registers active at the branch, `getActiveShift` threw
96
+ nothing and returned the most recently opened shift — so a till that had not named its register
97
+ (a reload, a second tab) rang sales into another cashier's drawer, surfacing only as an
98
+ unexplained variance at close. It now throws `RegisterRequiredError` (409,
99
+ `POS_REGISTER_REQUIRED`) whose `meta.registers` lists each active register's `registerId`,
100
+ `shiftId`, `state` and `openedAt`. One active shift, or a named register, behaves as before.
101
+
102
+ ### Changed — peer floors
103
+
104
+ `@classytic/order` `>=0.19.0` (was `>=0.17.0`), `@classytic/mongokit` `>=3.41.0`, `@classytic/primitives` `>=0.32.0`, `@classytic/repo-core` `>=0.31.0`, `@classytic/tax-core` `>=0.6.0`, `@classytic/validation` `>=0.6.0`, `mongoose` `>=9.11.0`.
105
+
106
+ ## [0.6.0] — 2026-09-04
107
+
108
+ ### Added
109
+
110
+ - `ShiftRepository.findActiveByBranch(organizationId)` — returns all active shifts for a branch (dashboard "registers open now" widget); routed through `findAll` so the tenant plugin injects and casts `organizationId`
111
+
112
+ ### Changed — peer floors raised to current
113
+
114
+ - `@classytic/mongokit` `>=3.33.0` → **`>=3.36.0`**
115
+ - `@classytic/primitives` `>=0.23.0` → **`>=0.26.4`**
116
+ - `@classytic/repo-core` `>=0.24.0` → **`>=0.26.0`**
117
+
3
118
  ## [0.5.0] — 2026-08-26
4
119
 
5
120
  ### Fixed — CRITICAL: cash drawer identified by kind, not by code spelling
@@ -0,0 +1,2 @@
1
+ import { DocumentState, DocumentWrite, POS_COMMAND, PosCommandRejection, RecordableCustomer, RecordableShift, RecordableStock, RecordedRefund, RecordedSale, RefundableOrder, addRefund, addRefundToShift, addTakings, docKey, posCommandPack, recordRefundWrites, recordSaleWrites, refundableOf, takeFromStock } from "./pos-commands.mjs";
2
+ export { DocumentState, DocumentWrite, POS_COMMAND, PosCommandRejection, RecordableCustomer, RecordableShift, RecordableStock, RecordedRefund, RecordedSale, RefundableOrder, addRefund, addRefundToShift, addTakings, docKey, posCommandPack, recordRefundWrites, recordSaleWrites, refundableOf, takeFromStock };
@@ -0,0 +1 @@
1
+ export { POS_COMMAND, PosCommandRejection, addRefund, addRefundToShift, addTakings, docKey, posCommandPack, recordRefundWrites, recordSaleWrites, refundableOf, takeFromStock } from "./pos-commands.mjs";
@@ -0,0 +1,228 @@
1
+ import { ContactInfo, PersonName } from "@classytic/primitives/person";
2
+ //#region src/commands/pos-commands.d.ts
3
+ export declare const POS_COMMAND: {
4
+ readonly shiftOpen: 'pos.shift.open';
5
+ readonly sale: 'pos.sale';
6
+ readonly refund: 'pos.refund';
7
+ readonly shiftClose: 'pos.shift.close';
8
+ readonly customerUpsert: 'pos.customer.upsert';
9
+ };
10
+ /** Documents by `collection/id` — arc-sync's document-state key format. */
11
+ export type DocumentState = ReadonlyMap<string, unknown>;
12
+ export declare const docKey: (collection: string, id: string) => string;
13
+ export interface DocumentWrite {
14
+ collection: string;
15
+ id: string;
16
+ doc?: unknown;
17
+ }
18
+ /** A server refusal. `rejection: true` + `code` is arc-sync's structural rejection contract. */
19
+ export declare class PosCommandRejection extends Error {
20
+ readonly rejection: true;
21
+ readonly code: string;
22
+ constructor(code: string, message?: string);
23
+ }
24
+ interface BreakdownRow {
25
+ method: string;
26
+ methodKind?: string;
27
+ openingAmount: number;
28
+ salesAmount: number;
29
+ refundAmount: number;
30
+ cashInAmount: number;
31
+ cashOutAmount: number;
32
+ expectedAmount: number | null;
33
+ countedAmount: number | null;
34
+ difference: number | null;
35
+ }
36
+ export interface RecordableShift {
37
+ _id: string;
38
+ registerId: string;
39
+ state: string;
40
+ openingCash: number;
41
+ salesCount: number;
42
+ salesTotal: number;
43
+ refundCount?: number;
44
+ refundTotal?: number;
45
+ expectedCash: number | null;
46
+ paymentBreakdown: BreakdownRow[];
47
+ updatedAt?: string;
48
+ /** Set on a device whose close the server refused — the drawer was counted; it awaits resolution. */
49
+ unresolved?: boolean;
50
+ }
51
+ /**
52
+ * A product's stock at one branch — the `stock/<productId>` document: published by the server
53
+ * (`@spinekit/inventory` `createBranchStockFeed`), or the till's own in free mode. Its quantity may
54
+ * be NEGATIVE: a counter sale never waits for the count.
55
+ */
56
+ export interface RecordableStock {
57
+ _id: string;
58
+ productId: string;
59
+ quantity: number;
60
+ inStock?: boolean;
61
+ lowStock?: boolean;
62
+ variants?: Array<{
63
+ sku: string;
64
+ quantity: number;
65
+ }>;
66
+ updatedAt?: string;
67
+ }
68
+ /** A sale as the device decided it. `order` is the complete order document. `stock` names tracked goods only. */
69
+ export interface RecordedSale {
70
+ order: {
71
+ _id: string;
72
+ orderNumber: string;
73
+ metadata: {
74
+ shiftId: string;
75
+ registerId: string;
76
+ };
77
+ } & Record<string, unknown>;
78
+ /** What left the shelf. */
79
+ stock: ReadonlyArray<{
80
+ productId: string;
81
+ variantSku?: string;
82
+ quantity: number;
83
+ }>;
84
+ /** What the drawer took, by shift payment method (applied amounts — change excluded). */
85
+ takings: {
86
+ totalMinor: number;
87
+ byMethod: ReadonlyArray<{
88
+ method: string;
89
+ amountMinor: number;
90
+ }>;
91
+ };
92
+ at: string;
93
+ }
94
+ /** The order as a refund reads and writes it — the server's refund projection fields. */
95
+ export interface RefundableOrder {
96
+ _id: string;
97
+ status: string;
98
+ metadata: {
99
+ shiftId: string;
100
+ } & Record<string, unknown>;
101
+ totals: {
102
+ grandTotal: {
103
+ amount: number;
104
+ };
105
+ };
106
+ paymentState: {
107
+ totalCharged: {
108
+ amount: number;
109
+ currency: string;
110
+ };
111
+ totalRefunded: {
112
+ amount: number;
113
+ currency: string;
114
+ };
115
+ transactionRefs: Array<Record<string, unknown>>;
116
+ } & Record<string, unknown>;
117
+ updatedAt?: string;
118
+ }
119
+ /**
120
+ * A refund as the device decided it: MONEY back on one order — never goods (that is a return).
121
+ * `byMethod` is the way the money leaves: the way it came in.
122
+ */
123
+ export interface RecordedRefund {
124
+ refundId: string;
125
+ orderId: string;
126
+ /** The sale's shift: the drawer the money leaves, while it is open. */
127
+ shiftId: string;
128
+ amountMinor: number;
129
+ /** `methodKind`: the payment-method kind each leg leaves by (`@classytic/primitives/payment-method-kind`). */
130
+ byMethod: ReadonlyArray<{
131
+ method: string;
132
+ methodKind: string;
133
+ amountMinor: number;
134
+ }>;
135
+ reason: string;
136
+ at: string;
137
+ }
138
+ /**
139
+ * A customer as the till holds it. Created with a device-minted id; a server that already knows the
140
+ * phone keeps its own record and aliases the till's id to it.
141
+ */
142
+ export interface RecordableCustomer {
143
+ _id: string;
144
+ name: PersonName;
145
+ contact?: ContactInfo;
146
+ updatedAt?: string;
147
+ [field: string]: unknown;
148
+ }
149
+ /** The stock with `quantity` taken off — from nothing when the product has no stock document yet. */
150
+ export declare function takeFromStock(current: RecordableStock | undefined, productId: string, variantSku: string | undefined, quantity: number): RecordableStock;
151
+ /** The shift with a sale's takings added: count, total, and each method's sales. */
152
+ export declare function addTakings(shift: RecordableShift, takings: RecordedSale['takings'], at: string): RecordableShift;
153
+ /** What an order still has to refund: charged less refunded. */
154
+ export declare const refundableOf: (order: RefundableOrder) => number;
155
+ /** The order with a refund recorded as the server projects one; fully refunded ⇒ `refunded`. */
156
+ export declare function addRefund(order: RefundableOrder, refund: RecordedRefund): RefundableOrder;
157
+ /** The shift with a refund paid out of its drawer: each method's refunds, count and total. */
158
+ export declare function addRefundToShift(shift: RecordableShift, refund: RecordedRefund): RecordableShift;
159
+ /**
160
+ * Every write a recorded refund makes. The drawer is charged only while the sale's shift is open —
161
+ * a closed shift's count already stands, so a later refund shows as the open drawer's difference.
162
+ */
163
+ export declare function recordRefundWrites(refund: RecordedRefund, current: {
164
+ order: RefundableOrder;
165
+ shift: RecordableShift | undefined;
166
+ }): DocumentWrite[];
167
+ /** Every write a recorded sale makes, from the current documents it touches. */
168
+ export declare function recordSaleWrites(sale: RecordedSale, current: {
169
+ shift: RecordableShift;
170
+ stock: ReadonlyMap<string, RecordableStock>;
171
+ }, options?: {
172
+ unresolved?: boolean;
173
+ }): DocumentWrite[];
174
+ interface Command<T> {
175
+ payload: T;
176
+ }
177
+ export declare const posCommandPack: {
178
+ "pos.customer.upsert": {
179
+ /** A refused customer is administrative — it stops showing; sales keep their customer snapshot. */
180
+ whenRefused: 'suppressed';
181
+ apply: (_state: DocumentState, command: Command<{
182
+ customer: RecordableCustomer;
183
+ }>) => DocumentWrite[];
184
+ handle(state: DocumentState, command: Command<{
185
+ customer: RecordableCustomer;
186
+ }>): DocumentWrite[];
187
+ };
188
+ "pos.shift.open": {
189
+ /** A refused open is an administrative change — it stops showing; the server's shift stands. */
190
+ whenRefused: 'suppressed';
191
+ apply: (_state: DocumentState, command: Command<{
192
+ shift: RecordableShift;
193
+ }>) => DocumentWrite[];
194
+ handle(state: DocumentState, command: Command<{
195
+ shift: RecordableShift;
196
+ }>): DocumentWrite[];
197
+ };
198
+ "pos.sale": {
199
+ /** A refused sale is a physical fact — the goods and money moved; it stays visible, unresolved. */
200
+ whenRefused: 'unresolved';
201
+ apply(state: DocumentState, command: Command<RecordedSale>, unresolved: boolean): DocumentWrite[];
202
+ /**
203
+ * After the server records the sale, its stock still leaves the shelf HERE until the server's own
204
+ * count includes it: the order's `metadata.stockIssue` reaches `posted` only after the branch's
205
+ * stock documents were republished. `failed` keeps the subtraction — the shelf really is emptier.
206
+ */
207
+ pending(state: DocumentState, command: Command<RecordedSale>): DocumentWrite[];
208
+ handle(state: DocumentState, command: Command<RecordedSale>): DocumentWrite[];
209
+ };
210
+ "pos.refund": {
211
+ /** A refused refund is a physical fact — the money was handed back; it stays visible, unresolved. */
212
+ whenRefused: 'unresolved';
213
+ apply(state: DocumentState, command: Command<RecordedRefund>): DocumentWrite[];
214
+ handle(state: DocumentState, command: Command<RecordedRefund>): DocumentWrite[];
215
+ };
216
+ "pos.shift.close": {
217
+ /** A refused close is a physical fact — the drawer was counted; it stays visible, unresolved. */
218
+ whenRefused: 'unresolved';
219
+ apply: (_state: DocumentState, command: Command<{
220
+ shift: RecordableShift;
221
+ }>, unresolved: boolean) => DocumentWrite[];
222
+ handle(state: DocumentState, command: Command<{
223
+ shift: RecordableShift;
224
+ }>): DocumentWrite[];
225
+ };
226
+ };
227
+ //#endregion
228
+ export {};