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