@classytic/pos 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +263 -10
  2. package/LICENSE +75 -21
  3. package/README.md +11 -4
  4. package/dist/domain/enums/cash-movement-reason.enum.d.mts +15 -1
  5. package/dist/domain/enums/closed-by.enum.d.mts +1 -1
  6. package/dist/domain/enums/payment-method.enum.d.mts +23 -9
  7. package/dist/domain/enums/payment-method.enum.mjs +27 -7
  8. package/dist/domain/enums/shift-state.enum.d.mts +1 -1
  9. package/dist/domain/errors/pos.errors.d.mts +53 -10
  10. package/dist/domain/errors/pos.errors.mjs +58 -13
  11. package/dist/domain/index.d.mts +5 -5
  12. package/dist/domain/index.mjs +5 -4
  13. package/dist/domain/ports/common.d.mts +0 -1
  14. package/dist/domain/ports/ledger.bridge.d.mts +42 -8
  15. package/dist/domain/ports/ledger.bridge.mjs +14 -0
  16. package/dist/domain/ports/notification.bridge.d.mts +0 -1
  17. package/dist/domain/ports/policy.bridge.d.mts +0 -1
  18. package/dist/domain/state-machines/shift.fsm.d.mts +1 -2
  19. package/dist/domain/value-objects/cash-movement.vo.d.mts +0 -1
  20. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -1
  21. package/dist/domain/value-objects/shift-policy.vo.d.mts +31 -3
  22. package/dist/domain/value-objects/shift-policy.vo.mjs +35 -1
  23. package/dist/engine/define-pos.d.mts +9 -0
  24. package/dist/engine/define-pos.mjs +126 -0
  25. package/dist/engine/engine-types.d.mts +84 -36
  26. package/dist/engine/index.d.mts +4 -3
  27. package/dist/engine/index.mjs +2 -2
  28. package/dist/events/event-catalog.d.mts +6 -7
  29. package/dist/events/event-constants.d.mts +8 -8
  30. package/dist/events/event-payloads.d.mts +0 -1
  31. package/dist/events/helpers.d.mts +0 -1
  32. package/dist/events/helpers.mjs +5 -5
  33. package/dist/events/in-process-bus.d.mts +4 -15
  34. package/dist/events/in-process-bus.mjs +14 -32
  35. package/dist/events/outbox-store.d.mts +3 -19
  36. package/dist/events/outbox-store.mjs +1 -27
  37. package/dist/index.d.mts +15 -10
  38. package/dist/index.mjs +8 -6
  39. package/dist/models/create-models.d.mts +31 -4
  40. package/dist/models/create-models.mjs +80 -13
  41. package/dist/models/hide-soft-delete.mjs +11 -0
  42. package/dist/models/inject-tenant.d.mts +2 -2
  43. package/dist/models/inject-tenant.mjs +4 -10
  44. package/dist/models/register.model.d.mts +37 -0
  45. package/dist/models/register.model.mjs +82 -0
  46. package/dist/models/shift-sale-dedupe.model.d.mts +16 -0
  47. package/dist/models/shift-sale-dedupe.model.mjs +57 -0
  48. package/dist/models/shift.model.d.mts +48 -2
  49. package/dist/models/shift.model.mjs +88 -25
  50. package/dist/repositories/register.repository.d.mts +22 -0
  51. package/dist/repositories/register.repository.mjs +25 -0
  52. package/dist/repositories/shift.repository.d.mts +217 -12
  53. package/dist/repositories/shift.repository.mjs +508 -90
  54. package/dist/schemas/shift.d.mts +7 -18
  55. package/dist/schemas/shift.mjs +1 -2
  56. package/dist/testing/fixtures.d.mts +0 -1
  57. package/package.json +13 -10
  58. package/dist/engine/create-pos.d.mts +0 -6
  59. package/dist/engine/create-pos.mjs +0 -82
@@ -1,14 +1,14 @@
1
1
  import { ShiftPolicy } from "../domain/value-objects/shift-policy.vo.mjs";
2
- import { IShift } from "../models/shift.model.mjs";
3
2
  import { LedgerBridge } from "../domain/ports/ledger.bridge.mjs";
4
3
  import { PolicyBridge } from "../domain/ports/policy.bridge.mjs";
5
4
  import { NotificationBridge } from "../domain/ports/notification.bridge.mjs";
5
+ import { PosModels } from "../models/create-models.mjs";
6
+ import { RegisterRepository } from "../repositories/register.repository.mjs";
6
7
  import { ShiftRepository } from "../repositories/shift.repository.mjs";
7
- import { EventTransport } from "@classytic/primitives/events";
8
- import { Connection, Model } from "mongoose";
9
8
  import { TenantConfig } from "@classytic/repo-core/tenant";
9
+ import { Connection } from "mongoose";
10
+ import { EventTransport } from "@classytic/primitives/events";
10
11
  import { OutboxStore } from "@classytic/primitives/outbox";
11
-
12
12
  //#region src/engine/engine-types.d.ts
13
13
  interface PosBridges {
14
14
  /**
@@ -26,60 +26,87 @@ interface PosBridges {
26
26
  interface PosLogger {
27
27
  error(message: string, ...args: unknown[]): void;
28
28
  }
29
- interface PosConfig {
30
- /** Mongoose connection (or `mongoose.connection`). */
31
- connection: Connection;
29
+ /**
30
+ * Everything that determines the persistence SHAPE / domain policy and needs
31
+ * no connection or I/O to inspect. Nothing here opens a socket or reads a
32
+ * secret — safe to call at import / module-composition time.
33
+ */
34
+ interface PosShape {
32
35
  /** Default shift policy when neither `bridges.policy` nor a per-call override is supplied. */
33
36
  defaultPolicy: ShiftPolicy;
34
- /** Bridges — every method is opt-in, package degrades gracefully without them. */
37
+ /** Canonical persistence tenancy. Default `true`. */
38
+ tenant?: boolean | TenantConfig | undefined;
39
+ /**
40
+ * Soft-delete policy for POS collections (Shift + Register). Default `true`
41
+ * = on with a 2555-day (7-year) TTL — the BD finance-audit retention floor.
42
+ * Pass `{ ttlDays }` to override retention, or `false` to disable soft-delete
43
+ * entirely (deletes become hard deletes; no `deletedAt` tombstone or TTL
44
+ * index).
45
+ */
46
+ softDelete?: boolean | {
47
+ ttlDays?: number;
48
+ } | undefined;
49
+ /** Optional collection-name namespace. See PACKAGE_RULES §20.1. */
50
+ collectionPrefix?: string | undefined;
51
+ /** Disable Mongoose autoIndex in production; run `syncIndexes()` explicitly. */
52
+ autoIndex?: boolean | undefined;
53
+ /** Hot-reload escape hatch for test fixtures. Default false. */
54
+ forceRecreate?: boolean | undefined;
55
+ }
56
+ /**
57
+ * The live connection is the first `bind` arg; these are the rest. A transport,
58
+ * outbox, logger or host bridge belongs here, not in the shape — each is a
59
+ * runtime collaborator (may perform I/O, may be shared infrastructure).
60
+ */
61
+ interface PosRuntime {
62
+ /** Bridges — every method is opt-in; the package degrades gracefully without them. */
35
63
  bridges?: PosBridges | undefined;
36
- /** Inject your own event bus; otherwise an in-process bus is used. */
64
+ /** Inject your own event bus; otherwise an in-process bus is created (and owned). */
37
65
  eventTransport?: EventTransport | undefined;
38
66
  /**
39
67
  * Transactional outbox (host-composed — PACKAGE_RULES §5.5 / §16). When
40
68
  * wired, every domain event is `save`d to the outbox under `ctx.session`
41
69
  * 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.
70
+ * the shift write. The host owns durability, the relay, retries, and DLQ.
71
+ *
72
+ * "Commits atomically" is a promise only the STORE can keep —
73
+ * `OutboxWriteOptions.session` is best-effort by contract. A supplied store must
74
+ * declare `transactionalSave: true`; `bind` refuses one that does not
75
+ * (`PosCapabilityError`), and `allowNonTransactional` does not waive it.
44
76
  */
45
77
  outbox?: OutboxStore | undefined;
46
78
  /**
47
79
  * Skip the boot-time capability gate. The close / forceClose pipelines run
48
80
  * 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.
81
+ * The gate asserts the backend declares `transactions` at bind (fail loud at
82
+ * boot, not with a cryptic driver error on the first close). Set `true` for
83
+ * standalone-Mongo local dev where transactions are absent.
52
84
  */
53
85
  allowNonTransactional?: boolean | undefined;
54
- /**
55
- * Multi-tenant scoping. `true` (default) wires the mongokit
56
- * `multiTenantPlugin` and prepends `organizationId` to every compound
57
- * index. `false` disables the plugin (host enforces scope at its own
58
- * framework layer); the field is still added.
59
- */
60
- multiTenant?: boolean | TenantConfig | undefined;
61
- /**
62
- * Legacy shorthand — `'objectId' | 'string'`. Most hosts pass `'objectId'`
63
- * (the Better Auth org id is an ObjectId).
64
- */
65
- tenantFieldType?: 'objectId' | 'string' | undefined;
66
- /** Optional collection-name namespace. See PACKAGE_RULES §20.1. */
67
- collectionPrefix?: string | undefined;
68
- /** Disable Mongoose autoIndex in production; run `Shift.syncIndexes()` explicitly. */
69
- autoIndex?: boolean | undefined;
70
- /** Hot-reload escape hatch for test fixtures. Default false. */
71
- forceRecreate?: boolean | undefined;
72
86
  /** Custom logger; defaults to `console`. */
73
87
  logger?: PosLogger | undefined;
74
88
  }
75
- interface PosModels {
76
- Shift: Model<IShift>;
89
+ /**
90
+ * The immutable, resolved describe+bind configuration surfaced on the engine
91
+ * (`engine.config`). Excludes the live connection and secrets.
92
+ */
93
+ interface ResolvedPosConfig {
94
+ readonly defaultPolicy: ShiftPolicy;
95
+ readonly tenant: import('@classytic/repo-core/tenant').ResolvedTenantConfig;
96
+ readonly softDelete: false | {
97
+ ttlDays: number;
98
+ };
99
+ readonly collectionPrefix: string | undefined;
100
+ readonly autoIndex: boolean | undefined;
101
+ readonly forceRecreate: boolean;
102
+ readonly allowNonTransactional: boolean;
77
103
  }
78
104
  interface PosRepositories {
79
105
  shift: ShiftRepository;
106
+ register: RegisterRepository;
80
107
  }
81
108
  interface PosEngine {
82
- readonly config: Readonly<PosConfig>;
109
+ readonly config: ResolvedPosConfig;
83
110
  readonly bridges: Readonly<PosBridges>;
84
111
  readonly events: EventTransport;
85
112
  /** Host-provided outbox (if wired), surfaced for relay composition. */
@@ -87,6 +114,27 @@ interface PosEngine {
87
114
  readonly models: PosModels;
88
115
  readonly repositories: PosRepositories;
89
116
  readonly defaultPolicy: ShiftPolicy;
117
+ /** Reconcile indexes for every POS model. Explicit operational action — never called by `bind`. */
118
+ syncIndexes(): Promise<unknown>;
119
+ /**
120
+ * Tear the engine down. Closes the event bus ONLY when the engine created it
121
+ * itself (`InProcessPosBus`); a host-injected `eventTransport` is the host's
122
+ * to close. The `outbox` store is always host-provided and is never touched.
123
+ * Idempotent — a second call is a no-op. Mongoose models/connection are
124
+ * untouched.
125
+ */
126
+ close(): Promise<void>;
127
+ }
128
+ interface PosBlueprint {
129
+ readonly id: 'pos';
130
+ /** The model names this blueprint registers — known without a connection. */
131
+ readonly modelNames: readonly string[];
132
+ /**
133
+ * Compile + register the models on `connection`, wire the engine, verify
134
+ * capabilities. Synchronous today (model registration and repo wiring are
135
+ * synchronous); the `KernelBlueprint` contract still permits async binds.
136
+ */
137
+ bind(connection: Connection, runtime?: PosRuntime): PosEngine;
90
138
  }
91
139
  //#endregion
92
- export { PosBridges, PosConfig, PosEngine, PosLogger, PosModels, PosRepositories };
140
+ export { PosBlueprint, PosBridges, PosEngine, PosLogger, type PosModels, PosRepositories, PosRuntime, PosShape, ResolvedPosConfig };
@@ -1,3 +1,4 @@
1
- import { PosBridges, PosConfig, PosEngine, PosLogger, PosModels, PosRepositories } from "./engine-types.mjs";
2
- import { createPosEngine } from "./create-pos.mjs";
3
- export { type PosBridges, type PosConfig, type PosEngine, type PosLogger, type PosModels, type PosRepositories, createPosEngine };
1
+ import { PosModels } from "../models/create-models.mjs";
2
+ import { PosBlueprint, PosBridges, PosEngine, PosLogger, PosRepositories, PosRuntime, PosShape, ResolvedPosConfig } from "./engine-types.mjs";
3
+ import { definePos } from "./define-pos.mjs";
4
+ export { type PosBlueprint, type PosBridges, type PosEngine, type PosLogger, type PosModels, type PosRepositories, type PosRuntime, type PosShape, type ResolvedPosConfig, definePos };
@@ -1,2 +1,2 @@
1
- import { createPosEngine } from "./create-pos.mjs";
2
- export { createPosEngine };
1
+ import { definePos } from "./define-pos.mjs";
2
+ export { definePos };
@@ -1,6 +1,5 @@
1
1
  import { DomainEvent } from "@classytic/primitives/events";
2
2
  import { z } from "zod";
3
-
4
3
  //#region src/events/event-catalog.d.ts
5
4
  interface PosEventDefinition<TSchema extends z.ZodType = z.ZodType> {
6
5
  readonly name: string;
@@ -42,8 +41,8 @@ declare const shiftClosedEvent: PosEventDefinition<z.ZodObject<{
42
41
  declare const shiftForceClosedEvent: PosEventDefinition<z.ZodObject<{
43
42
  shiftId: z.ZodString;
44
43
  reason: z.ZodEnum<{
45
- orphan_eod: "orphan_eod";
46
44
  admin_override: "admin_override";
45
+ orphan_eod: "orphan_eod";
47
46
  }>;
48
47
  }, z.core.$strip>>;
49
48
  declare const cashMovementRecordedEvent: PosEventDefinition<z.ZodObject<{
@@ -54,13 +53,13 @@ declare const cashMovementRecordedEvent: PosEventDefinition<z.ZodObject<{
54
53
  }>;
55
54
  amount: z.ZodNumber;
56
55
  reasonCode: z.ZodEnum<{
57
- safe_drop: "safe_drop";
58
- petty_cash: "petty_cash";
59
- owner_withdrawal: "owner_withdrawal";
60
- correction: "correction";
61
56
  bank_deposit: "bank_deposit";
62
- till_top_up: "till_top_up";
57
+ correction: "correction";
63
58
  other: "other";
59
+ owner_withdrawal: "owner_withdrawal";
60
+ petty_cash: "petty_cash";
61
+ safe_drop: "safe_drop";
62
+ till_top_up: "till_top_up";
64
63
  }>;
65
64
  }, z.core.$strip>>;
66
65
  declare const varianceDetectedEvent: PosEventDefinition<z.ZodObject<{
@@ -7,14 +7,14 @@
7
7
  * Naming follows PACKAGE_RULES §12: `package:resource.verb`.
8
8
  */
9
9
  declare const POS_EVENTS: {
10
- readonly SHIFT_OPENED: "pos:shift.opened";
11
- readonly SHIFT_PAUSED: "pos:shift.paused";
12
- readonly SHIFT_RESUMED: "pos:shift.resumed";
13
- readonly SHIFT_BLIND_CLOSED: "pos:shift.blind_closed";
14
- readonly SHIFT_CLOSED: "pos:shift.closed";
15
- readonly SHIFT_FORCE_CLOSED: "pos:shift.force_closed";
16
- readonly CASH_MOVEMENT_RECORDED: "pos:cash_movement.recorded";
17
- readonly VARIANCE_DETECTED: "pos:shift.variance.detected";
10
+ readonly SHIFT_OPENED: 'pos:shift.opened';
11
+ readonly SHIFT_PAUSED: 'pos:shift.paused';
12
+ readonly SHIFT_RESUMED: 'pos:shift.resumed';
13
+ readonly SHIFT_BLIND_CLOSED: 'pos:shift.blind_closed';
14
+ readonly SHIFT_CLOSED: 'pos:shift.closed';
15
+ readonly SHIFT_FORCE_CLOSED: 'pos:shift.force_closed';
16
+ readonly CASH_MOVEMENT_RECORDED: 'pos:cash_movement.recorded';
17
+ readonly VARIANCE_DETECTED: 'pos:shift.variance.detected';
18
18
  };
19
19
  type PosEventName = (typeof POS_EVENTS)[keyof typeof POS_EVENTS];
20
20
  //#endregion
@@ -1,6 +1,5 @@
1
1
  import { CashMovementReasonCode } from "../domain/enums/cash-movement-reason.enum.mjs";
2
2
  import { ClosedBy } from "../domain/enums/closed-by.enum.mjs";
3
-
4
3
  //#region src/events/event-payloads.d.ts
5
4
  interface ShiftOpenedPayload {
6
5
  shiftId: string;
@@ -1,5 +1,4 @@
1
1
  import { DomainEvent } from "@classytic/primitives/events";
2
-
3
2
  //#region src/events/helpers.d.ts
4
3
  declare function createPosEvent<T extends Record<string, unknown>>(name: string, payload: T): DomainEvent<T>;
5
4
  //#endregion
@@ -1,12 +1,12 @@
1
- import { createEvent } from "@classytic/primitives/events";
1
+ import { createScopedEvent } from "@classytic/primitives/events";
2
2
  //#region src/events/helpers.ts
3
3
  /**
4
- * Thin typed wrapper around primitives' `createEvent` so the event id /
5
- * timestamp / version live in one place. Internal — the package's domain
6
- * verbs call this.
4
+ * Thin typed wrapper around primitives' `createScopedEvent` (0.13.0) so the
5
+ * event id / timestamp / source stamping live in one shared place. Internal —
6
+ * the package's domain verbs call this.
7
7
  */
8
8
  function createPosEvent(name, payload) {
9
- return createEvent(name, payload, { source: "@classytic/pos" });
9
+ return createScopedEvent("@classytic/pos", name, payload);
10
10
  }
11
11
  //#endregion
12
12
  export { createPosEvent };
@@ -1,19 +1,8 @@
1
- import { DomainEvent, EventHandler, EventTransport } from "@classytic/primitives/events";
2
-
1
+ import { InProcessEventBus, InProcessEventBusOptions } from "@classytic/primitives/event-infra";
3
2
  //#region src/events/in-process-bus.d.ts
4
- interface InProcessPosBusOptions {
5
- logger?: {
6
- error(message: string, ...args: unknown[]): void;
7
- };
8
- }
9
- declare class InProcessPosBus implements EventTransport {
10
- readonly name = "in-process-pos";
11
- private handlers;
12
- private logger;
3
+ type InProcessPosBusOptions = InProcessEventBusOptions;
4
+ declare class InProcessPosBus extends InProcessEventBus {
13
5
  constructor(options?: InProcessPosBusOptions);
14
- publish(event: DomainEvent): Promise<void>;
15
- subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
16
- close(): Promise<void>;
17
6
  }
18
7
  //#endregion
19
- export { InProcessPosBus };
8
+ export { InProcessPosBus, InProcessPosBusOptions };
@@ -1,37 +1,19 @@
1
- import { matchEventPattern } from "@classytic/primitives/events";
1
+ import { InProcessEventBus } from "@classytic/primitives/event-infra";
2
2
  //#region src/events/in-process-bus.ts
3
- var InProcessPosBus = class {
4
- name = "in-process-pos";
5
- handlers = /* @__PURE__ */ new Map();
6
- logger;
3
+ /**
4
+ * InProcessPosBus — default `EventTransport` when the host doesn't inject
5
+ * one. Thin subclass of primitives' shared `InProcessEventBus`
6
+ * (`@classytic/primitives/event-infra`, 0.13.0) — glob matching, per-handler
7
+ * error isolation, `publishMany`, and idempotent `close()` all live there so
8
+ * every @classytic kernel shares one implementation.
9
+ */
10
+ var InProcessPosBus = class extends InProcessEventBus {
7
11
  constructor(options = {}) {
8
- this.logger = options.logger ?? console;
9
- }
10
- async publish(event) {
11
- const matched = /* @__PURE__ */ new Set();
12
- for (const [pattern, handlers] of this.handlers.entries()) if (matchEventPattern(pattern, event.type)) for (const h of handlers) matched.add(h);
13
- for (const handler of matched) try {
14
- await handler(event);
15
- } catch (err) {
16
- this.logger.error(`[pos] handler error for ${event.type}:`, err);
17
- }
18
- }
19
- async subscribe(pattern, handler) {
20
- let set = this.handlers.get(pattern);
21
- if (!set) {
22
- set = /* @__PURE__ */ new Set();
23
- this.handlers.set(pattern, set);
24
- }
25
- set.add(handler);
26
- return () => {
27
- const s = this.handlers.get(pattern);
28
- if (!s) return;
29
- s.delete(handler);
30
- if (s.size === 0) this.handlers.delete(pattern);
31
- };
32
- }
33
- async close() {
34
- this.handlers.clear();
12
+ super({
13
+ name: "in-process-pos",
14
+ logLabel: "pos",
15
+ ...options
16
+ });
35
17
  }
36
18
  };
37
19
  //#endregion
@@ -1,19 +1,3 @@
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 };
1
+ import { InvalidOutboxEventError, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxFailOptions, OutboxOwnershipError, OutboxStore as OutboxStore$1, OutboxWriteOptions } from "@classytic/primitives/outbox";
2
+ import { MemoryOutboxStore } from "@classytic/primitives/memory-outbox";
3
+ export { InvalidOutboxEventError, MemoryOutboxStore, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxFailOptions, OutboxOwnershipError, type OutboxStore$1 as OutboxStore, type OutboxWriteOptions };
@@ -1,29 +1,3 @@
1
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
2
+ import { MemoryOutboxStore } from "@classytic/primitives/memory-outbox";
29
3
  export { InvalidOutboxEventError, MemoryOutboxStore, OutboxOwnershipError };
package/dist/index.d.mts CHANGED
@@ -1,25 +1,30 @@
1
1
  import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, ShiftState, isActiveShiftState, isFinalShiftState } from "./domain/enums/shift-state.enum.mjs";
2
- import { SHIFT_PAYMENT_METHODS, ShiftPaymentMethod } from "./domain/enums/payment-method.enum.mjs";
2
+ import { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS, ShiftPaymentMethod, resolveMethodKind } from "./domain/enums/payment-method.enum.mjs";
3
3
  import { CASH_MOVEMENT_REASON_CODES, CashMovementReasonCode } from "./domain/enums/cash-movement-reason.enum.mjs";
4
4
  import { CLOSED_BY_VALUES, ClosedBy } from "./domain/enums/closed-by.enum.mjs";
5
5
  import { SHIFT_VERBS, ShiftVerb, allowedVerbs, canTransition, nextState } from "./domain/state-machines/shift.fsm.mjs";
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
- import { ShiftPolicy, isWithinVarianceThreshold } from "./domain/value-objects/shift-policy.vo.mjs";
9
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
8
+ import { ShiftPolicy, defaultShiftPolicy, isWithinVarianceThreshold } from "./domain/value-objects/shift-policy.vo.mjs";
9
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
10
10
  import { PosContext } from "./domain/ports/common.mjs";
11
- import { IShift, ShiftDocument, ShiftModel } from "./models/shift.model.mjs";
12
- import { LedgerBridge } from "./domain/ports/ledger.bridge.mjs";
11
+ import { IShift, PendingLedgerPost, PendingLedgerPostTrigger, ShiftDocument, ShiftModel } from "./models/shift.model.mjs";
12
+ import { LedgerBridge, ShiftClosePosting, shiftCloseIdempotencyKey } 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 "./domain/index.mjs";
16
+ import { IRegister, RegisterDocument, RegisterModel } from "./models/register.model.mjs";
17
+ import { IShiftSaleDedupe, ShiftSaleDedupeDocument, ShiftSaleDedupeModel } from "./models/shift-sale-dedupe.model.mjs";
18
+ import { DEFAULT_COLLECTIONS, POS_MODEL_NAMES, PosModels } from "./models/create-models.mjs";
19
+ import { RegisterRepository, RegisterRepositoryConfig } from "./repositories/register.repository.mjs";
15
20
  import { InvalidOutboxEventError, MemoryOutboxStore, OutboxAcknowledgeOptions, OutboxClaimOptions, OutboxFailOptions, OutboxOwnershipError, OutboxStore, OutboxWriteOptions } from "./events/outbox-store.mjs";
16
- import { BlindCloseInput, CloseShiftInput, IncrementSalesInput, OpenShiftInput, RecordCashMovementInput, ShiftRepository, ShiftRepositoryConfig } from "./repositories/shift.repository.mjs";
17
- import { PosBridges, PosConfig, PosEngine, PosLogger, PosModels, PosRepositories } from "./engine/engine-types.mjs";
18
- import { createPosEngine } from "./engine/create-pos.mjs";
21
+ import { BlindCloseInput, CloseShiftInput, CloseShiftResult, IncrementSalesInput, IncrementSalesResult, OpenShiftInput, RecordCashMovementInput, ShiftCloseOutcome, ShiftRepository, ShiftRepositoryConfig } from "./repositories/shift.repository.mjs";
22
+ import { PosBlueprint, PosBridges, PosEngine, PosLogger, PosRepositories, PosRuntime, PosShape, ResolvedPosConfig } from "./engine/engine-types.mjs";
23
+ import { definePos } from "./engine/define-pos.mjs";
19
24
  import { POS_EVENTS, PosEventName } from "./events/event-constants.mjs";
20
25
  import { CashMovementRecordedPayload, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload } from "./events/event-payloads.mjs";
21
26
  import { createPosEvent } from "./events/helpers.mjs";
22
27
  import { InProcessPosBus } from "./events/in-process-bus.mjs";
23
28
  import { PosEventDefinition, PosEventPayloadOf, cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent } from "./events/event-catalog.mjs";
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, UnmanagedSessionError, VarianceDetectedPayload, VarianceExceededError, allowedVerbs, canTransition, cashMovementRecordedEvent, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
29
+ import "./events/index.mjs";
30
+ export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, type BlindCloseInput, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementReasonCode, CashMovementRecordedPayload, type CloseShiftInput, type CloseShiftResult, ClosedBy, DEFAULT_COLLECTIONS, DEFAULT_METHOD_KINDS, FINAL_SHIFT_STATES, type IRegister, type IShift, type IShiftSaleDedupe, IllegalShiftTransitionError, InProcessPosBus, type IncrementSalesInput, type IncrementSalesResult, InvalidOutboxEventError, type LedgerBridge, MemoryOutboxStore, type NotificationBridge, type OpenShiftInput, type OutboxAcknowledgeOptions, type OutboxClaimOptions, type OutboxFailOptions, OutboxOwnershipError, type OutboxStore, type OutboxWriteOptions, PAYMENT_METHOD_KIND_VALUES, POS_EVENTS, POS_MODEL_NAMES, PaymentBreakdown, type PendingLedgerPost, type PendingLedgerPostTrigger, type PolicyBridge, type PosBlueprint, type PosBridges, PosCapabilityError, type PosContext, type PosEngine, PosError, type PosEventDefinition, PosEventName, type PosEventPayloadOf, PosEventPayloads, type PosLogger, type PosModels, type PosRepositories, type PosRuntime, type PosShape, type RecordCashMovementInput, type RegisterDocument, type RegisterModel, RegisterRepository, type RegisterRepositoryConfig, type ResolvedPosConfig, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftBlindClosedPayload, type ShiftCloseOutcome, type ShiftClosePosting, ShiftClosedPayload, ShiftCountsRequiredError, type ShiftDocument, ShiftFinalizedError, ShiftForceClosedPayload, type ShiftModel, ShiftNotFoundError, ShiftOpenedPayload, ShiftPausedError, ShiftPaymentMethod, ShiftPolicy, ShiftRepository, type ShiftRepositoryConfig, type ShiftSaleDedupeDocument, type ShiftSaleDedupeModel, ShiftState, ShiftStateChangedPayload, ShiftVerb, UnmanagedSessionError, VarianceDetectedPayload, VarianceExceededError, allowedVerbs, canTransition, cashMovementRecordedEvent, computeDifference, computeExpected, createPosEvent, defaultShiftPolicy, definePos, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, posEventDefinitions, resolveMethodKind, shiftBlindClosedEvent, shiftCloseIdempotencyKey, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
package/dist/index.mjs CHANGED
@@ -1,17 +1,19 @@
1
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
1
2
  import { InProcessPosBus } from "./events/in-process-bus.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
- import { SHIFT_PAYMENT_METHODS } from "./domain/enums/payment-method.enum.mjs";
5
+ import { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS, resolveMethodKind } from "./domain/enums/payment-method.enum.mjs";
6
6
  import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, isActiveShiftState, isFinalShiftState } from "./domain/enums/shift-state.enum.mjs";
7
- import { DEFAULT_COLLECTIONS } from "./models/create-models.mjs";
7
+ import { DEFAULT_COLLECTIONS, POS_MODEL_NAMES } from "./models/create-models.mjs";
8
+ import { RegisterRepository } from "./repositories/register.repository.mjs";
9
+ import { shiftCloseIdempotencyKey } from "./domain/ports/ledger.bridge.mjs";
8
10
  import { SHIFT_VERBS, allowedVerbs, canTransition, nextState } from "./domain/state-machines/shift.fsm.mjs";
9
11
  import { computeDifference, computeExpected } from "./domain/value-objects/payment-breakdown.vo.mjs";
10
- import { isWithinVarianceThreshold } from "./domain/value-objects/shift-policy.vo.mjs";
12
+ import { defaultShiftPolicy, isWithinVarianceThreshold } from "./domain/value-objects/shift-policy.vo.mjs";
11
13
  import { POS_EVENTS } from "./events/event-constants.mjs";
12
14
  import { createPosEvent } from "./events/helpers.mjs";
13
15
  import { ShiftRepository } from "./repositories/shift.repository.mjs";
14
- import { createPosEngine } from "./engine/create-pos.mjs";
16
+ import { definePos } from "./engine/define-pos.mjs";
15
17
  import { cashMovementRecordedEvent, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent } from "./events/event-catalog.mjs";
16
18
  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, UnmanagedSessionError, VarianceExceededError, allowedVerbs, canTransition, cashMovementRecordedEvent, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, posEventDefinitions, shiftBlindClosedEvent, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
19
+ export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, DEFAULT_COLLECTIONS, DEFAULT_METHOD_KINDS, FINAL_SHIFT_STATES, IllegalShiftTransitionError, InProcessPosBus, InvalidOutboxEventError, MemoryOutboxStore, OutboxOwnershipError, PAYMENT_METHOD_KIND_VALUES, POS_EVENTS, POS_MODEL_NAMES, PosCapabilityError, PosError, RegisterRepository, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, ShiftRepository, UnmanagedSessionError, VarianceExceededError, allowedVerbs, canTransition, cashMovementRecordedEvent, computeDifference, computeExpected, createPosEvent, defaultShiftPolicy, definePos, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, posEventDefinitions, resolveMethodKind, shiftBlindClosedEvent, shiftCloseIdempotencyKey, shiftClosedEvent, shiftForceClosedEvent, shiftOpenedEvent, shiftPausedEvent, shiftResumedEvent, varianceDetectedEvent };
@@ -1,9 +1,36 @@
1
- import { Connection } from "mongoose";
2
-
1
+ import "./inject-tenant.mjs";
2
+ import { IShift } from "./shift.model.mjs";
3
+ import { IRegister } from "./register.model.mjs";
4
+ import { IShiftSaleDedupe } from "./shift-sale-dedupe.model.mjs";
5
+ import "@classytic/mongokit";
6
+ import { Model } from "mongoose";
3
7
  //#region src/models/create-models.d.ts
8
+ /**
9
+ * Single source of truth for MODEL names — the strings mongoose registers under,
10
+ * and therefore the strings any cross-package reference must use.
11
+ *
12
+ * A `sourceRef.sourceModel` written as a literal by a consumer is a join that
13
+ * fails silently: nothing throws, the reference simply matches no document, and
14
+ * the reader sees a plausible empty result. So the name is stated once, here, by
15
+ * the package that owns the model, and consumers import it.
16
+ */
17
+ declare const POS_MODEL_NAMES: {
18
+ readonly Shift: 'Shift';
19
+ readonly Register: 'Register';
20
+ readonly ShiftSaleDedupe: 'ShiftSaleDedupe';
21
+ };
4
22
  /** Single source of truth for collection names. Renaming = breaking change. */
5
23
  declare const DEFAULT_COLLECTIONS: {
6
- readonly Shift: "pos_shifts";
24
+ readonly Shift: 'pos_shifts';
25
+ readonly Register: 'pos_registers';
26
+ readonly ShiftSaleDedupe: 'pos_shift_sale_dedupe';
7
27
  };
28
+ /** The typed model bag every bind produces — the engine's `models` surface. */
29
+ interface PosModels {
30
+ Shift: Model<IShift>;
31
+ Register: Model<IRegister>;
32
+ /** incrementSales({ dedupeRef }) claim ledger — see shift-sale-dedupe.model.ts. */
33
+ ShiftSaleDedupe: Model<IShiftSaleDedupe>;
34
+ }
8
35
  //#endregion
9
- export { DEFAULT_COLLECTIONS };
36
+ export { DEFAULT_COLLECTIONS, POS_MODEL_NAMES, PosModels };
@@ -1,20 +1,87 @@
1
- import { ShiftModelCollisionError } from "../domain/errors/pos.errors.mjs";
1
+ import { buildRegisterSchema } from "./register.model.mjs";
2
+ import { buildShiftSaleDedupeSchema } from "./shift-sale-dedupe.model.mjs";
2
3
  import { buildShiftSchema } from "./shift.model.mjs";
4
+ import { defineModels } from "@classytic/mongokit";
3
5
  //#region src/models/create-models.ts
6
+ /**
7
+ * POS model specification — the ONE authoritative place the POS models are
8
+ * described (Kernel Construction Standard §5/§6).
9
+ *
10
+ * `definePosModels(config)` returns a connection-free mongokit `ModelBlueprint`;
11
+ * `definePos` binds it during engine construction. Collection naming, tenant
12
+ * shape, auto-index and collision policy live here once. A name collision
13
+ * surfaces as mongokit's typed `ModelCollisionError` — there is no
14
+ * POS-specific collision wrapper and no manual `connection.models[...]`
15
+ * pre-check loop; `defineModels` owns that.
16
+ *
17
+ * POS has NO optional model families — Shift, Register and ShiftSaleDedupe are
18
+ * always registered together. (If a family were ever gated, it would appear as
19
+ * a conditional `ModelSpec` entry in the `models` array.)
20
+ */
21
+ /**
22
+ * Single source of truth for MODEL names — the strings mongoose registers under,
23
+ * and therefore the strings any cross-package reference must use.
24
+ *
25
+ * A `sourceRef.sourceModel` written as a literal by a consumer is a join that
26
+ * fails silently: nothing throws, the reference simply matches no document, and
27
+ * the reader sees a plausible empty result. So the name is stated once, here, by
28
+ * the package that owns the model, and consumers import it.
29
+ */
30
+ const POS_MODEL_NAMES = {
31
+ Shift: "Shift",
32
+ Register: "Register",
33
+ ShiftSaleDedupe: "ShiftSaleDedupe"
34
+ };
4
35
  /** Single source of truth for collection names. Renaming = breaking change. */
5
- const DEFAULT_COLLECTIONS = { Shift: "pos_shifts" };
6
- const POS_MODEL_NAMES = ["Shift"];
7
- function createPosModels(options) {
8
- const { connection, tenant, collectionPrefix, autoIndex, forceRecreate } = options;
9
- if (forceRecreate) {
10
- for (const name of POS_MODEL_NAMES) if (connection.models[name]) connection.deleteModel(name);
11
- } else for (const name of POS_MODEL_NAMES) if (connection.models[name]) throw new ShiftModelCollisionError(name);
36
+ const DEFAULT_COLLECTIONS = {
37
+ Shift: "pos_shifts",
38
+ Register: "pos_registers",
39
+ ShiftSaleDedupe: "pos_shift_sale_dedupe"
40
+ };
41
+ /**
42
+ * Describe the POS model set as a connection-free blueprint. Pure — builds no
43
+ * schema and registers nothing until `.bind(connection)`.
44
+ */
45
+ function definePosModels(config) {
46
+ const { tenant, collectionPrefix, autoIndex, forceRecreate } = config;
12
47
  const prefix = collectionPrefix ?? "";
13
- const shiftSchema = buildShiftSchema({
14
- tenant,
15
- autoIndex
48
+ const existing = forceRecreate ? {
49
+ mode: "replace",
50
+ environment: "test"
51
+ } : { mode: "throw" };
52
+ return defineModels({
53
+ models: [
54
+ {
55
+ name: POS_MODEL_NAMES.Shift,
56
+ collection: prefix + DEFAULT_COLLECTIONS.Shift,
57
+ schema: () => buildShiftSchema({
58
+ tenant,
59
+ autoIndex
60
+ }),
61
+ existing
62
+ },
63
+ {
64
+ name: POS_MODEL_NAMES.Register,
65
+ collection: prefix + DEFAULT_COLLECTIONS.Register,
66
+ schema: () => buildRegisterSchema({
67
+ tenant,
68
+ autoIndex
69
+ }),
70
+ existing
71
+ },
72
+ {
73
+ name: POS_MODEL_NAMES.ShiftSaleDedupe,
74
+ collection: prefix + DEFAULT_COLLECTIONS.ShiftSaleDedupe,
75
+ schema: () => buildShiftSaleDedupeSchema({ autoIndex }),
76
+ existing
77
+ }
78
+ ],
79
+ assemble: (models) => Object.freeze({
80
+ Shift: models.get("Shift"),
81
+ Register: models.get("Register"),
82
+ ShiftSaleDedupe: models.get("ShiftSaleDedupe")
83
+ })
16
84
  });
17
- return { Shift: connection.model("Shift", shiftSchema, prefix + DEFAULT_COLLECTIONS.Shift) };
18
85
  }
19
86
  //#endregion
20
- export { DEFAULT_COLLECTIONS, createPosModels };
87
+ export { DEFAULT_COLLECTIONS, POS_MODEL_NAMES, definePosModels };