@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
@@ -3,15 +3,15 @@ import { ClosedBy } from "../domain/enums/closed-by.enum.mjs";
3
3
  import { CashMovement } from "../domain/value-objects/cash-movement.vo.mjs";
4
4
  import { ShiftPolicy } from "../domain/value-objects/shift-policy.vo.mjs";
5
5
  import { PosContext } from "../domain/ports/common.mjs";
6
- import { IShift, ShiftDocument } from "../models/shift.model.mjs";
6
+ import { IShift, PendingLedgerPost, 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 { IShiftSaleDedupe } from "../models/shift-sale-dedupe.model.mjs";
10
11
  import { OutboxStore } from "../events/outbox-store.mjs";
11
12
  import { PluginType, Repository } from "@classytic/mongokit";
12
- import { EventTransport } from "@classytic/primitives/events";
13
13
  import { Model } from "mongoose";
14
-
14
+ import { EventTransport } from "@classytic/primitives/events";
15
15
  //#region src/repositories/shift.repository.d.ts
16
16
  interface OpenShiftInput {
17
17
  registerId: string;
@@ -60,10 +60,80 @@ interface IncrementSalesInput {
60
60
  /** Cashier whose order touched the shift — appended to teamMemberIds. */
61
61
  cashierId?: string;
62
62
  cashierName?: string;
63
+ /**
64
+ * Optional claim-first dedupe key. When set, the repo insert-first claims
65
+ * `(shiftId, dedupeRef)` in the `pos_shift_sale_dedupe` collection BEFORE
66
+ * applying the `$inc`; a duplicate claim means the increment was already
67
+ * applied (e.g. a host transaction retry re-ran the order-create hook) and
68
+ * the call returns `{ applied: false }` without touching the shift.
69
+ *
70
+ * MUST be a retry-stable identity — e.g. `shift-sale:{orderNumber}:{method}`
71
+ * (orderNumber survives a Mongo transient-txn retry; a per-attempt `_id`
72
+ * does not and would defeat the dedupe). Omit to keep the legacy
73
+ * "idempotency is the host's responsibility" behavior.
74
+ */
75
+ dedupeRef?: string;
76
+ }
77
+ /** Result of `incrementSales` — `applied: false` = dedupe hit or zero amount. */
78
+ interface IncrementSalesResult {
79
+ applied: boolean;
80
+ reason?: 'duplicate' | 'zero-amount';
81
+ }
82
+ /**
83
+ * What a `close()` / `forceClose()` call actually DID.
84
+ *
85
+ * - `closed` — this call won the CAS and finalized the shift.
86
+ * - `already-closed` — the shift was already terminal (a concurrent closer
87
+ * won, or the caller is retrying). Nothing was
88
+ * written, no journal entry was posted.
89
+ * - `resumed` — the shift was terminal with an unrecorded ledger
90
+ * post (a crash between the CAS and the ledger write);
91
+ * this call converged it.
92
+ *
93
+ * `already-closed` is a legitimate IDEMPOTENT RESULT, not an error. It used to
94
+ * be an `IllegalShiftTransitionError` thrown after the loser had already
95
+ * posted its journal entry — which every host caught and logged, turning a
96
+ * double-post into a log line. Returning it as an outcome is what lets the
97
+ * lazy-close / cron / oversight triggers stop swallowing exceptions.
98
+ *
99
+ * **Counts submitted by a losing caller are NOT applied** — the shift was
100
+ * reconciled by whoever won. Check `outcome` before reporting success to a
101
+ * human who just typed a drawer count.
102
+ */
103
+ type ShiftCloseOutcome = 'closed' | 'already-closed' | 'resumed';
104
+ interface CloseShiftResult {
105
+ /** The shift as persisted. Terminal in every outcome. */
106
+ shift: ShiftDocument;
107
+ outcome: ShiftCloseOutcome;
108
+ /** The recorded entry id, or null when nothing was posted. */
109
+ journalEntryId: string | null;
110
+ /** True only when THIS call invoked the ledger bridge and it succeeded. */
111
+ ledgerPosted: boolean;
112
+ /**
113
+ * Set when the ledger bridge threw on a `forceClose` — the orphan still
114
+ * landed (it must), the shift keeps its `pendingLedgerPost` marker, and a
115
+ * later `forceClose(id)` converges it. `close()` never returns this: it
116
+ * compensates the CAS and rethrows instead.
117
+ */
118
+ ledgerError?: unknown;
63
119
  }
64
120
  interface ShiftRepositoryConfig {
65
121
  model: Model<IShift>;
122
+ /**
123
+ * Claim ledger backing `incrementSales({ dedupeRef })`. Optional so tests /
124
+ * legacy constructions without the model keep working — a `dedupeRef` call
125
+ * without the model throws (fail loud, never silently double-count).
126
+ */
127
+ dedupeModel?: Model<IShiftSaleDedupe> | undefined;
66
128
  plugins?: PluginType[] | undefined;
129
+ /**
130
+ * Soft-delete policy. `{ ttlDays }` (default 2555 = 7yr) wires
131
+ * `softDeletePlugin`; `false` disables it (hard deletes). Resolved by the
132
+ * engine from `PosShape.softDelete`.
133
+ */
134
+ softDelete?: false | {
135
+ ttlDays?: number;
136
+ } | undefined;
67
137
  defaultPolicy: ShiftPolicy;
68
138
  ledgerBridge?: LedgerBridge | undefined;
69
139
  policyBridge?: PolicyBridge | undefined;
@@ -81,6 +151,7 @@ interface ShiftRepositoryConfig {
81
151
  } | undefined;
82
152
  }
83
153
  declare class ShiftRepository extends Repository<IShift> {
154
+ private readonly dedupeModel;
84
155
  private readonly defaultPolicy;
85
156
  private readonly ledgerBridge;
86
157
  private readonly policyBridge;
@@ -100,21 +171,32 @@ declare class ShiftRepository extends Repository<IShift> {
100
171
  recordCashMovement(input: RecordCashMovementInput, ctx: PosContext): Promise<ShiftDocument>;
101
172
  /**
102
173
  * Atomically increment shift aggregates from an order-create hook in the
103
- * host. Idempotency is the host's responsibility (don't call twice for
104
- * the same order). Refunds pass `refund: true`.
174
+ * host. Refunds pass `refund: true`.
175
+ *
176
+ * Idempotency: pass `dedupeRef` (a retry-stable order identity, e.g.
177
+ * `shift-sale:{orderNumber}:{method}`) to make the call exactly-once — the
178
+ * repo claims `(shiftId, dedupeRef)` insert-first in the dedupe ledger and
179
+ * skips the `$inc` on a duplicate claim (`{ applied: false }`). Without
180
+ * `dedupeRef` the legacy contract applies: idempotency is the host's
181
+ * responsibility (don't call twice for the same order).
105
182
  */
106
- incrementSales(input: IncrementSalesInput, ctx: PosContext): Promise<void>;
183
+ incrementSales(input: IncrementSalesInput, ctx: PosContext): Promise<IncrementSalesResult>;
107
184
  /**
108
185
  * Lightspeed-style cashier blind-close — counts are recorded but the
109
186
  * variance check is deferred to the manager-driven `close()`.
110
187
  */
111
188
  blindClose(input: BlindCloseInput, ctx: PosContext): Promise<ShiftDocument>;
112
189
  /**
113
- * Final close — fires the variance gate, the ledger bridge, and the
114
- * `pos:shift.closed` event in that order. State write happens last; a
115
- * thrown bridge keeps the shift in its previous state.
190
+ * Final close — variance gate, **CAS**, ledger bridge, `pos:shift.closed`,
191
+ * in that order. The state write happens FIRST so exactly one caller can
192
+ * reach the bridge; a thrown bridge compensates the CAS and rethrows, so
193
+ * the shift still ends up in its previous state (Odoo semantics preserved).
194
+ *
195
+ * Returns a {@link CloseShiftResult}, not a bare document — a caller that
196
+ * lost the race, or that is retrying a crashed close, needs to know which
197
+ * of those happened without catching an exception.
116
198
  */
117
- close(input: CloseShiftInput, ctx: PosContext): Promise<ShiftDocument>;
199
+ close(input: CloseShiftInput, ctx: PosContext): Promise<CloseShiftResult>;
118
200
  /**
119
201
  * Find shifts in any active state whose `businessDate` is strictly before
120
202
  * `asOf`. Used by the EOD cron backstop to identify orphans the cashier
@@ -135,12 +217,127 @@ declare class ShiftRepository extends Repository<IShift> {
135
217
  state: string;
136
218
  businessDate: Date;
137
219
  }>>;
220
+ /**
221
+ * The currently ACTIVE shift (`open | paused | blind_closed`), or `null`.
222
+ *
223
+ * DOMAIN LOGIC, not a `getAll` alias (CLAUDE.md "don't wrap"): it encodes
224
+ * (a) which states count as active and (b) the at-most-one invariant that
225
+ * the `uniq_active_shift_per_register` partial index enforces. Every POS
226
+ * surface needs this exact question — "can this cashier ring a sale?" — so
227
+ * it lives here once instead of being re-derived per host.
228
+ *
229
+ * Scope:
230
+ * - `registerId` given → the active shift for THAT register (at most one).
231
+ * This is the correct scope once a branch runs multiple registers.
232
+ * - `registerId` omitted → the active shift for the branch. Back-compat for
233
+ * single-register callers; with several registers open this returns an
234
+ * ARBITRARY one, so multi-register call sites MUST pass `registerId`.
235
+ *
236
+ * Routed through the inherited `findAll`, so the tenant plugin injects — and
237
+ * CASTS — the scope field. A raw `Model.findOne` here would need the host to
238
+ * hand-cast `organizationId` to an ObjectId (the bug that made the previous
239
+ * host-side shim carry its own `isValid` dance).
240
+ */
241
+ getActiveShift(ctx: PosContext, registerId?: string): Promise<ShiftDocument | null>;
242
+ /**
243
+ * Lean, DELIBERATELY UNSCOPED read by `_id`.
244
+ *
245
+ * Exists so a host can distinguish "shift does not exist" (404) from "shift
246
+ * belongs to another branch" (403) — a tenant-scoped read collapses both to
247
+ * `null`, which forces every POS surface to lie about one of the two. Named
248
+ * distinctly so it can never shadow the inherited, SCOPED `getById`.
249
+ *
250
+ * RAW `Model` read, flagged per CLAUDE.md — same documented exception as
251
+ * `findStaleShifts`. The tenant plugin is bypassed BY DESIGN; the soft-delete
252
+ * plugin is bypassed as a side effect, so `deletedAt: null` is explicit.
253
+ *
254
+ * CALLER CONTRACT: you MUST compare the returned `organizationId` against the
255
+ * caller's scope before acting on the document. This method grants no
256
+ * authority — it only tells you the row exists.
257
+ */
258
+ getByIdUnscoped(shiftId: string): Promise<ShiftDocument | null>;
138
259
  /**
139
260
  * Backstop / EOD-cron path. Defaults counts to expected (zero variance)
140
261
  * and routes `closedBy: 'system_auto'`. Result is `orphaned_closed` —
141
262
  * a flag for manager review.
263
+ *
264
+ * Same claim-first ordering as {@link close}: the CAS runs before the
265
+ * ledger bridge, so the cron and a lazy-close firing at the same instant
266
+ * cannot both post. The ONE difference is the failure policy — an orphan
267
+ * MUST land (a shift that cannot finalize is stranded forever), so a
268
+ * throwing bridge is logged rather than compensated, and the shift keeps
269
+ * its `pendingLedgerPost` marker for a later `forceClose(id)` to converge.
142
270
  */
143
- forceClose(shiftId: string, ctx: PosContext): Promise<ShiftDocument>;
271
+ forceClose(shiftId: string, ctx: PosContext): Promise<CloseShiftResult>;
272
+ /**
273
+ * Shifts that won a close CAS but whose journal entry was never recorded —
274
+ * the crash window between the claim and the ledger write.
275
+ *
276
+ * Cross-tenant (backs an operational sweep, like `findStaleShifts`), so it
277
+ * reads the model directly and re-adds the soft-delete guard the bypassed
278
+ * plugin would have injected. Each row converges by calling
279
+ * `close({ shiftId, ... })` or `forceClose(shiftId)` again — the retry
280
+ * resumes rather than re-posting.
281
+ *
282
+ * Exists because an unobservable stuck state is the FAIL-LOUD failure mode:
283
+ * without this query, a crashed post converges only if someone happens to
284
+ * retry that exact shift.
285
+ */
286
+ findShiftsWithPendingLedgerPost(olderThan?: Date): Promise<Array<{
287
+ _id: unknown;
288
+ organizationId: unknown;
289
+ registerId: string;
290
+ state: string;
291
+ pendingLedgerPost: PendingLedgerPost;
292
+ }>>;
293
+ /**
294
+ * The ledger post a close is about to OWE, or null when none is owed
295
+ * (no bridge wired, or the shift already carries an entry id).
296
+ *
297
+ * The key is derived from the shift id alone — same value on every attempt,
298
+ * which is the whole point: a resume after a crash must collide with the
299
+ * entry the crashed attempt may have already written.
300
+ */
301
+ private buildPendingLedgerPost;
302
+ /**
303
+ * Invoke the ledger bridge for a shift THIS CALL has already claimed, then
304
+ * record the entry id and clear the marker in one write.
305
+ *
306
+ * Never call this before the CAS. `pending === null` means nothing is owed
307
+ * and the bridge is skipped entirely.
308
+ */
309
+ private runLedgerPost;
310
+ /**
311
+ * Persist the entry id and retire the marker in ONE write — the pair is the
312
+ * proof that the post completed. An empty-string id is the bridge's
313
+ * "nothing to post" sentinel and persists as null.
314
+ */
315
+ private recordLedgerPost;
316
+ /** Stamp the failed attempt + the fact that the lifecycle event was sent. */
317
+ private markLedgerPostAnnounced;
318
+ /**
319
+ * A CAS miss on close / forceClose. Returns an idempotent result when the
320
+ * on-disk state says another caller finalized the shift; returns null when
321
+ * the failure is a genuine illegal transition the caller should throw.
322
+ *
323
+ * The LOSER NEVER POSTS. That is the entire fix: previously the loser had
324
+ * already committed its journal entry by the time it got here.
325
+ */
326
+ private diagnoseLostClaim;
327
+ /**
328
+ * The shift is already terminal. Either an unrecorded ledger post is
329
+ * outstanding (crash recovery — resume it) or there is nothing to do.
330
+ */
331
+ private convergeTerminal;
332
+ /**
333
+ * Converge a close that won the CAS but died before recording its entry.
334
+ *
335
+ * Re-invokes the bridge with the SAME deterministic key, so a durable
336
+ * adapter returns the entry the crashed attempt may already have written
337
+ * rather than posting a second one. This is the call site that makes
338
+ * `idempotencyKey` load-bearing rather than advisory.
339
+ */
340
+ private resumeLedgerPost;
144
341
  /**
145
342
  * Build a single-step approved `ApprovalChain` for a manager's variance
146
343
  * override. Uses primitives' `createChain` + `applyDecision` rather than
@@ -154,6 +351,14 @@ declare class ShiftRepository extends Repository<IShift> {
154
351
  */
155
352
  private buildVarianceApprovalChain;
156
353
  private transitionState;
354
+ /** Scoped read or 404. No state opinion — the caller decides. */
355
+ private requireShift;
356
+ /**
357
+ * Scoped read that refuses a finalized shift. Used by the MUTATING verbs
358
+ * (pause / resume / cash movement / blindClose) where "already closed" is a
359
+ * genuine error. `close` / `forceClose` deliberately do NOT use it — for
360
+ * them a terminal shift is an idempotent outcome, not a failure.
361
+ */
157
362
  private requireActive;
158
363
  private applyCounts;
159
364
  /**
@@ -168,4 +373,4 @@ declare class ShiftRepository extends Repository<IShift> {
168
373
  private dispatch;
169
374
  }
170
375
  //#endregion
171
- export { BlindCloseInput, CloseShiftInput, IncrementSalesInput, OpenShiftInput, RecordCashMovementInput, ShiftRepository, ShiftRepositoryConfig };
376
+ export { BlindCloseInput, CloseShiftInput, CloseShiftResult, IncrementSalesInput, IncrementSalesResult, OpenShiftInput, RecordCashMovementInput, ShiftCloseOutcome, ShiftRepository, ShiftRepositoryConfig };