@classytic/pos 0.6.0 → 0.7.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 (71) hide show
  1. package/CHANGELOG.md +103 -0
  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 +228 -0
  5. package/dist/commands/pos-commands.mjs +355 -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/shift-state.enum.d.mts +7 -8
  10. package/dist/domain/errors/pos.errors.d.mts +82 -13
  11. package/dist/domain/errors/pos.errors.mjs +111 -1
  12. package/dist/domain/index.d.mts +11 -3
  13. package/dist/domain/index.mjs +10 -3
  14. package/dist/domain/ports/common.d.mts +2 -3
  15. package/dist/domain/ports/ledger.bridge.d.mts +6 -7
  16. package/dist/domain/ports/notification.bridge.d.mts +5 -6
  17. package/dist/domain/ports/policy.bridge.d.mts +2 -3
  18. package/dist/domain/sale/discount.d.mts +62 -0
  19. package/dist/domain/sale/discount.mjs +58 -0
  20. package/dist/domain/sale/price-override.d.mts +51 -0
  21. package/dist/domain/sale/price-override.mjs +51 -0
  22. package/dist/domain/sale/quick-cash.d.mts +10 -0
  23. package/dist/domain/sale/quick-cash.mjs +27 -0
  24. package/dist/domain/sale/service-line.d.mts +7 -0
  25. package/dist/domain/sale/service-line.mjs +10 -0
  26. package/dist/domain/sale/tender.d.mts +256 -0
  27. package/dist/domain/sale/tender.mjs +242 -0
  28. package/dist/domain/shift/shift-decisions.d.mts +52 -0
  29. package/dist/domain/shift/shift-decisions.mjs +93 -0
  30. package/dist/domain/shift/shift-report.d.mts +127 -0
  31. package/dist/domain/shift/shift-report.mjs +95 -0
  32. package/dist/domain/shift/shift.types.d.mts +109 -0
  33. package/dist/domain/state-machines/shift.fsm.d.mts +6 -7
  34. package/dist/domain/value-objects/cash-movement.vo.d.mts +7 -3
  35. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -5
  36. package/dist/domain/value-objects/shift-policy.vo.d.mts +11 -7
  37. package/dist/domain/value-objects/shift-policy.vo.mjs +12 -1
  38. package/dist/engine/define-pos.d.mts +2 -3
  39. package/dist/engine/define-pos.mjs +13 -2
  40. package/dist/engine/engine-types.d.mts +24 -9
  41. package/dist/engine/index.mjs +1 -2
  42. package/dist/events/event-catalog.d.mts +18 -14
  43. package/dist/events/event-catalog.mjs +10 -4
  44. package/dist/events/event-constants.d.mts +3 -4
  45. package/dist/events/event-payloads.d.mts +9 -10
  46. package/dist/events/helpers.d.mts +6 -3
  47. package/dist/events/helpers.mjs +12 -2
  48. package/dist/events/in-process-bus.d.mts +3 -4
  49. package/dist/events/index.mjs +1 -1
  50. package/dist/grant/till-grant.d.mts +50 -0
  51. package/dist/grant/till-grant.mjs +47 -0
  52. package/dist/index.d.mts +14 -4
  53. package/dist/index.mjs +12 -4
  54. package/dist/models/create-models.d.mts +10 -6
  55. package/dist/models/create-models.mjs +16 -3
  56. package/dist/models/register.model.d.mts +7 -6
  57. package/dist/models/shift-sale-dedupe.model.d.mts +4 -5
  58. package/dist/models/shift.model.d.mts +4 -111
  59. package/dist/models/shift.model.mjs +26 -2
  60. package/dist/models/till-grant.model.d.mts +19 -0
  61. package/dist/models/till-grant.model.mjs +52 -0
  62. package/dist/repositories/register.repository.d.mts +3 -4
  63. package/dist/repositories/shift.repository.d.mts +71 -30
  64. package/dist/repositories/shift.repository.mjs +295 -108
  65. package/dist/repositories/till-grant.repository.d.mts +22 -0
  66. package/dist/repositories/till-grant.repository.mjs +41 -0
  67. package/dist/schemas/index.mjs +1 -2
  68. package/dist/schemas/shift.d.mts +9 -10
  69. package/dist/testing/fixtures.d.mts +4 -5
  70. package/dist/testing/index.mjs +1 -2
  71. 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";
1
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, RegisterRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError } from "../domain/errors/pos.errors.mjs";
3
2
  import { ACTIVE_SHIFT_STATES, isFinalShiftState } from "../domain/enums/shift-state.enum.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>`.
@@ -56,29 +56,21 @@ import { applyDecision, createChain } from "@classytic/primitives/approval";
56
56
  *
57
57
  * Idempotency is no longer prose: `ShiftClosePosting.idempotencyKey` is a
58
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
59
  *
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.
60
+ * ## `ledgerPost: 'deferred'`
76
61
  *
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.
62
+ * Steps 4-5 leave the request. The close commits the CAS (with its marker) and a durable
63
+ * `pos:shift.closed` row in one unit of work, and answers `ledgerPending`. The row's subscriber calls
64
+ * {@link ShiftRepository.postPendingLedger}, which posts under the SAME key and records the entry.
80
65
  */
81
- const isCashRow = (r) => r.methodKind === PAYMENT_METHOD_KIND.CASH || r.methodKind === void 0 && r.method === "cash";
66
+ /** The fixed-id spec of a durable event, from its definition; absent for an ephemeral one. */
67
+ function durableSpecOf(name, payload) {
68
+ const def = posEventDefinitions.find((d) => d.name === name);
69
+ return def?.occurrence ? {
70
+ version: def.version,
71
+ occurrence: def.occurrence(payload)
72
+ } : void 0;
73
+ }
82
74
  /**
83
75
  * Mongoose DocumentArrays don't spread (`...row`) cleanly — coerce to plain
84
76
  * objects so spreads and numeric ops see every field. One definition; the
@@ -105,6 +97,8 @@ var ShiftRepository = class extends Repository {
105
97
  notificationBridge;
106
98
  eventTransport;
107
99
  outbox;
100
+ ledgerPost;
101
+ allowNonTransactional;
108
102
  logger;
109
103
  constructor(config) {
110
104
  const { model, plugins = [], softDelete = { ttlDays: 2555 } } = config;
@@ -120,6 +114,8 @@ var ShiftRepository = class extends Repository {
120
114
  this.notificationBridge = config.notificationBridge;
121
115
  this.eventTransport = config.eventTransport;
122
116
  this.outbox = config.outbox;
117
+ this.ledgerPost = config.ledgerPost ?? "inline";
118
+ this.allowNonTransactional = config.allowNonTransactional ?? false;
123
119
  this.logger = config.logger ?? console;
124
120
  }
125
121
  /**
@@ -129,31 +125,19 @@ var ShiftRepository = class extends Repository {
129
125
  */
130
126
  async open(input, ctx) {
131
127
  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
- }));
128
+ const seededBreakdown = seedBreakdown(policy, input.openingCash);
146
129
  try {
147
130
  const shift = await this.create({
131
+ ...input.id === void 0 ? {} : { _id: input.id },
148
132
  registerId: input.registerId,
149
133
  businessDate: input.businessDate,
150
134
  state: "open",
151
135
  openingCashierId: input.openingCashierId,
152
136
  openingCashierName: input.openingCashierName,
153
137
  teamMemberIds: [input.openingCashierId],
154
- openedAt: /* @__PURE__ */ new Date(),
138
+ openedAt: input.openedAt ?? /* @__PURE__ */ new Date(),
155
139
  openingCash: input.openingCash,
156
- paymentBreakdown: seedBreakdown,
140
+ paymentBreakdown: seededBreakdown,
157
141
  policySnapshot: policy,
158
142
  notes: input.notes ?? ""
159
143
  }, repoOptionsFromCtx(ctx));
@@ -185,14 +169,26 @@ var ShiftRepository = class extends Repository {
185
169
  if (!cashRow) {}
186
170
  const update = { $push: { cashMovements: movement } };
187
171
  if (cashRow) update.$inc = movement.type === "in" ? { "paymentBreakdown.$[cashElem].cashInAmount": movement.amount } : { "paymentBreakdown.$[cashElem].cashOutAmount": movement.amount };
172
+ const guardDrawer = input.refuseOverdraw === true && movement.type === "out" && cashRow !== void 0;
188
173
  const updated = await this.findOneAndUpdate({
189
174
  _id: shift._id,
190
- state: shift.state
175
+ state: shift.state,
176
+ ...movement.movementKey ? { "cashMovements.movementKey": { $ne: movement.movementKey } } : {},
177
+ ...guardDrawer && cashRow ? { $expr: drawerCovers(cashRow.method, movement.amount) } : {}
191
178
  }, update, {
192
179
  ...cashRow ? { arrayFilters: [{ "cashElem.method": "cash" }] } : {},
193
180
  ...repoOptionsFromCtx(ctx)
194
181
  });
195
- if (!updated) throw new ShiftNotFoundError(input.shiftId);
182
+ if (!updated) {
183
+ const booked = movement.movementKey ? await this.bookedMovement(input.shiftId, movement, ctx) : null;
184
+ if (booked) return booked;
185
+ if (guardDrawer) {
186
+ const nowCash = (await this.requireActive(input.shiftId, ctx)).paymentBreakdown.find(isCashRow);
187
+ const drawer = nowCash ? computeExpected(nowCash) : 0;
188
+ if (movement.amount > drawer) throw new CashOutExceedsDrawerError(movement.amount, drawer);
189
+ }
190
+ throw new ShiftNotFoundError(input.shiftId);
191
+ }
196
192
  await this.dispatch(POS_EVENTS.CASH_MOVEMENT_RECORDED, {
197
193
  shiftId: input.shiftId,
198
194
  type: movement.type,
@@ -202,6 +198,17 @@ var ShiftRepository = class extends Repository {
202
198
  return updated;
203
199
  }
204
200
  /**
201
+ * The shift, when `movement`'s key is already booked on it — the same movement, applied once.
202
+ * The same key on a DIFFERENT movement is two commands sharing a key, refused.
203
+ */
204
+ async bookedMovement(shiftId, movement, ctx) {
205
+ const shift = await this.requireActive(shiftId, ctx);
206
+ const booked = shift.cashMovements.find((m) => m.movementKey === movement.movementKey);
207
+ if (!booked) return null;
208
+ if (booked.type !== movement.type || booked.amount !== movement.amount) throw new CashMovementKeyReusedError(String(movement.movementKey));
209
+ return shift;
210
+ }
211
+ /**
205
212
  * Atomically increment shift aggregates from an order-create hook in the
206
213
  * host. Refunds pass `refund: true`.
207
214
  *
@@ -286,9 +293,11 @@ var ShiftRepository = class extends Repository {
286
293
  */
287
294
  async blindClose(input, ctx) {
288
295
  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);
296
+ const decision = decideBlindClose({
297
+ state: shift.state,
298
+ breakdown: toPlainBreakdown(shift.paymentBreakdown),
299
+ countedByMethod: input.countedByMethod
300
+ });
292
301
  const updated = await this.applyTransition(String(shift._id), shiftMachine("blindClose"), {
293
302
  field: "state",
294
303
  from: "open",
@@ -296,10 +305,10 @@ var ShiftRepository = class extends Repository {
296
305
  history: false,
297
306
  set: {
298
307
  blindClosedAt: /* @__PURE__ */ new Date(),
299
- paymentBreakdown: updatedBreakdown,
300
- expectedCash: cashRow?.expectedAmount ?? null,
301
- countedCash: cashRow?.countedAmount ?? null,
302
- cashDifference: cashRow?.difference ?? null,
308
+ paymentBreakdown: decision.breakdown,
309
+ expectedCash: decision.expectedCash,
310
+ countedCash: decision.countedCash,
311
+ cashDifference: decision.cashDifference,
303
312
  closingCashierId: input.closingCashierId,
304
313
  closingCashierName: input.closingCashierName,
305
314
  ...input.notes ? { notes: input.notes } : {}
@@ -324,20 +333,22 @@ var ShiftRepository = class extends Repository {
324
333
  async close(input, ctx) {
325
334
  const shift = await this.requireShift(input.shiftId, ctx);
326
335
  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
- }
336
+ const decision = decideShiftClose({
337
+ shiftId: input.shiftId,
338
+ state: shift.state,
339
+ breakdown: toPlainBreakdown(shift.paymentBreakdown),
340
+ policy: shift.policySnapshot,
341
+ countedByMethod: input.countedByMethod,
342
+ hasVarianceOverride: input.varianceOverride !== void 0
343
+ });
344
+ const { breakdown, varianceExceeded } = decision;
336
345
  const fromState = shift.state;
337
346
  const shiftId = String(shift._id);
338
347
  const priorSet = {
339
348
  closedAt: shift.closedAt ?? null,
340
349
  closedBy: shift.closedBy ?? null,
350
+ closingCashierId: shift.closingCashierId ?? null,
351
+ closingCashierName: shift.closingCashierName ?? null,
341
352
  paymentBreakdown: toPlainBreakdown(shift.paymentBreakdown),
342
353
  expectedCash: shift.expectedCash ?? null,
343
354
  countedCash: shift.countedCash ?? null,
@@ -345,17 +356,66 @@ var ShiftRepository = class extends Repository {
345
356
  approvals: shift.approvals ?? null,
346
357
  pendingLedgerPost: null
347
358
  };
348
- const pending = this.buildPendingLedgerPost(shift, "close");
359
+ const deferred = this.ledgerPost === "deferred";
360
+ const pending = this.buildPendingLedgerPost(shift, "close", deferred);
349
361
  const set = {
350
362
  closedAt: /* @__PURE__ */ new Date(),
351
363
  closedBy: input.closedBy,
364
+ ...shift.closingCashierId ? {} : {
365
+ closingCashierId: input.closer.id,
366
+ closingCashierName: input.closer.name
367
+ },
352
368
  paymentBreakdown: breakdown,
353
- expectedCash: cashRow?.expectedAmount ?? null,
354
- countedCash: cashRow?.countedAmount ?? null,
355
- cashDifference: cashRow?.difference ?? null,
369
+ expectedCash: decision.expectedCash,
370
+ countedCash: decision.countedCash,
371
+ cashDifference: decision.cashDifference,
356
372
  pendingLedgerPost: pending,
357
373
  ...input.varianceOverride ? { approvals: this.buildVarianceApprovalChain(input.varianceOverride.overriddenBy, input.varianceOverride.reason) } : {}
358
374
  };
375
+ if (deferred) {
376
+ const announced = [];
377
+ let committed;
378
+ try {
379
+ committed = await this.inUnit(ctx, async (unit) => {
380
+ announced.length = 0;
381
+ const doc = await this.applyTransition(shiftId, shiftMachine("close"), {
382
+ field: "state",
383
+ from: fromState,
384
+ to: "closed",
385
+ set,
386
+ history: false
387
+ }, repoOptionsFromCtx(unit));
388
+ if (varianceExceeded && decision.expectedCash != null) announced.push(await this.dispatchInUnit(POS_EVENTS.VARIANCE_DETECTED, {
389
+ shiftId: input.shiftId,
390
+ difference: decision.cashDifference ?? 0,
391
+ expected: decision.expectedCash
392
+ }, unit));
393
+ announced.push(await this.dispatchInUnit(POS_EVENTS.SHIFT_CLOSED, {
394
+ shiftId: input.shiftId,
395
+ journalEntryId: null,
396
+ closedBy: input.closedBy
397
+ }, unit));
398
+ return doc;
399
+ });
400
+ } catch (err) {
401
+ const lost = await this.diagnoseLostClaim(err, shiftId, fromState, "close", ctx);
402
+ if (lost) return lost;
403
+ throw err;
404
+ }
405
+ await this.announceCommitted(announced, ctx);
406
+ if (input.varianceOverride && this.notificationBridge?.onVarianceOverride) try {
407
+ await this.notificationBridge.onVarianceOverride(committed, ctx);
408
+ } catch (err) {
409
+ this.logger.error("[pos] notificationBridge.onVarianceOverride threw", err);
410
+ }
411
+ return {
412
+ shift: committed,
413
+ outcome: "closed",
414
+ journalEntryId: null,
415
+ ledgerPosted: false,
416
+ ledgerPending: pending !== null
417
+ };
418
+ }
359
419
  let claimed;
360
420
  try {
361
421
  claimed = await this.applyTransition(shiftId, shiftMachine("close"), {
@@ -379,10 +439,10 @@ var ShiftRepository = class extends Repository {
379
439
  throw bridgeErr;
380
440
  } });
381
441
  const updated = posted.shift;
382
- if (varianceExceeded && cashRow?.expectedAmount != null) await this.dispatch(POS_EVENTS.VARIANCE_DETECTED, {
442
+ if (varianceExceeded && decision.expectedCash != null) await this.dispatch(POS_EVENTS.VARIANCE_DETECTED, {
383
443
  shiftId: input.shiftId,
384
- difference: cashRow.difference ?? 0,
385
- expected: cashRow.expectedAmount
444
+ difference: decision.cashDifference ?? 0,
445
+ expected: decision.expectedCash
386
446
  }, ctx);
387
447
  await this.dispatch(POS_EVENTS.SHIFT_CLOSED, {
388
448
  shiftId: input.shiftId,
@@ -398,7 +458,8 @@ var ShiftRepository = class extends Repository {
398
458
  shift: updated,
399
459
  outcome: "closed",
400
460
  journalEntryId: posted.journalEntryId,
401
- ledgerPosted: posted.ledgerPosted
461
+ ledgerPosted: posted.ledgerPosted,
462
+ ledgerPending: false
402
463
  };
403
464
  }
404
465
  /**
@@ -430,33 +491,28 @@ var ShiftRepository = class extends Repository {
430
491
  /**
431
492
  * The currently ACTIVE shift (`open | paused | blind_closed`), or `null`.
432
493
  *
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.
494
+ * With `registerId`: that register's shift (at most one — the
495
+ * `uniq_active_shift_per_register` index). Without it: the branch's only active
496
+ * shift, and {@link RegisterRequiredError} when there are several — returning one
497
+ * would ring the sale into another cashier's drawer.
438
498
  *
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).
499
+ * Routed through `findAll`, so the tenant plugin injects and casts the scope.
450
500
  */
451
501
  async getActiveShift(ctx, registerId) {
452
- return (await this.findAll({
502
+ const rows = await this.findAll({
453
503
  state: { $in: [...ACTIVE_SHIFT_STATES] },
454
504
  ...registerId !== void 0 ? { registerId } : {}
455
505
  }, {
456
506
  ...repoOptionsFromCtx(ctx),
457
- limit: 1,
458
507
  sort: { openedAt: -1 }
459
- }))[0] ?? null;
508
+ });
509
+ if (registerId === void 0 && rows.length > 1) throw new RegisterRequiredError(rows.map((r) => ({
510
+ registerId: r.registerId ?? null,
511
+ shiftId: String(r._id),
512
+ state: r.state,
513
+ openedAt: r.openedAt
514
+ })));
515
+ return rows[0] ?? null;
460
516
  }
461
517
  /**
462
518
  * Every active shift for ONE branch — the "/status" dashboard widget
@@ -520,7 +576,54 @@ var ShiftRepository = class extends Repository {
520
576
  });
521
577
  const cashRow = breakdown.find(isCashRow);
522
578
  const fromState = shift.state;
523
- const pending = this.buildPendingLedgerPost(shift, "forceClose");
579
+ const deferred = this.ledgerPost === "deferred";
580
+ const pending = this.buildPendingLedgerPost(shift, "forceClose", deferred);
581
+ if (deferred) {
582
+ const announced = [];
583
+ let committed;
584
+ try {
585
+ committed = await this.inUnit(ctx, async (unit) => {
586
+ announced.length = 0;
587
+ const doc = await this.applyTransition(String(shift._id), shiftMachine("forceClose"), {
588
+ field: "state",
589
+ from: fromState,
590
+ to: "orphaned_closed",
591
+ set: {
592
+ closedAt: /* @__PURE__ */ new Date(),
593
+ closedBy: "system_auto",
594
+ paymentBreakdown: breakdown,
595
+ expectedCash: cashRow?.expectedAmount ?? null,
596
+ countedCash: cashRow?.countedAmount ?? null,
597
+ cashDifference: 0,
598
+ pendingLedgerPost: pending
599
+ },
600
+ history: false
601
+ }, repoOptionsFromCtx(unit));
602
+ announced.push(await this.dispatchInUnit(POS_EVENTS.SHIFT_FORCE_CLOSED, {
603
+ shiftId,
604
+ reason: "orphan_eod"
605
+ }, unit));
606
+ return doc;
607
+ });
608
+ } catch (err) {
609
+ const lost = await this.diagnoseLostClaim(err, shiftId, fromState, "forceClose", ctx);
610
+ if (lost) return lost;
611
+ throw err;
612
+ }
613
+ await this.announceCommitted(announced, ctx);
614
+ if (this.notificationBridge?.onOrphanedClose) try {
615
+ await this.notificationBridge.onOrphanedClose(committed, ctx);
616
+ } catch (err) {
617
+ this.logger.error("[pos] notificationBridge.onOrphanedClose threw", err);
618
+ }
619
+ return {
620
+ shift: committed,
621
+ outcome: "closed",
622
+ journalEntryId: null,
623
+ ledgerPosted: false,
624
+ ledgerPending: pending !== null
625
+ };
626
+ }
524
627
  let claimed;
525
628
  try {
526
629
  claimed = await this.applyTransition(String(shift._id), shiftMachine("forceClose"), {
@@ -564,6 +667,7 @@ var ShiftRepository = class extends Repository {
564
667
  outcome: "closed",
565
668
  journalEntryId: posted.journalEntryId,
566
669
  ledgerPosted: posted.ledgerPosted,
670
+ ledgerPending: ledgerError !== void 0,
567
671
  ...ledgerError !== void 0 ? { ledgerError } : {}
568
672
  };
569
673
  }
@@ -601,7 +705,7 @@ var ShiftRepository = class extends Repository {
601
705
  * which is the whole point: a resume after a crash must collide with the
602
706
  * entry the crashed attempt may have already written.
603
707
  */
604
- buildPendingLedgerPost(shift, trigger) {
708
+ buildPendingLedgerPost(shift, trigger, durable = false) {
605
709
  if (!this.ledgerBridge) return null;
606
710
  if (shift.journalEntryId) return null;
607
711
  return {
@@ -610,7 +714,8 @@ var ShiftRepository = class extends Repository {
610
714
  attempts: 1,
611
715
  stampedAt: /* @__PURE__ */ new Date(),
612
716
  lastAttemptAt: null,
613
- announced: false
717
+ announced: durable,
718
+ ...durable ? { durable: true } : {}
614
719
  };
615
720
  }
616
721
  /**
@@ -690,15 +795,45 @@ var ShiftRepository = class extends Repository {
690
795
  */
691
796
  async convergeTerminal(shift, ctx) {
692
797
  const pending = shift.pendingLedgerPost ?? null;
693
- if (!pending) return {
798
+ if (!pending || pending.durable === true) return {
694
799
  shift,
695
800
  outcome: "already-closed",
696
801
  journalEntryId: shift.journalEntryId ?? null,
697
- ledgerPosted: false
802
+ ledgerPosted: false,
803
+ ledgerPending: pending !== null
698
804
  };
699
805
  return this.resumeLedgerPost(shift, pending, ctx);
700
806
  }
701
807
  /**
808
+ * Post the journal entry a deferred close owes — the subscriber verb of `pos:shift.closed` /
809
+ * `pos:shift.force_closed`. Idempotent: the entry is posted under the marker's own key, a recorded entry
810
+ * retires the marker, and a delivery that finds no marker does nothing. Throws when the post fails (the
811
+ * delivery then retries under the outbox's failure policy) — it never reports a failure as a success.
812
+ *
813
+ * Cross-tenant by design (the event carries only the shift id): the scope is the shift's own branch.
814
+ */
815
+ async postPendingLedger(shiftId) {
816
+ const shift = await this.getByIdUnscoped(shiftId);
817
+ if (!shift) throw new ShiftNotFoundError(shiftId);
818
+ if (!isFinalShiftState(shift.state)) throw new Error(`[pos] postPendingLedger(${shiftId}): the shift is '${shift.state}', not closed — nothing is owed yet`);
819
+ const pending = shift.pendingLedgerPost ?? null;
820
+ if (!pending) return {
821
+ shift,
822
+ outcome: "already-closed",
823
+ journalEntryId: shift.journalEntryId ?? null,
824
+ ledgerPosted: false,
825
+ ledgerPending: false
826
+ };
827
+ if (!this.ledgerBridge) throw new Error(`[pos] postPendingLedger(${shiftId}): the shift owes a ledger post but no ledger bridge is wired in this process`);
828
+ const ctx = {
829
+ organizationId: String(shift.organizationId),
830
+ ...shift.closingCashierId ? { actorId: String(shift.closingCashierId) } : {}
831
+ };
832
+ const result = await this.resumeLedgerPost(shift, pending, ctx);
833
+ if (result.ledgerError !== void 0) throw result.ledgerError;
834
+ return result;
835
+ }
836
+ /**
702
837
  * Converge a close that won the CAS but died before recording its entry.
703
838
  *
704
839
  * Re-invokes the bridge with the SAME deterministic key, so a durable
@@ -712,7 +847,8 @@ var ShiftRepository = class extends Repository {
712
847
  shift,
713
848
  outcome: "already-closed",
714
849
  journalEntryId: shift.journalEntryId ?? null,
715
- ledgerPosted: false
850
+ ledgerPosted: false,
851
+ ledgerPending: true
716
852
  };
717
853
  const claimed = await this.findOneAndUpdate({
718
854
  _id: shiftId,
@@ -727,7 +863,8 @@ var ShiftRepository = class extends Repository {
727
863
  shift: doc,
728
864
  outcome: "already-closed",
729
865
  journalEntryId: doc.journalEntryId ?? null,
730
- ledgerPosted: false
866
+ ledgerPosted: false,
867
+ ledgerPending: (doc.pendingLedgerPost ?? null) !== null
731
868
  };
732
869
  }
733
870
  let entryId;
@@ -746,6 +883,7 @@ var ShiftRepository = class extends Repository {
746
883
  outcome: "already-closed",
747
884
  journalEntryId: claimed.journalEntryId ?? null,
748
885
  ledgerPosted: false,
886
+ ledgerPending: true,
749
887
  ledgerError: err
750
888
  };
751
889
  }
@@ -765,7 +903,8 @@ var ShiftRepository = class extends Repository {
765
903
  shift: doc,
766
904
  outcome: "resumed",
767
905
  journalEntryId: normalizeEntryId(entryId),
768
- ledgerPosted: true
906
+ ledgerPosted: true,
907
+ ledgerPending: false
769
908
  };
770
909
  }
771
910
  /**
@@ -835,19 +974,6 @@ var ShiftRepository = class extends Repository {
835
974
  if (isFinalShiftState(shift.state)) throw new ShiftFinalizedError(shiftId);
836
975
  return shift;
837
976
  }
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
977
  /**
852
978
  * Session-bound dispatch (PACKAGE_RULES §P8). Build the envelope ONCE so an
853
979
  * outbox-relay re-publish and the live transport publish share `meta.id`
@@ -857,10 +983,57 @@ var ShiftRepository = class extends Repository {
857
983
  * than a redelivered one). Transport publish runs second; its failures are
858
984
  * swallowed because the durable row drives re-delivery.
859
985
  */
986
+ /**
987
+ * One unit of work for a deferred close: the caller's session when it owns one (it commits and flushes),
988
+ * else a transaction this repository opens. Without transactions the engine's waiver
989
+ * (`allowNonTransactional`) runs the work with no session — the row is then saved after the CAS, not with it.
990
+ */
991
+ async inUnit(ctx, work) {
992
+ if (ctx.session !== void 0) return work(ctx);
993
+ return this.withTransaction(async (_tx, uow) => work(uow?.session ? {
994
+ ...ctx,
995
+ session: uow.session
996
+ } : ctx), this.allowNonTransactional ? {
997
+ allowFallback: true,
998
+ onFallback: (err) => this.logger.error("[pos] no transaction: the deferred close ran WITHOUT atomicity (allowNonTransactional)", err)
999
+ } : {});
1000
+ }
1001
+ /**
1002
+ * Write one event inside `unit`. Under a session the row commits with the unit through `dispatchDomainEvent`
1003
+ * (a durable type REFUSES to write anywhere else); returns the event for {@link announceCommitted}. With no
1004
+ * session (the waived fallback) the legacy save-then-publish runs and `null` says it already published.
1005
+ */
1006
+ async dispatchInUnit(name, payload, unit) {
1007
+ if (unit.session === void 0) {
1008
+ await this.dispatch(name, payload, unit);
1009
+ return null;
1010
+ }
1011
+ const spec = durableSpecOf(name, payload);
1012
+ const event = createPosEvent(name, payload, spec);
1013
+ await dispatchDomainEvent({
1014
+ outbox: this.outbox,
1015
+ transport: this.eventTransport,
1016
+ label: "pos",
1017
+ logger: this.logger
1018
+ }, { session: unit.session }, event, spec ? "durable" : "ephemeral");
1019
+ return event;
1020
+ }
1021
+ /** After the unit committed: wake the transport (the relay nudge). A caller-owned session flushes for itself. */
1022
+ async announceCommitted(events, ctx) {
1023
+ if (ctx.session !== void 0 || !this.eventTransport) return;
1024
+ for (const event of events) {
1025
+ if (!event) continue;
1026
+ try {
1027
+ await this.eventTransport.publish(event);
1028
+ } catch (err) {
1029
+ this.logger.error(`[pos] event transport failed for ${event.type}`, err);
1030
+ }
1031
+ }
1032
+ }
860
1033
  async dispatch(name, payload, ctx) {
861
1034
  if (!this.outbox && !this.eventTransport) return;
862
1035
  if (ctx.session && !this.outbox) throw new UnmanagedSessionError();
863
- const event = createPosEvent(name, payload);
1036
+ const event = createPosEvent(name, payload, durableSpecOf(name, payload));
864
1037
  if (this.outbox) try {
865
1038
  await this.outbox.save(event, ctx.session !== void 0 ? { session: ctx.session } : {});
866
1039
  } catch (err) {
@@ -874,5 +1047,19 @@ var ShiftRepository = class extends Repository {
874
1047
  }
875
1048
  }
876
1049
  };
1050
+ /** `$expr`: the stored drawer on the `method` row (opening + sales − refunds + in − out) covers `amount`. */
1051
+ function drawerCovers(method, amount) {
1052
+ return { $let: {
1053
+ vars: { c: { $arrayElemAt: [{ $filter: {
1054
+ input: "$paymentBreakdown",
1055
+ cond: { $eq: ["$$this.method", method] }
1056
+ } }, 0] } },
1057
+ in: { $gte: [{ $subtract: [{ $add: [
1058
+ "$$c.openingAmount",
1059
+ "$$c.salesAmount",
1060
+ "$$c.cashInAmount"
1061
+ ] }, { $add: ["$$c.refundAmount", "$$c.cashOutAmount"] }] }, amount] }
1062
+ } };
1063
+ }
877
1064
  //#endregion
878
1065
  export { ShiftRepository };
@@ -0,0 +1,22 @@
1
+ import { ITillGrant } from "../models/till-grant.model.mjs";
2
+ import { TillGrant } from "../grant/till-grant.mjs";
3
+ import { PluginType, Repository } from "@classytic/mongokit";
4
+ import { Model } from "mongoose";
5
+ //#region src/repositories/till-grant.repository.d.ts
6
+ export declare class TillGrantRepository extends Repository<ITillGrant> {
7
+ constructor(config: {
8
+ model: Model<ITillGrant>;
9
+ plugins?: PluginType[] | undefined;
10
+ });
11
+ /** The server's record of a grant it signed. */
12
+ record(grant: TillGrant, ctx: {
13
+ organizationId: string;
14
+ session?: unknown;
15
+ }): Promise<void>;
16
+ /** The grant `jti` names, if this tenant issued it to this till; else null. */
17
+ forTill(jti: string, sn: string, ctx: {
18
+ organizationId: string;
19
+ session?: unknown;
20
+ }): Promise<ITillGrant | null>;
21
+ }
22
+ //#endregion