@classytic/pos 0.3.0 → 0.4.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 (59) hide show
  1. package/CHANGELOG.md +236 -0
  2. package/LICENSE +75 -21
  3. package/README.md +11 -4
  4. package/dist/domain/enums/cash-movement-reason.enum.d.mts +15 -1
  5. package/dist/domain/enums/closed-by.enum.d.mts +1 -1
  6. package/dist/domain/enums/payment-method.enum.d.mts +23 -9
  7. package/dist/domain/enums/payment-method.enum.mjs +27 -7
  8. package/dist/domain/enums/shift-state.enum.d.mts +1 -1
  9. package/dist/domain/errors/pos.errors.d.mts +53 -10
  10. package/dist/domain/errors/pos.errors.mjs +58 -13
  11. package/dist/domain/index.d.mts +5 -5
  12. package/dist/domain/index.mjs +5 -4
  13. package/dist/domain/ports/common.d.mts +0 -1
  14. package/dist/domain/ports/ledger.bridge.d.mts +42 -8
  15. package/dist/domain/ports/ledger.bridge.mjs +14 -0
  16. package/dist/domain/ports/notification.bridge.d.mts +0 -1
  17. package/dist/domain/ports/policy.bridge.d.mts +0 -1
  18. package/dist/domain/state-machines/shift.fsm.d.mts +1 -2
  19. package/dist/domain/value-objects/cash-movement.vo.d.mts +0 -1
  20. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -1
  21. package/dist/domain/value-objects/shift-policy.vo.d.mts +31 -3
  22. package/dist/domain/value-objects/shift-policy.vo.mjs +35 -1
  23. package/dist/engine/define-pos.d.mts +9 -0
  24. package/dist/engine/define-pos.mjs +126 -0
  25. package/dist/engine/engine-types.d.mts +84 -36
  26. package/dist/engine/index.d.mts +4 -3
  27. package/dist/engine/index.mjs +2 -2
  28. package/dist/events/event-catalog.d.mts +6 -7
  29. package/dist/events/event-constants.d.mts +8 -8
  30. package/dist/events/event-payloads.d.mts +0 -1
  31. package/dist/events/helpers.d.mts +0 -1
  32. package/dist/events/helpers.mjs +5 -5
  33. package/dist/events/in-process-bus.d.mts +4 -15
  34. package/dist/events/in-process-bus.mjs +14 -32
  35. package/dist/events/outbox-store.d.mts +3 -19
  36. package/dist/events/outbox-store.mjs +1 -27
  37. package/dist/index.d.mts +15 -10
  38. package/dist/index.mjs +8 -6
  39. package/dist/models/create-models.d.mts +31 -4
  40. package/dist/models/create-models.mjs +80 -13
  41. package/dist/models/hide-soft-delete.mjs +11 -0
  42. package/dist/models/inject-tenant.d.mts +2 -2
  43. package/dist/models/inject-tenant.mjs +5 -11
  44. package/dist/models/register.model.d.mts +37 -0
  45. package/dist/models/register.model.mjs +82 -0
  46. package/dist/models/shift-sale-dedupe.model.d.mts +16 -0
  47. package/dist/models/shift-sale-dedupe.model.mjs +57 -0
  48. package/dist/models/shift.model.d.mts +48 -2
  49. package/dist/models/shift.model.mjs +88 -25
  50. package/dist/repositories/register.repository.d.mts +22 -0
  51. package/dist/repositories/register.repository.mjs +25 -0
  52. package/dist/repositories/shift.repository.d.mts +217 -12
  53. package/dist/repositories/shift.repository.mjs +480 -85
  54. package/dist/schemas/shift.d.mts +7 -18
  55. package/dist/schemas/shift.mjs +1 -2
  56. package/dist/testing/fixtures.d.mts +0 -1
  57. package/package.json +113 -110
  58. package/dist/engine/create-pos.d.mts +0 -6
  59. package/dist/engine/create-pos.mjs +0 -82
package/CHANGELOG.md CHANGED
@@ -1,5 +1,241 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.0] — 2026-08-17
4
+
5
+ ### Fixed — CRITICAL: the Z-report journal entry could post twice
6
+
7
+ `close()` and `forceClose()` invoked `ledger.onShiftClosed` **before** the FSM
8
+ compare-and-set, outside any transaction. Three shipped triggers close the same
9
+ shift (the lazy-close at register open, the oversight endpoint, the EOD cron),
10
+ so two of them reading `state: 'open'` at the same instant both passed
11
+ `canTransition` and **both posted a journal entry for one day's cash**. One won
12
+ the state write; the loser threw `IllegalShiftTransitionError` *after* its entry
13
+ had committed, and hosts caught and logged it. Two Z-reports in the GL, one
14
+ shift document, nothing errored. The crash variant was worse: a process dying
15
+ between the post and the state write left the shift `open` with
16
+ `journalEntryId` unset, so every retry posted another entry forever.
17
+
18
+ The bridge now runs **after** the CAS, so it is unreachable to every caller but
19
+ one, and the claim is durable so a crash converges instead of re-posting.
20
+
21
+ ### Changed — BREAKING
22
+
23
+ - **`LedgerBridge.onShiftClosed` takes a request object with a REQUIRED
24
+ `idempotencyKey`**: `onShiftClosed({ idempotencyKey, shift, trigger, attempt }, ctx)`.
25
+ The key is deterministic — `pos:shift:<shiftId>:close`, exported as
26
+ `shiftCloseIdempotencyKey(shiftId)`. The old contract ("idempotency is the
27
+ host's responsibility; the bridge SHOULD return the same id on retry") was
28
+ prose with nothing enforcing it; the resume path now depends on it, so it is
29
+ a compiler-enforced field. Hosts must dedupe on it.
30
+ - **`close()` and `forceClose()` return `CloseShiftResult`**, not
31
+ `ShiftDocument`: `{ shift, outcome, journalEntryId, ledgerPosted, ledgerError? }`
32
+ where `outcome` is `'closed' | 'already-closed' | 'resumed'`. A caller that
33
+ lost the race, or that is retrying a crashed close, needs to distinguish those
34
+ without catching an exception. **A losing caller's `countedByMethod` is not
35
+ applied** — check `outcome` before telling a human their drawer count landed.
36
+ - **`forceClose()` on an already-terminal shift no longer throws
37
+ `ShiftFinalizedError`** — it returns `{ outcome: 'already-closed' }`. Same for
38
+ `close()`. Every MUTATING verb (`pause`, `resume`, `recordCashMovement`,
39
+ `blindClose`) still throws; only the two close verbs converge.
40
+
41
+ ### Added
42
+
43
+ - `Shift.pendingLedgerPost` — a durable claim marker written in the SAME CAS
44
+ that moves the shift to its terminal state and cleared by the write that
45
+ records `journalEntryId`. Non-null means "a close won the CAS and the entry
46
+ is not yet recorded"; retrying `close`/`forceClose` resumes from it.
47
+ - `ShiftRepository.findShiftsWithPendingLedgerPost(olderThan?)` — the
48
+ operational sweep for shifts stuck mid-post (backed by a partial index). An
49
+ unobservable stuck state converges only by luck.
50
+ - `shiftCloseIdempotencyKey(shiftId)` + the `ShiftClosePosting` type, exported
51
+ from the root and `@classytic/pos/domain`.
52
+ - `mockIdempotentLedgerBridge()` in the test helpers — a *correct* host adapter
53
+ that dedupes on the key, so a test can assert "one shift, one journal entry"
54
+ independently of invocation count.
55
+
56
+ ## 1.0.0 - 2026-07-29
57
+
58
+ ### Changed
59
+ - **License:** relicensed from MIT to the **Classytic Source-Available License** (Community & Commercial). Evaluation/development use remains free; production use now requires a commercial license from Classytic LLC. See `LICENSE`.
60
+ - Major bump marks the license change; versions published before 1.0.0 remain under their original MIT terms.
61
+
62
+ ## [0.8.0] — 2026-07-27
63
+
64
+ ### Added — three active-shift read verbs, absorbed from host shims
65
+
66
+ `getActiveShift` and `getByIdUnscoped` existed as hand-rolled helpers in the
67
+ be-prod host (`resources/sales/pos/shift.repository.ts`, whose own docstring
68
+ already said "repository now lives in @classytic/pos"). Every fork would have
69
+ had to re-derive them — and the host copy had already drifted, hand-casting
70
+ `organizationId` to an ObjectId and keeping a private duplicate of the
71
+ active-state set. They are kernel domain logic, so they live here now:
72
+
73
+ - **`getActiveShift(ctx, registerId?)`** — the active shift (`open | paused |
74
+ blind_closed`) or `null`. Encodes which states count as active
75
+ (`ACTIVE_SHIFT_STATES`) plus the at-most-one invariant the
76
+ `uniq_active_shift_per_register` partial index enforces. Routed through the
77
+ inherited `findAll`, so the tenant plugin injects AND CASTS the scope field —
78
+ a hex-string `organizationId` now just works, with no host-side `isValid`
79
+ dance. Pass `registerId` on any multi-till deployment; omitting it returns an
80
+ arbitrary active shift for the branch (single-register back-compat).
81
+ - **`getByIdUnscoped(id)`** — deliberately UNSCOPED lean read so a host can
82
+ distinguish "shift does not exist" (404) from "shift belongs to another
83
+ branch" (403); a tenant-scoped read collapses both to `null`. Raw `Model`
84
+ read, flagged per CLAUDE.md (same documented exception as `findStaleShifts`),
85
+ with `deletedAt: null` explicit because the soft-delete plugin is bypassed
86
+ too. **Caller contract: compare `organizationId` before acting — this grants
87
+ no authority.**
88
+ - `findStaleShifts` is now listed as a canonical verb (it always existed) and no
89
+ longer inlines its own copy of the active-state array.
90
+
91
+ Hosts must NOT re-add these or an `ACTIVE_SHIFT_STATES` copy — importing the
92
+ kernel's is the whole point.
93
+
94
+ ### Changed
95
+
96
+ - Peers: `@classytic/mongokit` `>=3.22.0` → **`>=3.25.0`**, `@classytic/repo-core`
97
+ `>=0.13.0` → **`>=0.17.0`** (mongokit 3.25+ itself requires repo-core 0.17, so
98
+ every consumer inherits that floor — declaring it makes the constraint visible
99
+ instead of an install-time ERESOLVE).
100
+ - Toolchain: tsdown `^0.21.5` → **`^0.22.13`**, TypeScript `^5.7` → **`^7.0.2`**.
101
+ Output extensions are UNCHANGED (`.mjs` / `.d.mts`), so the exports map and
102
+ every consumer's deep imports are untouched. `tsconfig` gained
103
+ `"types": ["node"]` — TS7 native needs node globals (`console`, `AbortSignal`)
104
+ named explicitly.
105
+
106
+ 148 tests green (10 new).
107
+
108
+
109
+ ## [0.7.0] — unpublished (2026-07-23)
110
+
111
+ ### Added — `incrementSales({ dedupeRef })` exactly-once claim
112
+
113
+ - `IncrementSalesInput.dedupeRef?: string` — optional claim-first dedupe key.
114
+ When set, the repo insert-first claims `(shiftId, dedupeRef)` in the new
115
+ `pos_shift_sale_dedupe` collection BEFORE applying the `$inc`; a duplicate
116
+ claim (unique-index hit) skips the increment and returns
117
+ `{ applied: false, reason: 'duplicate' }`. Motivation: hosts fire
118
+ `incrementSales` from order-create hooks that re-run when the surrounding
119
+ Mongo transaction retries transiently — the shift `$inc` is NOT part of that
120
+ transaction, so a naive re-run double-counted the sale. Callers pass a
121
+ retry-stable identity (e.g. `shift-sale:{orderNumber}:{method}` —
122
+ orderNumber survives a txn retry; a per-attempt `_id` does not). Claim
123
+ order is claim-then-`$inc` deliberately: the residual crash window
124
+ under-counts once (reconcilable at close) instead of double-counting money.
125
+ - `incrementSales` now returns `Promise<IncrementSalesResult>`
126
+ (`{ applied, reason? }`) instead of `void` — additive for callers that
127
+ ignored the old `void`. Zero/negative amounts return
128
+ `{ applied: false, reason: 'zero-amount' }` (previously silent return).
129
+ - New model `ShiftSaleDedupe` (`pos_shift_sale_dedupe`), registered in
130
+ `POS_MODEL_NAMES` / `DEFAULT_COLLECTIONS` / `PosModels`. Documented
131
+ deviations (mirrors `@classytic/order`'s `order_idempotency` exemption —
132
+ ephemeral claim state): NO soft delete (a soft-deleted claim would re-admit
133
+ a duplicate `$inc`), NO tenant field (scoping is structural via the
134
+ globally-unique `shiftId`); 30-day TTL reaps stale claims. New exports:
135
+ `IShiftSaleDedupe`, `ShiftSaleDedupeDocument`, `ShiftSaleDedupeModel`,
136
+ `IncrementSalesResult`.
137
+ - `ShiftRepositoryConfig.dedupeModel?` — wired automatically by
138
+ `createPosEngine`; a `dedupeRef` call on a repo constructed without the
139
+ model throws (fail loud, never silently double-count).
140
+
141
+ ## [0.6.0] — unpublished (2026-07-23)
142
+
143
+ Combined release reconciling two concurrently-developed change sets into one
144
+ coherent build (both were staged locally at `0.5.2`): the multi-register
145
+ feature (minor) and the `deletedAt` wire-hygiene fix.
146
+
147
+ ### Added — POS registers (multi-register)
148
+
149
+ - New `Register` model + `RegisterRepository`: a register/till/terminal is the
150
+ point of sale a cashier signs on to. A branch (`organizationId`) may have
151
+ MANY registers; the `Shift` partial-unique index
152
+ (`uniq_active_shift_per_register`) permits one active shift PER register, so
153
+ cashiers on different registers in the same branch run parallel shifts.
154
+ `code` is unique per branch among live (non-soft-deleted) registers — a
155
+ deleted register frees its code for reuse. Vertical-agnostic (retail till,
156
+ restaurant terminal, clinic desk, wash bay). New public exports:
157
+ `RegisterRepository`, `RegisterRepositoryConfig`, `IRegister`,
158
+ `RegisterDocument`, `RegisterModel`.
159
+
160
+ ### Fixed — `deletedAt` no longer leaks onto the wire
161
+
162
+ - The soft-delete marker `deletedAt` is a persistence-only field (it exists so
163
+ `softDeletePlugin` can `$set` it and the partial-unique indexes can filter on
164
+ `{ deletedAt: null }`), but it was serializing into API responses. Hosts
165
+ serialize POS docs on paths that bypass framework response-schema hygiene and
166
+ fall through to Mongoose serialization — `raw` routes (`POST /pos/shifts/open`)
167
+ via Fastify `JSON.stringify` → `doc.toJSON()`, and Arc's action pipeline
168
+ (`close`/`reconcile`) via `sendControllerResponse` → `rawData.toJSON()` — so
169
+ the model must hide the field itself.
170
+ - `Shift` and `Register` now declare `deletedAt` with `select: false` (covers
171
+ `.lean()` reads) and strip it via `toJSON`/`toObject` transforms (cover every
172
+ hydrated-document path) through the shared `hideSoftDeleteField` helper. No
173
+ behavior change to soft-delete itself: the field is still stored, still drives
174
+ the partial-unique indexes, and is still queryable with an explicit
175
+ `.select('+deletedAt')`.
176
+
177
+ ## [0.5.1] — unpublished (2026-07-22)
178
+
179
+ ### Changed — event infra consolidated onto `@classytic/primitives/event-infra`
180
+
181
+ - `InProcessPosBus` is now a thin subclass of primitives' shared
182
+ `InProcessEventBus` (name `in-process-pos`, log label `pos` — wire
183
+ behavior identical, gains `publishMany`). `MemoryOutboxStore` is
184
+ re-exported from `@classytic/primitives/event-infra` instead of a local
185
+ copy (gains `all()` / `clear()` test helpers). `createPosEvent` delegates
186
+ to primitives' `createScopedEvent`. No public API or event-shape changes.
187
+ - `@classytic/primitives` peer floor raised to `>=0.13.0` (the
188
+ `/event-infra` subpath + `createScopedEvent`).
189
+
190
+ ## [0.5.0] — unpublished (2026-07-22)
191
+
192
+ ### Added — engine lifecycle: `destroy()`
193
+
194
+ - **`PosEngine.destroy()`** — closes the self-created `InProcessPosBus`
195
+ (skipped when the host injected `eventTransport`). The `outbox` store is
196
+ always host-provided and is never touched.
197
+ - `destroy()` follows the fleet ownsBus convention (manufacturing/purchase
198
+ pattern): only what the engine itself created is closed; a host-injected
199
+ transport is the host's to close. Idempotent — a second call is a no-op.
200
+ Mongoose models/connection are untouched (host-owned).
201
+ - Lifecycle coverage in `tests/integration/engine-lifecycle.test.ts`.
202
+
203
+ ## [0.4.0] — unpublished (2026-07-22)
204
+
205
+ ### Changed — Shift money fields now REJECT floats at the persistence layer (new peer: `@classytic/validation >=0.2.0`)
206
+
207
+ - Every money-bearing Shift field now carries the shared
208
+ `mongooseMinorUnits` validator from `@classytic/validation/money`:
209
+ root cash totals (`openingCash`, `expectedCash`, `countedCash`,
210
+ `cashDifference`, `salesTotal`, `refundTotal`), every
211
+ `paymentBreakdown` amount (`openingAmount`, `salesAmount`, `taxAmount`,
212
+ `refundAmount`, `refundTaxAmount`, `cashInAmount`, `cashOutAmount`,
213
+ `expectedAmount`, `countedAmount`, `difference`), and
214
+ `cashMovements[].amount`. The repository verbs (`incrementSales`,
215
+ `recordCashMovement`) already rejected non-integer amounts — but a
216
+ direct `create`/`update` through the inherited mongokit verbs persisted
217
+ major-unit floats silently. Now the schema fails loudly with
218
+ `"<label> must be an integer in minor units (e.g. paisa), not major units"`.
219
+ - Sign semantics preserved per field's domain: magnitudes keep `min: 0`
220
+ (direction lives in `cashMovements[].type`); `cashDifference` /
221
+ `paymentBreakdown[].difference` (counted − expected) stay legitimately
222
+ SIGNED; nullable reconciliation fields still accept `null`.
223
+ - `@classytic/validation >=0.2.0` added as a peer dependency (dev
224
+ `^0.2.0`), matching the fleet convention (purchase, flow, order).
225
+ - Breaking-leaning for hosts that were (incorrectly) storing major-unit
226
+ floats — hence the minor bump. Integer-minor-unit callers are unaffected.
227
+ - Regression coverage: `tests/unit/shift-money-minor-units.test.ts`.
228
+
229
+ ## [0.3.1] — 2026-07-16
230
+
231
+ ### Fixed
232
+
233
+ - injectTenantField no longer force-indexes the tenant field: the compound
234
+ prepend makes the tenant the leading key of every index, so the bare single
235
+ was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
236
+ index audit). A dedicated tenant index is still created when a schema
237
+ declares no compounds to prepend. Index-declaration change only.
238
+
3
239
  ## [0.3.0] — unpublished (2026-07-15)
4
240
 
5
241
  ### Changed — mongokit 3.22 `applyTransition()` adopted (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
package/LICENSE CHANGED
@@ -1,21 +1,75 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Classytic
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Classytic Source-Available License (Community & Commercial), Version 1.0
2
+
3
+ Copyright (c) 2026 Classytic LLC. All rights reserved.
4
+
5
+ This software is source-available, not open source. Please read this License
6
+ before using it.
7
+
8
+ 1. DEFINITIONS
9
+ "Software" means the contents of this package and any accompanying source
10
+ code, object code, or documentation, in any form.
11
+ "Licensor" means Classytic LLC, a limited liability company organized in the
12
+ United States.
13
+ "You" means the individual or legal entity exercising rights under this
14
+ License.
15
+ "Evaluation Use" means use for evaluation, development, testing,
16
+ experimentation, or internal non-commercial purposes only.
17
+ "Production Use" means any use of the Software that is live, commercial,
18
+ revenue-generating, or customer-facing, or any use other than Evaluation Use.
19
+ "Commercial License" means a separate written agreement executed with
20
+ Licensor that grants Production Use rights.
21
+
22
+ 2. OWNERSHIP
23
+ The Software is licensed, not sold. Licensor retains all right, title, and
24
+ interest in and to the Software, including all intellectual property rights.
25
+ All rights not expressly granted in this License are reserved by Licensor.
26
+
27
+ 3. EVALUATION GRANT
28
+ Subject to Your compliance with this License, Licensor grants You a
29
+ worldwide, royalty-free, non-exclusive, non-transferable, revocable license
30
+ to download, install, run, and modify the Software solely for Evaluation Use.
31
+
32
+ 4. PRODUCTION USE REQUIRES A COMMERCIAL LICENSE
33
+ Production Use of the Software is NOT permitted under this License and
34
+ requires a Commercial License from Licensor. A Commercial License may be
35
+ granted at Licensor's discretion, with or without a fee, and may confer
36
+ perpetual, irrevocable, and transferable Production Use rights as set out in
37
+ that agreement. Contact licensing@classytic.com to obtain one.
38
+
39
+ 5. RESTRICTIONS
40
+ You may not:
41
+ (a) make any Production Use of the Software without a Commercial License;
42
+ (b) redistribute, resell, rent, sublicense, or otherwise make the Software
43
+ (in whole or in part, original or modified) available to third parties as
44
+ a stand-alone product, framework, library, or hosted/managed service that
45
+ competes with the Software or with Licensor;
46
+ (c) remove, obscure, or alter any copyright, license, or attribution notice.
47
+
48
+ 6. FEEDBACK AND CONTRIBUTIONS
49
+ Any feedback, suggestions, or contributions You provide relating to the
50
+ Software may be used by Licensor for any purpose without obligation to You.
51
+
52
+ 7. TERMINATION
53
+ This License and the Evaluation Grant terminate automatically if You breach
54
+ any term. Upon termination You must cease all use of the Software and destroy
55
+ all copies in Your possession. Rights under a Commercial License are governed
56
+ by that agreement's own terms and survive termination of this License to the
57
+ extent stated there.
58
+
59
+ 8. DISCLAIMER OF WARRANTY
60
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
61
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
62
+ FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
63
+
64
+ 9. LIMITATION OF LIABILITY
65
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, IN NO EVENT SHALL LICENSOR BE LIABLE
66
+ FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
67
+ TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE
68
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
69
+
70
+ 10. GOVERNING LAW
71
+ This License is governed by the laws of the State of Delaware, United States,
72
+ without regard to its conflict-of-laws principles. (Adjust to Your LLC's state
73
+ of formation.)
74
+
75
+ For commercial licensing, contact: licensing@classytic.com
package/README.md CHANGED
@@ -56,10 +56,12 @@ const pos = createPosEngine({
56
56
  },
57
57
  bridges: {
58
58
  ledger: {
59
- async onShiftClosed(shift, ctx) {
59
+ async onShiftClosed({ idempotencyKey, shift }, ctx) {
60
60
  // Build journal entry from shift.paymentBreakdown, post via your ledger
61
- // engine, return { journalEntryId }.
62
- const je = await myLedger.post(buildShiftJE(shift));
61
+ // engine, return { journalEntryId }. MUST dedupe on `idempotencyKey`
62
+ // (`pos:shift:<id>:close`) — the package re-invokes with the same key
63
+ // when converging a close that crashed before recording the entry.
64
+ const je = await myLedger.post(buildShiftJE(shift), { idempotencyKey });
63
65
  return { journalEntryId: je._id.toString() };
64
66
  },
65
67
  },
@@ -112,7 +114,12 @@ open ─► paused ─► open ─► blind_closed ─► closed
112
114
 
113
115
  All optional. The package degrades gracefully without any.
114
116
 
115
- - **`ledger`** — `onShiftClosed(shift, ctx) → { journalEntryId }`. Host emits the JE. Throw to roll back the close.
117
+ - **`ledger`** — `onShiftClosed({ idempotencyKey, shift, trigger, attempt }, ctx) → { journalEntryId }`.
118
+ Host emits the JE. Invoked **only after** the shift has been atomically claimed, so
119
+ exactly one caller can ever reach it. Throw to roll back the close (`forceClose`
120
+ keeps the orphan and retries later). **`idempotencyKey` is required** —
121
+ `pos:shift:<shiftId>:close`, same value on every attempt; dedupe on it or a
122
+ crash-resume double-posts.
116
123
  - **`policy`** — `resolvePolicy(ctx) → ShiftPolicy`. Per-branch policy override at open time. Without it, `defaultPolicy` is used.
117
124
  - **`notification`** — `onVarianceOverride`, `onOrphanedClose`. Best-effort; failures logged not raised.
118
125
 
@@ -6,7 +6,21 @@
6
6
  * every cash-in / cash-out call. Hosts can scope the allowed subset per
7
7
  * branch via `policy.allowedReasonCodes`.
8
8
  */
9
- declare const CASH_MOVEMENT_REASON_CODES: readonly ["safe_drop", "petty_cash", "owner_withdrawal", "correction", "bank_deposit", "till_top_up", "other"];
9
+ declare const CASH_MOVEMENT_REASON_CODES: readonly [
10
+ /** Money moved from drawer to safe mid-shift. */
11
+ 'safe_drop',
12
+ /** Operational expense paid from drawer (utility bill, ad-hoc supply). */
13
+ 'petty_cash',
14
+ /** Owner / manager took cash out. */
15
+ 'owner_withdrawal',
16
+ /** Fixing a prior mistake (miscount, wrong tender). */
17
+ 'correction',
18
+ /** Cash deposited to bank during shift. */
19
+ 'bank_deposit',
20
+ /** More change brought into the drawer. */
21
+ 'till_top_up',
22
+ /** Free-form; note required. */
23
+ 'other'];
10
24
  type CashMovementReasonCode = (typeof CASH_MOVEMENT_REASON_CODES)[number];
11
25
  //#endregion
12
26
  export { CASH_MOVEMENT_REASON_CODES, CashMovementReasonCode };
@@ -7,7 +7,7 @@
7
7
  * manager — a manager closed (typically post blind_close reconcile)
8
8
  * system_auto — EOD cron / forceClose (orphaned_closed)
9
9
  */
10
- declare const CLOSED_BY_VALUES: readonly ["cashier", "manager", "system_auto"];
10
+ declare const CLOSED_BY_VALUES: readonly ['cashier', 'manager', 'system_auto'];
11
11
  type ClosedBy = (typeof CLOSED_BY_VALUES)[number];
12
12
  //#endregion
13
13
  export { CLOSED_BY_VALUES, ClosedBy };
@@ -1,14 +1,28 @@
1
+ import { PaymentMethodKind } from "@classytic/primitives/payment-method-kind";
1
2
  //#region src/domain/enums/payment-method.enum.d.ts
2
3
  /**
3
- * Default payment method enum.
4
+ * Payment methods are OPEN codes, not a closed enum. The persisted breakdown
5
+ * `method` accepts any deployment/provider-specific code — `bkash`, `nagad`,
6
+ * `stripe_card`, `gift_card`, `on_account`, `cheque`, … — while the SHIFT's
7
+ * `policySnapshot.allowedPaymentMethods` is the closed table for THAT shift
8
+ * (see `ShiftPolicy`). Each code resolves to a universal
9
+ * {@link PaymentMethodKind} (from `@classytic/primitives`) for reconciliation.
4
10
  *
5
- * Hosts can extend the set via `schemaOptions.shift.extraFields` if they
6
- * accept methods beyond this baseline (e.g. crypto, gift card, on-account).
7
- * The package treats payment methods as opaque keys for the breakdown
8
- * accumulator — the actual GL mapping and tax routing live in the host's
9
- * shift→JE contract.
11
+ * `SHIFT_PAYMENT_METHODS` is only the out-of-the-box DEFAULT policy + the seed
12
+ * for kind resolution — never a hard constraint on what a host may accept.
10
13
  */
11
- declare const SHIFT_PAYMENT_METHODS: readonly ["cash", "card", "mfs", "bank_transfer"];
12
- type ShiftPaymentMethod = (typeof SHIFT_PAYMENT_METHODS)[number];
14
+ declare const SHIFT_PAYMENT_METHODS: readonly ['cash', 'card', 'mfs', 'bank_transfer'];
15
+ /** A payment method CODE (open string). Baseline defaults in {@link SHIFT_PAYMENT_METHODS}. */
16
+ type ShiftPaymentMethod = string;
17
+ /** Default baseline code → universal kind. */
18
+ declare const DEFAULT_METHOD_KINDS: Readonly<Record<string, PaymentMethodKind>>;
19
+ /** Every valid kind value — for the mongoose enum on `paymentBreakdown.methodKind`. */
20
+ declare const PAYMENT_METHOD_KIND_VALUES: readonly PaymentMethodKind[];
21
+ /**
22
+ * Resolve a code's universal kind: an explicit override wins, else the default
23
+ * baseline map, else `other` (the always-valid fallback). Hosts pass explicit
24
+ * kinds for custom codes via `ShiftPolicy.paymentMethodKinds`.
25
+ */
26
+ declare function resolveMethodKind(code: string, explicit?: PaymentMethodKind): PaymentMethodKind;
13
27
  //#endregion
14
- export { SHIFT_PAYMENT_METHODS, ShiftPaymentMethod };
28
+ export { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS, ShiftPaymentMethod, resolveMethodKind };
@@ -1,12 +1,15 @@
1
+ import { PAYMENT_METHOD_KIND } from "@classytic/primitives/payment-method-kind";
1
2
  //#region src/domain/enums/payment-method.enum.ts
2
3
  /**
3
- * Default payment method enum.
4
+ * Payment methods are OPEN codes, not a closed enum. The persisted breakdown
5
+ * `method` accepts any deployment/provider-specific code — `bkash`, `nagad`,
6
+ * `stripe_card`, `gift_card`, `on_account`, `cheque`, … — while the SHIFT's
7
+ * `policySnapshot.allowedPaymentMethods` is the closed table for THAT shift
8
+ * (see `ShiftPolicy`). Each code resolves to a universal
9
+ * {@link PaymentMethodKind} (from `@classytic/primitives`) for reconciliation.
4
10
  *
5
- * Hosts can extend the set via `schemaOptions.shift.extraFields` if they
6
- * accept methods beyond this baseline (e.g. crypto, gift card, on-account).
7
- * The package treats payment methods as opaque keys for the breakdown
8
- * accumulator — the actual GL mapping and tax routing live in the host's
9
- * shift→JE contract.
11
+ * `SHIFT_PAYMENT_METHODS` is only the out-of-the-box DEFAULT policy + the seed
12
+ * for kind resolution — never a hard constraint on what a host may accept.
10
13
  */
11
14
  const SHIFT_PAYMENT_METHODS = [
12
15
  "cash",
@@ -14,5 +17,22 @@ const SHIFT_PAYMENT_METHODS = [
14
17
  "mfs",
15
18
  "bank_transfer"
16
19
  ];
20
+ /** Default baseline code → universal kind. */
21
+ const DEFAULT_METHOD_KINDS = {
22
+ cash: PAYMENT_METHOD_KIND.CASH,
23
+ card: PAYMENT_METHOD_KIND.CARD,
24
+ mfs: PAYMENT_METHOD_KIND.MOBILE_MONEY,
25
+ bank_transfer: PAYMENT_METHOD_KIND.BANK_TRANSFER
26
+ };
27
+ /** Every valid kind value — for the mongoose enum on `paymentBreakdown.methodKind`. */
28
+ const PAYMENT_METHOD_KIND_VALUES = Object.values(PAYMENT_METHOD_KIND);
29
+ /**
30
+ * Resolve a code's universal kind: an explicit override wins, else the default
31
+ * baseline map, else `other` (the always-valid fallback). Hosts pass explicit
32
+ * kinds for custom codes via `ShiftPolicy.paymentMethodKinds`.
33
+ */
34
+ function resolveMethodKind(code, explicit) {
35
+ return explicit ?? DEFAULT_METHOD_KINDS[code] ?? PAYMENT_METHOD_KIND.OTHER;
36
+ }
17
37
  //#endregion
18
- export { SHIFT_PAYMENT_METHODS };
38
+ export { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS, resolveMethodKind };
@@ -14,7 +14,7 @@
14
14
  * orphaned_closed — auto-closed by EOD cron / forceClose; counts default to
15
15
  * expected; flagged for manager review
16
16
  */
17
- declare const SHIFT_STATES: readonly ["open", "paused", "blind_closed", "closed", "orphaned_closed"];
17
+ declare const SHIFT_STATES: readonly ['open', 'paused', 'blind_closed', 'closed', 'orphaned_closed'];
18
18
  type ShiftState = (typeof SHIFT_STATES)[number];
19
19
  /** States that block opening a new shift for the same scope. */
20
20
  declare const ACTIVE_SHIFT_STATES: readonly ShiftState[];
@@ -1,13 +1,18 @@
1
+ import { HttpError } from "@classytic/repo-core/errors";
1
2
  //#region src/domain/errors/pos.errors.d.ts
2
3
  /**
3
- * Custom error classes thrown by the POS package.
4
+ * `status` makes every POS throwable satisfy `HttpError` from
5
+ * `@classytic/repo-core/errors`, so arc's global handler serializes it with
6
+ * the correct status natively — no per-host `errorMapper`. Without it every
7
+ * POS error reached the client as `arc.internal_error` / 500, including
8
+ * `ShiftNotFoundError` (404) and `ActiveShiftAlreadyOpenError` (409).
4
9
  *
5
- * Hosts catch these by `name` (or `instanceof`) and translate to HTTP status
6
- * codes — the package itself stays HTTP-agnostic. Each error carries a
7
- * stable `code` for log-mining and i18n.
10
+ * Defaults to 422; subclasses override with `readonly status = N` (a subclass
11
+ * field initializer runs after this constructor, so it wins).
8
12
  */
9
- declare class PosError extends Error {
13
+ declare class PosError extends Error implements HttpError {
10
14
  readonly code: string;
15
+ readonly status: number;
11
16
  constructor(code: string, message: string);
12
17
  }
13
18
  /**
@@ -16,34 +21,72 @@ declare class PosError extends Error {
16
21
  * Session + outbox is legal durable-relay-only mode.
17
22
  */
18
23
  declare class UnmanagedSessionError extends PosError {
24
+ readonly status = 500;
19
25
  constructor();
20
26
  }
21
27
  declare class ShiftNotFoundError extends PosError {
28
+ readonly status = 404;
22
29
  constructor(id: string);
23
30
  }
24
31
  declare class IllegalShiftTransitionError extends PosError {
32
+ readonly status = 422;
25
33
  constructor(from: string, verb: string);
26
34
  }
27
35
  declare class ActiveShiftAlreadyOpenError extends PosError {
36
+ readonly status = 409;
28
37
  constructor(scope: string);
29
38
  }
30
39
  declare class VarianceExceededError extends PosError {
40
+ readonly status = 409;
31
41
  readonly difference: number;
32
42
  readonly expected: number;
33
43
  constructor(difference: number, expected: number);
34
44
  }
35
45
  declare class ShiftFinalizedError extends PosError {
46
+ readonly status = 409;
47
+ constructor(id: string);
48
+ }
49
+ /**
50
+ * Thrown when a NEW SALE is attempted against a paused shift. A paused till
51
+ * takes no new sales until it is resumed (refunds and cash movements are
52
+ * corrections and remain allowed). Distinct from {@link ShiftFinalizedError}:
53
+ * the shift is recoverable — resume it and retry.
54
+ */
55
+ declare class ShiftPausedError extends PosError {
56
+ readonly status = 409;
57
+ constructor(id: string);
58
+ }
59
+ /**
60
+ * Thrown when a shift is closed directly from `open` (no prior blind-close
61
+ * reading) without any counted amounts. There is no expected-vs-counted
62
+ * reconciliation to perform, so the drawer would close with a null variance
63
+ * regardless of policy — closing a till you never counted. The caller must
64
+ * pass `countedByMethod` (cash always, plus any non-cash tender being
65
+ * reconciled) or blind-close first.
66
+ */
67
+ declare class ShiftCountsRequiredError extends PosError {
68
+ readonly status = 422;
36
69
  constructor(id: string);
37
70
  }
38
71
  declare class CashMovementInvalidError extends PosError {
72
+ readonly status = 422;
39
73
  constructor(reason: string);
40
74
  }
41
75
  declare class PosCapabilityError extends Error {
76
+ readonly code = "POS_CAPABILITY";
77
+ readonly status = 422;
42
78
  readonly missing: readonly string[];
43
- constructor(missing: readonly string[]);
44
- }
45
- declare class ShiftModelCollisionError extends Error {
46
- constructor(name: string);
79
+ /**
80
+ * `true` when the backend never ANSWERED (the connection was not open at
81
+ * bind, or the driver exposed no topology) rather than answering "no".
82
+ * Both refuse — an unobserved outcome is never a positive one (AGENTS.md
83
+ * FAIL LOUD rule 3) — but the operator's fix is completely different, so
84
+ * the message has to distinguish them.
85
+ */
86
+ readonly indeterminate: boolean;
87
+ constructor(missing: readonly string[], opts?: {
88
+ indeterminate?: boolean;
89
+ });
47
90
  }
48
91
  //#endregion
49
- export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError };
92
+ export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError };