@classytic/pos 0.2.0 → 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,54 +1,75 @@
1
- # Changelog
2
-
3
- ## 0.2.0 — Stack upgrade + PACKAGE_RULES compliance
4
-
5
- Peer minimums raised to `@classytic/mongokit >=3.16.0`, `@classytic/repo-core >=0.6.0`,
6
- `@classytic/primitives >=0.7.2`. No new features — correctness + compliance.
7
-
8
- ### Added
9
- - **Transactional outbox support (P8 / §5.5 / §16).** Engine + repository accept
10
- `outbox?: OutboxStore`. Every domain event now flows through one session-bound
11
- `dispatch()`: `outbox.save` runs first under `ctx.session` and **propagates** on
12
- failure (the host's transaction rolls back); `transport.publish` runs second and
13
- **swallows** failures (the host relay re-delivers). Both sides share one envelope
14
- `meta.id` so relay re-publish is dedup-able. `MemoryOutboxStore` shipped from
15
- `@classytic/pos/events` for tests/dev (host owns production durability).
16
- - **Zod event catalog (§18).** `posEventDefinitions[]` exported from the package
17
- root and `/events`; one Zod schema per `POS_EVENTS` constant drives runtime
18
- validation, static types, and arc `EventRegistry`/OpenAPI introspection. No-drift
19
- invariant test added.
20
- - **`pos:shift.variance.detected`** is now emitted at close when the variance gate
21
- trips (including manager-overridden closes) — previously a declared-but-unused
22
- constant.
23
- - **Capability boot gate.** `createPosEngine` asserts `repo.capabilities.transactions`
24
- at boot (fail loud, not a cryptic driver error on the first close); opt out with
25
- `allowNonTransactional: true` for standalone-Mongo dev.
26
- - `ctx.signal` / `ctx.retryPolicy` are now threaded to every repo call via
27
- `repoOptionsFromCtx` (cooperative cancellation + driver-round-trip retries).
28
-
29
- ### Fixed
30
- - **Money integrity.** `incrementSales` and `recordCashMovement` reject non-integer
31
- (fractional) minor-unit amounts instead of `$inc`-ing float drift into totals.
32
- - **Event-name drift.** `pause`/`resume` emitted `pos:shift.pause`/`pos:shift.resume`;
33
- now correctly emit the catalog names `pos:shift.paused`/`pos:shift.resumed`.
34
- - **Soft-delete leak in `findStaleShifts`.** The raw cross-tenant cron scan now
35
- carries an explicit `deletedAt: null` guard so the EOD backstop can't revive a
36
- soft-deleted shift.
37
- - **Build hygiene.** `declarationMap` / `sourceMap` turned OFF in tsconfig (they leak
38
- source); `exactOptionalPropertyTypes: true` enabled (mandatory).
39
-
40
- ## 0.1.1 — Initial public release
41
-
42
- - `createPosEngine()` factory with `connection` + `defaultPolicy`
43
- - `Shift` model + Mongoose schema (3 indexes, all justified)
44
- - `ShiftRepository` extending mongokit `Repository<IShift>` with domain verbs:
45
- `open`, `pause`, `resume`, `recordCashMovement`, `incrementSales`,
46
- `blindClose`, `close`, `forceClose`
47
- - 5-state FSM: `open` → `paused` ↔ `open` → `blind_closed` → `closed`;
48
- any active state → `orphaned_closed` via `forceClose`
49
- - Bridges: `ledger` (JE emission), `policy` (per-branch policy resolver),
50
- `notification` (variance + orphan alerts)
51
- - Multi-tenant scoping via mongokit `multiTenantPlugin` (default ON)
52
- - 7-year soft-delete retention via `softDeletePlugin`
53
- - Zod v4 body schemas at `@classytic/pos/schemas` for arc 2.11 wiring
54
- - 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
@@ -10,6 +10,14 @@ declare class PosError extends Error {
10
10
  readonly code: string;
11
11
  constructor(code: string, message: string);
12
12
  }
13
+ /**
14
+ * Thrown when a host passes ctx.session but NO outbox is wired —
15
+ * publishing mid-transaction leaks ghost events on rollback (§P8.1).
16
+ * Session + outbox is legal durable-relay-only mode.
17
+ */
18
+ declare class UnmanagedSessionError extends PosError {
19
+ constructor();
20
+ }
13
21
  declare class ShiftNotFoundError extends PosError {
14
22
  constructor(id: string);
15
23
  }
@@ -38,4 +46,4 @@ declare class ShiftModelCollisionError extends Error {
38
46
  constructor(name: string);
39
47
  }
40
48
  //#endregion
41
- export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError };
49
+ export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError };
@@ -14,6 +14,16 @@ var PosError = class extends Error {
14
14
  this.code = code;
15
15
  }
16
16
  };
17
+ /**
18
+ * Thrown when a host passes ctx.session but NO outbox is wired —
19
+ * publishing mid-transaction leaks ghost events on rollback (§P8.1).
20
+ * Session + outbox is legal durable-relay-only mode.
21
+ */
22
+ var UnmanagedSessionError = class extends PosError {
23
+ constructor() {
24
+ super("POS_SESSION_UNMANAGED", "ctx.session provided but no OutboxStore is wired — events would leak or be lost. Wire an outbox or drop the session.");
25
+ }
26
+ };
17
27
  var ShiftNotFoundError = class extends PosError {
18
28
  constructor(id) {
19
29
  super("SHIFT_NOT_FOUND", `Shift not found: ${id}`);
@@ -69,4 +79,4 @@ var ShiftModelCollisionError = class extends Error {
69
79
  }
70
80
  };
71
81
  //#endregion
72
- export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError };
82
+ export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError };
@@ -6,9 +6,9 @@ import { SHIFT_VERBS, ShiftVerb, allowedVerbs, canTransition, nextState } from "
6
6
  import { CashMovement } from "./value-objects/cash-movement.vo.mjs";
7
7
  import { PaymentBreakdown, computeDifference, computeExpected } from "./value-objects/payment-breakdown.vo.mjs";
8
8
  import { ShiftPolicy, isWithinVarianceThreshold } from "./value-objects/shift-policy.vo.mjs";
9
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./errors/pos.errors.mjs";
9
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError } from "./errors/pos.errors.mjs";
10
10
  import { PosContext } from "./ports/common.mjs";
11
11
  import { LedgerBridge } from "./ports/ledger.bridge.mjs";
12
12
  import { PolicyBridge } from "./ports/policy.bridge.mjs";
13
13
  import { NotificationBridge } from "./ports/notification.bridge.mjs";
14
- export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementReasonCode, ClosedBy, FINAL_SHIFT_STATES, IllegalShiftTransitionError, type LedgerBridge, type NotificationBridge, PaymentBreakdown, type PolicyBridge, PosCapabilityError, type PosContext, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, ShiftPaymentMethod, ShiftPolicy, ShiftState, ShiftVerb, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
14
+ export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementReasonCode, ClosedBy, FINAL_SHIFT_STATES, IllegalShiftTransitionError, type LedgerBridge, type NotificationBridge, PaymentBreakdown, type PolicyBridge, PosCapabilityError, type PosContext, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, ShiftPaymentMethod, ShiftPolicy, ShiftState, ShiftVerb, UnmanagedSessionError, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
@@ -1,4 +1,4 @@
1
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./errors/pos.errors.mjs";
1
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError } from "./errors/pos.errors.mjs";
2
2
  import { CASH_MOVEMENT_REASON_CODES } from "./enums/cash-movement-reason.enum.mjs";
3
3
  import { CLOSED_BY_VALUES } from "./enums/closed-by.enum.mjs";
4
4
  import { SHIFT_PAYMENT_METHODS } from "./enums/payment-method.enum.mjs";
@@ -6,4 +6,4 @@ import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, isActiveShiftSta
6
6
  import { SHIFT_VERBS, allowedVerbs, canTransition, nextState } from "./state-machines/shift.fsm.mjs";
7
7
  import { computeDifference, computeExpected } from "./value-objects/payment-breakdown.vo.mjs";
8
8
  import { isWithinVarianceThreshold } from "./value-objects/shift-policy.vo.mjs";
9
- export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, FINAL_SHIFT_STATES, IllegalShiftTransitionError, PosCapabilityError, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
9
+ export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, FINAL_SHIFT_STATES, IllegalShiftTransitionError, PosCapabilityError, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
package/dist/index.d.mts CHANGED
@@ -6,7 +6,7 @@ import { SHIFT_VERBS, ShiftVerb, allowedVerbs, canTransition, nextState } from "
6
6
  import { CashMovement } from "./domain/value-objects/cash-movement.vo.mjs";
7
7
  import { PaymentBreakdown, computeDifference, computeExpected } from "./domain/value-objects/payment-breakdown.vo.mjs";
8
8
  import { ShiftPolicy, isWithinVarianceThreshold } from "./domain/value-objects/shift-policy.vo.mjs";
9
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
9
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
10
10
  import { PosContext } from "./domain/ports/common.mjs";
11
11
  import { IShift, ShiftDocument, ShiftModel } from "./models/shift.model.mjs";
12
12
  import { LedgerBridge } from "./domain/ports/ledger.bridge.mjs";
@@ -22,4 +22,4 @@ import { createPosEvent } from "./events/helpers.mjs";
22
22
  import { InProcessPosBus } from "./events/in-process-bus.mjs";
23
23
  import { PosEventDefinition, PosEventPayloadOf, cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent } from "./events/event-catalog.mjs";
24
24
  import { DEFAULT_COLLECTIONS } from "./models/create-models.mjs";
25
- export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, type BlindCloseInput, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementReasonCode, CashMovementRecordedPayload, type CloseShiftInput, ClosedBy, DEFAULT_COLLECTIONS, FINAL_SHIFT_STATES, type IShift, IllegalShiftTransitionError, InProcessPosBus, type IncrementSalesInput, InvalidOutboxEventError, LedgerBridge, MemoryOutboxStore, NotificationBridge, type OpenShiftInput, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxFailOptions, OutboxOwnershipError, OutboxStore, OutboxWriteOptions, POS_EVENTS, PaymentBreakdown, PolicyBridge, type PosBridges, PosCapabilityError, type PosConfig, PosContext, type PosEngine, PosError, PosEventDefinition, PosEventName, PosEventPayloadOf, PosEventPayloads, type PosLogger, type PosModels, type PosRepositories, type RecordCashMovementInput, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftBlindClosedPayload, ShiftClosedPayload, type ShiftDocument, ShiftFinalizedError, ShiftForceClosedPayload, type ShiftModel, ShiftModelCollisionError, ShiftNotFoundError, ShiftOpenedPayload, ShiftPaymentMethod, ShiftPolicy, ShiftRepository, type ShiftRepositoryConfig, ShiftState, ShiftStateChangedPayload, ShiftVerb, VarianceDetectedPayload, VarianceExceededError, allowedVerbs, canTransition, cashMovementRecordedEvent, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
25
+ export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, type BlindCloseInput, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementReasonCode, CashMovementRecordedPayload, type CloseShiftInput, ClosedBy, DEFAULT_COLLECTIONS, FINAL_SHIFT_STATES, type IShift, IllegalShiftTransitionError, InProcessPosBus, type IncrementSalesInput, InvalidOutboxEventError, LedgerBridge, MemoryOutboxStore, NotificationBridge, type OpenShiftInput, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxFailOptions, OutboxOwnershipError, OutboxStore, OutboxWriteOptions, POS_EVENTS, PaymentBreakdown, PolicyBridge, type PosBridges, PosCapabilityError, type PosConfig, PosContext, type PosEngine, PosError, PosEventDefinition, PosEventName, PosEventPayloadOf, PosEventPayloads, type PosLogger, type PosModels, type PosRepositories, type RecordCashMovementInput, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftBlindClosedPayload, ShiftClosedPayload, type ShiftDocument, ShiftFinalizedError, ShiftForceClosedPayload, type ShiftModel, ShiftModelCollisionError, ShiftNotFoundError, ShiftOpenedPayload, ShiftPaymentMethod, ShiftPolicy, ShiftRepository, type ShiftRepositoryConfig, ShiftState, ShiftStateChangedPayload, ShiftVerb, UnmanagedSessionError, VarianceDetectedPayload, VarianceExceededError, allowedVerbs, canTransition, cashMovementRecordedEvent, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { InProcessPosBus } from "./events/in-process-bus.mjs";
2
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
2
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
3
3
  import { CASH_MOVEMENT_REASON_CODES } from "./domain/enums/cash-movement-reason.enum.mjs";
4
4
  import { CLOSED_BY_VALUES } from "./domain/enums/closed-by.enum.mjs";
5
5
  import { SHIFT_PAYMENT_METHODS } from "./domain/enums/payment-method.enum.mjs";
@@ -14,4 +14,4 @@ import { ShiftRepository } from "./repositories/shift.repository.mjs";
14
14
  import { createPosEngine } from "./engine/create-pos.mjs";
15
15
  import { cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent } from "./events/event-catalog.mjs";
16
16
  import { InvalidOutboxEventError, MemoryOutboxStore, OutboxOwnershipError } from "./events/outbox-store.mjs";
17
- export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, DEFAULT_COLLECTIONS, FINAL_SHIFT_STATES, IllegalShiftTransitionError, InProcessPosBus, InvalidOutboxEventError, MemoryOutboxStore, OutboxOwnershipError, POS_EVENTS, PosCapabilityError, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, ShiftRepository, VarianceExceededError, allowedVerbs, canTransition, cashMovementRecordedEvent, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
17
+ export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, DEFAULT_COLLECTIONS, FINAL_SHIFT_STATES, IllegalShiftTransitionError, InProcessPosBus, InvalidOutboxEventError, MemoryOutboxStore, OutboxOwnershipError, POS_EVENTS, PosCapabilityError, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, ShiftRepository, UnmanagedSessionError, VarianceExceededError, allowedVerbs, canTransition, cashMovementRecordedEvent, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
@@ -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 };
@@ -1,10 +1,11 @@
1
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, ShiftFinalizedError, ShiftNotFoundError, VarianceExceededError } from "../domain/errors/pos.errors.mjs";
1
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, ShiftFinalizedError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError } from "../domain/errors/pos.errors.mjs";
2
2
  import { canTransition, nextState } from "../domain/state-machines/shift.fsm.mjs";
3
3
  import { computeDifference, computeExpected } from "../domain/value-objects/payment-breakdown.vo.mjs";
4
4
  import { isWithinVarianceThreshold } from "../domain/value-objects/shift-policy.vo.mjs";
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,
@@ -412,6 +429,7 @@ var ShiftRepository = class extends Repository {
412
429
  */
413
430
  async dispatch(name, payload, ctx) {
414
431
  if (!this.outbox && !this.eventTransport) return;
432
+ if (ctx.session && !this.outbox) throw new UnmanagedSessionError();
415
433
  const event = createPosEvent(name, payload);
416
434
  if (this.outbox) try {
417
435
  await this.outbox.save(event, ctx.session !== void 0 ? { session: ctx.session } : {});
@@ -419,7 +437,7 @@ var ShiftRepository = class extends Repository {
419
437
  this.logger.error(`[pos] outbox.save failed for ${name}`, err);
420
438
  throw err;
421
439
  }
422
- if (this.eventTransport) try {
440
+ if (this.eventTransport && !ctx.session) try {
423
441
  await this.eventTransport.publish(event);
424
442
  } catch (err) {
425
443
  this.logger.error(`[pos] event transport failed for ${name}`, err);
@@ -13,24 +13,25 @@ import { z } from "zod";
13
13
  */
14
14
  const objectIdString = z.string().regex(/^[a-f0-9]{24}$/i, "invalid ObjectId");
15
15
  const isoDate = z.union([z.iso.datetime(), z.iso.date()]);
16
+ const minorUnits = z.number().int();
16
17
  const openShiftBody = z.object({
17
18
  registerId: z.string().min(1),
18
19
  businessDate: isoDate,
19
20
  openingCashierId: z.string().min(1),
20
21
  openingCashierName: z.string().min(1),
21
- openingCash: z.number().min(0),
22
+ openingCash: minorUnits.min(0),
22
23
  notes: z.string().optional()
23
24
  });
24
25
  const recordCashMovementBody = z.object({
25
26
  type: z.enum(["in", "out"]),
26
- amount: z.number().positive(),
27
+ amount: minorUnits.positive(),
27
28
  reasonCode: z.enum(CASH_MOVEMENT_REASON_CODES),
28
29
  note: z.string().default(""),
29
30
  cashierId: z.string().min(1),
30
31
  cashierName: z.string().min(1),
31
32
  timestamp: isoDate.optional()
32
33
  });
33
- const countedByMethodSchema = z.record(z.enum(SHIFT_PAYMENT_METHODS), z.number().min(0));
34
+ const countedByMethodSchema = z.record(z.enum(SHIFT_PAYMENT_METHODS), minorUnits.min(0));
34
35
  const blindCloseBody = z.object({
35
36
  countedByMethod: countedByMethodSchema,
36
37
  closingCashierId: z.string().min(1),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/pos",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
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",
@@ -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.16.0",
75
- "@classytic/primitives": ">=0.7.2",
76
- "@classytic/repo-core": ">=0.6.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.16.0",
83
- "@classytic/primitives": "^0.7.2",
84
- "@classytic/repo-core": "^0.6.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",