@classytic/pos 0.3.1 → 0.4.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 +236 -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 +480 -85
  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,4 +1,7 @@
1
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, ShiftFinalizedError, ShiftNotFoundError, UnmanagedSessionError, VarianceExceededError } from "../domain/errors/pos.errors.mjs";
1
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError } from "../domain/errors/pos.errors.mjs";
2
+ import { resolveMethodKind } from "../domain/enums/payment-method.enum.mjs";
3
+ import { ACTIVE_SHIFT_STATES, isFinalShiftState } from "../domain/enums/shift-state.enum.mjs";
4
+ import { shiftCloseIdempotencyKey } from "../domain/ports/ledger.bridge.mjs";
2
5
  import { canTransition, nextState } from "../domain/state-machines/shift.fsm.mjs";
3
6
  import { computeDifference, computeExpected } from "../domain/value-objects/payment-breakdown.vo.mjs";
4
7
  import { isWithinVarianceThreshold } from "../domain/value-objects/shift-policy.vo.mjs";
@@ -7,6 +10,7 @@ import { createPosEvent } from "../events/helpers.mjs";
7
10
  import { repoOptionsFromCtx } from "./repo-options.mjs";
8
11
  import { isTransitionRace, shiftMachine } from "./shift-transition-support.mjs";
9
12
  import { Repository, methodRegistryPlugin, softDeletePlugin } from "@classytic/mongokit";
13
+ import { isValidObjectId } from "mongoose";
10
14
  import { applyDecision, createChain } from "@classytic/primitives/approval";
11
15
  //#region src/repositories/shift.repository.ts
12
16
  /**
@@ -17,20 +21,61 @@ import { applyDecision, createChain } from "@classytic/primitives/approval";
17
21
  * the ledger-bridge handshake. Hosts should call these verbs (not raw CRUD)
18
22
  * for state changes.
19
23
  *
20
- * Transactional close pipeline:
24
+ * Close pipeline — CLAIM FIRST, THEN POST (reordered 2026-08-05):
21
25
  * 1. Compute expected per method + cash totals
22
26
  * 2. Variance gate (policy.varianceThresholdAbs/Pct)
23
- * 3. Bridge: ledger.onShiftClosed → returns journalEntryId (host posts JE)
24
- * 4. State write to `closed` + persist journalEntryId
25
- * 5. Publish `pos:shift.closed`
27
+ * 3. **CAS** the shift into its terminal state, stamping `pendingLedgerPost`
28
+ * in the SAME write. Exactly one caller wins.
29
+ * 4. Bridge: ledger.onShiftClosed → returns journalEntryId (host posts JE).
30
+ * Only the CAS winner reaches this line.
31
+ * 5. Persist `journalEntryId` + clear `pendingLedgerPost`
32
+ * 6. Publish `pos:shift.closed`
26
33
  *
27
- * If step 3 throws, the state write is skipped (Odoo rollback). Hosts using
28
- * MongoDB transactions thread `ctx.session` so steps 3+4 commit atomically.
34
+ * ## Why this order (the defect it fixes)
29
35
  *
30
- * Raw `findOneAndUpdate` is used ONLY for the FSM transition with a
31
- * `{ state }` guard — concurrent close attempts can't double-post the JE.
36
+ * The bridge used to run BEFORE the CAS, outside any transaction, and the
37
+ * loser's `IllegalShiftTransitionError` was thrown AFTER its journal entry had
38
+ * already committed — which hosts caught and logged. Three shipped triggers
39
+ * close the same shift (lazy-close at register open, the oversight endpoint,
40
+ * the EOD cron), so at 08:00 a cashier opening a till and the cron sweeping
41
+ * yesterday's orphan would BOTH read `state: 'open'`, BOTH pass `canTransition`
42
+ * and BOTH post a Z-report for one day's cash. One shift document, two journal
43
+ * entries, no error surfaced. Claiming first makes the bridge unreachable to
44
+ * every caller but one.
45
+ *
46
+ * ## Crash convergence
47
+ *
48
+ * A pod eviction between step 3 and step 5 leaves the shift terminal with
49
+ * `pendingLedgerPost` set and `journalEntryId` null. Retrying `close()` /
50
+ * `forceClose()` RESUMES from that state — same deterministic
51
+ * `idempotencyKey`, so a durable bridge returns the existing entry instead of
52
+ * posting a second one. `findShiftsWithPendingLedgerPost()` lists anything
53
+ * stuck there. On the old ordering the same crash re-posted a fresh JE on
54
+ * every retry, forever.
55
+ *
56
+ * Idempotency is no longer prose: `ShiftClosePosting.idempotencyKey` is a
57
+ * required field the compiler enforces on every implementation.
58
+ */
59
+ /**
60
+ * Mongoose DocumentArrays don't spread (`...row`) cleanly — coerce to plain
61
+ * objects so spreads and numeric ops see every field. One definition; the
62
+ * close, forceClose and compensation paths all read it, and they diverged
63
+ * before.
32
64
  */
65
+ function toPlainBreakdown(breakdown) {
66
+ return breakdown.map((r) => typeof r.toObject === "function" ? r.toObject() : r);
67
+ }
68
+ /**
69
+ * `''` is the ledger bridge's documented "nothing to post" sentinel (zero-net
70
+ * shift, posting policy `off`). Persist it as null so `journalEntryId` is
71
+ * either a real reference or absent — never an empty string a reader has to
72
+ * special-case.
73
+ */
74
+ function normalizeEntryId(entryId) {
75
+ return entryId === "" ? null : entryId;
76
+ }
33
77
  var ShiftRepository = class extends Repository {
78
+ dedupeModel;
34
79
  defaultPolicy;
35
80
  ledgerBridge;
36
81
  policyBridge;
@@ -39,12 +84,13 @@ var ShiftRepository = class extends Repository {
39
84
  outbox;
40
85
  logger;
41
86
  constructor(config) {
42
- const { model, plugins = [] } = config;
87
+ const { model, plugins = [], softDelete = { ttlDays: 2555 } } = config;
43
88
  super(model, [
44
89
  methodRegistryPlugin(),
45
- softDeletePlugin({ ttlDays: 2555 }),
90
+ ...softDelete === false ? [] : [softDeletePlugin({ ttlDays: softDelete.ttlDays ?? 2555 })],
46
91
  ...plugins
47
92
  ]);
93
+ this.dedupeModel = config.dedupeModel;
48
94
  this.defaultPolicy = config.defaultPolicy;
49
95
  this.ledgerBridge = config.ledgerBridge;
50
96
  this.policyBridge = config.policyBridge;
@@ -62,6 +108,7 @@ var ShiftRepository = class extends Repository {
62
108
  const policy = input.policy ?? (this.policyBridge ? await this.policyBridge.resolvePolicy(ctx) : this.defaultPolicy);
63
109
  const seedBreakdown = policy.allowedPaymentMethods.map((method) => ({
64
110
  method,
111
+ methodKind: resolveMethodKind(method, policy.paymentMethodKinds?.[method]),
65
112
  openingAmount: method === "cash" ? input.openingCash : 0,
66
113
  salesAmount: 0,
67
114
  taxAmount: 0,
@@ -94,7 +141,7 @@ var ShiftRepository = class extends Repository {
94
141
  }, ctx);
95
142
  return shift;
96
143
  } catch (err) {
97
- if (err.code === 11e3) throw new ActiveShiftAlreadyOpenError(`${input.registerId}`);
144
+ if (this.isDuplicateKeyError(err) || err.code === 11e3) throw new ActiveShiftAlreadyOpenError(`${input.registerId}`);
98
145
  throw err;
99
146
  }
100
147
  }
@@ -133,15 +180,42 @@ var ShiftRepository = class extends Repository {
133
180
  }
134
181
  /**
135
182
  * Atomically increment shift aggregates from an order-create hook in the
136
- * host. Idempotency is the host's responsibility (don't call twice for
137
- * the same order). Refunds pass `refund: true`.
183
+ * host. Refunds pass `refund: true`.
184
+ *
185
+ * Idempotency: pass `dedupeRef` (a retry-stable order identity, e.g.
186
+ * `shift-sale:{orderNumber}:{method}`) to make the call exactly-once — the
187
+ * repo claims `(shiftId, dedupeRef)` insert-first in the dedupe ledger and
188
+ * skips the `$inc` on a duplicate claim (`{ applied: false }`). Without
189
+ * `dedupeRef` the legacy contract applies: idempotency is the host's
190
+ * responsibility (don't call twice for the same order).
138
191
  */
139
192
  async incrementSales(input, ctx) {
140
- if (input.amount <= 0) return;
193
+ if (input.amount <= 0) return {
194
+ applied: false,
195
+ reason: "zero-amount"
196
+ };
141
197
  if (!Number.isInteger(input.amount)) throw new CashMovementInvalidError(`incrementSales amount must be integer minor units; got ${input.amount}`);
142
198
  const refund = input.refund === true;
143
- const tax = Math.max(0, Math.trunc(input.tax ?? 0));
199
+ const rawTax = input.tax ?? 0;
200
+ if (!Number.isInteger(rawTax)) throw new CashMovementInvalidError(`incrementSales tax must be integer minor units; got ${rawTax}`);
201
+ const tax = Math.max(0, rawTax);
144
202
  if (tax > input.amount) throw new CashMovementInvalidError(`tax (${tax}) cannot exceed amount (${input.amount})`);
203
+ const txnSession = repoOptionsFromCtx(ctx).session;
204
+ if (input.dedupeRef !== void 0) {
205
+ if (!this.dedupeModel) throw new CashMovementInvalidError("incrementSales dedupeRef requires the ShiftSaleDedupe model — construct the engine via definePos().bind (or pass dedupeModel)");
206
+ try {
207
+ await this.dedupeModel.create([{
208
+ shiftId: input.shiftId,
209
+ orderRef: input.dedupeRef
210
+ }], txnSession ? { session: txnSession } : {});
211
+ } catch (err) {
212
+ if (err.code === 11e3) return {
213
+ applied: false,
214
+ reason: "duplicate"
215
+ };
216
+ throw err;
217
+ }
218
+ }
145
219
  const update = { $inc: refund ? {
146
220
  refundCount: 1,
147
221
  refundTotal: input.amount,
@@ -160,13 +234,28 @@ var ShiftRepository = class extends Repository {
160
234
  endingCashierName: input.cashierName ?? input.cashierId
161
235
  };
162
236
  }
163
- await this.findOneAndUpdate({
237
+ const allowedStates = refund ? ["open", "paused"] : ["open"];
238
+ if (!await this.findOneAndUpdate({
164
239
  _id: input.shiftId,
165
- state: { $in: ["open", "paused"] }
240
+ state: { $in: allowedStates },
241
+ "paymentBreakdown.method": input.method
166
242
  }, update, {
167
243
  arrayFilters: [{ "methodElem.method": input.method }],
168
244
  ...repoOptionsFromCtx(ctx)
169
- });
245
+ })) {
246
+ if (input.dedupeRef !== void 0 && this.dedupeModel) await this.dedupeModel.deleteOne({
247
+ shiftId: input.shiftId,
248
+ orderRef: input.dedupeRef
249
+ }, txnSession ? { session: txnSession } : {});
250
+ const existing = await this.getByIdUnscoped(input.shiftId);
251
+ if (!existing) throw new ShiftNotFoundError(input.shiftId);
252
+ if (!refund && existing.state === "paused") throw new ShiftPausedError(input.shiftId);
253
+ const isActive = existing.state === "open" || existing.state === "paused";
254
+ const methodPresent = (existing.paymentBreakdown ?? []).some((r) => r.method === input.method);
255
+ if (isActive && !methodPresent) throw new CashMovementInvalidError(`payment method '${input.method}' is not in the shift's allowedPaymentMethods`);
256
+ throw new ShiftFinalizedError(input.shiftId);
257
+ }
258
+ return { applied: true };
170
259
  }
171
260
  /**
172
261
  * Lightspeed-style cashier blind-close — counts are recorded but the
@@ -200,13 +289,20 @@ var ShiftRepository = class extends Repository {
200
289
  return updated;
201
290
  }
202
291
  /**
203
- * Final close — fires the variance gate, the ledger bridge, and the
204
- * `pos:shift.closed` event in that order. State write happens last; a
205
- * thrown bridge keeps the shift in its previous state.
292
+ * Final close — variance gate, **CAS**, ledger bridge, `pos:shift.closed`,
293
+ * in that order. The state write happens FIRST so exactly one caller can
294
+ * reach the bridge; a thrown bridge compensates the CAS and rethrows, so
295
+ * the shift still ends up in its previous state (Odoo semantics preserved).
296
+ *
297
+ * Returns a {@link CloseShiftResult}, not a bare document — a caller that
298
+ * lost the race, or that is retrying a crashed close, needs to know which
299
+ * of those happened without catching an exception.
206
300
  */
207
301
  async close(input, ctx) {
208
- const shift = await this.requireActive(input.shiftId, ctx);
302
+ const shift = await this.requireShift(input.shiftId, ctx);
303
+ if (isFinalShiftState(shift.state)) return this.convergeTerminal(shift, ctx);
209
304
  if (!canTransition(shift.state, "close")) throw new IllegalShiftTransitionError(shift.state, "close");
305
+ if (shift.state === "open" && input.countedByMethod === void 0) throw new ShiftCountsRequiredError(input.shiftId);
210
306
  const breakdown = input.countedByMethod ? this.applyCounts(shift.paymentBreakdown, input.countedByMethod, true) : shift.paymentBreakdown;
211
307
  const cashRow = breakdown.find((r) => r.method === "cash");
212
308
  let varianceExceeded = false;
@@ -215,14 +311,18 @@ var ShiftRepository = class extends Repository {
215
311
  if (varianceExceeded && shift.policySnapshot.managerOverrideRequired && !input.varianceOverride) throw new VarianceExceededError(cashRow.difference ?? 0, cashRow.expectedAmount);
216
312
  }
217
313
  const fromState = shift.state;
218
- let journalEntryId = shift.journalEntryId ?? null;
219
- if (this.ledgerBridge && !journalEntryId) {
220
- const projected = {
221
- ...shift.toObject(),
222
- paymentBreakdown: breakdown
223
- };
224
- journalEntryId = (await this.ledgerBridge.onShiftClosed(projected, ctx)).journalEntryId;
225
- }
314
+ const shiftId = String(shift._id);
315
+ const priorSet = {
316
+ closedAt: shift.closedAt ?? null,
317
+ closedBy: shift.closedBy ?? null,
318
+ paymentBreakdown: toPlainBreakdown(shift.paymentBreakdown),
319
+ expectedCash: shift.expectedCash ?? null,
320
+ countedCash: shift.countedCash ?? null,
321
+ cashDifference: shift.cashDifference ?? null,
322
+ approvals: shift.approvals ?? null,
323
+ pendingLedgerPost: null
324
+ };
325
+ const pending = this.buildPendingLedgerPost(shift, "close");
226
326
  const set = {
227
327
  closedAt: /* @__PURE__ */ new Date(),
228
328
  closedBy: input.closedBy,
@@ -230,19 +330,32 @@ var ShiftRepository = class extends Repository {
230
330
  expectedCash: cashRow?.expectedAmount ?? null,
231
331
  countedCash: cashRow?.countedAmount ?? null,
232
332
  cashDifference: cashRow?.difference ?? null,
233
- ...journalEntryId ? { journalEntryId } : {},
333
+ pendingLedgerPost: pending,
234
334
  ...input.varianceOverride ? { approvals: this.buildVarianceApprovalChain(input.varianceOverride.overriddenBy, input.varianceOverride.reason) } : {}
235
335
  };
236
- const updated = await this.applyTransition(String(shift._id), shiftMachine("close"), {
237
- field: "state",
238
- from: fromState,
239
- to: "closed",
240
- set,
241
- history: false
242
- }, repoOptionsFromCtx(ctx)).catch((err) => {
243
- if (isTransitionRace(err)) throw new IllegalShiftTransitionError(fromState, "close");
336
+ let claimed;
337
+ try {
338
+ claimed = await this.applyTransition(shiftId, shiftMachine("close"), {
339
+ field: "state",
340
+ from: fromState,
341
+ to: "closed",
342
+ set,
343
+ history: false
344
+ }, repoOptionsFromCtx(ctx));
345
+ } catch (err) {
346
+ const lost = await this.diagnoseLostClaim(err, shiftId, fromState, "close", ctx);
347
+ if (lost) return lost;
244
348
  throw err;
245
- });
349
+ }
350
+ const posted = await this.runLedgerPost(claimed, pending, ctx, { onFailure: async (bridgeErr) => {
351
+ if (!await this.claim(shiftId, {
352
+ field: "state",
353
+ from: "closed",
354
+ to: fromState
355
+ }, { $set: priorSet }, repoOptionsFromCtx(ctx))) this.logger.error(`[pos] COMPENSATION FAILED for close(${shiftId}) — the shift is marked 'closed' but the ledger bridge failed and the rollback CAS did not match. Manual reconciliation required.`, bridgeErr);
356
+ throw bridgeErr;
357
+ } });
358
+ const updated = posted.shift;
246
359
  if (varianceExceeded && cashRow?.expectedAmount != null) await this.dispatch(POS_EVENTS.VARIANCE_DETECTED, {
247
360
  shiftId: input.shiftId,
248
361
  difference: cashRow.difference ?? 0,
@@ -250,7 +363,7 @@ var ShiftRepository = class extends Repository {
250
363
  }, ctx);
251
364
  await this.dispatch(POS_EVENTS.SHIFT_CLOSED, {
252
365
  shiftId: input.shiftId,
253
- journalEntryId,
366
+ journalEntryId: posted.journalEntryId,
254
367
  closedBy: input.closedBy
255
368
  }, ctx);
256
369
  if (input.varianceOverride && this.notificationBridge?.onVarianceOverride) try {
@@ -258,7 +371,12 @@ var ShiftRepository = class extends Repository {
258
371
  } catch (err) {
259
372
  this.logger.error("[pos] notificationBridge.onVarianceOverride threw", err);
260
373
  }
261
- return updated;
374
+ return {
375
+ shift: updated,
376
+ outcome: "closed",
377
+ journalEntryId: posted.journalEntryId,
378
+ ledgerPosted: posted.ledgerPosted
379
+ };
262
380
  }
263
381
  /**
264
382
  * Find shifts in any active state whose `businessDate` is strictly before
@@ -275,11 +393,7 @@ var ShiftRepository = class extends Repository {
275
393
  */
276
394
  async findStaleShifts(asOf) {
277
395
  return this.Model.find({
278
- state: { $in: [
279
- "open",
280
- "paused",
281
- "blind_closed"
282
- ] },
396
+ state: { $in: [...ACTIVE_SHIFT_STATES] },
283
397
  businessDate: { $lt: asOf },
284
398
  deletedAt: null
285
399
  }, {
@@ -291,14 +405,76 @@ var ShiftRepository = class extends Repository {
291
405
  }).lean();
292
406
  }
293
407
  /**
408
+ * The currently ACTIVE shift (`open | paused | blind_closed`), or `null`.
409
+ *
410
+ * DOMAIN LOGIC, not a `getAll` alias (CLAUDE.md "don't wrap"): it encodes
411
+ * (a) which states count as active and (b) the at-most-one invariant that
412
+ * the `uniq_active_shift_per_register` partial index enforces. Every POS
413
+ * surface needs this exact question — "can this cashier ring a sale?" — so
414
+ * it lives here once instead of being re-derived per host.
415
+ *
416
+ * Scope:
417
+ * - `registerId` given → the active shift for THAT register (at most one).
418
+ * This is the correct scope once a branch runs multiple registers.
419
+ * - `registerId` omitted → the active shift for the branch. Back-compat for
420
+ * single-register callers; with several registers open this returns an
421
+ * ARBITRARY one, so multi-register call sites MUST pass `registerId`.
422
+ *
423
+ * Routed through the inherited `findAll`, so the tenant plugin injects — and
424
+ * CASTS — the scope field. A raw `Model.findOne` here would need the host to
425
+ * hand-cast `organizationId` to an ObjectId (the bug that made the previous
426
+ * host-side shim carry its own `isValid` dance).
427
+ */
428
+ async getActiveShift(ctx, registerId) {
429
+ return (await this.findAll({
430
+ state: { $in: [...ACTIVE_SHIFT_STATES] },
431
+ ...registerId !== void 0 ? { registerId } : {}
432
+ }, {
433
+ ...repoOptionsFromCtx(ctx),
434
+ limit: 1,
435
+ sort: { openedAt: -1 }
436
+ }))[0] ?? null;
437
+ }
438
+ /**
439
+ * Lean, DELIBERATELY UNSCOPED read by `_id`.
440
+ *
441
+ * Exists so a host can distinguish "shift does not exist" (404) from "shift
442
+ * belongs to another branch" (403) — a tenant-scoped read collapses both to
443
+ * `null`, which forces every POS surface to lie about one of the two. Named
444
+ * distinctly so it can never shadow the inherited, SCOPED `getById`.
445
+ *
446
+ * RAW `Model` read, flagged per CLAUDE.md — same documented exception as
447
+ * `findStaleShifts`. The tenant plugin is bypassed BY DESIGN; the soft-delete
448
+ * plugin is bypassed as a side effect, so `deletedAt: null` is explicit.
449
+ *
450
+ * CALLER CONTRACT: you MUST compare the returned `organizationId` against the
451
+ * caller's scope before acting on the document. This method grants no
452
+ * authority — it only tells you the row exists.
453
+ */
454
+ async getByIdUnscoped(shiftId) {
455
+ if (!isValidObjectId(shiftId)) return null;
456
+ return this.Model.findOne({
457
+ _id: shiftId,
458
+ deletedAt: null
459
+ }).lean();
460
+ }
461
+ /**
294
462
  * Backstop / EOD-cron path. Defaults counts to expected (zero variance)
295
463
  * and routes `closedBy: 'system_auto'`. Result is `orphaned_closed` —
296
464
  * a flag for manager review.
465
+ *
466
+ * Same claim-first ordering as {@link close}: the CAS runs before the
467
+ * ledger bridge, so the cron and a lazy-close firing at the same instant
468
+ * cannot both post. The ONE difference is the failure policy — an orphan
469
+ * MUST land (a shift that cannot finalize is stranded forever), so a
470
+ * throwing bridge is logged rather than compensated, and the shift keeps
471
+ * its `pendingLedgerPost` marker for a later `forceClose(id)` to converge.
297
472
  */
298
473
  async forceClose(shiftId, ctx) {
299
- const shift = await this.requireActive(shiftId, ctx);
474
+ const shift = await this.requireShift(shiftId, ctx);
475
+ if (isFinalShiftState(shift.state)) return this.convergeTerminal(shift, ctx);
300
476
  if (!canTransition(shift.state, "forceClose")) throw new IllegalShiftTransitionError(shift.state, "forceClose");
301
- const breakdown = shift.paymentBreakdown.map((r) => typeof r.toObject === "function" ? r.toObject() : r).map((row) => {
477
+ const breakdown = toPlainBreakdown(shift.paymentBreakdown).map((row) => {
302
478
  const expected = row.expectedAmount ?? computeExpected(row);
303
479
  return {
304
480
  ...row,
@@ -308,37 +484,37 @@ var ShiftRepository = class extends Repository {
308
484
  };
309
485
  });
310
486
  const cashRow = breakdown.find((r) => r.method === "cash");
311
- let journalEntryId = shift.journalEntryId ?? null;
312
- if (this.ledgerBridge && !journalEntryId) {
313
- const projected = {
314
- ...shift.toObject(),
315
- paymentBreakdown: breakdown
316
- };
317
- try {
318
- journalEntryId = (await this.ledgerBridge.onShiftClosed(projected, ctx)).journalEntryId;
319
- } catch (err) {
320
- this.logger.error("[pos] ledgerBridge threw on forceClose", err);
321
- }
322
- }
323
487
  const fromState = shift.state;
324
- const updated = await this.applyTransition(String(shift._id), shiftMachine("forceClose"), {
325
- field: "state",
326
- from: fromState,
327
- to: "orphaned_closed",
328
- set: {
329
- closedAt: /* @__PURE__ */ new Date(),
330
- closedBy: "system_auto",
331
- paymentBreakdown: breakdown,
332
- expectedCash: cashRow?.expectedAmount ?? null,
333
- countedCash: cashRow?.countedAmount ?? null,
334
- cashDifference: 0,
335
- ...journalEntryId ? { journalEntryId } : {}
336
- },
337
- history: false
338
- }, repoOptionsFromCtx(ctx)).catch((err) => {
339
- if (isTransitionRace(err)) throw new IllegalShiftTransitionError(fromState, "forceClose");
488
+ const pending = this.buildPendingLedgerPost(shift, "forceClose");
489
+ let claimed;
490
+ try {
491
+ claimed = await this.applyTransition(String(shift._id), shiftMachine("forceClose"), {
492
+ field: "state",
493
+ from: fromState,
494
+ to: "orphaned_closed",
495
+ set: {
496
+ closedAt: /* @__PURE__ */ new Date(),
497
+ closedBy: "system_auto",
498
+ paymentBreakdown: breakdown,
499
+ expectedCash: cashRow?.expectedAmount ?? null,
500
+ countedCash: cashRow?.countedAmount ?? null,
501
+ cashDifference: 0,
502
+ pendingLedgerPost: pending
503
+ },
504
+ history: false
505
+ }, repoOptionsFromCtx(ctx));
506
+ } catch (err) {
507
+ const lost = await this.diagnoseLostClaim(err, shiftId, fromState, "forceClose", ctx);
508
+ if (lost) return lost;
340
509
  throw err;
341
- });
510
+ }
511
+ let ledgerError;
512
+ const posted = await this.runLedgerPost(claimed, pending, ctx, { onFailure: async (bridgeErr) => {
513
+ ledgerError = bridgeErr;
514
+ this.logger.error(`[pos] ledgerBridge threw on forceClose(${shiftId}) — the orphan still landed and keeps its pendingLedgerPost marker; retry forceClose to converge, or post the entry manually.`, bridgeErr);
515
+ await this.markLedgerPostAnnounced(shiftId, ctx);
516
+ } });
517
+ const updated = posted.shift;
342
518
  await this.dispatch(POS_EVENTS.SHIFT_FORCE_CLOSED, {
343
519
  shiftId,
344
520
  reason: "orphan_eod"
@@ -348,7 +524,214 @@ var ShiftRepository = class extends Repository {
348
524
  } catch (err) {
349
525
  this.logger.error("[pos] notificationBridge.onOrphanedClose threw", err);
350
526
  }
351
- return updated;
527
+ return {
528
+ shift: updated,
529
+ outcome: "closed",
530
+ journalEntryId: posted.journalEntryId,
531
+ ledgerPosted: posted.ledgerPosted,
532
+ ...ledgerError !== void 0 ? { ledgerError } : {}
533
+ };
534
+ }
535
+ /**
536
+ * Shifts that won a close CAS but whose journal entry was never recorded —
537
+ * the crash window between the claim and the ledger write.
538
+ *
539
+ * Cross-tenant (backs an operational sweep, like `findStaleShifts`), so it
540
+ * reads the model directly and re-adds the soft-delete guard the bypassed
541
+ * plugin would have injected. Each row converges by calling
542
+ * `close({ shiftId, ... })` or `forceClose(shiftId)` again — the retry
543
+ * resumes rather than re-posting.
544
+ *
545
+ * Exists because an unobservable stuck state is the FAIL-LOUD failure mode:
546
+ * without this query, a crashed post converges only if someone happens to
547
+ * retry that exact shift.
548
+ */
549
+ async findShiftsWithPendingLedgerPost(olderThan) {
550
+ return this.Model.find({
551
+ "pendingLedgerPost.stampedAt": olderThan ? { $lt: olderThan } : { $exists: true },
552
+ deletedAt: null
553
+ }, {
554
+ _id: 1,
555
+ organizationId: 1,
556
+ registerId: 1,
557
+ state: 1,
558
+ pendingLedgerPost: 1
559
+ }).lean();
560
+ }
561
+ /**
562
+ * The ledger post a close is about to OWE, or null when none is owed
563
+ * (no bridge wired, or the shift already carries an entry id).
564
+ *
565
+ * The key is derived from the shift id alone — same value on every attempt,
566
+ * which is the whole point: a resume after a crash must collide with the
567
+ * entry the crashed attempt may have already written.
568
+ */
569
+ buildPendingLedgerPost(shift, trigger) {
570
+ if (!this.ledgerBridge) return null;
571
+ if (shift.journalEntryId) return null;
572
+ return {
573
+ idempotencyKey: shiftCloseIdempotencyKey(String(shift._id)),
574
+ trigger,
575
+ attempts: 1,
576
+ stampedAt: /* @__PURE__ */ new Date(),
577
+ lastAttemptAt: null,
578
+ announced: false
579
+ };
580
+ }
581
+ /**
582
+ * Invoke the ledger bridge for a shift THIS CALL has already claimed, then
583
+ * record the entry id and clear the marker in one write.
584
+ *
585
+ * Never call this before the CAS. `pending === null` means nothing is owed
586
+ * and the bridge is skipped entirely.
587
+ */
588
+ async runLedgerPost(claimed, pending, ctx, handlers) {
589
+ if (!pending || !this.ledgerBridge) return {
590
+ shift: claimed,
591
+ journalEntryId: claimed.journalEntryId ?? null,
592
+ ledgerPosted: false
593
+ };
594
+ let entryId;
595
+ try {
596
+ entryId = (await this.ledgerBridge.onShiftClosed({
597
+ idempotencyKey: pending.idempotencyKey,
598
+ shift: claimed,
599
+ trigger: pending.trigger,
600
+ attempt: pending.attempts
601
+ }, ctx)).journalEntryId;
602
+ } catch (err) {
603
+ await handlers.onFailure(err);
604
+ return {
605
+ shift: claimed,
606
+ journalEntryId: null,
607
+ ledgerPosted: false
608
+ };
609
+ }
610
+ return {
611
+ shift: await this.recordLedgerPost(String(claimed._id), entryId, ctx) ?? claimed,
612
+ journalEntryId: normalizeEntryId(entryId),
613
+ ledgerPosted: true
614
+ };
615
+ }
616
+ /**
617
+ * Persist the entry id and retire the marker in ONE write — the pair is the
618
+ * proof that the post completed. An empty-string id is the bridge's
619
+ * "nothing to post" sentinel and persists as null.
620
+ */
621
+ async recordLedgerPost(shiftId, entryId, ctx) {
622
+ return await this.findOneAndUpdate({ _id: shiftId }, { $set: {
623
+ journalEntryId: normalizeEntryId(entryId),
624
+ pendingLedgerPost: null
625
+ } }, repoOptionsFromCtx(ctx));
626
+ }
627
+ /** Stamp the failed attempt + the fact that the lifecycle event was sent. */
628
+ async markLedgerPostAnnounced(shiftId, ctx) {
629
+ await this.findOneAndUpdate({
630
+ _id: shiftId,
631
+ "pendingLedgerPost.stampedAt": { $exists: true }
632
+ }, { $set: {
633
+ "pendingLedgerPost.lastAttemptAt": /* @__PURE__ */ new Date(),
634
+ "pendingLedgerPost.announced": true
635
+ } }, repoOptionsFromCtx(ctx));
636
+ }
637
+ /**
638
+ * A CAS miss on close / forceClose. Returns an idempotent result when the
639
+ * on-disk state says another caller finalized the shift; returns null when
640
+ * the failure is a genuine illegal transition the caller should throw.
641
+ *
642
+ * The LOSER NEVER POSTS. That is the entire fix: previously the loser had
643
+ * already committed its journal entry by the time it got here.
644
+ */
645
+ async diagnoseLostClaim(err, shiftId, fromState, verb, ctx) {
646
+ if (!(err instanceof IllegalShiftTransitionError) && !isTransitionRace(err)) return null;
647
+ const current = await this.getById(shiftId, repoOptionsFromCtx(ctx));
648
+ if (current && isFinalShiftState(current.state)) return this.convergeTerminal(current, ctx);
649
+ if (isTransitionRace(err)) throw new IllegalShiftTransitionError(current?.state ?? fromState, verb);
650
+ return null;
651
+ }
652
+ /**
653
+ * The shift is already terminal. Either an unrecorded ledger post is
654
+ * outstanding (crash recovery — resume it) or there is nothing to do.
655
+ */
656
+ async convergeTerminal(shift, ctx) {
657
+ const pending = shift.pendingLedgerPost ?? null;
658
+ if (!pending) return {
659
+ shift,
660
+ outcome: "already-closed",
661
+ journalEntryId: shift.journalEntryId ?? null,
662
+ ledgerPosted: false
663
+ };
664
+ return this.resumeLedgerPost(shift, pending, ctx);
665
+ }
666
+ /**
667
+ * Converge a close that won the CAS but died before recording its entry.
668
+ *
669
+ * Re-invokes the bridge with the SAME deterministic key, so a durable
670
+ * adapter returns the entry the crashed attempt may already have written
671
+ * rather than posting a second one. This is the call site that makes
672
+ * `idempotencyKey` load-bearing rather than advisory.
673
+ */
674
+ async resumeLedgerPost(shift, pending, ctx) {
675
+ const shiftId = String(shift._id);
676
+ if (!this.ledgerBridge) return {
677
+ shift,
678
+ outcome: "already-closed",
679
+ journalEntryId: shift.journalEntryId ?? null,
680
+ ledgerPosted: false
681
+ };
682
+ const claimed = await this.findOneAndUpdate({
683
+ _id: shiftId,
684
+ "pendingLedgerPost.attempts": pending.attempts
685
+ }, {
686
+ $inc: { "pendingLedgerPost.attempts": 1 },
687
+ $set: { "pendingLedgerPost.lastAttemptAt": /* @__PURE__ */ new Date() }
688
+ }, repoOptionsFromCtx(ctx));
689
+ if (!claimed) {
690
+ const doc = await this.getById(shiftId, repoOptionsFromCtx(ctx)) ?? shift;
691
+ return {
692
+ shift: doc,
693
+ outcome: "already-closed",
694
+ journalEntryId: doc.journalEntryId ?? null,
695
+ ledgerPosted: false
696
+ };
697
+ }
698
+ let entryId;
699
+ try {
700
+ entryId = (await this.ledgerBridge.onShiftClosed({
701
+ idempotencyKey: pending.idempotencyKey,
702
+ shift: claimed,
703
+ trigger: pending.trigger,
704
+ attempt: pending.attempts + 1
705
+ }, ctx)).journalEntryId;
706
+ } catch (err) {
707
+ if (pending.trigger === "close") throw err;
708
+ this.logger.error(`[pos] ledgerBridge threw while resuming the orphan close of ${shiftId} — marker retained; retry forceClose to converge.`, err);
709
+ return {
710
+ shift: claimed,
711
+ outcome: "already-closed",
712
+ journalEntryId: claimed.journalEntryId ?? null,
713
+ ledgerPosted: false,
714
+ ledgerError: err
715
+ };
716
+ }
717
+ const doc = await this.recordLedgerPost(shiftId, entryId, ctx) ?? claimed;
718
+ if (!pending.announced) {
719
+ if (pending.trigger === "forceClose") await this.dispatch(POS_EVENTS.SHIFT_FORCE_CLOSED, {
720
+ shiftId,
721
+ reason: "orphan_eod"
722
+ }, ctx);
723
+ else await this.dispatch(POS_EVENTS.SHIFT_CLOSED, {
724
+ shiftId,
725
+ journalEntryId: normalizeEntryId(entryId),
726
+ closedBy: doc.closedBy ?? "system_auto"
727
+ }, ctx);
728
+ }
729
+ return {
730
+ shift: doc,
731
+ outcome: "resumed",
732
+ journalEntryId: normalizeEntryId(entryId),
733
+ ledgerPosted: true
734
+ };
352
735
  }
353
736
  /**
354
737
  * Build a single-step approved `ApprovalChain` for a manager's variance
@@ -362,7 +745,7 @@ var ShiftRepository = class extends Repository {
362
745
  * manually. The persisted field is `approvals` (P7 canonical).
363
746
  */
364
747
  buildVarianceApprovalChain(approverId, reason) {
365
- return applyDecision(createChain({
748
+ const chain = createChain({
366
749
  order: "sequential",
367
750
  steps: [{
368
751
  id: "variance-override",
@@ -370,7 +753,8 @@ var ShiftRepository = class extends Repository {
370
753
  approvers: [{ id: approverId }],
371
754
  requiredApprovals: 1
372
755
  }]
373
- }), {
756
+ });
757
+ return applyDecision(chain, {
374
758
  stepId: "variance-override",
375
759
  approverId,
376
760
  decision: "approved",
@@ -399,14 +783,25 @@ var ShiftRepository = class extends Repository {
399
783
  }, ctx);
400
784
  return updated;
401
785
  }
402
- async requireActive(shiftId, ctx) {
786
+ /** Scoped read or 404. No state opinion — the caller decides. */
787
+ async requireShift(shiftId, ctx) {
403
788
  const shift = await this.getById(shiftId, repoOptionsFromCtx(ctx));
404
789
  if (!shift) throw new ShiftNotFoundError(shiftId);
405
- if (shift.state === "closed" || shift.state === "orphaned_closed") throw new ShiftFinalizedError(shiftId);
790
+ return shift;
791
+ }
792
+ /**
793
+ * Scoped read that refuses a finalized shift. Used by the MUTATING verbs
794
+ * (pause / resume / cash movement / blindClose) where "already closed" is a
795
+ * genuine error. `close` / `forceClose` deliberately do NOT use it — for
796
+ * them a terminal shift is an idempotent outcome, not a failure.
797
+ */
798
+ async requireActive(shiftId, ctx) {
799
+ const shift = await this.requireShift(shiftId, ctx);
800
+ if (isFinalShiftState(shift.state)) throw new ShiftFinalizedError(shiftId);
406
801
  return shift;
407
802
  }
408
803
  applyCounts(breakdown, counted, computeAll) {
409
- return breakdown.map((r) => typeof r.toObject === "function" ? r.toObject() : r).map((row) => {
804
+ return toPlainBreakdown(breakdown).map((row) => {
410
805
  const expected = computeAll ? computeExpected(row) : row.expectedAmount;
411
806
  const newCounted = counted[row.method] ?? row.countedAmount;
412
807
  const diff = expected !== null && newCounted !== null && newCounted !== void 0 ? computeDifference(expected, newCounted) : null;