@classytic/pos 0.5.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.
- package/CHANGELOG.md +115 -0
- package/dist/commands/index.d.mts +2 -0
- package/dist/commands/index.mjs +1 -0
- package/dist/commands/pos-commands.d.mts +228 -0
- package/dist/commands/pos-commands.mjs +355 -0
- package/dist/domain/enums/cash-movement-reason.enum.d.mts +3 -4
- package/dist/domain/enums/closed-by.enum.d.mts +3 -4
- package/dist/domain/enums/payment-method.enum.d.mts +6 -7
- package/dist/domain/enums/shift-state.enum.d.mts +7 -8
- package/dist/domain/errors/pos.errors.d.mts +82 -13
- package/dist/domain/errors/pos.errors.mjs +111 -1
- package/dist/domain/index.d.mts +11 -3
- package/dist/domain/index.mjs +10 -3
- package/dist/domain/ports/common.d.mts +2 -3
- package/dist/domain/ports/ledger.bridge.d.mts +6 -7
- package/dist/domain/ports/notification.bridge.d.mts +5 -6
- package/dist/domain/ports/policy.bridge.d.mts +2 -3
- package/dist/domain/sale/discount.d.mts +62 -0
- package/dist/domain/sale/discount.mjs +58 -0
- package/dist/domain/sale/price-override.d.mts +51 -0
- package/dist/domain/sale/price-override.mjs +51 -0
- package/dist/domain/sale/quick-cash.d.mts +10 -0
- package/dist/domain/sale/quick-cash.mjs +27 -0
- package/dist/domain/sale/service-line.d.mts +7 -0
- package/dist/domain/sale/service-line.mjs +10 -0
- package/dist/domain/sale/tender.d.mts +256 -0
- package/dist/domain/sale/tender.mjs +242 -0
- package/dist/domain/shift/shift-decisions.d.mts +52 -0
- package/dist/domain/shift/shift-decisions.mjs +93 -0
- package/dist/domain/shift/shift-report.d.mts +127 -0
- package/dist/domain/shift/shift-report.mjs +95 -0
- package/dist/domain/shift/shift.types.d.mts +109 -0
- package/dist/domain/state-machines/shift.fsm.d.mts +6 -7
- package/dist/domain/value-objects/cash-movement.vo.d.mts +7 -3
- package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -5
- package/dist/domain/value-objects/shift-policy.vo.d.mts +11 -7
- package/dist/domain/value-objects/shift-policy.vo.mjs +12 -1
- package/dist/engine/define-pos.d.mts +2 -3
- package/dist/engine/define-pos.mjs +13 -2
- package/dist/engine/engine-types.d.mts +24 -9
- package/dist/engine/index.mjs +1 -2
- package/dist/events/event-catalog.d.mts +18 -14
- package/dist/events/event-catalog.mjs +10 -4
- package/dist/events/event-constants.d.mts +3 -4
- package/dist/events/event-payloads.d.mts +9 -10
- package/dist/events/helpers.d.mts +6 -3
- package/dist/events/helpers.mjs +12 -2
- package/dist/events/in-process-bus.d.mts +3 -4
- package/dist/events/index.mjs +1 -1
- package/dist/grant/till-grant.d.mts +50 -0
- package/dist/grant/till-grant.mjs +47 -0
- package/dist/index.d.mts +14 -4
- package/dist/index.mjs +12 -4
- package/dist/models/create-models.d.mts +10 -6
- package/dist/models/create-models.mjs +16 -3
- package/dist/models/register.model.d.mts +7 -6
- package/dist/models/shift-sale-dedupe.model.d.mts +4 -5
- package/dist/models/shift.model.d.mts +4 -111
- package/dist/models/shift.model.mjs +26 -2
- package/dist/models/till-grant.model.d.mts +19 -0
- package/dist/models/till-grant.model.mjs +52 -0
- package/dist/repositories/register.repository.d.mts +3 -4
- package/dist/repositories/shift.repository.d.mts +77 -30
- package/dist/repositories/shift.repository.mjs +307 -108
- package/dist/repositories/till-grant.repository.d.mts +22 -0
- package/dist/repositories/till-grant.repository.mjs +41 -0
- package/dist/schemas/index.mjs +1 -2
- package/dist/schemas/shift.d.mts +9 -10
- package/dist/testing/fixtures.d.mts +4 -5
- package/dist/testing/index.mjs +1 -2
- package/package.json +50 -19
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError,
|
|
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 {
|
|
7
|
-
import {
|
|
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
|
-
*
|
|
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
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
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
|
-
|
|
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
|
|
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:
|
|
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)
|
|
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
|
-
|
|
290
|
-
|
|
291
|
-
|
|
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:
|
|
300
|
-
expectedCash:
|
|
301
|
-
countedCash:
|
|
302
|
-
cashDifference:
|
|
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
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
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
|
|
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:
|
|
354
|
-
countedCash:
|
|
355
|
-
cashDifference:
|
|
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 &&
|
|
442
|
+
if (varianceExceeded && decision.expectedCash != null) await this.dispatch(POS_EVENTS.VARIANCE_DETECTED, {
|
|
383
443
|
shiftId: input.shiftId,
|
|
384
|
-
difference:
|
|
385
|
-
expected:
|
|
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,40 @@ var ShiftRepository = class extends Repository {
|
|
|
430
491
|
/**
|
|
431
492
|
* The currently ACTIVE shift (`open | paused | blind_closed`), or `null`.
|
|
432
493
|
*
|
|
433
|
-
*
|
|
434
|
-
*
|
|
435
|
-
*
|
|
436
|
-
*
|
|
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`.
|
|
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.
|
|
445
498
|
*
|
|
446
|
-
* Routed through
|
|
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
|
-
|
|
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
|
-
})
|
|
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;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Every active shift for ONE branch — the "/status" dashboard widget
|
|
519
|
+
* ("registers open now"). Routed through `findAll` so the tenant plugin
|
|
520
|
+
* injects and CASTS `organizationId`, same reasoning as `getActiveShift`.
|
|
521
|
+
*/
|
|
522
|
+
async findActiveByBranch(organizationId) {
|
|
523
|
+
return await this.findAll({ state: { $in: [...ACTIVE_SHIFT_STATES] } }, {
|
|
524
|
+
organizationId,
|
|
525
|
+
select: "_id state registerId openingCashierId openedAt blindClosedAt salesCount salesTotal",
|
|
526
|
+
lean: true
|
|
527
|
+
});
|
|
460
528
|
}
|
|
461
529
|
/**
|
|
462
530
|
* Lean, DELIBERATELY UNSCOPED read by `_id`.
|
|
@@ -508,7 +576,54 @@ var ShiftRepository = class extends Repository {
|
|
|
508
576
|
});
|
|
509
577
|
const cashRow = breakdown.find(isCashRow);
|
|
510
578
|
const fromState = shift.state;
|
|
511
|
-
const
|
|
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
|
+
}
|
|
512
627
|
let claimed;
|
|
513
628
|
try {
|
|
514
629
|
claimed = await this.applyTransition(String(shift._id), shiftMachine("forceClose"), {
|
|
@@ -552,6 +667,7 @@ var ShiftRepository = class extends Repository {
|
|
|
552
667
|
outcome: "closed",
|
|
553
668
|
journalEntryId: posted.journalEntryId,
|
|
554
669
|
ledgerPosted: posted.ledgerPosted,
|
|
670
|
+
ledgerPending: ledgerError !== void 0,
|
|
555
671
|
...ledgerError !== void 0 ? { ledgerError } : {}
|
|
556
672
|
};
|
|
557
673
|
}
|
|
@@ -589,7 +705,7 @@ var ShiftRepository = class extends Repository {
|
|
|
589
705
|
* which is the whole point: a resume after a crash must collide with the
|
|
590
706
|
* entry the crashed attempt may have already written.
|
|
591
707
|
*/
|
|
592
|
-
buildPendingLedgerPost(shift, trigger) {
|
|
708
|
+
buildPendingLedgerPost(shift, trigger, durable = false) {
|
|
593
709
|
if (!this.ledgerBridge) return null;
|
|
594
710
|
if (shift.journalEntryId) return null;
|
|
595
711
|
return {
|
|
@@ -598,7 +714,8 @@ var ShiftRepository = class extends Repository {
|
|
|
598
714
|
attempts: 1,
|
|
599
715
|
stampedAt: /* @__PURE__ */ new Date(),
|
|
600
716
|
lastAttemptAt: null,
|
|
601
|
-
announced:
|
|
717
|
+
announced: durable,
|
|
718
|
+
...durable ? { durable: true } : {}
|
|
602
719
|
};
|
|
603
720
|
}
|
|
604
721
|
/**
|
|
@@ -678,15 +795,45 @@ var ShiftRepository = class extends Repository {
|
|
|
678
795
|
*/
|
|
679
796
|
async convergeTerminal(shift, ctx) {
|
|
680
797
|
const pending = shift.pendingLedgerPost ?? null;
|
|
681
|
-
if (!pending) return {
|
|
798
|
+
if (!pending || pending.durable === true) return {
|
|
682
799
|
shift,
|
|
683
800
|
outcome: "already-closed",
|
|
684
801
|
journalEntryId: shift.journalEntryId ?? null,
|
|
685
|
-
ledgerPosted: false
|
|
802
|
+
ledgerPosted: false,
|
|
803
|
+
ledgerPending: pending !== null
|
|
686
804
|
};
|
|
687
805
|
return this.resumeLedgerPost(shift, pending, ctx);
|
|
688
806
|
}
|
|
689
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
|
+
/**
|
|
690
837
|
* Converge a close that won the CAS but died before recording its entry.
|
|
691
838
|
*
|
|
692
839
|
* Re-invokes the bridge with the SAME deterministic key, so a durable
|
|
@@ -700,7 +847,8 @@ var ShiftRepository = class extends Repository {
|
|
|
700
847
|
shift,
|
|
701
848
|
outcome: "already-closed",
|
|
702
849
|
journalEntryId: shift.journalEntryId ?? null,
|
|
703
|
-
ledgerPosted: false
|
|
850
|
+
ledgerPosted: false,
|
|
851
|
+
ledgerPending: true
|
|
704
852
|
};
|
|
705
853
|
const claimed = await this.findOneAndUpdate({
|
|
706
854
|
_id: shiftId,
|
|
@@ -715,7 +863,8 @@ var ShiftRepository = class extends Repository {
|
|
|
715
863
|
shift: doc,
|
|
716
864
|
outcome: "already-closed",
|
|
717
865
|
journalEntryId: doc.journalEntryId ?? null,
|
|
718
|
-
ledgerPosted: false
|
|
866
|
+
ledgerPosted: false,
|
|
867
|
+
ledgerPending: (doc.pendingLedgerPost ?? null) !== null
|
|
719
868
|
};
|
|
720
869
|
}
|
|
721
870
|
let entryId;
|
|
@@ -734,6 +883,7 @@ var ShiftRepository = class extends Repository {
|
|
|
734
883
|
outcome: "already-closed",
|
|
735
884
|
journalEntryId: claimed.journalEntryId ?? null,
|
|
736
885
|
ledgerPosted: false,
|
|
886
|
+
ledgerPending: true,
|
|
737
887
|
ledgerError: err
|
|
738
888
|
};
|
|
739
889
|
}
|
|
@@ -753,7 +903,8 @@ var ShiftRepository = class extends Repository {
|
|
|
753
903
|
shift: doc,
|
|
754
904
|
outcome: "resumed",
|
|
755
905
|
journalEntryId: normalizeEntryId(entryId),
|
|
756
|
-
ledgerPosted: true
|
|
906
|
+
ledgerPosted: true,
|
|
907
|
+
ledgerPending: false
|
|
757
908
|
};
|
|
758
909
|
}
|
|
759
910
|
/**
|
|
@@ -823,19 +974,6 @@ var ShiftRepository = class extends Repository {
|
|
|
823
974
|
if (isFinalShiftState(shift.state)) throw new ShiftFinalizedError(shiftId);
|
|
824
975
|
return shift;
|
|
825
976
|
}
|
|
826
|
-
applyCounts(breakdown, counted, computeAll) {
|
|
827
|
-
return toPlainBreakdown(breakdown).map((row) => {
|
|
828
|
-
const expected = computeAll ? computeExpected(row) : row.expectedAmount;
|
|
829
|
-
const newCounted = counted[row.method] ?? row.countedAmount;
|
|
830
|
-
const diff = expected !== null && newCounted !== null && newCounted !== void 0 ? computeDifference(expected, newCounted) : null;
|
|
831
|
-
return {
|
|
832
|
-
...row,
|
|
833
|
-
expectedAmount: expected,
|
|
834
|
-
countedAmount: newCounted ?? null,
|
|
835
|
-
difference: diff
|
|
836
|
-
};
|
|
837
|
-
});
|
|
838
|
-
}
|
|
839
977
|
/**
|
|
840
978
|
* Session-bound dispatch (PACKAGE_RULES §P8). Build the envelope ONCE so an
|
|
841
979
|
* outbox-relay re-publish and the live transport publish share `meta.id`
|
|
@@ -845,10 +983,57 @@ var ShiftRepository = class extends Repository {
|
|
|
845
983
|
* than a redelivered one). Transport publish runs second; its failures are
|
|
846
984
|
* swallowed because the durable row drives re-delivery.
|
|
847
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
|
+
}
|
|
848
1033
|
async dispatch(name, payload, ctx) {
|
|
849
1034
|
if (!this.outbox && !this.eventTransport) return;
|
|
850
1035
|
if (ctx.session && !this.outbox) throw new UnmanagedSessionError();
|
|
851
|
-
const event = createPosEvent(name, payload);
|
|
1036
|
+
const event = createPosEvent(name, payload, durableSpecOf(name, payload));
|
|
852
1037
|
if (this.outbox) try {
|
|
853
1038
|
await this.outbox.save(event, ctx.session !== void 0 ? { session: ctx.session } : {});
|
|
854
1039
|
} catch (err) {
|
|
@@ -862,5 +1047,19 @@ var ShiftRepository = class extends Repository {
|
|
|
862
1047
|
}
|
|
863
1048
|
}
|
|
864
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
|
+
}
|
|
865
1064
|
//#endregion
|
|
866
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
|