@classytic/pos 0.6.0 → 0.8.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 (75) hide show
  1. package/CHANGELOG.md +10 -350
  2. package/dist/commands/index.d.mts +2 -0
  3. package/dist/commands/index.mjs +1 -0
  4. package/dist/commands/pos-commands.d.mts +230 -0
  5. package/dist/commands/pos-commands.mjs +357 -0
  6. package/dist/domain/enums/cash-movement-reason.enum.d.mts +3 -4
  7. package/dist/domain/enums/closed-by.enum.d.mts +3 -4
  8. package/dist/domain/enums/payment-method.enum.d.mts +6 -7
  9. package/dist/domain/enums/payment-method.enum.mjs +2 -2
  10. package/dist/domain/enums/shift-state.enum.d.mts +7 -8
  11. package/dist/domain/errors/pos.errors.d.mts +82 -34
  12. package/dist/domain/errors/pos.errors.mjs +108 -23
  13. package/dist/domain/index.d.mts +11 -3
  14. package/dist/domain/index.mjs +10 -3
  15. package/dist/domain/ports/common.d.mts +2 -3
  16. package/dist/domain/ports/ledger.bridge.d.mts +6 -7
  17. package/dist/domain/ports/notification.bridge.d.mts +5 -6
  18. package/dist/domain/ports/policy.bridge.d.mts +2 -3
  19. package/dist/domain/sale/discount.d.mts +62 -0
  20. package/dist/domain/sale/discount.mjs +58 -0
  21. package/dist/domain/sale/price-override.d.mts +51 -0
  22. package/dist/domain/sale/price-override.mjs +51 -0
  23. package/dist/domain/sale/quick-cash.d.mts +10 -0
  24. package/dist/domain/sale/quick-cash.mjs +27 -0
  25. package/dist/domain/sale/service-line.d.mts +7 -0
  26. package/dist/domain/sale/service-line.mjs +10 -0
  27. package/dist/domain/sale/tender.d.mts +256 -0
  28. package/dist/domain/sale/tender.mjs +242 -0
  29. package/dist/domain/shift/shift-decisions.d.mts +51 -0
  30. package/dist/domain/shift/shift-decisions.mjs +93 -0
  31. package/dist/domain/shift/shift-report.d.mts +127 -0
  32. package/dist/domain/shift/shift-report.mjs +95 -0
  33. package/dist/domain/shift/shift.types.d.mts +107 -0
  34. package/dist/domain/state-machines/shift.fsm.d.mts +6 -7
  35. package/dist/domain/value-objects/cash-movement.vo.d.mts +7 -3
  36. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -5
  37. package/dist/domain/value-objects/shift-policy.vo.d.mts +12 -13
  38. package/dist/domain/value-objects/shift-policy.vo.mjs +13 -7
  39. package/dist/engine/capability.errors.d.mts +23 -0
  40. package/dist/engine/capability.errors.mjs +28 -0
  41. package/dist/engine/define-pos.d.mts +2 -3
  42. package/dist/engine/define-pos.mjs +14 -3
  43. package/dist/engine/engine-types.d.mts +24 -9
  44. package/dist/engine/index.d.mts +2 -1
  45. package/dist/engine/index.mjs +2 -1
  46. package/dist/events/event-catalog.d.mts +18 -14
  47. package/dist/events/event-catalog.mjs +10 -4
  48. package/dist/events/event-constants.d.mts +3 -4
  49. package/dist/events/event-payloads.d.mts +9 -10
  50. package/dist/events/helpers.d.mts +6 -3
  51. package/dist/events/helpers.mjs +12 -2
  52. package/dist/events/in-process-bus.d.mts +3 -4
  53. package/dist/events/index.mjs +1 -1
  54. package/dist/grant/till-grant.d.mts +50 -0
  55. package/dist/grant/till-grant.mjs +47 -0
  56. package/dist/index.d.mts +15 -4
  57. package/dist/index.mjs +13 -4
  58. package/dist/models/create-models.d.mts +10 -6
  59. package/dist/models/create-models.mjs +16 -3
  60. package/dist/models/register.model.d.mts +7 -6
  61. package/dist/models/shift-sale-dedupe.model.d.mts +4 -5
  62. package/dist/models/shift.model.d.mts +4 -111
  63. package/dist/models/shift.model.mjs +27 -3
  64. package/dist/models/till-grant.model.d.mts +19 -0
  65. package/dist/models/till-grant.model.mjs +52 -0
  66. package/dist/repositories/register.repository.d.mts +3 -4
  67. package/dist/repositories/shift.repository.d.mts +90 -60
  68. package/dist/repositories/shift.repository.mjs +323 -150
  69. package/dist/repositories/till-grant.repository.d.mts +22 -0
  70. package/dist/repositories/till-grant.repository.mjs +41 -0
  71. package/dist/schemas/index.mjs +1 -2
  72. package/dist/schemas/shift.d.mts +9 -10
  73. package/dist/testing/fixtures.d.mts +4 -5
  74. package/dist/testing/index.mjs +1 -2
  75. package/package.json +50 -19
@@ -1,18 +1,18 @@
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
1
  import { ACTIVE_SHIFT_STATES, isFinalShiftState } from "../domain/enums/shift-state.enum.mjs";
2
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, RegisterRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError } from "../domain/errors/pos.errors.mjs";
4
3
  import { shiftCloseIdempotencyKey } from "../domain/ports/ledger.bridge.mjs";
5
4
  import { canTransition, nextState } from "../domain/state-machines/shift.fsm.mjs";
6
- import { computeDifference, computeExpected } from "../domain/value-objects/payment-breakdown.vo.mjs";
7
- import { isWithinVarianceThreshold } from "../domain/value-objects/shift-policy.vo.mjs";
5
+ import { computeExpected } from "../domain/value-objects/payment-breakdown.vo.mjs";
6
+ import { decideBlindClose, decideShiftClose, isCashRow, seedBreakdown } from "../domain/shift/shift-decisions.mjs";
8
7
  import { POS_EVENTS } from "../events/event-constants.mjs";
8
+ import { posEventDefinitions } from "../events/event-catalog.mjs";
9
9
  import { createPosEvent } from "../events/helpers.mjs";
10
10
  import { repoOptionsFromCtx } from "./repo-options.mjs";
11
11
  import { isTransitionRace, shiftMachine } from "./shift-transition-support.mjs";
12
12
  import { Repository, methodRegistryPlugin, softDeletePlugin } from "@classytic/mongokit";
13
13
  import { isValidObjectId } from "mongoose";
14
- import { PAYMENT_METHOD_KIND } from "@classytic/primitives/payment-method-kind";
15
14
  import { applyDecision, createChain } from "@classytic/primitives/approval";
15
+ import { dispatchDomainEvent } from "@classytic/primitives/durable-events";
16
16
  //#region src/repositories/shift.repository.ts
17
17
  /**
18
18
  * ShiftRepository — extends mongokit `Repository<IShift>`.
@@ -32,17 +32,11 @@ import { applyDecision, createChain } from "@classytic/primitives/approval";
32
32
  * 5. Persist `journalEntryId` + clear `pendingLedgerPost`
33
33
  * 6. Publish `pos:shift.closed`
34
34
  *
35
- * ## Why this order (the defect it fixes)
35
+ * ## Why claim first
36
36
  *
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.
37
+ * Three triggers close the same shift (lazy-close at register open, the oversight endpoint, the EOD
38
+ * cron) and can race. Claiming before the bridge makes the bridge reachable by exactly one caller, so
39
+ * one shift posts one journal entry.
46
40
  *
47
41
  * ## Crash convergence
48
42
  *
@@ -51,34 +45,22 @@ import { applyDecision, createChain } from "@classytic/primitives/approval";
51
45
  * `forceClose()` RESUMES from that state — same deterministic
52
46
  * `idempotencyKey`, so a durable bridge returns the existing entry instead of
53
47
  * 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.
48
+ * stuck there. `ShiftClosePosting.idempotencyKey` is required by the type, so every bridge receives it.
56
49
  *
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".
50
+ * ## `ledgerPost: 'deferred'`
68
51
  *
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.
52
+ * Steps 4-5 leave the request. The close commits the CAS (with its marker) and a durable
53
+ * `pos:shift.closed` row in one unit of work, and answers `ledgerPending`. The row's subscriber calls
54
+ * {@link ShiftRepository.postPendingLedger}, which posts under the SAME key and records the entry.
80
55
  */
81
- const isCashRow = (r) => r.methodKind === PAYMENT_METHOD_KIND.CASH || r.methodKind === void 0 && r.method === "cash";
56
+ /** The fixed-id spec of a durable event, from its definition; absent for an ephemeral one. */
57
+ function durableSpecOf(name, payload) {
58
+ const def = posEventDefinitions.find((d) => d.name === name);
59
+ return def?.occurrence ? {
60
+ version: def.version,
61
+ occurrence: def.occurrence(payload)
62
+ } : void 0;
63
+ }
82
64
  /**
83
65
  * Mongoose DocumentArrays don't spread (`...row`) cleanly — coerce to plain
84
66
  * objects so spreads and numeric ops see every field. One definition; the
@@ -105,6 +87,8 @@ var ShiftRepository = class extends Repository {
105
87
  notificationBridge;
106
88
  eventTransport;
107
89
  outbox;
90
+ ledgerPost;
91
+ allowNonTransactional;
108
92
  logger;
109
93
  constructor(config) {
110
94
  const { model, plugins = [], softDelete = { ttlDays: 2555 } } = config;
@@ -120,6 +104,8 @@ var ShiftRepository = class extends Repository {
120
104
  this.notificationBridge = config.notificationBridge;
121
105
  this.eventTransport = config.eventTransport;
122
106
  this.outbox = config.outbox;
107
+ this.ledgerPost = config.ledgerPost ?? "inline";
108
+ this.allowNonTransactional = config.allowNonTransactional ?? false;
123
109
  this.logger = config.logger ?? console;
124
110
  }
125
111
  /**
@@ -129,31 +115,19 @@ var ShiftRepository = class extends Repository {
129
115
  */
130
116
  async open(input, ctx) {
131
117
  const policy = input.policy ?? (this.policyBridge ? await this.policyBridge.resolvePolicy(ctx) : this.defaultPolicy);
132
- const seedBreakdown = policy.allowedPaymentMethods.map((method) => ({
133
- method,
134
- methodKind: resolveMethodKind(method, policy.paymentMethodKinds?.[method]),
135
- openingAmount: resolveMethodKind(method, policy.paymentMethodKinds?.[method]) === PAYMENT_METHOD_KIND.CASH ? input.openingCash : 0,
136
- salesAmount: 0,
137
- taxAmount: 0,
138
- refundAmount: 0,
139
- refundTaxAmount: 0,
140
- cashInAmount: 0,
141
- cashOutAmount: 0,
142
- expectedAmount: null,
143
- countedAmount: null,
144
- difference: null
145
- }));
118
+ const seededBreakdown = seedBreakdown(policy, input.openingCash);
146
119
  try {
147
120
  const shift = await this.create({
121
+ ...input.id === void 0 ? {} : { _id: input.id },
148
122
  registerId: input.registerId,
149
123
  businessDate: input.businessDate,
150
124
  state: "open",
151
125
  openingCashierId: input.openingCashierId,
152
126
  openingCashierName: input.openingCashierName,
153
127
  teamMemberIds: [input.openingCashierId],
154
- openedAt: /* @__PURE__ */ new Date(),
128
+ openedAt: input.openedAt ?? /* @__PURE__ */ new Date(),
155
129
  openingCash: input.openingCash,
156
- paymentBreakdown: seedBreakdown,
130
+ paymentBreakdown: seededBreakdown,
157
131
  policySnapshot: policy,
158
132
  notes: input.notes ?? ""
159
133
  }, repoOptionsFromCtx(ctx));
@@ -164,7 +138,7 @@ var ShiftRepository = class extends Repository {
164
138
  }, ctx);
165
139
  return shift;
166
140
  } catch (err) {
167
- if (this.isDuplicateKeyError(err) || err.code === 11e3) throw new ActiveShiftAlreadyOpenError(`${input.registerId}`);
141
+ if (this.isDuplicateKeyError(err)) throw new ActiveShiftAlreadyOpenError(`${input.registerId}`);
168
142
  throw err;
169
143
  }
170
144
  }
@@ -185,14 +159,26 @@ var ShiftRepository = class extends Repository {
185
159
  if (!cashRow) {}
186
160
  const update = { $push: { cashMovements: movement } };
187
161
  if (cashRow) update.$inc = movement.type === "in" ? { "paymentBreakdown.$[cashElem].cashInAmount": movement.amount } : { "paymentBreakdown.$[cashElem].cashOutAmount": movement.amount };
162
+ const guardDrawer = input.refuseOverdraw === true && movement.type === "out" && cashRow !== void 0;
188
163
  const updated = await this.findOneAndUpdate({
189
164
  _id: shift._id,
190
- state: shift.state
165
+ state: shift.state,
166
+ ...movement.movementKey ? { "cashMovements.movementKey": { $ne: movement.movementKey } } : {},
167
+ ...guardDrawer && cashRow ? { $expr: drawerCovers(cashRow.method, movement.amount) } : {}
191
168
  }, update, {
192
169
  ...cashRow ? { arrayFilters: [{ "cashElem.method": "cash" }] } : {},
193
170
  ...repoOptionsFromCtx(ctx)
194
171
  });
195
- if (!updated) throw new ShiftNotFoundError(input.shiftId);
172
+ if (!updated) {
173
+ const booked = movement.movementKey ? await this.bookedMovement(input.shiftId, movement, ctx) : null;
174
+ if (booked) return booked;
175
+ if (guardDrawer) {
176
+ const nowCash = (await this.requireActive(input.shiftId, ctx)).paymentBreakdown.find(isCashRow);
177
+ const drawer = nowCash ? computeExpected(nowCash) : 0;
178
+ if (movement.amount > drawer) throw new CashOutExceedsDrawerError(movement.amount, drawer);
179
+ }
180
+ throw new ShiftNotFoundError(input.shiftId);
181
+ }
196
182
  await this.dispatch(POS_EVENTS.CASH_MOVEMENT_RECORDED, {
197
183
  shiftId: input.shiftId,
198
184
  type: movement.type,
@@ -202,15 +188,22 @@ var ShiftRepository = class extends Repository {
202
188
  return updated;
203
189
  }
204
190
  /**
191
+ * The shift, when `movement`'s key is already booked on it — the same movement, applied once.
192
+ * The same key on a DIFFERENT movement is two commands sharing a key, refused.
193
+ */
194
+ async bookedMovement(shiftId, movement, ctx) {
195
+ const shift = await this.requireActive(shiftId, ctx);
196
+ const booked = shift.cashMovements.find((m) => m.movementKey === movement.movementKey);
197
+ if (!booked) return null;
198
+ if (booked.type !== movement.type || booked.amount !== movement.amount) throw new CashMovementKeyReusedError(String(movement.movementKey));
199
+ return shift;
200
+ }
201
+ /**
205
202
  * Atomically increment shift aggregates from an order-create hook in the
206
203
  * host. Refunds pass `refund: true`.
207
204
  *
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).
205
+ * Exactly-once on `dedupeRef`: the repo claims `(shiftId, dedupeRef)` insert-first in the dedupe
206
+ * ledger and skips the `$inc` on a duplicate claim (`{ applied: false }`).
214
207
  */
215
208
  async incrementSales(input, ctx) {
216
209
  if (input.amount <= 0) return {
@@ -224,28 +217,27 @@ var ShiftRepository = class extends Repository {
224
217
  const tax = Math.max(0, rawTax);
225
218
  if (tax > input.amount) throw new CashMovementInvalidError(`tax (${tax}) cannot exceed amount (${input.amount})`);
226
219
  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
- }
220
+ if (typeof input.dedupeRef !== "string" || !input.dedupeRef) throw new CashMovementInvalidError("incrementSales requires a retry-stable dedupeRef");
221
+ try {
222
+ await this.dedupeModel.create([{
223
+ shiftId: input.shiftId,
224
+ orderRef: input.dedupeRef
225
+ }], txnSession ? { session: txnSession } : {});
226
+ } catch (err) {
227
+ if (err.code === 11e3) return {
228
+ applied: false,
229
+ reason: "duplicate"
230
+ };
231
+ throw err;
241
232
  }
233
+ const countsTransaction = input.countsTransaction !== false;
242
234
  const update = { $inc: refund ? {
243
- refundCount: 1,
235
+ ...countsTransaction ? { refundCount: 1 } : {},
244
236
  refundTotal: input.amount,
245
237
  "paymentBreakdown.$[methodElem].refundAmount": input.amount,
246
238
  ...tax > 0 ? { "paymentBreakdown.$[methodElem].refundTaxAmount": tax } : {}
247
239
  } : {
248
- salesCount: 1,
240
+ ...countsTransaction ? { salesCount: 1 } : {},
249
241
  salesTotal: input.amount,
250
242
  "paymentBreakdown.$[methodElem].salesAmount": input.amount,
251
243
  ...tax > 0 ? { "paymentBreakdown.$[methodElem].taxAmount": tax } : {}
@@ -266,7 +258,7 @@ var ShiftRepository = class extends Repository {
266
258
  arrayFilters: [{ "methodElem.method": input.method }],
267
259
  ...repoOptionsFromCtx(ctx)
268
260
  })) {
269
- if (input.dedupeRef !== void 0 && this.dedupeModel) await this.dedupeModel.deleteOne({
261
+ await this.dedupeModel.deleteOne({
270
262
  shiftId: input.shiftId,
271
263
  orderRef: input.dedupeRef
272
264
  }, txnSession ? { session: txnSession } : {});
@@ -286,9 +278,11 @@ var ShiftRepository = class extends Repository {
286
278
  */
287
279
  async blindClose(input, ctx) {
288
280
  const shift = await this.requireActive(input.shiftId, ctx);
289
- if (shift.state !== "open") throw new IllegalShiftTransitionError(shift.state, "blindClose");
290
- const updatedBreakdown = this.applyCounts(shift.paymentBreakdown, input.countedByMethod, true);
291
- const cashRow = updatedBreakdown.find(isCashRow);
281
+ const decision = decideBlindClose({
282
+ state: shift.state,
283
+ breakdown: toPlainBreakdown(shift.paymentBreakdown),
284
+ countedByMethod: input.countedByMethod
285
+ });
292
286
  const updated = await this.applyTransition(String(shift._id), shiftMachine("blindClose"), {
293
287
  field: "state",
294
288
  from: "open",
@@ -296,10 +290,10 @@ var ShiftRepository = class extends Repository {
296
290
  history: false,
297
291
  set: {
298
292
  blindClosedAt: /* @__PURE__ */ new Date(),
299
- paymentBreakdown: updatedBreakdown,
300
- expectedCash: cashRow?.expectedAmount ?? null,
301
- countedCash: cashRow?.countedAmount ?? null,
302
- cashDifference: cashRow?.difference ?? null,
293
+ paymentBreakdown: decision.breakdown,
294
+ expectedCash: decision.expectedCash,
295
+ countedCash: decision.countedCash,
296
+ cashDifference: decision.cashDifference,
303
297
  closingCashierId: input.closingCashierId,
304
298
  closingCashierName: input.closingCashierName,
305
299
  ...input.notes ? { notes: input.notes } : {}
@@ -324,20 +318,22 @@ var ShiftRepository = class extends Repository {
324
318
  async close(input, ctx) {
325
319
  const shift = await this.requireShift(input.shiftId, ctx);
326
320
  if (isFinalShiftState(shift.state)) return this.convergeTerminal(shift, ctx);
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);
329
- const breakdown = input.countedByMethod ? this.applyCounts(shift.paymentBreakdown, input.countedByMethod, true) : shift.paymentBreakdown;
330
- const cashRow = breakdown.find(isCashRow);
331
- let varianceExceeded = false;
332
- if (cashRow?.expectedAmount != null && cashRow.countedAmount != null) {
333
- varianceExceeded = !isWithinVarianceThreshold(cashRow.difference ?? 0, cashRow.expectedAmount, shift.policySnapshot);
334
- if (varianceExceeded && shift.policySnapshot.managerOverrideRequired && !input.varianceOverride) throw new VarianceExceededError(cashRow.difference ?? 0, cashRow.expectedAmount);
335
- }
321
+ const decision = decideShiftClose({
322
+ shiftId: input.shiftId,
323
+ state: shift.state,
324
+ breakdown: toPlainBreakdown(shift.paymentBreakdown),
325
+ policy: shift.policySnapshot,
326
+ countedByMethod: input.countedByMethod,
327
+ hasVarianceOverride: input.varianceOverride !== void 0
328
+ });
329
+ const { breakdown, varianceExceeded } = decision;
336
330
  const fromState = shift.state;
337
331
  const shiftId = String(shift._id);
338
332
  const priorSet = {
339
333
  closedAt: shift.closedAt ?? null,
340
334
  closedBy: shift.closedBy ?? null,
335
+ closingCashierId: shift.closingCashierId ?? null,
336
+ closingCashierName: shift.closingCashierName ?? null,
341
337
  paymentBreakdown: toPlainBreakdown(shift.paymentBreakdown),
342
338
  expectedCash: shift.expectedCash ?? null,
343
339
  countedCash: shift.countedCash ?? null,
@@ -345,17 +341,66 @@ var ShiftRepository = class extends Repository {
345
341
  approvals: shift.approvals ?? null,
346
342
  pendingLedgerPost: null
347
343
  };
348
- const pending = this.buildPendingLedgerPost(shift, "close");
344
+ const deferred = this.ledgerPost === "deferred";
345
+ const pending = this.buildPendingLedgerPost(shift, "close", deferred);
349
346
  const set = {
350
347
  closedAt: /* @__PURE__ */ new Date(),
351
348
  closedBy: input.closedBy,
349
+ ...shift.closingCashierId ? {} : {
350
+ closingCashierId: input.closer.id,
351
+ closingCashierName: input.closer.name
352
+ },
352
353
  paymentBreakdown: breakdown,
353
- expectedCash: cashRow?.expectedAmount ?? null,
354
- countedCash: cashRow?.countedAmount ?? null,
355
- cashDifference: cashRow?.difference ?? null,
354
+ expectedCash: decision.expectedCash,
355
+ countedCash: decision.countedCash,
356
+ cashDifference: decision.cashDifference,
356
357
  pendingLedgerPost: pending,
357
358
  ...input.varianceOverride ? { approvals: this.buildVarianceApprovalChain(input.varianceOverride.overriddenBy, input.varianceOverride.reason) } : {}
358
359
  };
360
+ if (deferred) {
361
+ const announced = [];
362
+ let committed;
363
+ try {
364
+ committed = await this.inUnit(ctx, async (unit) => {
365
+ announced.length = 0;
366
+ const doc = await this.applyTransition(shiftId, shiftMachine("close"), {
367
+ field: "state",
368
+ from: fromState,
369
+ to: "closed",
370
+ set,
371
+ history: false
372
+ }, repoOptionsFromCtx(unit));
373
+ if (varianceExceeded && decision.expectedCash != null) announced.push(await this.dispatchInUnit(POS_EVENTS.VARIANCE_DETECTED, {
374
+ shiftId: input.shiftId,
375
+ difference: decision.cashDifference ?? 0,
376
+ expected: decision.expectedCash
377
+ }, unit));
378
+ announced.push(await this.dispatchInUnit(POS_EVENTS.SHIFT_CLOSED, {
379
+ shiftId: input.shiftId,
380
+ journalEntryId: null,
381
+ closedBy: input.closedBy
382
+ }, unit));
383
+ return doc;
384
+ });
385
+ } catch (err) {
386
+ const lost = await this.diagnoseLostClaim(err, shiftId, fromState, "close", ctx);
387
+ if (lost) return lost;
388
+ throw err;
389
+ }
390
+ await this.announceCommitted(announced, ctx);
391
+ if (input.varianceOverride && this.notificationBridge?.onVarianceOverride) try {
392
+ await this.notificationBridge.onVarianceOverride(committed, ctx);
393
+ } catch (err) {
394
+ this.logger.error("[pos] notificationBridge.onVarianceOverride threw", err);
395
+ }
396
+ return {
397
+ shift: committed,
398
+ outcome: "closed",
399
+ journalEntryId: null,
400
+ ledgerPosted: false,
401
+ ledgerPending: pending !== null
402
+ };
403
+ }
359
404
  let claimed;
360
405
  try {
361
406
  claimed = await this.applyTransition(shiftId, shiftMachine("close"), {
@@ -379,10 +424,10 @@ var ShiftRepository = class extends Repository {
379
424
  throw bridgeErr;
380
425
  } });
381
426
  const updated = posted.shift;
382
- if (varianceExceeded && cashRow?.expectedAmount != null) await this.dispatch(POS_EVENTS.VARIANCE_DETECTED, {
427
+ if (varianceExceeded && decision.expectedCash != null) await this.dispatch(POS_EVENTS.VARIANCE_DETECTED, {
383
428
  shiftId: input.shiftId,
384
- difference: cashRow.difference ?? 0,
385
- expected: cashRow.expectedAmount
429
+ difference: decision.cashDifference ?? 0,
430
+ expected: decision.expectedCash
386
431
  }, ctx);
387
432
  await this.dispatch(POS_EVENTS.SHIFT_CLOSED, {
388
433
  shiftId: input.shiftId,
@@ -398,7 +443,8 @@ var ShiftRepository = class extends Repository {
398
443
  shift: updated,
399
444
  outcome: "closed",
400
445
  journalEntryId: posted.journalEntryId,
401
- ledgerPosted: posted.ledgerPosted
446
+ ledgerPosted: posted.ledgerPosted,
447
+ ledgerPending: false
402
448
  };
403
449
  }
404
450
  /**
@@ -424,39 +470,36 @@ var ShiftRepository = class extends Repository {
424
470
  organizationId: 1,
425
471
  registerId: 1,
426
472
  state: 1,
427
- businessDate: 1
473
+ businessDate: 1,
474
+ salesCount: 1,
475
+ salesTotal: 1
428
476
  }).lean();
429
477
  }
430
478
  /**
431
479
  * The currently ACTIVE shift (`open | paused | blind_closed`), or `null`.
432
480
  *
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.
481
+ * With `registerId`: that register's shift (at most one — the
482
+ * `uniq_active_shift_per_register` index). Without it: the branch's only active
483
+ * shift, and {@link RegisterRequiredError} when there are several — returning one
484
+ * would ring the sale into another cashier's drawer.
438
485
  *
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).
486
+ * Routed through `findAll`, so the tenant plugin injects and casts the scope.
450
487
  */
451
488
  async getActiveShift(ctx, registerId) {
452
- return (await this.findAll({
489
+ const rows = await this.findAll({
453
490
  state: { $in: [...ACTIVE_SHIFT_STATES] },
454
491
  ...registerId !== void 0 ? { registerId } : {}
455
492
  }, {
456
493
  ...repoOptionsFromCtx(ctx),
457
- limit: 1,
458
494
  sort: { openedAt: -1 }
459
- }))[0] ?? null;
495
+ });
496
+ if (registerId === void 0 && rows.length > 1) throw new RegisterRequiredError(rows.map((r) => ({
497
+ registerId: r.registerId ?? null,
498
+ shiftId: String(r._id),
499
+ state: r.state,
500
+ openedAt: r.openedAt
501
+ })));
502
+ return rows[0] ?? null;
460
503
  }
461
504
  /**
462
505
  * Every active shift for ONE branch — the "/status" dashboard widget
@@ -520,7 +563,54 @@ var ShiftRepository = class extends Repository {
520
563
  });
521
564
  const cashRow = breakdown.find(isCashRow);
522
565
  const fromState = shift.state;
523
- const pending = this.buildPendingLedgerPost(shift, "forceClose");
566
+ const deferred = this.ledgerPost === "deferred";
567
+ const pending = this.buildPendingLedgerPost(shift, "forceClose", deferred);
568
+ if (deferred) {
569
+ const announced = [];
570
+ let committed;
571
+ try {
572
+ committed = await this.inUnit(ctx, async (unit) => {
573
+ announced.length = 0;
574
+ const doc = await this.applyTransition(String(shift._id), shiftMachine("forceClose"), {
575
+ field: "state",
576
+ from: fromState,
577
+ to: "orphaned_closed",
578
+ set: {
579
+ closedAt: /* @__PURE__ */ new Date(),
580
+ closedBy: "system_auto",
581
+ paymentBreakdown: breakdown,
582
+ expectedCash: cashRow?.expectedAmount ?? null,
583
+ countedCash: cashRow?.countedAmount ?? null,
584
+ cashDifference: 0,
585
+ pendingLedgerPost: pending
586
+ },
587
+ history: false
588
+ }, repoOptionsFromCtx(unit));
589
+ announced.push(await this.dispatchInUnit(POS_EVENTS.SHIFT_FORCE_CLOSED, {
590
+ shiftId,
591
+ reason: "orphan_eod"
592
+ }, unit));
593
+ return doc;
594
+ });
595
+ } catch (err) {
596
+ const lost = await this.diagnoseLostClaim(err, shiftId, fromState, "forceClose", ctx);
597
+ if (lost) return lost;
598
+ throw err;
599
+ }
600
+ await this.announceCommitted(announced, ctx);
601
+ if (this.notificationBridge?.onOrphanedClose) try {
602
+ await this.notificationBridge.onOrphanedClose(committed, ctx);
603
+ } catch (err) {
604
+ this.logger.error("[pos] notificationBridge.onOrphanedClose threw", err);
605
+ }
606
+ return {
607
+ shift: committed,
608
+ outcome: "closed",
609
+ journalEntryId: null,
610
+ ledgerPosted: false,
611
+ ledgerPending: pending !== null
612
+ };
613
+ }
524
614
  let claimed;
525
615
  try {
526
616
  claimed = await this.applyTransition(String(shift._id), shiftMachine("forceClose"), {
@@ -564,6 +654,7 @@ var ShiftRepository = class extends Repository {
564
654
  outcome: "closed",
565
655
  journalEntryId: posted.journalEntryId,
566
656
  ledgerPosted: posted.ledgerPosted,
657
+ ledgerPending: ledgerError !== void 0,
567
658
  ...ledgerError !== void 0 ? { ledgerError } : {}
568
659
  };
569
660
  }
@@ -601,7 +692,7 @@ var ShiftRepository = class extends Repository {
601
692
  * which is the whole point: a resume after a crash must collide with the
602
693
  * entry the crashed attempt may have already written.
603
694
  */
604
- buildPendingLedgerPost(shift, trigger) {
695
+ buildPendingLedgerPost(shift, trigger, durable = false) {
605
696
  if (!this.ledgerBridge) return null;
606
697
  if (shift.journalEntryId) return null;
607
698
  return {
@@ -610,7 +701,8 @@ var ShiftRepository = class extends Repository {
610
701
  attempts: 1,
611
702
  stampedAt: /* @__PURE__ */ new Date(),
612
703
  lastAttemptAt: null,
613
- announced: false
704
+ announced: durable,
705
+ ...durable ? { durable: true } : {}
614
706
  };
615
707
  }
616
708
  /**
@@ -674,8 +766,7 @@ var ShiftRepository = class extends Repository {
674
766
  * on-disk state says another caller finalized the shift; returns null when
675
767
  * the failure is a genuine illegal transition the caller should throw.
676
768
  *
677
- * The LOSER NEVER POSTS. That is the entire fix: previously the loser had
678
- * already committed its journal entry by the time it got here.
769
+ * The LOSER NEVER POSTS: it reaches here before any journal entry.
679
770
  */
680
771
  async diagnoseLostClaim(err, shiftId, fromState, verb, ctx) {
681
772
  if (!(err instanceof IllegalShiftTransitionError) && !isTransitionRace(err)) return null;
@@ -690,15 +781,45 @@ var ShiftRepository = class extends Repository {
690
781
  */
691
782
  async convergeTerminal(shift, ctx) {
692
783
  const pending = shift.pendingLedgerPost ?? null;
693
- if (!pending) return {
784
+ if (!pending || pending.durable === true) return {
694
785
  shift,
695
786
  outcome: "already-closed",
696
787
  journalEntryId: shift.journalEntryId ?? null,
697
- ledgerPosted: false
788
+ ledgerPosted: false,
789
+ ledgerPending: pending !== null
698
790
  };
699
791
  return this.resumeLedgerPost(shift, pending, ctx);
700
792
  }
701
793
  /**
794
+ * Post the journal entry a deferred close owes — the subscriber verb of `pos:shift.closed` /
795
+ * `pos:shift.force_closed`. Idempotent: the entry is posted under the marker's own key, a recorded entry
796
+ * retires the marker, and a delivery that finds no marker does nothing. Throws when the post fails (the
797
+ * delivery then retries under the outbox's failure policy) — it never reports a failure as a success.
798
+ *
799
+ * Cross-tenant by design (the event carries only the shift id): the scope is the shift's own branch.
800
+ */
801
+ async postPendingLedger(shiftId) {
802
+ const shift = await this.getByIdUnscoped(shiftId);
803
+ if (!shift) throw new ShiftNotFoundError(shiftId);
804
+ if (!isFinalShiftState(shift.state)) throw new Error(`[pos] postPendingLedger(${shiftId}): the shift is '${shift.state}', not closed — nothing is owed yet`);
805
+ const pending = shift.pendingLedgerPost ?? null;
806
+ if (!pending) return {
807
+ shift,
808
+ outcome: "already-closed",
809
+ journalEntryId: shift.journalEntryId ?? null,
810
+ ledgerPosted: false,
811
+ ledgerPending: false
812
+ };
813
+ if (!this.ledgerBridge) throw new Error(`[pos] postPendingLedger(${shiftId}): the shift owes a ledger post but no ledger bridge is wired in this process`);
814
+ const ctx = {
815
+ organizationId: String(shift.organizationId),
816
+ ...shift.closingCashierId ? { actorId: String(shift.closingCashierId) } : {}
817
+ };
818
+ const result = await this.resumeLedgerPost(shift, pending, ctx);
819
+ if (result.ledgerError !== void 0) throw result.ledgerError;
820
+ return result;
821
+ }
822
+ /**
702
823
  * Converge a close that won the CAS but died before recording its entry.
703
824
  *
704
825
  * Re-invokes the bridge with the SAME deterministic key, so a durable
@@ -712,7 +833,8 @@ var ShiftRepository = class extends Repository {
712
833
  shift,
713
834
  outcome: "already-closed",
714
835
  journalEntryId: shift.journalEntryId ?? null,
715
- ledgerPosted: false
836
+ ledgerPosted: false,
837
+ ledgerPending: true
716
838
  };
717
839
  const claimed = await this.findOneAndUpdate({
718
840
  _id: shiftId,
@@ -727,7 +849,8 @@ var ShiftRepository = class extends Repository {
727
849
  shift: doc,
728
850
  outcome: "already-closed",
729
851
  journalEntryId: doc.journalEntryId ?? null,
730
- ledgerPosted: false
852
+ ledgerPosted: false,
853
+ ledgerPending: (doc.pendingLedgerPost ?? null) !== null
731
854
  };
732
855
  }
733
856
  let entryId;
@@ -746,6 +869,7 @@ var ShiftRepository = class extends Repository {
746
869
  outcome: "already-closed",
747
870
  journalEntryId: claimed.journalEntryId ?? null,
748
871
  ledgerPosted: false,
872
+ ledgerPending: true,
749
873
  ledgerError: err
750
874
  };
751
875
  }
@@ -765,7 +889,8 @@ var ShiftRepository = class extends Repository {
765
889
  shift: doc,
766
890
  outcome: "resumed",
767
891
  journalEntryId: normalizeEntryId(entryId),
768
- ledgerPosted: true
892
+ ledgerPosted: true,
893
+ ledgerPending: false
769
894
  };
770
895
  }
771
896
  /**
@@ -835,19 +960,6 @@ var ShiftRepository = class extends Repository {
835
960
  if (isFinalShiftState(shift.state)) throw new ShiftFinalizedError(shiftId);
836
961
  return shift;
837
962
  }
838
- applyCounts(breakdown, counted, computeAll) {
839
- return toPlainBreakdown(breakdown).map((row) => {
840
- const expected = computeAll ? computeExpected(row) : row.expectedAmount;
841
- const newCounted = counted[row.method] ?? row.countedAmount;
842
- const diff = expected !== null && newCounted !== null && newCounted !== void 0 ? computeDifference(expected, newCounted) : null;
843
- return {
844
- ...row,
845
- expectedAmount: expected,
846
- countedAmount: newCounted ?? null,
847
- difference: diff
848
- };
849
- });
850
- }
851
963
  /**
852
964
  * Session-bound dispatch (PACKAGE_RULES §P8). Build the envelope ONCE so an
853
965
  * outbox-relay re-publish and the live transport publish share `meta.id`
@@ -857,10 +969,57 @@ var ShiftRepository = class extends Repository {
857
969
  * than a redelivered one). Transport publish runs second; its failures are
858
970
  * swallowed because the durable row drives re-delivery.
859
971
  */
972
+ /**
973
+ * One unit of work for a deferred close: the caller's session when it owns one (it commits and flushes),
974
+ * else a transaction this repository opens. Without transactions the engine's waiver
975
+ * (`allowNonTransactional`) runs the work with no session — the row is then saved after the CAS, not with it.
976
+ */
977
+ async inUnit(ctx, work) {
978
+ if (ctx.session !== void 0) return work(ctx);
979
+ return this.withTransaction(async (_tx, uow) => work(uow?.session ? {
980
+ ...ctx,
981
+ session: uow.session
982
+ } : ctx), this.allowNonTransactional ? {
983
+ allowFallback: true,
984
+ onFallback: (err) => this.logger.error("[pos] no transaction: the deferred close ran WITHOUT atomicity (allowNonTransactional)", err)
985
+ } : {});
986
+ }
987
+ /**
988
+ * Write one event inside `unit`. Under a session the row commits with the unit through `dispatchDomainEvent`
989
+ * (a durable type REFUSES to write anywhere else); returns the event for {@link announceCommitted}. With no
990
+ * session (`allowNonTransactional`) it saves then publishes, and `null` says it already published.
991
+ */
992
+ async dispatchInUnit(name, payload, unit) {
993
+ if (unit.session === void 0) {
994
+ await this.dispatch(name, payload, unit);
995
+ return null;
996
+ }
997
+ const spec = durableSpecOf(name, payload);
998
+ const event = createPosEvent(name, payload, spec);
999
+ await dispatchDomainEvent({
1000
+ outbox: this.outbox,
1001
+ transport: this.eventTransport,
1002
+ label: "pos",
1003
+ logger: this.logger
1004
+ }, { session: unit.session }, event, spec ? "durable" : "ephemeral");
1005
+ return event;
1006
+ }
1007
+ /** After the unit committed: wake the transport (the relay nudge). A caller-owned session flushes for itself. */
1008
+ async announceCommitted(events, ctx) {
1009
+ if (ctx.session !== void 0 || !this.eventTransport) return;
1010
+ for (const event of events) {
1011
+ if (!event) continue;
1012
+ try {
1013
+ await this.eventTransport.publish(event);
1014
+ } catch (err) {
1015
+ this.logger.error(`[pos] event transport failed for ${event.type}`, err);
1016
+ }
1017
+ }
1018
+ }
860
1019
  async dispatch(name, payload, ctx) {
861
1020
  if (!this.outbox && !this.eventTransport) return;
862
1021
  if (ctx.session && !this.outbox) throw new UnmanagedSessionError();
863
- const event = createPosEvent(name, payload);
1022
+ const event = createPosEvent(name, payload, durableSpecOf(name, payload));
864
1023
  if (this.outbox) try {
865
1024
  await this.outbox.save(event, ctx.session !== void 0 ? { session: ctx.session } : {});
866
1025
  } catch (err) {
@@ -874,5 +1033,19 @@ var ShiftRepository = class extends Repository {
874
1033
  }
875
1034
  }
876
1035
  };
1036
+ /** `$expr`: the stored drawer on the `method` row (opening + sales − refunds + in − out) covers `amount`. */
1037
+ function drawerCovers(method, amount) {
1038
+ return { $let: {
1039
+ vars: { c: { $arrayElemAt: [{ $filter: {
1040
+ input: "$paymentBreakdown",
1041
+ cond: { $eq: ["$$this.method", method] }
1042
+ } }, 0] } },
1043
+ in: { $gte: [{ $subtract: [{ $add: [
1044
+ "$$c.openingAmount",
1045
+ "$$c.salesAmount",
1046
+ "$$c.cashInAmount"
1047
+ ] }, { $add: ["$$c.refundAmount", "$$c.cashOutAmount"] }] }, amount] }
1048
+ } };
1049
+ }
877
1050
  //#endregion
878
1051
  export { ShiftRepository };