@classytic/pos 0.6.0 → 0.8.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 (75) hide show
  1. package/CHANGELOG.md +10 -350
  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 +230 -0
  5. package/dist/commands/pos-commands.mjs +357 -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/payment-method.enum.mjs +2 -2
  10. package/dist/domain/enums/shift-state.enum.d.mts +7 -8
  11. package/dist/domain/errors/pos.errors.d.mts +82 -34
  12. package/dist/domain/errors/pos.errors.mjs +108 -23
  13. package/dist/domain/index.d.mts +11 -3
  14. package/dist/domain/index.mjs +10 -3
  15. package/dist/domain/ports/common.d.mts +2 -3
  16. package/dist/domain/ports/ledger.bridge.d.mts +6 -7
  17. package/dist/domain/ports/notification.bridge.d.mts +5 -6
  18. package/dist/domain/ports/policy.bridge.d.mts +2 -3
  19. package/dist/domain/sale/discount.d.mts +62 -0
  20. package/dist/domain/sale/discount.mjs +58 -0
  21. package/dist/domain/sale/price-override.d.mts +51 -0
  22. package/dist/domain/sale/price-override.mjs +51 -0
  23. package/dist/domain/sale/quick-cash.d.mts +10 -0
  24. package/dist/domain/sale/quick-cash.mjs +27 -0
  25. package/dist/domain/sale/service-line.d.mts +7 -0
  26. package/dist/domain/sale/service-line.mjs +10 -0
  27. package/dist/domain/sale/tender.d.mts +256 -0
  28. package/dist/domain/sale/tender.mjs +242 -0
  29. package/dist/domain/shift/shift-decisions.d.mts +51 -0
  30. package/dist/domain/shift/shift-decisions.mjs +93 -0
  31. package/dist/domain/shift/shift-report.d.mts +127 -0
  32. package/dist/domain/shift/shift-report.mjs +95 -0
  33. package/dist/domain/shift/shift.types.d.mts +107 -0
  34. package/dist/domain/state-machines/shift.fsm.d.mts +6 -7
  35. package/dist/domain/value-objects/cash-movement.vo.d.mts +7 -3
  36. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -5
  37. package/dist/domain/value-objects/shift-policy.vo.d.mts +12 -13
  38. package/dist/domain/value-objects/shift-policy.vo.mjs +13 -7
  39. package/dist/engine/capability.errors.d.mts +23 -0
  40. package/dist/engine/capability.errors.mjs +28 -0
  41. package/dist/engine/define-pos.d.mts +2 -3
  42. package/dist/engine/define-pos.mjs +14 -3
  43. package/dist/engine/engine-types.d.mts +24 -9
  44. package/dist/engine/index.d.mts +2 -1
  45. package/dist/engine/index.mjs +2 -1
  46. package/dist/events/event-catalog.d.mts +18 -14
  47. package/dist/events/event-catalog.mjs +10 -4
  48. package/dist/events/event-constants.d.mts +3 -4
  49. package/dist/events/event-payloads.d.mts +9 -10
  50. package/dist/events/helpers.d.mts +6 -3
  51. package/dist/events/helpers.mjs +12 -2
  52. package/dist/events/in-process-bus.d.mts +3 -4
  53. package/dist/events/index.mjs +1 -1
  54. package/dist/grant/till-grant.d.mts +50 -0
  55. package/dist/grant/till-grant.mjs +47 -0
  56. package/dist/index.d.mts +15 -4
  57. package/dist/index.mjs +13 -4
  58. package/dist/models/create-models.d.mts +10 -6
  59. package/dist/models/create-models.mjs +16 -3
  60. package/dist/models/register.model.d.mts +7 -6
  61. package/dist/models/shift-sale-dedupe.model.d.mts +4 -5
  62. package/dist/models/shift.model.d.mts +4 -111
  63. package/dist/models/shift.model.mjs +27 -3
  64. package/dist/models/till-grant.model.d.mts +19 -0
  65. package/dist/models/till-grant.model.mjs +52 -0
  66. package/dist/repositories/register.repository.d.mts +3 -4
  67. package/dist/repositories/shift.repository.d.mts +90 -60
  68. package/dist/repositories/shift.repository.mjs +323 -150
  69. package/dist/repositories/till-grant.repository.d.mts +22 -0
  70. package/dist/repositories/till-grant.repository.mjs +41 -0
  71. package/dist/schemas/index.mjs +1 -2
  72. package/dist/schemas/shift.d.mts +9 -10
  73. package/dist/testing/fixtures.d.mts +4 -5
  74. package/dist/testing/index.mjs +1 -2
  75. package/package.json +50 -19
package/CHANGELOG.md CHANGED
@@ -1,350 +1,10 @@
1
- # Changelog
2
-
3
- ## [0.6.0] — 2026-09-04
4
-
5
- ### Added
6
-
7
- - `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`
8
-
9
- ### Changed — peer floors raised to current
10
-
11
- - `@classytic/mongokit` `>=3.33.0` → **`>=3.36.0`**
12
- - `@classytic/primitives` `>=0.23.0` → **`>=0.26.4`**
13
- - `@classytic/repo-core` `>=0.24.0` → **`>=0.26.0`**
14
-
15
- ## [0.5.0] — 2026-08-26
16
-
17
- ### Fixed — CRITICAL: cash drawer identified by kind, not by code spelling
18
-
19
- Five call sites in `ShiftRepository` located the cash breakdown row with
20
- `r.method === 'cash'`. On any deployment whose cash code is not literally
21
- `"cash"` — a Spanish till (`'efectivo'`), a French one (`'espèces'`), or the
22
- package's own documented `'cash_register_3'` — every comparison matched nothing
23
- silently:
24
-
25
- - the opening float was written to no row (`open()`)
26
- - `recordCashMovement` could not find a row to increment
27
- - `expectedCash` read `null` on every close projection
28
- - the variance gate skipped entirely (`if (expectedAmount != null)` never fired)
29
- - the till closed unreconciled with no error
30
-
31
- The row already carried the right answer: `open()` resolves `methodKind` on the
32
- line immediately above the first of those comparisons.
33
-
34
- **Fix:** `isCashRow(r)` keys on `r.methodKind === PAYMENT_METHOD_KIND.CASH` from
35
- `@classytic/primitives/payment-method-kind`. Legacy rows written before
36
- `methodKind` existed (Mongoose default `'other'` for absent field) fall back to
37
- `r.method === 'cash'` so an in-flight shift from an older deployment remains
38
- reconcilable. All five call sites replaced. Covered by
39
- `tests/unit/cash-row-is-kind-not-code.test.ts` with non-English codes on purpose
40
- — a test seeding `'cash'` passes with or without the fix and proves nothing.
41
-
42
- ## [0.4.0] — 2026-08-17
43
-
44
- ### Fixed — CRITICAL: the Z-report journal entry could post twice
45
-
46
- `close()` and `forceClose()` invoked `ledger.onShiftClosed` **before** the FSM
47
- compare-and-set, outside any transaction. Three shipped triggers close the same
48
- shift (the lazy-close at register open, the oversight endpoint, the EOD cron),
49
- so two of them reading `state: 'open'` at the same instant both passed
50
- `canTransition` and **both posted a journal entry for one day's cash**. One won
51
- the state write; the loser threw `IllegalShiftTransitionError` *after* its entry
52
- had committed, and hosts caught and logged it. Two Z-reports in the GL, one
53
- shift document, nothing errored. The crash variant was worse: a process dying
54
- between the post and the state write left the shift `open` with
55
- `journalEntryId` unset, so every retry posted another entry forever.
56
-
57
- The bridge now runs **after** the CAS, so it is unreachable to every caller but
58
- one, and the claim is durable so a crash converges instead of re-posting.
59
-
60
- ### Changed — BREAKING
61
-
62
- - **`LedgerBridge.onShiftClosed` takes a request object with a REQUIRED
63
- `idempotencyKey`**: `onShiftClosed({ idempotencyKey, shift, trigger, attempt }, ctx)`.
64
- The key is deterministic — `pos:shift:<shiftId>:close`, exported as
65
- `shiftCloseIdempotencyKey(shiftId)`. The old contract ("idempotency is the
66
- host's responsibility; the bridge SHOULD return the same id on retry") was
67
- prose with nothing enforcing it; the resume path now depends on it, so it is
68
- a compiler-enforced field. Hosts must dedupe on it.
69
- - **`close()` and `forceClose()` return `CloseShiftResult`**, not
70
- `ShiftDocument`: `{ shift, outcome, journalEntryId, ledgerPosted, ledgerError? }`
71
- where `outcome` is `'closed' | 'already-closed' | 'resumed'`. A caller that
72
- lost the race, or that is retrying a crashed close, needs to distinguish those
73
- without catching an exception. **A losing caller's `countedByMethod` is not
74
- applied** — check `outcome` before telling a human their drawer count landed.
75
- - **`forceClose()` on an already-terminal shift no longer throws
76
- `ShiftFinalizedError`** — it returns `{ outcome: 'already-closed' }`. Same for
77
- `close()`. Every MUTATING verb (`pause`, `resume`, `recordCashMovement`,
78
- `blindClose`) still throws; only the two close verbs converge.
79
-
80
- ### Added
81
-
82
- - `Shift.pendingLedgerPost` — a durable claim marker written in the SAME CAS
83
- that moves the shift to its terminal state and cleared by the write that
84
- records `journalEntryId`. Non-null means "a close won the CAS and the entry
85
- is not yet recorded"; retrying `close`/`forceClose` resumes from it.
86
- - `ShiftRepository.findShiftsWithPendingLedgerPost(olderThan?)` — the
87
- operational sweep for shifts stuck mid-post (backed by a partial index). An
88
- unobservable stuck state converges only by luck.
89
- - `shiftCloseIdempotencyKey(shiftId)` + the `ShiftClosePosting` type, exported
90
- from the root and `@classytic/pos/domain`.
91
- - `mockIdempotentLedgerBridge()` in the test helpers — a *correct* host adapter
92
- that dedupes on the key, so a test can assert "one shift, one journal entry"
93
- independently of invocation count.
94
-
95
- ## 1.0.0 - 2026-07-29
96
-
97
- ### Changed
98
- - **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`.
99
- - Major bump marks the license change; versions published before 1.0.0 remain under their original MIT terms.
100
-
101
- ## [0.8.0] — 2026-07-27
102
-
103
- ### Added — three active-shift read verbs, absorbed from host shims
104
-
105
- `getActiveShift` and `getByIdUnscoped` existed as hand-rolled helpers in the
106
- be-prod host (`resources/sales/pos/shift.repository.ts`, whose own docstring
107
- already said "repository now lives in @classytic/pos"). Every fork would have
108
- had to re-derive them — and the host copy had already drifted, hand-casting
109
- `organizationId` to an ObjectId and keeping a private duplicate of the
110
- active-state set. They are kernel domain logic, so they live here now:
111
-
112
- - **`getActiveShift(ctx, registerId?)`** — the active shift (`open | paused |
113
- blind_closed`) or `null`. Encodes which states count as active
114
- (`ACTIVE_SHIFT_STATES`) plus the at-most-one invariant the
115
- `uniq_active_shift_per_register` partial index enforces. Routed through the
116
- inherited `findAll`, so the tenant plugin injects AND CASTS the scope field —
117
- a hex-string `organizationId` now just works, with no host-side `isValid`
118
- dance. Pass `registerId` on any multi-till deployment; omitting it returns an
119
- arbitrary active shift for the branch (single-register back-compat).
120
- - **`getByIdUnscoped(id)`** — deliberately UNSCOPED lean read so a host can
121
- distinguish "shift does not exist" (404) from "shift belongs to another
122
- branch" (403); a tenant-scoped read collapses both to `null`. Raw `Model`
123
- read, flagged per CLAUDE.md (same documented exception as `findStaleShifts`),
124
- with `deletedAt: null` explicit because the soft-delete plugin is bypassed
125
- too. **Caller contract: compare `organizationId` before acting — this grants
126
- no authority.**
127
- - `findStaleShifts` is now listed as a canonical verb (it always existed) and no
128
- longer inlines its own copy of the active-state array.
129
-
130
- Hosts must NOT re-add these or an `ACTIVE_SHIFT_STATES` copy — importing the
131
- kernel's is the whole point.
132
-
133
- ### Changed
134
-
135
- - Peers: `@classytic/mongokit` `>=3.22.0` → **`>=3.25.0`**, `@classytic/repo-core`
136
- `>=0.13.0` → **`>=0.17.0`** (mongokit 3.25+ itself requires repo-core 0.17, so
137
- every consumer inherits that floor — declaring it makes the constraint visible
138
- instead of an install-time ERESOLVE).
139
- - Toolchain: tsdown `^0.21.5` → **`^0.22.13`**, TypeScript `^5.7` → **`^7.0.2`**.
140
- Output extensions are UNCHANGED (`.mjs` / `.d.mts`), so the exports map and
141
- every consumer's deep imports are untouched. `tsconfig` gained
142
- `"types": ["node"]` — TS7 native needs node globals (`console`, `AbortSignal`)
143
- named explicitly.
144
-
145
- 148 tests green (10 new).
146
-
147
-
148
- ## [0.7.0] — unpublished (2026-07-23)
149
-
150
- ### Added — `incrementSales({ dedupeRef })` exactly-once claim
151
-
152
- - `IncrementSalesInput.dedupeRef?: string` — optional claim-first dedupe key.
153
- When set, the repo insert-first claims `(shiftId, dedupeRef)` in the new
154
- `pos_shift_sale_dedupe` collection BEFORE applying the `$inc`; a duplicate
155
- claim (unique-index hit) skips the increment and returns
156
- `{ applied: false, reason: 'duplicate' }`. Motivation: hosts fire
157
- `incrementSales` from order-create hooks that re-run when the surrounding
158
- Mongo transaction retries transiently — the shift `$inc` is NOT part of that
159
- transaction, so a naive re-run double-counted the sale. Callers pass a
160
- retry-stable identity (e.g. `shift-sale:{orderNumber}:{method}` —
161
- orderNumber survives a txn retry; a per-attempt `_id` does not). Claim
162
- order is claim-then-`$inc` deliberately: the residual crash window
163
- under-counts once (reconcilable at close) instead of double-counting money.
164
- - `incrementSales` now returns `Promise<IncrementSalesResult>`
165
- (`{ applied, reason? }`) instead of `void` — additive for callers that
166
- ignored the old `void`. Zero/negative amounts return
167
- `{ applied: false, reason: 'zero-amount' }` (previously silent return).
168
- - New model `ShiftSaleDedupe` (`pos_shift_sale_dedupe`), registered in
169
- `POS_MODEL_NAMES` / `DEFAULT_COLLECTIONS` / `PosModels`. Documented
170
- deviations (mirrors `@classytic/order`'s `order_idempotency` exemption —
171
- ephemeral claim state): NO soft delete (a soft-deleted claim would re-admit
172
- a duplicate `$inc`), NO tenant field (scoping is structural via the
173
- globally-unique `shiftId`); 30-day TTL reaps stale claims. New exports:
174
- `IShiftSaleDedupe`, `ShiftSaleDedupeDocument`, `ShiftSaleDedupeModel`,
175
- `IncrementSalesResult`.
176
- - `ShiftRepositoryConfig.dedupeModel?` — wired automatically by
177
- `createPosEngine`; a `dedupeRef` call on a repo constructed without the
178
- model throws (fail loud, never silently double-count).
179
-
180
- ## [0.6.0] — unpublished (2026-07-23)
181
-
182
- Combined release reconciling two concurrently-developed change sets into one
183
- coherent build (both were staged locally at `0.5.2`): the multi-register
184
- feature (minor) and the `deletedAt` wire-hygiene fix.
185
-
186
- ### Added — POS registers (multi-register)
187
-
188
- - New `Register` model + `RegisterRepository`: a register/till/terminal is the
189
- point of sale a cashier signs on to. A branch (`organizationId`) may have
190
- MANY registers; the `Shift` partial-unique index
191
- (`uniq_active_shift_per_register`) permits one active shift PER register, so
192
- cashiers on different registers in the same branch run parallel shifts.
193
- `code` is unique per branch among live (non-soft-deleted) registers — a
194
- deleted register frees its code for reuse. Vertical-agnostic (retail till,
195
- restaurant terminal, clinic desk, wash bay). New public exports:
196
- `RegisterRepository`, `RegisterRepositoryConfig`, `IRegister`,
197
- `RegisterDocument`, `RegisterModel`.
198
-
199
- ### Fixed — `deletedAt` no longer leaks onto the wire
200
-
201
- - The soft-delete marker `deletedAt` is a persistence-only field (it exists so
202
- `softDeletePlugin` can `$set` it and the partial-unique indexes can filter on
203
- `{ deletedAt: null }`), but it was serializing into API responses. Hosts
204
- serialize POS docs on paths that bypass framework response-schema hygiene and
205
- fall through to Mongoose serialization — `raw` routes (`POST /pos/shifts/open`)
206
- via Fastify `JSON.stringify` → `doc.toJSON()`, and Arc's action pipeline
207
- (`close`/`reconcile`) via `sendControllerResponse` → `rawData.toJSON()` — so
208
- the model must hide the field itself.
209
- - `Shift` and `Register` now declare `deletedAt` with `select: false` (covers
210
- `.lean()` reads) and strip it via `toJSON`/`toObject` transforms (cover every
211
- hydrated-document path) through the shared `hideSoftDeleteField` helper. No
212
- behavior change to soft-delete itself: the field is still stored, still drives
213
- the partial-unique indexes, and is still queryable with an explicit
214
- `.select('+deletedAt')`.
215
-
216
- ## [0.5.1] — unpublished (2026-07-22)
217
-
218
- ### Changed — event infra consolidated onto `@classytic/primitives/event-infra`
219
-
220
- - `InProcessPosBus` is now a thin subclass of primitives' shared
221
- `InProcessEventBus` (name `in-process-pos`, log label `pos` — wire
222
- behavior identical, gains `publishMany`). `MemoryOutboxStore` is
223
- re-exported from `@classytic/primitives/event-infra` instead of a local
224
- copy (gains `all()` / `clear()` test helpers). `createPosEvent` delegates
225
- to primitives' `createScopedEvent`. No public API or event-shape changes.
226
- - `@classytic/primitives` peer floor raised to `>=0.13.0` (the
227
- `/event-infra` subpath + `createScopedEvent`).
228
-
229
- ## [0.5.0] — unpublished (2026-07-22)
230
-
231
- ### Added — engine lifecycle: `destroy()`
232
-
233
- - **`PosEngine.destroy()`** — closes the self-created `InProcessPosBus`
234
- (skipped when the host injected `eventTransport`). The `outbox` store is
235
- always host-provided and is never touched.
236
- - `destroy()` follows the fleet ownsBus convention (manufacturing/purchase
237
- pattern): only what the engine itself created is closed; a host-injected
238
- transport is the host's to close. Idempotent — a second call is a no-op.
239
- Mongoose models/connection are untouched (host-owned).
240
- - Lifecycle coverage in `tests/integration/engine-lifecycle.test.ts`.
241
-
242
- ## [0.4.0] — unpublished (2026-07-22)
243
-
244
- ### Changed — Shift money fields now REJECT floats at the persistence layer (new peer: `@classytic/validation >=0.2.0`)
245
-
246
- - Every money-bearing Shift field now carries the shared
247
- `mongooseMinorUnits` validator from `@classytic/validation/money`:
248
- root cash totals (`openingCash`, `expectedCash`, `countedCash`,
249
- `cashDifference`, `salesTotal`, `refundTotal`), every
250
- `paymentBreakdown` amount (`openingAmount`, `salesAmount`, `taxAmount`,
251
- `refundAmount`, `refundTaxAmount`, `cashInAmount`, `cashOutAmount`,
252
- `expectedAmount`, `countedAmount`, `difference`), and
253
- `cashMovements[].amount`. The repository verbs (`incrementSales`,
254
- `recordCashMovement`) already rejected non-integer amounts — but a
255
- direct `create`/`update` through the inherited mongokit verbs persisted
256
- major-unit floats silently. Now the schema fails loudly with
257
- `"<label> must be an integer in minor units (e.g. paisa), not major units"`.
258
- - Sign semantics preserved per field's domain: magnitudes keep `min: 0`
259
- (direction lives in `cashMovements[].type`); `cashDifference` /
260
- `paymentBreakdown[].difference` (counted − expected) stay legitimately
261
- SIGNED; nullable reconciliation fields still accept `null`.
262
- - `@classytic/validation >=0.2.0` added as a peer dependency (dev
263
- `^0.2.0`), matching the fleet convention (purchase, flow, order).
264
- - Breaking-leaning for hosts that were (incorrectly) storing major-unit
265
- floats — hence the minor bump. Integer-minor-unit callers are unaffected.
266
- - Regression coverage: `tests/unit/shift-money-minor-units.test.ts`.
267
-
268
- ## [0.3.1] — 2026-07-16
269
-
270
- ### Fixed
271
-
272
- - injectTenantField no longer force-indexes the tenant field: the compound
273
- prepend makes the tenant the leading key of every index, so the bare single
274
- was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
275
- index audit). A dedicated tenant index is still created when a schema
276
- declares no compounds to prepend. Index-declaration change only.
277
-
278
- ## [0.3.0] — unpublished (2026-07-15)
279
-
280
- ### Changed — mongokit 3.22 `applyTransition()` adopted (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
281
-
282
- - Shift lifecycle (`pause` / `resume` via the shared helper, plus
283
- `blindClose` / `close` / `forceClose`) rides `applyTransition` with the
284
- new verb-closing `shiftMachine(verb)` adapter over the FSM module —
285
- pre-flight AND race diagnosis throw the verb-keyed
286
- `IllegalShiftTransitionError`, now with the ON-DISK state on
287
- now-illegal races (previously the stale pre-read); pure races remap to
288
- the historical shape. Clean registry install.
289
-
290
- ## 0.2.0 — Stack upgrade + PACKAGE_RULES compliance
291
-
292
- ### Fixed (behavioral) — 2026-07-05 addendum
293
-
294
- - **Ghost-event publish under host sessions (§P8.1).** `dispatch` published
295
- to the transport regardless of `ctx.session` — a host rollback left
296
- subscribers having seen an event for a write that never landed. Now:
297
- session + NO outbox throws the new `UnmanagedSessionError`
298
- (`POS_SESSION_UNMANAGED`); session + outbox is durable-relay-only (row
299
- joins the host tx, immediate publish skipped).
300
-
301
- Peer minimums raised to `@classytic/mongokit >=3.16.0`, `@classytic/repo-core >=0.6.0`,
302
- `@classytic/primitives >=0.7.2`. No new features — correctness + compliance.
303
-
304
- ### Added
305
- - **Transactional outbox support (P8 / §5.5 / §16).** Engine + repository accept
306
- `outbox?: OutboxStore`. Every domain event now flows through one session-bound
307
- `dispatch()`: `outbox.save` runs first under `ctx.session` and **propagates** on
308
- failure (the host's transaction rolls back); `transport.publish` runs second and
309
- **swallows** failures (the host relay re-delivers). Both sides share one envelope
310
- `meta.id` so relay re-publish is dedup-able. `MemoryOutboxStore` shipped from
311
- `@classytic/pos/events` for tests/dev (host owns production durability).
312
- - **Zod event catalog (§18).** `posEventDefinitions[]` exported from the package
313
- root and `/events`; one Zod schema per `POS_EVENTS` constant drives runtime
314
- validation, static types, and arc `EventRegistry`/OpenAPI introspection. No-drift
315
- invariant test added.
316
- - **`pos:shift.variance.detected`** is now emitted at close when the variance gate
317
- trips (including manager-overridden closes) — previously a declared-but-unused
318
- constant.
319
- - **Capability boot gate.** `createPosEngine` asserts `repo.capabilities.transactions`
320
- at boot (fail loud, not a cryptic driver error on the first close); opt out with
321
- `allowNonTransactional: true` for standalone-Mongo dev.
322
- - `ctx.signal` / `ctx.retryPolicy` are now threaded to every repo call via
323
- `repoOptionsFromCtx` (cooperative cancellation + driver-round-trip retries).
324
-
325
- ### Fixed
326
- - **Money integrity.** `incrementSales` and `recordCashMovement` reject non-integer
327
- (fractional) minor-unit amounts instead of `$inc`-ing float drift into totals.
328
- - **Event-name drift.** `pause`/`resume` emitted `pos:shift.pause`/`pos:shift.resume`;
329
- now correctly emit the catalog names `pos:shift.paused`/`pos:shift.resumed`.
330
- - **Soft-delete leak in `findStaleShifts`.** The raw cross-tenant cron scan now
331
- carries an explicit `deletedAt: null` guard so the EOD backstop can't revive a
332
- soft-deleted shift.
333
- - **Build hygiene.** `declarationMap` / `sourceMap` turned OFF in tsconfig (they leak
334
- source); `exactOptionalPropertyTypes: true` enabled (mandatory).
335
-
336
- ## 0.1.1 — Initial public release
337
-
338
- - `createPosEngine()` factory with `connection` + `defaultPolicy`
339
- - `Shift` model + Mongoose schema (3 indexes, all justified)
340
- - `ShiftRepository` extending mongokit `Repository<IShift>` with domain verbs:
341
- `open`, `pause`, `resume`, `recordCashMovement`, `incrementSales`,
342
- `blindClose`, `close`, `forceClose`
343
- - 5-state FSM: `open` → `paused` ↔ `open` → `blind_closed` → `closed`;
344
- any active state → `orphaned_closed` via `forceClose`
345
- - Bridges: `ledger` (JE emission), `policy` (per-branch policy resolver),
346
- `notification` (variance + orphan alerts)
347
- - Multi-tenant scoping via mongokit `multiTenantPlugin` (default ON)
348
- - 7-year soft-delete retention via `softDeletePlugin`
349
- - Zod v4 body schemas at `@classytic/pos/schemas` for arc 2.11 wiring
350
- - Test fixtures at `@classytic/pos/testing` for host integration tests
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.8.0 — 2026-11-28
6
+
7
+ Peers raised to the latest published: `@classytic/mongokit >=3.47.0`, `@classytic/order >=0.24.0`, `@classytic/primitives >=0.39.0`, `@classytic/repo-core >=0.39.0`, `@classytic/tax-core >=0.7.0`, `mongoose >=9.13.1`.
8
+
9
+ - `ShiftRepository.findStaleShifts` returns each shift's `salesCount` and `salesTotal` (minor units). No consumer action.
10
+ - `TenderSettlement` gains `acquirer-captured` (a card captured at the counter); it settles immediately like cash and is never change-capable by default.
@@ -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,230 @@
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
+ /** `methodKind` per leg, as on a refund: a method the shift has not seen yet still lands on the right row kind. */
86
+ takings: {
87
+ totalMinor: number;
88
+ byMethod: ReadonlyArray<{
89
+ method: string;
90
+ methodKind: string;
91
+ amountMinor: number;
92
+ }>;
93
+ };
94
+ at: string;
95
+ }
96
+ /** The order as a refund reads and writes it — the server's refund projection fields. */
97
+ export interface RefundableOrder {
98
+ _id: string;
99
+ status: string;
100
+ metadata: {
101
+ shiftId: string;
102
+ } & Record<string, unknown>;
103
+ totals: {
104
+ grandTotal: {
105
+ amount: number;
106
+ };
107
+ };
108
+ paymentState: {
109
+ totalCharged: {
110
+ amount: number;
111
+ currency: string;
112
+ };
113
+ totalRefunded: {
114
+ amount: number;
115
+ currency: string;
116
+ };
117
+ transactionRefs: Array<Record<string, unknown>>;
118
+ } & Record<string, unknown>;
119
+ updatedAt?: string;
120
+ }
121
+ /**
122
+ * A refund as the device decided it: MONEY back on one order — never goods (that is a return).
123
+ * `byMethod` is the way the money leaves: the way it came in.
124
+ */
125
+ export interface RecordedRefund {
126
+ refundId: string;
127
+ orderId: string;
128
+ /** The sale's shift: the drawer the money leaves, while it is open. */
129
+ shiftId: string;
130
+ amountMinor: number;
131
+ /** `methodKind`: the payment-method kind each leg leaves by (`@classytic/primitives/payment-method-kind`). */
132
+ byMethod: ReadonlyArray<{
133
+ method: string;
134
+ methodKind: string;
135
+ amountMinor: number;
136
+ }>;
137
+ reason: string;
138
+ at: string;
139
+ }
140
+ /**
141
+ * A customer as the till holds it. Created with a device-minted id; a server that already knows the
142
+ * phone keeps its own record and aliases the till's id to it.
143
+ */
144
+ export interface RecordableCustomer {
145
+ _id: string;
146
+ name: PersonName;
147
+ contact?: ContactInfo;
148
+ updatedAt?: string;
149
+ [field: string]: unknown;
150
+ }
151
+ /** The stock with `quantity` taken off — from nothing when the product has no stock document yet. */
152
+ export declare function takeFromStock(current: RecordableStock | undefined, productId: string, variantSku: string | undefined, quantity: number): RecordableStock;
153
+ /** The shift with a sale's takings added: count, total, and each method's sales. */
154
+ export declare function addTakings(shift: RecordableShift, takings: RecordedSale['takings'], at: string): RecordableShift;
155
+ /** What an order still has to refund: charged less refunded. */
156
+ export declare const refundableOf: (order: RefundableOrder) => number;
157
+ /** The order with a refund recorded as the server projects one; fully refunded ⇒ `refunded`. */
158
+ export declare function addRefund(order: RefundableOrder, refund: RecordedRefund): RefundableOrder;
159
+ /** The shift with a refund paid out of its drawer: each method's refunds, count and total. */
160
+ export declare function addRefundToShift(shift: RecordableShift, refund: RecordedRefund): RecordableShift;
161
+ /**
162
+ * Every write a recorded refund makes. The drawer is charged only while the sale's shift is open —
163
+ * a closed shift's count already stands, so a later refund shows as the open drawer's difference.
164
+ */
165
+ export declare function recordRefundWrites(refund: RecordedRefund, current: {
166
+ order: RefundableOrder;
167
+ shift: RecordableShift | undefined;
168
+ }): DocumentWrite[];
169
+ /** Every write a recorded sale makes, from the current documents it touches. */
170
+ export declare function recordSaleWrites(sale: RecordedSale, current: {
171
+ shift: RecordableShift;
172
+ stock: ReadonlyMap<string, RecordableStock>;
173
+ }, options?: {
174
+ unresolved?: boolean;
175
+ }): DocumentWrite[];
176
+ interface Command<T> {
177
+ payload: T;
178
+ }
179
+ export declare const posCommandPack: {
180
+ "pos.customer.upsert": {
181
+ /** A refused customer is administrative — it stops showing; sales keep their customer snapshot. */
182
+ whenRefused: 'suppressed';
183
+ apply: (_state: DocumentState, command: Command<{
184
+ customer: RecordableCustomer;
185
+ }>) => DocumentWrite[];
186
+ handle(state: DocumentState, command: Command<{
187
+ customer: RecordableCustomer;
188
+ }>): DocumentWrite[];
189
+ };
190
+ "pos.shift.open": {
191
+ /** A refused open is an administrative change — it stops showing; the server's shift stands. */
192
+ whenRefused: 'suppressed';
193
+ apply: (_state: DocumentState, command: Command<{
194
+ shift: RecordableShift;
195
+ }>) => DocumentWrite[];
196
+ handle(state: DocumentState, command: Command<{
197
+ shift: RecordableShift;
198
+ }>): DocumentWrite[];
199
+ };
200
+ "pos.sale": {
201
+ /** A refused sale is a physical fact — the goods and money moved; it stays visible, unresolved. */
202
+ whenRefused: 'unresolved';
203
+ apply(state: DocumentState, command: Command<RecordedSale>, unresolved: boolean): DocumentWrite[];
204
+ /**
205
+ * After the server records the sale, its stock still leaves the shelf HERE until the server's own
206
+ * count includes it: the order's `metadata.stockIssue` reaches `posted` only after the branch's
207
+ * stock documents were republished. `failed` keeps the subtraction — the shelf really is emptier.
208
+ */
209
+ pending(state: DocumentState, command: Command<RecordedSale>): DocumentWrite[];
210
+ handle(state: DocumentState, command: Command<RecordedSale>): DocumentWrite[];
211
+ };
212
+ "pos.refund": {
213
+ /** A refused refund is a physical fact — the money was handed back; it stays visible, unresolved. */
214
+ whenRefused: 'unresolved';
215
+ apply(state: DocumentState, command: Command<RecordedRefund>): DocumentWrite[];
216
+ handle(state: DocumentState, command: Command<RecordedRefund>): DocumentWrite[];
217
+ };
218
+ "pos.shift.close": {
219
+ /** A refused close is a physical fact — the drawer was counted; it stays visible, unresolved. */
220
+ whenRefused: 'unresolved';
221
+ apply: (_state: DocumentState, command: Command<{
222
+ shift: RecordableShift;
223
+ }>, unresolved: boolean) => DocumentWrite[];
224
+ handle(state: DocumentState, command: Command<{
225
+ shift: RecordableShift;
226
+ }>): DocumentWrite[];
227
+ };
228
+ };
229
+ //#endregion
230
+ export {};