@classytic/pos 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,63 +1,75 @@
1
- # Changelog
2
-
3
- ## 0.2.0 — Stack upgrade + PACKAGE_RULES compliance
4
-
5
- ### Fixed (behavioral) — 2026-07-05 addendum
6
-
7
- - **Ghost-event publish under host sessions (§P8.1).** `dispatch` published
8
- to the transport regardless of `ctx.session` — a host rollback left
9
- subscribers having seen an event for a write that never landed. Now:
10
- session + NO outbox throws the new `UnmanagedSessionError`
11
- (`POS_SESSION_UNMANAGED`); session + outbox is durable-relay-only (row
12
- joins the host tx, immediate publish skipped).
13
-
14
- Peer minimums raised to `@classytic/mongokit >=3.16.0`, `@classytic/repo-core >=0.6.0`,
15
- `@classytic/primitives >=0.7.2`. No new features — correctness + compliance.
16
-
17
- ### Added
18
- - **Transactional outbox support (P8 / §5.5 / §16).** Engine + repository accept
19
- `outbox?: OutboxStore`. Every domain event now flows through one session-bound
20
- `dispatch()`: `outbox.save` runs first under `ctx.session` and **propagates** on
21
- failure (the host's transaction rolls back); `transport.publish` runs second and
22
- **swallows** failures (the host relay re-delivers). Both sides share one envelope
23
- `meta.id` so relay re-publish is dedup-able. `MemoryOutboxStore` shipped from
24
- `@classytic/pos/events` for tests/dev (host owns production durability).
25
- - **Zod event catalog (§18).** `posEventDefinitions[]` exported from the package
26
- root and `/events`; one Zod schema per `POS_EVENTS` constant drives runtime
27
- validation, static types, and arc `EventRegistry`/OpenAPI introspection. No-drift
28
- invariant test added.
29
- - **`pos:shift.variance.detected`** is now emitted at close when the variance gate
30
- trips (including manager-overridden closes) — previously a declared-but-unused
31
- constant.
32
- - **Capability boot gate.** `createPosEngine` asserts `repo.capabilities.transactions`
33
- at boot (fail loud, not a cryptic driver error on the first close); opt out with
34
- `allowNonTransactional: true` for standalone-Mongo dev.
35
- - `ctx.signal` / `ctx.retryPolicy` are now threaded to every repo call via
36
- `repoOptionsFromCtx` (cooperative cancellation + driver-round-trip retries).
37
-
38
- ### Fixed
39
- - **Money integrity.** `incrementSales` and `recordCashMovement` reject non-integer
40
- (fractional) minor-unit amounts instead of `$inc`-ing float drift into totals.
41
- - **Event-name drift.** `pause`/`resume` emitted `pos:shift.pause`/`pos:shift.resume`;
42
- now correctly emit the catalog names `pos:shift.paused`/`pos:shift.resumed`.
43
- - **Soft-delete leak in `findStaleShifts`.** The raw cross-tenant cron scan now
44
- carries an explicit `deletedAt: null` guard so the EOD backstop can't revive a
45
- soft-deleted shift.
46
- - **Build hygiene.** `declarationMap` / `sourceMap` turned OFF in tsconfig (they leak
47
- source); `exactOptionalPropertyTypes: true` enabled (mandatory).
48
-
49
- ## 0.1.1 — Initial public release
50
-
51
- - `createPosEngine()` factory with `connection` + `defaultPolicy`
52
- - `Shift` model + Mongoose schema (3 indexes, all justified)
53
- - `ShiftRepository` extending mongokit `Repository<IShift>` with domain verbs:
54
- `open`, `pause`, `resume`, `recordCashMovement`, `incrementSales`,
55
- `blindClose`, `close`, `forceClose`
56
- - 5-state FSM: `open` → `paused` ↔ `open` → `blind_closed` → `closed`;
57
- any active state → `orphaned_closed` via `forceClose`
58
- - Bridges: `ledger` (JE emission), `policy` (per-branch policy resolver),
59
- `notification` (variance + orphan alerts)
60
- - Multi-tenant scoping via mongokit `multiTenantPlugin` (default ON)
61
- - 7-year soft-delete retention via `softDeletePlugin`
62
- - Zod v4 body schemas at `@classytic/pos/schemas` for arc 2.11 wiring
63
- - Test fixtures at `@classytic/pos/testing` for host integration tests
1
+ # Changelog
2
+
3
+ ## [0.3.0] — unpublished (2026-07-15)
4
+
5
+ ### Changed — mongokit 3.22 `applyTransition()` adopted (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
6
+
7
+ - Shift lifecycle (`pause` / `resume` via the shared helper, plus
8
+ `blindClose` / `close` / `forceClose`) rides `applyTransition` with the
9
+ new verb-closing `shiftMachine(verb)` adapter over the FSM module —
10
+ pre-flight AND race diagnosis throw the verb-keyed
11
+ `IllegalShiftTransitionError`, now with the ON-DISK state on
12
+ now-illegal races (previously the stale pre-read); pure races remap to
13
+ the historical shape. Clean registry install.
14
+
15
+ ## 0.2.0 — Stack upgrade + PACKAGE_RULES compliance
16
+
17
+ ### Fixed (behavioral) — 2026-07-05 addendum
18
+
19
+ - **Ghost-event publish under host sessions (§P8.1).** `dispatch` published
20
+ to the transport regardless of `ctx.session` — a host rollback left
21
+ subscribers having seen an event for a write that never landed. Now:
22
+ session + NO outbox throws the new `UnmanagedSessionError`
23
+ (`POS_SESSION_UNMANAGED`); session + outbox is durable-relay-only (row
24
+ joins the host tx, immediate publish skipped).
25
+
26
+ Peer minimums raised to `@classytic/mongokit >=3.16.0`, `@classytic/repo-core >=0.6.0`,
27
+ `@classytic/primitives >=0.7.2`. No new features — correctness + compliance.
28
+
29
+ ### Added
30
+ - **Transactional outbox support (P8 / §5.5 / §16).** Engine + repository accept
31
+ `outbox?: OutboxStore`. Every domain event now flows through one session-bound
32
+ `dispatch()`: `outbox.save` runs first under `ctx.session` and **propagates** on
33
+ failure (the host's transaction rolls back); `transport.publish` runs second and
34
+ **swallows** failures (the host relay re-delivers). Both sides share one envelope
35
+ `meta.id` so relay re-publish is dedup-able. `MemoryOutboxStore` shipped from
36
+ `@classytic/pos/events` for tests/dev (host owns production durability).
37
+ - **Zod event catalog (§18).** `posEventDefinitions[]` exported from the package
38
+ root and `/events`; one Zod schema per `POS_EVENTS` constant drives runtime
39
+ validation, static types, and arc `EventRegistry`/OpenAPI introspection. No-drift
40
+ invariant test added.
41
+ - **`pos:shift.variance.detected`** is now emitted at close when the variance gate
42
+ trips (including manager-overridden closes) — previously a declared-but-unused
43
+ constant.
44
+ - **Capability boot gate.** `createPosEngine` asserts `repo.capabilities.transactions`
45
+ at boot (fail loud, not a cryptic driver error on the first close); opt out with
46
+ `allowNonTransactional: true` for standalone-Mongo dev.
47
+ - `ctx.signal` / `ctx.retryPolicy` are now threaded to every repo call via
48
+ `repoOptionsFromCtx` (cooperative cancellation + driver-round-trip retries).
49
+
50
+ ### Fixed
51
+ - **Money integrity.** `incrementSales` and `recordCashMovement` reject non-integer
52
+ (fractional) minor-unit amounts instead of `$inc`-ing float drift into totals.
53
+ - **Event-name drift.** `pause`/`resume` emitted `pos:shift.pause`/`pos:shift.resume`;
54
+ now correctly emit the catalog names `pos:shift.paused`/`pos:shift.resumed`.
55
+ - **Soft-delete leak in `findStaleShifts`.** The raw cross-tenant cron scan now
56
+ carries an explicit `deletedAt: null` guard so the EOD backstop can't revive a
57
+ soft-deleted shift.
58
+ - **Build hygiene.** `declarationMap` / `sourceMap` turned OFF in tsconfig (they leak
59
+ source); `exactOptionalPropertyTypes: true` enabled (mandatory).
60
+
61
+ ## 0.1.1 — Initial public release
62
+
63
+ - `createPosEngine()` factory with `connection` + `defaultPolicy`
64
+ - `Shift` model + Mongoose schema (3 indexes, all justified)
65
+ - `ShiftRepository` extending mongokit `Repository<IShift>` with domain verbs:
66
+ `open`, `pause`, `resume`, `recordCashMovement`, `incrementSales`,
67
+ `blindClose`, `close`, `forceClose`
68
+ - 5-state FSM: `open` → `paused` ↔ `open` → `blind_closed` → `closed`;
69
+ any active state → `orphaned_closed` via `forceClose`
70
+ - Bridges: `ledger` (JE emission), `policy` (per-branch policy resolver),
71
+ `notification` (variance + orphan alerts)
72
+ - Multi-tenant scoping via mongokit `multiTenantPlugin` (default ON)
73
+ - 7-year soft-delete retention via `softDeletePlugin`
74
+ - Zod v4 body schemas at `@classytic/pos/schemas` for arc 2.11 wiring
75
+ - Test fixtures at `@classytic/pos/testing` for host integration tests
@@ -0,0 +1,17 @@
1
+ import { IllegalShiftTransitionError } from "../domain/errors/pos.errors.mjs";
2
+ import { canTransition } from "../domain/state-machines/shift.fsm.mjs";
3
+ //#region src/repositories/shift-transition-support.ts
4
+ function shiftMachine(verb) {
5
+ return {
6
+ name: "shift",
7
+ assertTransition(_entityId, from, _to) {
8
+ if (!canTransition(from, verb)) throw new IllegalShiftTransitionError(from, verb);
9
+ }
10
+ };
11
+ }
12
+ function isTransitionRace(err) {
13
+ const code = err?.code;
14
+ return code === "TRANSITION_RACE_LOST" || code === "TRANSITION_TARGET_MISSING";
15
+ }
16
+ //#endregion
17
+ export { isTransitionRace, shiftMachine };
@@ -5,6 +5,7 @@ import { isWithinVarianceThreshold } from "../domain/value-objects/shift-policy.
5
5
  import { POS_EVENTS } from "../events/event-constants.mjs";
6
6
  import { createPosEvent } from "../events/helpers.mjs";
7
7
  import { repoOptionsFromCtx } from "./repo-options.mjs";
8
+ import { isTransitionRace, shiftMachine } from "./shift-transition-support.mjs";
8
9
  import { Repository, methodRegistryPlugin, softDeletePlugin } from "@classytic/mongokit";
9
10
  import { applyDecision, createChain } from "@classytic/primitives/approval";
10
11
  //#region src/repositories/shift.repository.ts
@@ -176,21 +177,25 @@ var ShiftRepository = class extends Repository {
176
177
  if (shift.state !== "open") throw new IllegalShiftTransitionError(shift.state, "blindClose");
177
178
  const updatedBreakdown = this.applyCounts(shift.paymentBreakdown, input.countedByMethod, true);
178
179
  const cashRow = updatedBreakdown.find((r) => r.method === "cash");
179
- const updated = await this.claim(shift._id, {
180
+ const updated = await this.applyTransition(String(shift._id), shiftMachine("blindClose"), {
180
181
  field: "state",
181
182
  from: "open",
182
- to: "blind_closed"
183
- }, {
184
- blindClosedAt: /* @__PURE__ */ new Date(),
185
- paymentBreakdown: updatedBreakdown,
186
- expectedCash: cashRow?.expectedAmount ?? null,
187
- countedCash: cashRow?.countedAmount ?? null,
188
- cashDifference: cashRow?.difference ?? null,
189
- closingCashierId: input.closingCashierId,
190
- closingCashierName: input.closingCashierName,
191
- ...input.notes ? { notes: input.notes } : {}
192
- }, repoOptionsFromCtx(ctx));
193
- if (!updated) throw new IllegalShiftTransitionError(shift.state, "blindClose");
183
+ to: "blind_closed",
184
+ history: false,
185
+ set: {
186
+ blindClosedAt: /* @__PURE__ */ new Date(),
187
+ paymentBreakdown: updatedBreakdown,
188
+ expectedCash: cashRow?.expectedAmount ?? null,
189
+ countedCash: cashRow?.countedAmount ?? null,
190
+ cashDifference: cashRow?.difference ?? null,
191
+ closingCashierId: input.closingCashierId,
192
+ closingCashierName: input.closingCashierName,
193
+ ...input.notes ? { notes: input.notes } : {}
194
+ }
195
+ }, repoOptionsFromCtx(ctx)).catch((err) => {
196
+ if (isTransitionRace(err)) throw new IllegalShiftTransitionError(shift.state, "blindClose");
197
+ throw err;
198
+ });
194
199
  await this.dispatch(POS_EVENTS.SHIFT_BLIND_CLOSED, { shiftId: input.shiftId }, ctx);
195
200
  return updated;
196
201
  }
@@ -228,12 +233,16 @@ var ShiftRepository = class extends Repository {
228
233
  ...journalEntryId ? { journalEntryId } : {},
229
234
  ...input.varianceOverride ? { approvals: this.buildVarianceApprovalChain(input.varianceOverride.overriddenBy, input.varianceOverride.reason) } : {}
230
235
  };
231
- const updated = await this.claim(shift._id, {
236
+ const updated = await this.applyTransition(String(shift._id), shiftMachine("close"), {
232
237
  field: "state",
233
238
  from: fromState,
234
- to: "closed"
235
- }, set, repoOptionsFromCtx(ctx));
236
- if (!updated) throw new IllegalShiftTransitionError(fromState, "close");
239
+ to: "closed",
240
+ set,
241
+ history: false
242
+ }, repoOptionsFromCtx(ctx)).catch((err) => {
243
+ if (isTransitionRace(err)) throw new IllegalShiftTransitionError(fromState, "close");
244
+ throw err;
245
+ });
237
246
  if (varianceExceeded && cashRow?.expectedAmount != null) await this.dispatch(POS_EVENTS.VARIANCE_DETECTED, {
238
247
  shiftId: input.shiftId,
239
248
  difference: cashRow.difference ?? 0,
@@ -312,20 +321,24 @@ var ShiftRepository = class extends Repository {
312
321
  }
313
322
  }
314
323
  const fromState = shift.state;
315
- const updated = await this.claim(shift._id, {
324
+ const updated = await this.applyTransition(String(shift._id), shiftMachine("forceClose"), {
316
325
  field: "state",
317
326
  from: fromState,
318
- to: "orphaned_closed"
319
- }, {
320
- closedAt: /* @__PURE__ */ new Date(),
321
- closedBy: "system_auto",
322
- paymentBreakdown: breakdown,
323
- expectedCash: cashRow?.expectedAmount ?? null,
324
- countedCash: cashRow?.countedAmount ?? null,
325
- cashDifference: 0,
326
- ...journalEntryId ? { journalEntryId } : {}
327
- }, repoOptionsFromCtx(ctx));
328
- if (!updated) throw new IllegalShiftTransitionError(fromState, "forceClose");
327
+ to: "orphaned_closed",
328
+ set: {
329
+ closedAt: /* @__PURE__ */ new Date(),
330
+ closedBy: "system_auto",
331
+ paymentBreakdown: breakdown,
332
+ expectedCash: cashRow?.expectedAmount ?? null,
333
+ countedCash: cashRow?.countedAmount ?? null,
334
+ cashDifference: 0,
335
+ ...journalEntryId ? { journalEntryId } : {}
336
+ },
337
+ history: false
338
+ }, repoOptionsFromCtx(ctx)).catch((err) => {
339
+ if (isTransitionRace(err)) throw new IllegalShiftTransitionError(fromState, "forceClose");
340
+ throw err;
341
+ });
329
342
  await this.dispatch(POS_EVENTS.SHIFT_FORCE_CLOSED, {
330
343
  shiftId,
331
344
  reason: "orphan_eod"
@@ -368,12 +381,16 @@ var ShiftRepository = class extends Repository {
368
381
  const shift = await this.requireActive(shiftId, ctx);
369
382
  const target = nextState(shift.state, verb);
370
383
  if (!target) throw new IllegalShiftTransitionError(shift.state, verb);
371
- const updated = await this.claim(shift._id, {
384
+ const updated = await this.applyTransition(String(shift._id), shiftMachine(verb), {
372
385
  field: "state",
373
386
  from: shift.state,
374
- to: target
375
- }, extraSet, repoOptionsFromCtx(ctx));
376
- if (!updated) throw new IllegalShiftTransitionError(shift.state, verb);
387
+ to: target,
388
+ set: extraSet,
389
+ history: false
390
+ }, repoOptionsFromCtx(ctx)).catch((err) => {
391
+ if (isTransitionRace(err)) throw new IllegalShiftTransitionError(shift.state, verb);
392
+ throw err;
393
+ });
377
394
  const eventName = verb === "pause" ? POS_EVENTS.SHIFT_PAUSED : POS_EVENTS.SHIFT_RESUMED;
378
395
  await this.dispatch(eventName, {
379
396
  shiftId,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@classytic/pos",
3
- "version": "0.2.1",
4
- "description": "Multi-vertical POS / register-session kernel for MongoDB — shift lifecycle, cash-drawer reconciliation, payment-method breakdown, variance detection, FSM. Works for retail, restaurant, clinic, service-booking, car-wash and any vertical with a 'shift opens, shift closes, money is reconciled' workflow.",
3
+ "version": "0.3.0",
4
+ "description": "Multi-vertical POS / register-session kernel for MongoDB \u2014 shift lifecycle, cash-drawer reconciliation, payment-method breakdown, variance detection, FSM. Works for retail, restaurant, clinic, service-booking, car-wash and any vertical with a 'shift opens, shift closes, money is reconciled' workflow.",
5
5
  "author": "Classytic",
6
6
  "type": "module",
7
7
  "sideEffects": false,
@@ -71,17 +71,17 @@
71
71
  "release": "npm run push -- main && npm run release:tag && npm publish"
72
72
  },
73
73
  "peerDependencies": {
74
- "@classytic/mongokit": ">=3.18.0",
75
- "@classytic/primitives": ">=0.7.2",
76
- "@classytic/repo-core": ">=0.7.0",
74
+ "@classytic/mongokit": ">=3.22.0",
75
+ "@classytic/primitives": ">=0.11.0",
76
+ "@classytic/repo-core": ">=0.13.0",
77
77
  "mongoose": ">=9.4.1",
78
78
  "zod": ">=4.0.0"
79
79
  },
80
80
  "devDependencies": {
81
81
  "@classytic/dev-tools": "^0.2.0",
82
- "@classytic/mongokit": "^3.18.0",
83
- "@classytic/primitives": "^0.7.2",
84
- "@classytic/repo-core": "^0.7.0",
82
+ "@classytic/mongokit": "^3.22.0",
83
+ "@classytic/primitives": "^0.11.0",
84
+ "@classytic/repo-core": "^0.13.0",
85
85
  "@types/node": "^25.5.0",
86
86
  "@vitest/coverage-v8": "^3.2.4",
87
87
  "mongodb-memory-server": "^10.2.3",