@classytic/pos 0.1.1 → 0.2.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,5 +1,42 @@
1
1
  # Changelog
2
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
+
3
40
  ## 0.1.1 — Initial public release
4
41
 
5
42
  - `createPosEngine()` factory with `connection` + `defaultPolicy`
package/README.md CHANGED
@@ -28,7 +28,12 @@ The package's only assumption: "a session opens, accumulates payments, reconcile
28
28
  npm install @classytic/pos
29
29
  ```
30
30
 
31
- Peer deps: `mongoose >=9.4.1`, `@classytic/mongokit >=3.11.0`, `@classytic/primitives >=0.1.0`, `@classytic/repo-core >=0.2.0`, `zod >=4.0.0`.
31
+ Peer deps: `mongoose >=9.4.1`, `@classytic/mongokit >=3.16.0`, `@classytic/primitives >=0.7.2`, `@classytic/repo-core >=0.6.0`, `zod >=4.0.0`.
32
+
33
+ > **Transactions required.** The close pipeline is CAS-driven and hosts routinely
34
+ > wrap the shift + outbox writes in a transaction, so `createPosEngine` asserts the
35
+ > backend declares the `transactions` capability at boot (MongoDB replica set). Pass
36
+ > `allowNonTransactional: true` for standalone-Mongo local dev.
32
37
 
33
38
  ## Quick start
34
39
 
@@ -136,12 +141,46 @@ export default defineResource({
136
141
 
137
142
  Auto-CRUD (list/get/create/update/delete) comes from arc + mongokit. State transitions go through declarative actions. Custom routes only when you genuinely need them.
138
143
 
144
+ ## Events & transactional outbox
145
+
146
+ Every domain verb emits a `pos:*` event. Inject any arc `EventTransport`
147
+ (Memory / Redis / Kafka) — the package falls back to an in-process bus.
148
+
149
+ For at-least-once delivery, wire a host-owned `OutboxStore`. Each event is then
150
+ `save`d to the outbox under `ctx.session` **before** the transport publish, so the
151
+ event row commits atomically with the shift write. Save failures propagate (the
152
+ host's transaction rolls back); publish failures are swallowed (the relay
153
+ re-delivers from the durable row).
154
+
155
+ ```ts
156
+ import { createPosEngine } from '@classytic/pos';
157
+ import { MongoOutboxStore } from '@classytic/arc'; // or any OutboxStore impl
158
+
159
+ const pos = createPosEngine({
160
+ connection,
161
+ defaultPolicy,
162
+ eventTransport: redisTransport,
163
+ outbox: new MongoOutboxStore({ connection, name: 'outbox' }),
164
+ });
165
+ ```
166
+
167
+ Hosts wanting publish-time validation / OpenAPI introspection register the Zod
168
+ event catalog with arc's `EventRegistry`:
169
+
170
+ ```ts
171
+ import { posEventDefinitions } from '@classytic/pos/events';
172
+ for (const def of posEventDefinitions) registry.register(def);
173
+ ```
174
+
139
175
  ## Subpath exports
140
176
 
141
177
  ```ts
142
178
  import { createPosEngine } from '@classytic/pos'; // engine + types
143
179
  import { ShiftRepository, type IShift } from '@classytic/pos'; // repo + model types
144
- import { POS_EVENTS, InProcessPosBus } from '@classytic/pos/events';
180
+ import {
181
+ POS_EVENTS, InProcessPosBus,
182
+ posEventDefinitions, MemoryOutboxStore, type OutboxStore,
183
+ } from '@classytic/pos/events';
145
184
  import { canTransition, ShiftPolicy } from '@classytic/pos/domain';
146
185
  import { openShiftBody, closeBody } from '@classytic/pos/schemas';
147
186
  import { makePolicy, makeOpenShiftInput } from '@classytic/pos/testing';
@@ -30,8 +30,12 @@ declare class ShiftFinalizedError extends PosError {
30
30
  declare class CashMovementInvalidError extends PosError {
31
31
  constructor(reason: string);
32
32
  }
33
+ declare class PosCapabilityError extends Error {
34
+ readonly missing: readonly string[];
35
+ constructor(missing: readonly string[]);
36
+ }
33
37
  declare class ShiftModelCollisionError extends Error {
34
38
  constructor(name: string);
35
39
  }
36
40
  //#endregion
37
- export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError };
41
+ export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError };
@@ -54,6 +54,14 @@ var CashMovementInvalidError = class extends PosError {
54
54
  this.name = "CashMovementInvalidError";
55
55
  }
56
56
  };
57
+ var PosCapabilityError = class extends Error {
58
+ missing;
59
+ constructor(missing) {
60
+ super(`[pos] backend missing required capabilities: ${missing.join(", ")}. The close / forceClose pipelines run through CAS and are transactional — MongoDB must run as a replica set (repo-core 0.6 / mongokit 3.16+). Pass \`allowNonTransactional: true\` for standalone-Mongo local dev.`);
61
+ this.name = "PosCapabilityError";
62
+ this.missing = missing;
63
+ }
64
+ };
57
65
  var ShiftModelCollisionError = class extends Error {
58
66
  constructor(name) {
59
67
  super(`[pos] Mongoose model "${name}" already exists on this connection. For hot-reload / test fixtures, pass \`forceRecreate: true\` to clobber. For two pos engines in one process, use two Mongoose connections (\`mongoose.createConnection(...)\`) — each has its own model registry.`);
@@ -61,4 +69,4 @@ var ShiftModelCollisionError = class extends Error {
61
69
  }
62
70
  };
63
71
  //#endregion
64
- export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError };
72
+ export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, 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, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./errors/pos.errors.mjs";
9
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, 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, 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, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
@@ -1,4 +1,4 @@
1
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./errors/pos.errors.mjs";
1
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, 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, 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, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
@@ -1,9 +1,22 @@
1
1
  import { OperationContext } from "@classytic/primitives/context";
2
+ import { RetryPolicy } from "@classytic/repo-core/repository";
2
3
 
3
4
  //#region src/domain/ports/common.d.ts
4
5
  interface PosContext extends OperationContext {
5
6
  /** Host's local-TZ business date (YYYY-MM-DD) for shifts that derive at open. */
6
- businessDate?: string;
7
+ businessDate?: string | undefined;
8
+ /**
9
+ * Cooperative-cancellation signal. Threaded to every repo call via
10
+ * `repoOptionsFromCtx`; mongokit checks it at each op boundary and stops
11
+ * before the next driver round-trip (PACKAGE_RULES "Cancellation + retry").
12
+ */
13
+ signal?: AbortSignal | undefined;
14
+ /**
15
+ * Per-operation retry policy. mongokit wraps driver round-trips in
16
+ * `withRetry` when present; absent → single attempt. Threaded via
17
+ * `repoOptionsFromCtx`.
18
+ */
19
+ retryPolicy?: RetryPolicy | undefined;
7
20
  }
8
21
  //#endregion
9
22
  export { PosContext };
@@ -1,4 +1,5 @@
1
1
  import { InProcessPosBus } from "../events/in-process-bus.mjs";
2
+ import { PosCapabilityError } from "../domain/errors/pos.errors.mjs";
2
3
  import { resolvePosTenant } from "../models/inject-tenant.mjs";
3
4
  import { createPosModels } from "../models/create-models.mjs";
4
5
  import { ShiftRepository } from "../repositories/shift.repository.mjs";
@@ -20,6 +21,14 @@ import { multiTenantPlugin } from "@classytic/mongokit";
20
21
  * impossible to forget. Hosts that genuinely need single-tenant deployments
21
22
  * pass `multiTenant: false`.
22
23
  */
24
+ /**
25
+ * Runtime capabilities the transactional close pipeline requires at boot
26
+ * (PACKAGE_RULES "Runtime capabilities"). `close` / `forceClose` move state
27
+ * via `repo.claim` CAS and hosts routinely wrap multi-doc writes (shift +
28
+ * outbox row) in a transaction — assert the backend declares `transactions`
29
+ * here instead of failing with a cryptic driver error on the first close.
30
+ */
31
+ const REQUIRED_CAPABILITIES = ["transactions"];
23
32
  function createPosEngine(config) {
24
33
  if (!config.connection) throw new Error("createPosEngine: config.connection is required");
25
34
  if (!config.defaultPolicy) throw new Error("createPosEngine: config.defaultPolicy is required");
@@ -50,12 +59,20 @@ function createPosEngine(config) {
50
59
  ...bridges.policy ? { policyBridge: bridges.policy } : {},
51
60
  ...bridges.notification ? { notificationBridge: bridges.notification } : {},
52
61
  eventTransport: events,
62
+ ...config.outbox ? { outbox: config.outbox } : {},
53
63
  logger
54
64
  });
65
+ if (config.allowNonTransactional !== true) {
66
+ const caps = shiftRepo.capabilities;
67
+ if (!caps) throw new PosCapabilityError(["capabilities descriptor (repo-core 0.6 / mongokit 3.16+)"]);
68
+ const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
69
+ if (missing.length > 0) throw new PosCapabilityError(missing);
70
+ }
55
71
  return {
56
72
  config: Object.freeze({ ...config }),
57
73
  bridges: Object.freeze({ ...bridges }),
58
74
  events,
75
+ outbox: config.outbox,
59
76
  models,
60
77
  repositories: { shift: shiftRepo },
61
78
  defaultPolicy: config.defaultPolicy
@@ -7,6 +7,7 @@ import { ShiftRepository } from "../repositories/shift.repository.mjs";
7
7
  import { EventTransport } from "@classytic/primitives/events";
8
8
  import { Connection, Model } from "mongoose";
9
9
  import { TenantConfig } from "@classytic/repo-core/tenant";
10
+ import { OutboxStore } from "@classytic/primitives/outbox";
10
11
 
11
12
  //#region src/engine/engine-types.d.ts
12
13
  interface PosBridges {
@@ -34,6 +35,22 @@ interface PosConfig {
34
35
  bridges?: PosBridges | undefined;
35
36
  /** Inject your own event bus; otherwise an in-process bus is used. */
36
37
  eventTransport?: EventTransport | undefined;
38
+ /**
39
+ * Transactional outbox (host-composed — PACKAGE_RULES §5.5 / §16). When
40
+ * wired, every domain event is `save`d to the outbox under `ctx.session`
41
+ * BEFORE the transport publish, so the event row commits atomically with
42
+ * the shift write. The host owns durability, the relay, retries, and DLQ —
43
+ * drop in arc's `MongoOutboxStore` or any `OutboxStore` impl.
44
+ */
45
+ outbox?: OutboxStore | undefined;
46
+ /**
47
+ * Skip the boot-time capability gate. The close / forceClose pipelines run
48
+ * through `repo.claim` CAS and may be wrapped by hosts in a transaction.
49
+ * The gate asserts the backend declares `transactions` at engine creation
50
+ * (fail loud at boot, not with a cryptic driver error on the first close).
51
+ * Set `true` for standalone-Mongo local dev where transactions are absent.
52
+ */
53
+ allowNonTransactional?: boolean | undefined;
37
54
  /**
38
55
  * Multi-tenant scoping. `true` (default) wires the mongokit
39
56
  * `multiTenantPlugin` and prepends `organizationId` to every compound
@@ -65,6 +82,8 @@ interface PosEngine {
65
82
  readonly config: Readonly<PosConfig>;
66
83
  readonly bridges: Readonly<PosBridges>;
67
84
  readonly events: EventTransport;
85
+ /** Host-provided outbox (if wired), surfaced for relay composition. */
86
+ readonly outbox: OutboxStore | undefined;
68
87
  readonly models: PosModels;
69
88
  readonly repositories: PosRepositories;
70
89
  readonly defaultPolicy: ShiftPolicy;
@@ -0,0 +1,78 @@
1
+ import { DomainEvent } from "@classytic/primitives/events";
2
+ import { z } from "zod";
3
+
4
+ //#region src/events/event-catalog.d.ts
5
+ interface PosEventDefinition<TSchema extends z.ZodType = z.ZodType> {
6
+ readonly name: string;
7
+ readonly version: number;
8
+ readonly description?: string;
9
+ readonly schema: Record<string, unknown>;
10
+ readonly zodSchema: TSchema;
11
+ create(payload: z.infer<TSchema>, meta?: Partial<DomainEvent['meta']>): DomainEvent<z.infer<TSchema>>;
12
+ readonly __payload?: z.infer<TSchema>;
13
+ }
14
+ type PosEventPayloadOf<D> = D extends PosEventDefinition<infer S> ? z.infer<S> : never;
15
+ declare const shiftOpenedEvent: PosEventDefinition<z.ZodObject<{
16
+ shiftId: z.ZodString;
17
+ registerId: z.ZodString;
18
+ openingCashierId: z.ZodString;
19
+ }, z.core.$strip>>;
20
+ declare const shiftPausedEvent: PosEventDefinition<z.ZodObject<{
21
+ shiftId: z.ZodString;
22
+ from: z.ZodString;
23
+ to: z.ZodString;
24
+ }, z.core.$strip>>;
25
+ declare const shiftResumedEvent: PosEventDefinition<z.ZodObject<{
26
+ shiftId: z.ZodString;
27
+ from: z.ZodString;
28
+ to: z.ZodString;
29
+ }, z.core.$strip>>;
30
+ declare const shiftBlindClosedEvent: PosEventDefinition<z.ZodObject<{
31
+ shiftId: z.ZodString;
32
+ }, z.core.$strip>>;
33
+ declare const shiftClosedEvent: PosEventDefinition<z.ZodObject<{
34
+ shiftId: z.ZodString;
35
+ journalEntryId: z.ZodNullable<z.ZodString>;
36
+ closedBy: z.ZodEnum<{
37
+ cashier: "cashier";
38
+ manager: "manager";
39
+ system_auto: "system_auto";
40
+ }>;
41
+ }, z.core.$strip>>;
42
+ declare const shiftForceClosedEvent: PosEventDefinition<z.ZodObject<{
43
+ shiftId: z.ZodString;
44
+ reason: z.ZodEnum<{
45
+ orphan_eod: "orphan_eod";
46
+ admin_override: "admin_override";
47
+ }>;
48
+ }, z.core.$strip>>;
49
+ declare const cashMovementRecordedEvent: PosEventDefinition<z.ZodObject<{
50
+ shiftId: z.ZodString;
51
+ type: z.ZodEnum<{
52
+ in: "in";
53
+ out: "out";
54
+ }>;
55
+ amount: z.ZodNumber;
56
+ reasonCode: z.ZodEnum<{
57
+ safe_drop: "safe_drop";
58
+ petty_cash: "petty_cash";
59
+ owner_withdrawal: "owner_withdrawal";
60
+ correction: "correction";
61
+ bank_deposit: "bank_deposit";
62
+ till_top_up: "till_top_up";
63
+ other: "other";
64
+ }>;
65
+ }, z.core.$strip>>;
66
+ declare const varianceDetectedEvent: PosEventDefinition<z.ZodObject<{
67
+ shiftId: z.ZodString;
68
+ difference: z.ZodNumber;
69
+ expected: z.ZodNumber;
70
+ }, z.core.$strip>>;
71
+ /**
72
+ * Every POS event with a Zod schema. Export from the package root AND the
73
+ * `/events` subpath; the no-drift test asserts this covers every
74
+ * `POS_EVENTS` constant.
75
+ */
76
+ declare const posEventDefinitions: ReadonlyArray<PosEventDefinition>;
77
+ //#endregion
78
+ export { PosEventDefinition, PosEventPayloadOf, cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
@@ -0,0 +1,125 @@
1
+ import { CASH_MOVEMENT_REASON_CODES } from "../domain/enums/cash-movement-reason.enum.mjs";
2
+ import { CLOSED_BY_VALUES } from "../domain/enums/closed-by.enum.mjs";
3
+ import { POS_EVENTS } from "./event-constants.mjs";
4
+ import { createEvent } from "@classytic/primitives/events";
5
+ import { z } from "zod";
6
+ //#region src/events/event-catalog.ts
7
+ /**
8
+ * POS event catalog — every `pos:*` event defined with a Zod schema
9
+ * (PACKAGE_RULES §18). One Zod schema per event is the source of truth:
10
+ * runtime `safeParse()` validation, static payload types, and Arc's
11
+ * `EventRegistry` / OpenAPI introspection all derive from it.
12
+ *
13
+ * Definition shape is structurally identical to arc's `EventDefinitionOutput`
14
+ * — we do NOT import arc (compatibility is structural). Hosts wire with:
15
+ *
16
+ * for (const def of posEventDefinitions) registry.register(def);
17
+ *
18
+ * Timestamps in payloads are `z.iso.datetime()`, never `z.coerce.date()` —
19
+ * `z.toJSONSchema()` throws on coerce.date and the wire format is ISO string
20
+ * (§25).
21
+ */
22
+ function definePosEvent(input) {
23
+ const { name, version = 1, description, zodSchema } = input;
24
+ return {
25
+ name,
26
+ version,
27
+ ...description !== void 0 ? { description } : {},
28
+ schema: z.toJSONSchema(zodSchema),
29
+ zodSchema,
30
+ create(payload, meta) {
31
+ return createEvent(name, payload, {
32
+ resource: "shift",
33
+ ...meta
34
+ });
35
+ }
36
+ };
37
+ }
38
+ const shiftOpenedSchema = z.object({
39
+ shiftId: z.string(),
40
+ registerId: z.string(),
41
+ openingCashierId: z.string()
42
+ });
43
+ const shiftStateChangedSchema = z.object({
44
+ shiftId: z.string(),
45
+ from: z.string(),
46
+ to: z.string()
47
+ });
48
+ const shiftBlindClosedSchema = z.object({ shiftId: z.string() });
49
+ const shiftClosedSchema = z.object({
50
+ shiftId: z.string(),
51
+ journalEntryId: z.string().nullable(),
52
+ closedBy: z.enum(CLOSED_BY_VALUES)
53
+ });
54
+ const shiftForceClosedSchema = z.object({
55
+ shiftId: z.string(),
56
+ reason: z.enum(["orphan_eod", "admin_override"])
57
+ });
58
+ const cashMovementRecordedSchema = z.object({
59
+ shiftId: z.string(),
60
+ type: z.enum(["in", "out"]),
61
+ amount: z.number().int(),
62
+ reasonCode: z.enum(CASH_MOVEMENT_REASON_CODES)
63
+ });
64
+ const varianceDetectedSchema = z.object({
65
+ shiftId: z.string(),
66
+ difference: z.number().int(),
67
+ expected: z.number().int()
68
+ });
69
+ const shiftOpenedEvent = definePosEvent({
70
+ name: POS_EVENTS.SHIFT_OPENED,
71
+ description: "A register session opened with a cash float",
72
+ zodSchema: shiftOpenedSchema
73
+ });
74
+ const shiftPausedEvent = definePosEvent({
75
+ name: POS_EVENTS.SHIFT_PAUSED,
76
+ description: "Shift paused (Toast-style handover); drawer rejects new sales",
77
+ zodSchema: shiftStateChangedSchema
78
+ });
79
+ const shiftResumedEvent = definePosEvent({
80
+ name: POS_EVENTS.SHIFT_RESUMED,
81
+ description: "Paused shift resumed; drawer accepts sales again",
82
+ zodSchema: shiftStateChangedSchema
83
+ });
84
+ const shiftBlindClosedEvent = definePosEvent({
85
+ name: POS_EVENTS.SHIFT_BLIND_CLOSED,
86
+ description: "Cashier blind-counted; awaits manager reconcile (Lightspeed)",
87
+ zodSchema: shiftBlindClosedSchema
88
+ });
89
+ const shiftClosedEvent = definePosEvent({
90
+ name: POS_EVENTS.SHIFT_CLOSED,
91
+ description: "Shift reconciled and closed (Z-report); immutable thereafter",
92
+ zodSchema: shiftClosedSchema
93
+ });
94
+ const shiftForceClosedEvent = definePosEvent({
95
+ name: POS_EVENTS.SHIFT_FORCE_CLOSED,
96
+ description: "Orphaned shift auto-closed by EOD cron / admin; flagged for review",
97
+ zodSchema: shiftForceClosedSchema
98
+ });
99
+ const cashMovementRecordedEvent = definePosEvent({
100
+ name: POS_EVENTS.CASH_MOVEMENT_RECORDED,
101
+ description: "Mid-shift cash in/out movement appended to the drawer ledger",
102
+ zodSchema: cashMovementRecordedSchema
103
+ });
104
+ const varianceDetectedEvent = definePosEvent({
105
+ name: POS_EVENTS.VARIANCE_DETECTED,
106
+ description: "Cash variance exceeded the policy threshold at close",
107
+ zodSchema: varianceDetectedSchema
108
+ });
109
+ /**
110
+ * Every POS event with a Zod schema. Export from the package root AND the
111
+ * `/events` subpath; the no-drift test asserts this covers every
112
+ * `POS_EVENTS` constant.
113
+ */
114
+ const posEventDefinitions = [
115
+ shiftOpenedEvent,
116
+ shiftPausedEvent,
117
+ shiftResumedEvent,
118
+ shiftBlindClosedEvent,
119
+ shiftClosedEvent,
120
+ shiftForceClosedEvent,
121
+ cashMovementRecordedEvent,
122
+ varianceDetectedEvent
123
+ ];
124
+ //#endregion
125
+ export { cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
@@ -1,5 +1,7 @@
1
+ import { InvalidOutboxEventError, MemoryOutboxStore, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxFailOptions, OutboxOwnershipError, OutboxStore, OutboxWriteOptions } from "./outbox-store.mjs";
1
2
  import { POS_EVENTS, PosEventName } from "./event-constants.mjs";
2
3
  import { CashMovementRecordedPayload, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload } from "./event-payloads.mjs";
3
4
  import { createPosEvent } from "./helpers.mjs";
4
5
  import { InProcessPosBus } from "./in-process-bus.mjs";
5
- export { CashMovementRecordedPayload, InProcessPosBus, POS_EVENTS, PosEventName, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload, createPosEvent };
6
+ import { PosEventDefinition, PosEventPayloadOf, cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent } from "./event-catalog.mjs";
7
+ export { CashMovementRecordedPayload, InProcessPosBus, InvalidOutboxEventError, MemoryOutboxStore, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxFailOptions, OutboxOwnershipError, type OutboxStore, type OutboxWriteOptions, POS_EVENTS, type PosEventDefinition, PosEventName, type PosEventPayloadOf, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload, cashMovementRecordedEvent, createPosEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
@@ -1,4 +1,6 @@
1
1
  import { InProcessPosBus } from "./in-process-bus.mjs";
2
2
  import { POS_EVENTS } from "./event-constants.mjs";
3
3
  import { createPosEvent } from "./helpers.mjs";
4
- export { InProcessPosBus, POS_EVENTS, createPosEvent };
4
+ import { cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent } from "./event-catalog.mjs";
5
+ import { InvalidOutboxEventError, MemoryOutboxStore, OutboxOwnershipError } from "./outbox-store.mjs";
6
+ export { InProcessPosBus, InvalidOutboxEventError, MemoryOutboxStore, OutboxOwnershipError, POS_EVENTS, cashMovementRecordedEvent, createPosEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
@@ -0,0 +1,19 @@
1
+ import { DomainEvent } from "@classytic/primitives/events";
2
+ import { InvalidOutboxEventError, OutboxAcknowledgeOptions, OutboxAcknowledgeOptions as OutboxAcknowledgeOptions$1, OutboxClaimOptions, OutboxFailOptions, OutboxOwnershipError, OutboxStore, OutboxStore as OutboxStore$1, OutboxWriteOptions, OutboxWriteOptions as OutboxWriteOptions$1 } from "@classytic/primitives/outbox";
3
+
4
+ //#region src/events/outbox-store.d.ts
5
+ /**
6
+ * In-memory `OutboxStore` for tests and local dev. Not for production.
7
+ *
8
+ * Implements the required trio (`save` / `getPending` / `acknowledge`) plus
9
+ * optional `purge`. The package only calls `save()` itself.
10
+ */
11
+ declare class MemoryOutboxStore implements OutboxStore {
12
+ private events;
13
+ save(event: DomainEvent, _options?: OutboxWriteOptions): Promise<void>;
14
+ getPending(limit: number): Promise<DomainEvent[]>;
15
+ acknowledge(eventId: string, _options?: OutboxAcknowledgeOptions): Promise<void>;
16
+ purge(olderThanMs: number): Promise<number>;
17
+ }
18
+ //#endregion
19
+ export { InvalidOutboxEventError, MemoryOutboxStore, type OutboxAcknowledgeOptions$1 as OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxFailOptions, OutboxOwnershipError, type OutboxStore$1 as OutboxStore, type OutboxWriteOptions$1 as OutboxWriteOptions };
@@ -0,0 +1,29 @@
1
+ import { InvalidOutboxEventError, OutboxOwnershipError } from "@classytic/primitives/outbox";
2
+ //#region src/events/outbox-store.ts
3
+ /**
4
+ * In-memory `OutboxStore` for tests and local dev. Not for production.
5
+ *
6
+ * Implements the required trio (`save` / `getPending` / `acknowledge`) plus
7
+ * optional `purge`. The package only calls `save()` itself.
8
+ */
9
+ var MemoryOutboxStore = class {
10
+ events = [];
11
+ async save(event, _options) {
12
+ this.events.push({ event });
13
+ }
14
+ async getPending(limit) {
15
+ return this.events.filter((e) => !e.acknowledgedAt).slice(0, limit).map((e) => e.event);
16
+ }
17
+ async acknowledge(eventId, _options) {
18
+ const entry = this.events.find((e) => e.event.meta.id === eventId);
19
+ if (entry) entry.acknowledgedAt = /* @__PURE__ */ new Date();
20
+ }
21
+ async purge(olderThanMs) {
22
+ const cutoff = Date.now() - olderThanMs;
23
+ const before = this.events.length;
24
+ this.events = this.events.filter((e) => !e.acknowledgedAt || e.acknowledgedAt.getTime() >= cutoff);
25
+ return before - this.events.length;
26
+ }
27
+ };
28
+ //#endregion
29
+ export { InvalidOutboxEventError, MemoryOutboxStore, OutboxOwnershipError };
package/dist/index.d.mts CHANGED
@@ -6,12 +6,13 @@ 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, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
9
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, 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";
13
13
  import { PolicyBridge } from "./domain/ports/policy.bridge.mjs";
14
14
  import { NotificationBridge } from "./domain/ports/notification.bridge.mjs";
15
+ import { InvalidOutboxEventError, MemoryOutboxStore, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxFailOptions, OutboxOwnershipError, OutboxStore, OutboxWriteOptions } from "./events/outbox-store.mjs";
15
16
  import { BlindCloseInput, CloseShiftInput, IncrementSalesInput, OpenShiftInput, RecordCashMovementInput, ShiftRepository, ShiftRepositoryConfig } from "./repositories/shift.repository.mjs";
16
17
  import { PosBridges, PosConfig, PosEngine, PosLogger, PosModels, PosRepositories } from "./engine/engine-types.mjs";
17
18
  import { createPosEngine } from "./engine/create-pos.mjs";
@@ -19,5 +20,6 @@ import { POS_EVENTS, PosEventName } from "./events/event-constants.mjs";
19
20
  import { CashMovementRecordedPayload, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload } from "./events/event-payloads.mjs";
20
21
  import { createPosEvent } from "./events/helpers.mjs";
21
22
  import { InProcessPosBus } from "./events/in-process-bus.mjs";
23
+ import { PosEventDefinition, PosEventPayloadOf, cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent } from "./events/event-catalog.mjs";
22
24
  import { DEFAULT_COLLECTIONS } from "./models/create-models.mjs";
23
- 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, LedgerBridge, NotificationBridge, type OpenShiftInput, POS_EVENTS, PaymentBreakdown, PolicyBridge, type PosBridges, type PosConfig, PosContext, type PosEngine, PosError, PosEventName, 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, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
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 };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { InProcessPosBus } from "./events/in-process-bus.mjs";
2
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
2
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, 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";
@@ -12,4 +12,6 @@ import { POS_EVENTS } from "./events/event-constants.mjs";
12
12
  import { createPosEvent } from "./events/helpers.mjs";
13
13
  import { ShiftRepository } from "./repositories/shift.repository.mjs";
14
14
  import { createPosEngine } from "./engine/create-pos.mjs";
15
- export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, DEFAULT_COLLECTIONS, FINAL_SHIFT_STATES, IllegalShiftTransitionError, InProcessPosBus, POS_EVENTS, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, ShiftRepository, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
15
+ import { cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent } from "./events/event-catalog.mjs";
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 };
@@ -231,7 +231,7 @@ function buildShiftSchema(options) {
231
231
  }
232
232
  }, {
233
233
  timestamps: true,
234
- autoIndex: options.autoIndex
234
+ ...options.autoIndex !== void 0 ? { autoIndex: options.autoIndex } : {}
235
235
  });
236
236
  schema.index({
237
237
  registerId: 1,
@@ -3,15 +3,25 @@ import { createOptionsExtractor } from "@classytic/mongokit";
3
3
  /**
4
4
  * Translate a `PosContext` into mongokit `WriteOptions` / `QueryOptions`.
5
5
  *
6
- * Threads `actorId`, `session`, `organizationId` so:
7
- * - audit hooks see who made the change
8
- * - transactions span multiple writes (multiTenantPlugin + custom hooks)
9
- * - tenant policy filter has the right scope
6
+ * Threads the canonical fields so:
7
+ * - `organizationId` — tenant policy filter has the right scope
8
+ * - `actorId` / `requestId` — audit + observability hooks see who/which op
9
+ * - `session` — transactions span multiple writes (multiTenantPlugin + hooks)
10
+ * - `signal` — mongokit aborts before the next driver round-trip
11
+ * - `retryPolicy` — mongokit wraps round-trips in `withRetry`
12
+ * - `idempotencyKey` — surfaced for downstream idempotent stores
13
+ *
14
+ * Absent / `undefined` keys are omitted, so spreading the result into a
15
+ * parent options bag never erases inherited values.
10
16
  */
11
17
  const extract = createOptionsExtractor([
12
18
  "actorId",
13
19
  "organizationId",
14
- "session"
20
+ "requestId",
21
+ "session",
22
+ "signal",
23
+ "retryPolicy",
24
+ "idempotencyKey"
15
25
  ]);
16
26
  function repoOptionsFromCtx(ctx) {
17
27
  return extract(ctx);
@@ -7,6 +7,7 @@ import { IShift, ShiftDocument } from "../models/shift.model.mjs";
7
7
  import { LedgerBridge } from "../domain/ports/ledger.bridge.mjs";
8
8
  import { PolicyBridge } from "../domain/ports/policy.bridge.mjs";
9
9
  import { NotificationBridge } from "../domain/ports/notification.bridge.mjs";
10
+ import { OutboxStore } from "../events/outbox-store.mjs";
10
11
  import { PluginType, Repository } from "@classytic/mongokit";
11
12
  import { EventTransport } from "@classytic/primitives/events";
12
13
  import { Model } from "mongoose";
@@ -62,22 +63,30 @@ interface IncrementSalesInput {
62
63
  }
63
64
  interface ShiftRepositoryConfig {
64
65
  model: Model<IShift>;
65
- plugins?: PluginType[];
66
+ plugins?: PluginType[] | undefined;
66
67
  defaultPolicy: ShiftPolicy;
67
- ledgerBridge?: LedgerBridge;
68
- policyBridge?: PolicyBridge;
69
- notificationBridge?: NotificationBridge;
70
- eventTransport?: EventTransport;
68
+ ledgerBridge?: LedgerBridge | undefined;
69
+ policyBridge?: PolicyBridge | undefined;
70
+ notificationBridge?: NotificationBridge | undefined;
71
+ eventTransport?: EventTransport | undefined;
72
+ /**
73
+ * Transactional outbox (host-composed). When wired, every emitted event is
74
+ * `save`d under `ctx.session` BEFORE the transport publish — save failures
75
+ * propagate (the caller's transaction rolls back), publish failures are
76
+ * swallowed (the host's relay re-delivers). See PACKAGE_RULES §P8.
77
+ */
78
+ outbox?: OutboxStore | undefined;
71
79
  logger?: {
72
80
  error(message: string, ...args: unknown[]): void;
73
- };
81
+ } | undefined;
74
82
  }
75
83
  declare class ShiftRepository extends Repository<IShift> {
76
84
  private readonly defaultPolicy;
77
- private readonly ledgerBridge?;
78
- private readonly policyBridge?;
79
- private readonly notificationBridge?;
80
- private readonly eventTransport?;
85
+ private readonly ledgerBridge;
86
+ private readonly policyBridge;
87
+ private readonly notificationBridge;
88
+ private readonly eventTransport;
89
+ private readonly outbox;
81
90
  private readonly logger;
82
91
  constructor(config: ShiftRepositoryConfig);
83
92
  /**
@@ -147,7 +156,16 @@ declare class ShiftRepository extends Repository<IShift> {
147
156
  private transitionState;
148
157
  private requireActive;
149
158
  private applyCounts;
150
- private publishEvent;
159
+ /**
160
+ * Session-bound dispatch (PACKAGE_RULES §P8). Build the envelope ONCE so an
161
+ * outbox-relay re-publish and the live transport publish share `meta.id`
162
+ * (subscribers dedup on it). Outbox save runs FIRST under `ctx.session` so
163
+ * the event row commits atomically with the shift write; save failures
164
+ * PROPAGATE (the host's transaction rolls back — a vanished event is worse
165
+ * than a redelivered one). Transport publish runs second; its failures are
166
+ * swallowed because the durable row drives re-delivery.
167
+ */
168
+ private dispatch;
151
169
  }
152
170
  //#endregion
153
171
  export { BlindCloseInput, CloseShiftInput, IncrementSalesInput, OpenShiftInput, RecordCashMovementInput, ShiftRepository, ShiftRepositoryConfig };
@@ -1,4 +1,4 @@
1
- import { ActiveShiftAlreadyOpenError, IllegalShiftTransitionError, ShiftFinalizedError, ShiftNotFoundError, VarianceExceededError } from "../domain/errors/pos.errors.mjs";
1
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, ShiftFinalizedError, ShiftNotFoundError, 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";
@@ -35,6 +35,7 @@ var ShiftRepository = class extends Repository {
35
35
  policyBridge;
36
36
  notificationBridge;
37
37
  eventTransport;
38
+ outbox;
38
39
  logger;
39
40
  constructor(config) {
40
41
  const { model, plugins = [] } = config;
@@ -48,6 +49,7 @@ var ShiftRepository = class extends Repository {
48
49
  this.policyBridge = config.policyBridge;
49
50
  this.notificationBridge = config.notificationBridge;
50
51
  this.eventTransport = config.eventTransport;
52
+ this.outbox = config.outbox;
51
53
  this.logger = config.logger ?? console;
52
54
  }
53
55
  /**
@@ -84,11 +86,11 @@ var ShiftRepository = class extends Repository {
84
86
  policySnapshot: policy,
85
87
  notes: input.notes ?? ""
86
88
  }, repoOptionsFromCtx(ctx));
87
- await this.publishEvent(POS_EVENTS.SHIFT_OPENED, {
89
+ await this.dispatch(POS_EVENTS.SHIFT_OPENED, {
88
90
  shiftId: shift._id.toString(),
89
91
  registerId: shift.registerId,
90
92
  openingCashierId: shift.openingCashierId
91
- });
93
+ }, ctx);
92
94
  return shift;
93
95
  } catch (err) {
94
96
  if (err.code === 11e3) throw new ActiveShiftAlreadyOpenError(`${input.registerId}`);
@@ -103,6 +105,7 @@ var ShiftRepository = class extends Repository {
103
105
  }
104
106
  async recordCashMovement(input, ctx) {
105
107
  const shift = await this.requireActive(input.shiftId, ctx);
108
+ if (!Number.isInteger(input.movement.amount) || input.movement.amount < 0) throw new CashMovementInvalidError(`cash movement amount must be a non-negative integer (minor units); got ${input.movement.amount}`);
106
109
  const movement = {
107
110
  ...input.movement,
108
111
  timestamp: input.movement.timestamp ?? /* @__PURE__ */ new Date()
@@ -119,12 +122,12 @@ var ShiftRepository = class extends Repository {
119
122
  ...repoOptionsFromCtx(ctx)
120
123
  });
121
124
  if (!updated) throw new ShiftNotFoundError(input.shiftId);
122
- await this.publishEvent(POS_EVENTS.CASH_MOVEMENT_RECORDED, {
125
+ await this.dispatch(POS_EVENTS.CASH_MOVEMENT_RECORDED, {
123
126
  shiftId: input.shiftId,
124
127
  type: movement.type,
125
128
  amount: movement.amount,
126
129
  reasonCode: movement.reasonCode
127
- });
130
+ }, ctx);
128
131
  return updated;
129
132
  }
130
133
  /**
@@ -134,9 +137,10 @@ var ShiftRepository = class extends Repository {
134
137
  */
135
138
  async incrementSales(input, ctx) {
136
139
  if (input.amount <= 0) return;
140
+ if (!Number.isInteger(input.amount)) throw new CashMovementInvalidError(`incrementSales amount must be integer minor units; got ${input.amount}`);
137
141
  const refund = input.refund === true;
138
142
  const tax = Math.max(0, Math.trunc(input.tax ?? 0));
139
- if (tax > input.amount) throw new Error(`tax (${tax}) cannot exceed amount (${input.amount})`);
143
+ if (tax > input.amount) throw new CashMovementInvalidError(`tax (${tax}) cannot exceed amount (${input.amount})`);
140
144
  const update = { $inc: refund ? {
141
145
  refundCount: 1,
142
146
  refundTotal: input.amount,
@@ -187,7 +191,7 @@ var ShiftRepository = class extends Repository {
187
191
  ...input.notes ? { notes: input.notes } : {}
188
192
  }, repoOptionsFromCtx(ctx));
189
193
  if (!updated) throw new IllegalShiftTransitionError(shift.state, "blindClose");
190
- await this.publishEvent(POS_EVENTS.SHIFT_BLIND_CLOSED, { shiftId: input.shiftId });
194
+ await this.dispatch(POS_EVENTS.SHIFT_BLIND_CLOSED, { shiftId: input.shiftId }, ctx);
191
195
  return updated;
192
196
  }
193
197
  /**
@@ -200,8 +204,10 @@ var ShiftRepository = class extends Repository {
200
204
  if (!canTransition(shift.state, "close")) throw new IllegalShiftTransitionError(shift.state, "close");
201
205
  const breakdown = input.countedByMethod ? this.applyCounts(shift.paymentBreakdown, input.countedByMethod, true) : shift.paymentBreakdown;
202
206
  const cashRow = breakdown.find((r) => r.method === "cash");
207
+ let varianceExceeded = false;
203
208
  if (cashRow?.expectedAmount != null && cashRow.countedAmount != null) {
204
- if (!isWithinVarianceThreshold(cashRow.difference ?? 0, cashRow.expectedAmount, shift.policySnapshot) && shift.policySnapshot.managerOverrideRequired && !input.varianceOverride) throw new VarianceExceededError(cashRow.difference ?? 0, cashRow.expectedAmount);
209
+ varianceExceeded = !isWithinVarianceThreshold(cashRow.difference ?? 0, cashRow.expectedAmount, shift.policySnapshot);
210
+ if (varianceExceeded && shift.policySnapshot.managerOverrideRequired && !input.varianceOverride) throw new VarianceExceededError(cashRow.difference ?? 0, cashRow.expectedAmount);
205
211
  }
206
212
  const fromState = shift.state;
207
213
  let journalEntryId = shift.journalEntryId ?? null;
@@ -228,11 +234,16 @@ var ShiftRepository = class extends Repository {
228
234
  to: "closed"
229
235
  }, set, repoOptionsFromCtx(ctx));
230
236
  if (!updated) throw new IllegalShiftTransitionError(fromState, "close");
231
- await this.publishEvent(POS_EVENTS.SHIFT_CLOSED, {
237
+ if (varianceExceeded && cashRow?.expectedAmount != null) await this.dispatch(POS_EVENTS.VARIANCE_DETECTED, {
238
+ shiftId: input.shiftId,
239
+ difference: cashRow.difference ?? 0,
240
+ expected: cashRow.expectedAmount
241
+ }, ctx);
242
+ await this.dispatch(POS_EVENTS.SHIFT_CLOSED, {
232
243
  shiftId: input.shiftId,
233
244
  journalEntryId,
234
245
  closedBy: input.closedBy
235
- });
246
+ }, ctx);
236
247
  if (input.varianceOverride && this.notificationBridge?.onVarianceOverride) try {
237
248
  await this.notificationBridge.onVarianceOverride(updated, ctx);
238
249
  } catch (err) {
@@ -260,7 +271,8 @@ var ShiftRepository = class extends Repository {
260
271
  "paused",
261
272
  "blind_closed"
262
273
  ] },
263
- businessDate: { $lt: asOf }
274
+ businessDate: { $lt: asOf },
275
+ deletedAt: null
264
276
  }, {
265
277
  _id: 1,
266
278
  organizationId: 1,
@@ -314,10 +326,10 @@ var ShiftRepository = class extends Repository {
314
326
  ...journalEntryId ? { journalEntryId } : {}
315
327
  }, repoOptionsFromCtx(ctx));
316
328
  if (!updated) throw new IllegalShiftTransitionError(fromState, "forceClose");
317
- await this.publishEvent(POS_EVENTS.SHIFT_FORCE_CLOSED, {
329
+ await this.dispatch(POS_EVENTS.SHIFT_FORCE_CLOSED, {
318
330
  shiftId,
319
331
  reason: "orphan_eod"
320
- });
332
+ }, ctx);
321
333
  if (this.notificationBridge?.onOrphanedClose) try {
322
334
  await this.notificationBridge.onOrphanedClose(updated, ctx);
323
335
  } catch (err) {
@@ -362,11 +374,12 @@ var ShiftRepository = class extends Repository {
362
374
  to: target
363
375
  }, extraSet, repoOptionsFromCtx(ctx));
364
376
  if (!updated) throw new IllegalShiftTransitionError(shift.state, verb);
365
- await this.publishEvent(`pos:shift.${verb}`, {
377
+ const eventName = verb === "pause" ? POS_EVENTS.SHIFT_PAUSED : POS_EVENTS.SHIFT_RESUMED;
378
+ await this.dispatch(eventName, {
366
379
  shiftId,
367
380
  from: shift.state,
368
381
  to: target
369
- });
382
+ }, ctx);
370
383
  return updated;
371
384
  }
372
385
  async requireActive(shiftId, ctx) {
@@ -388,10 +401,26 @@ var ShiftRepository = class extends Repository {
388
401
  };
389
402
  });
390
403
  }
391
- async publishEvent(name, payload) {
392
- if (!this.eventTransport) return;
393
- try {
394
- await this.eventTransport.publish(createPosEvent(name, payload));
404
+ /**
405
+ * Session-bound dispatch (PACKAGE_RULES §P8). Build the envelope ONCE so an
406
+ * outbox-relay re-publish and the live transport publish share `meta.id`
407
+ * (subscribers dedup on it). Outbox save runs FIRST under `ctx.session` so
408
+ * the event row commits atomically with the shift write; save failures
409
+ * PROPAGATE (the host's transaction rolls back — a vanished event is worse
410
+ * than a redelivered one). Transport publish runs second; its failures are
411
+ * swallowed because the durable row drives re-delivery.
412
+ */
413
+ async dispatch(name, payload, ctx) {
414
+ if (!this.outbox && !this.eventTransport) return;
415
+ const event = createPosEvent(name, payload);
416
+ if (this.outbox) try {
417
+ await this.outbox.save(event, ctx.session !== void 0 ? { session: ctx.session } : {});
418
+ } catch (err) {
419
+ this.logger.error(`[pos] outbox.save failed for ${name}`, err);
420
+ throw err;
421
+ }
422
+ if (this.eventTransport) try {
423
+ await this.eventTransport.publish(event);
395
424
  } catch (err) {
396
425
  this.logger.error(`[pos] event transport failed for ${name}`, err);
397
426
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@classytic/pos",
3
- "version": "0.1.1",
4
- "description": "Multi-vertical POS / register-session kernel for MongoDB \u00e2\u20ac\u201d 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.2.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.13.0",
75
- "@classytic/primitives": ">=0.5.0",
76
- "@classytic/repo-core": ">=0.4.0",
74
+ "@classytic/mongokit": ">=3.16.0",
75
+ "@classytic/primitives": ">=0.7.2",
76
+ "@classytic/repo-core": ">=0.6.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.13.0",
83
- "@classytic/primitives": ">=0.5.0",
84
- "@classytic/repo-core": ">=0.4.0",
82
+ "@classytic/mongokit": "^3.16.0",
83
+ "@classytic/primitives": "^0.7.2",
84
+ "@classytic/repo-core": "^0.6.0",
85
85
  "@types/node": "^25.5.0",
86
86
  "@vitest/coverage-v8": "^3.2.4",
87
87
  "mongodb-memory-server": "^10.2.3",