@classytic/pos 0.1.1
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 +17 -0
- package/LICENSE +21 -0
- package/README.md +152 -0
- package/dist/domain/enums/cash-movement-reason.enum.d.mts +12 -0
- package/dist/domain/enums/cash-movement-reason.enum.mjs +19 -0
- package/dist/domain/enums/closed-by.enum.d.mts +13 -0
- package/dist/domain/enums/closed-by.enum.mjs +16 -0
- package/dist/domain/enums/payment-method.enum.d.mts +14 -0
- package/dist/domain/enums/payment-method.enum.mjs +18 -0
- package/dist/domain/enums/shift-state.enum.d.mts +26 -0
- package/dist/domain/enums/shift-state.enum.mjs +39 -0
- package/dist/domain/errors/pos.errors.d.mts +37 -0
- package/dist/domain/errors/pos.errors.mjs +64 -0
- package/dist/domain/index.d.mts +14 -0
- package/dist/domain/index.mjs +9 -0
- package/dist/domain/ports/common.d.mts +9 -0
- package/dist/domain/ports/ledger.bridge.d.mts +18 -0
- package/dist/domain/ports/notification.bridge.d.mts +12 -0
- package/dist/domain/ports/policy.bridge.d.mts +13 -0
- package/dist/domain/state-machines/shift.fsm.d.mts +14 -0
- package/dist/domain/state-machines/shift.fsm.mjs +41 -0
- package/dist/domain/value-objects/cash-movement.vo.d.mts +19 -0
- package/dist/domain/value-objects/payment-breakdown.vo.d.mts +24 -0
- package/dist/domain/value-objects/payment-breakdown.vo.mjs +11 -0
- package/dist/domain/value-objects/shift-policy.vo.d.mts +32 -0
- package/dist/domain/value-objects/shift-policy.vo.mjs +14 -0
- package/dist/engine/create-pos.d.mts +6 -0
- package/dist/engine/create-pos.mjs +65 -0
- package/dist/engine/engine-types.d.mts +73 -0
- package/dist/engine/index.d.mts +3 -0
- package/dist/engine/index.mjs +2 -0
- package/dist/events/event-constants.d.mts +21 -0
- package/dist/events/event-constants.mjs +20 -0
- package/dist/events/event-payloads.d.mts +49 -0
- package/dist/events/helpers.d.mts +6 -0
- package/dist/events/helpers.mjs +12 -0
- package/dist/events/in-process-bus.d.mts +19 -0
- package/dist/events/in-process-bus.mjs +38 -0
- package/dist/events/index.d.mts +5 -0
- package/dist/events/index.mjs +4 -0
- package/dist/index.d.mts +23 -0
- package/dist/index.mjs +15 -0
- package/dist/models/create-models.d.mts +9 -0
- package/dist/models/create-models.mjs +20 -0
- package/dist/models/inject-tenant.d.mts +2 -0
- package/dist/models/inject-tenant.mjs +48 -0
- package/dist/models/shift.model.d.mts +68 -0
- package/dist/models/shift.model.mjs +267 -0
- package/dist/repositories/repo-options.mjs +20 -0
- package/dist/repositories/shift.repository.d.mts +153 -0
- package/dist/repositories/shift.repository.mjs +401 -0
- package/dist/schemas/index.d.mts +2 -0
- package/dist/schemas/index.mjs +2 -0
- package/dist/schemas/shift.d.mts +67 -0
- package/dist/schemas/shift.mjs +52 -0
- package/dist/testing/fixtures.d.mts +9 -0
- package/dist/testing/fixtures.mjs +36 -0
- package/dist/testing/index.d.mts +2 -0
- package/dist/testing/index.mjs +2 -0
- package/package.json +110 -0
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { ActiveShiftAlreadyOpenError, IllegalShiftTransitionError, ShiftFinalizedError, ShiftNotFoundError, VarianceExceededError } from "../domain/errors/pos.errors.mjs";
|
|
2
|
+
import { canTransition, nextState } from "../domain/state-machines/shift.fsm.mjs";
|
|
3
|
+
import { computeDifference, computeExpected } from "../domain/value-objects/payment-breakdown.vo.mjs";
|
|
4
|
+
import { isWithinVarianceThreshold } from "../domain/value-objects/shift-policy.vo.mjs";
|
|
5
|
+
import { POS_EVENTS } from "../events/event-constants.mjs";
|
|
6
|
+
import { createPosEvent } from "../events/helpers.mjs";
|
|
7
|
+
import { repoOptionsFromCtx } from "./repo-options.mjs";
|
|
8
|
+
import { Repository, methodRegistryPlugin, softDeletePlugin } from "@classytic/mongokit";
|
|
9
|
+
import { applyDecision, createChain } from "@classytic/primitives/approval";
|
|
10
|
+
//#region src/repositories/shift.repository.ts
|
|
11
|
+
/**
|
|
12
|
+
* ShiftRepository — extends mongokit `Repository<IShift>`.
|
|
13
|
+
*
|
|
14
|
+
* Auto-CRUD inherits from mongokit (list/get/create/update/delete + queryParser
|
|
15
|
+
* surface). Domain verbs live HERE — they encode the FSM, variance check, and
|
|
16
|
+
* the ledger-bridge handshake. Hosts should call these verbs (not raw CRUD)
|
|
17
|
+
* for state changes.
|
|
18
|
+
*
|
|
19
|
+
* Transactional close pipeline:
|
|
20
|
+
* 1. Compute expected per method + cash totals
|
|
21
|
+
* 2. Variance gate (policy.varianceThresholdAbs/Pct)
|
|
22
|
+
* 3. Bridge: ledger.onShiftClosed → returns journalEntryId (host posts JE)
|
|
23
|
+
* 4. State write to `closed` + persist journalEntryId
|
|
24
|
+
* 5. Publish `pos:shift.closed`
|
|
25
|
+
*
|
|
26
|
+
* If step 3 throws, the state write is skipped (Odoo rollback). Hosts using
|
|
27
|
+
* MongoDB transactions thread `ctx.session` so steps 3+4 commit atomically.
|
|
28
|
+
*
|
|
29
|
+
* Raw `findOneAndUpdate` is used ONLY for the FSM transition with a
|
|
30
|
+
* `{ state }` guard — concurrent close attempts can't double-post the JE.
|
|
31
|
+
*/
|
|
32
|
+
var ShiftRepository = class extends Repository {
|
|
33
|
+
defaultPolicy;
|
|
34
|
+
ledgerBridge;
|
|
35
|
+
policyBridge;
|
|
36
|
+
notificationBridge;
|
|
37
|
+
eventTransport;
|
|
38
|
+
logger;
|
|
39
|
+
constructor(config) {
|
|
40
|
+
const { model, plugins = [] } = config;
|
|
41
|
+
super(model, [
|
|
42
|
+
methodRegistryPlugin(),
|
|
43
|
+
softDeletePlugin({ ttlDays: 2555 }),
|
|
44
|
+
...plugins
|
|
45
|
+
]);
|
|
46
|
+
this.defaultPolicy = config.defaultPolicy;
|
|
47
|
+
this.ledgerBridge = config.ledgerBridge;
|
|
48
|
+
this.policyBridge = config.policyBridge;
|
|
49
|
+
this.notificationBridge = config.notificationBridge;
|
|
50
|
+
this.eventTransport = config.eventTransport;
|
|
51
|
+
this.logger = config.logger ?? console;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Open a new shift. Throws `ActiveShiftAlreadyOpenError` if one already
|
|
55
|
+
* exists for the (org, register) pair — enforced both by the
|
|
56
|
+
* partial-unique index and a pre-check for a friendlier error.
|
|
57
|
+
*/
|
|
58
|
+
async open(input, ctx) {
|
|
59
|
+
const policy = input.policy ?? (this.policyBridge ? await this.policyBridge.resolvePolicy(ctx) : this.defaultPolicy);
|
|
60
|
+
const seedBreakdown = policy.allowedPaymentMethods.map((method) => ({
|
|
61
|
+
method,
|
|
62
|
+
openingAmount: method === "cash" ? input.openingCash : 0,
|
|
63
|
+
salesAmount: 0,
|
|
64
|
+
taxAmount: 0,
|
|
65
|
+
refundAmount: 0,
|
|
66
|
+
refundTaxAmount: 0,
|
|
67
|
+
cashInAmount: 0,
|
|
68
|
+
cashOutAmount: 0,
|
|
69
|
+
expectedAmount: null,
|
|
70
|
+
countedAmount: null,
|
|
71
|
+
difference: null
|
|
72
|
+
}));
|
|
73
|
+
try {
|
|
74
|
+
const shift = await this.create({
|
|
75
|
+
registerId: input.registerId,
|
|
76
|
+
businessDate: input.businessDate,
|
|
77
|
+
state: "open",
|
|
78
|
+
openingCashierId: input.openingCashierId,
|
|
79
|
+
openingCashierName: input.openingCashierName,
|
|
80
|
+
teamMemberIds: [input.openingCashierId],
|
|
81
|
+
openedAt: /* @__PURE__ */ new Date(),
|
|
82
|
+
openingCash: input.openingCash,
|
|
83
|
+
paymentBreakdown: seedBreakdown,
|
|
84
|
+
policySnapshot: policy,
|
|
85
|
+
notes: input.notes ?? ""
|
|
86
|
+
}, repoOptionsFromCtx(ctx));
|
|
87
|
+
await this.publishEvent(POS_EVENTS.SHIFT_OPENED, {
|
|
88
|
+
shiftId: shift._id.toString(),
|
|
89
|
+
registerId: shift.registerId,
|
|
90
|
+
openingCashierId: shift.openingCashierId
|
|
91
|
+
});
|
|
92
|
+
return shift;
|
|
93
|
+
} catch (err) {
|
|
94
|
+
if (err.code === 11e3) throw new ActiveShiftAlreadyOpenError(`${input.registerId}`);
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async pause(shiftId, ctx) {
|
|
99
|
+
return this.transitionState(shiftId, "pause", { pausedAt: /* @__PURE__ */ new Date() }, ctx);
|
|
100
|
+
}
|
|
101
|
+
async resume(shiftId, ctx) {
|
|
102
|
+
return this.transitionState(shiftId, "resume", { resumedAt: /* @__PURE__ */ new Date() }, ctx);
|
|
103
|
+
}
|
|
104
|
+
async recordCashMovement(input, ctx) {
|
|
105
|
+
const shift = await this.requireActive(input.shiftId, ctx);
|
|
106
|
+
const movement = {
|
|
107
|
+
...input.movement,
|
|
108
|
+
timestamp: input.movement.timestamp ?? /* @__PURE__ */ new Date()
|
|
109
|
+
};
|
|
110
|
+
const cashRow = shift.paymentBreakdown.find((r) => r.method === "cash");
|
|
111
|
+
if (!cashRow) {}
|
|
112
|
+
const update = { $push: { cashMovements: movement } };
|
|
113
|
+
if (cashRow) update.$inc = movement.type === "in" ? { "paymentBreakdown.$[cashElem].cashInAmount": movement.amount } : { "paymentBreakdown.$[cashElem].cashOutAmount": movement.amount };
|
|
114
|
+
const updated = await this.findOneAndUpdate({
|
|
115
|
+
_id: shift._id,
|
|
116
|
+
state: shift.state
|
|
117
|
+
}, update, {
|
|
118
|
+
...cashRow ? { arrayFilters: [{ "cashElem.method": "cash" }] } : {},
|
|
119
|
+
...repoOptionsFromCtx(ctx)
|
|
120
|
+
});
|
|
121
|
+
if (!updated) throw new ShiftNotFoundError(input.shiftId);
|
|
122
|
+
await this.publishEvent(POS_EVENTS.CASH_MOVEMENT_RECORDED, {
|
|
123
|
+
shiftId: input.shiftId,
|
|
124
|
+
type: movement.type,
|
|
125
|
+
amount: movement.amount,
|
|
126
|
+
reasonCode: movement.reasonCode
|
|
127
|
+
});
|
|
128
|
+
return updated;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Atomically increment shift aggregates from an order-create hook in the
|
|
132
|
+
* host. Idempotency is the host's responsibility (don't call twice for
|
|
133
|
+
* the same order). Refunds pass `refund: true`.
|
|
134
|
+
*/
|
|
135
|
+
async incrementSales(input, ctx) {
|
|
136
|
+
if (input.amount <= 0) return;
|
|
137
|
+
const refund = input.refund === true;
|
|
138
|
+
const tax = Math.max(0, Math.trunc(input.tax ?? 0));
|
|
139
|
+
if (tax > input.amount) throw new Error(`tax (${tax}) cannot exceed amount (${input.amount})`);
|
|
140
|
+
const update = { $inc: refund ? {
|
|
141
|
+
refundCount: 1,
|
|
142
|
+
refundTotal: input.amount,
|
|
143
|
+
"paymentBreakdown.$[methodElem].refundAmount": input.amount,
|
|
144
|
+
...tax > 0 ? { "paymentBreakdown.$[methodElem].refundTaxAmount": tax } : {}
|
|
145
|
+
} : {
|
|
146
|
+
salesCount: 1,
|
|
147
|
+
salesTotal: input.amount,
|
|
148
|
+
"paymentBreakdown.$[methodElem].salesAmount": input.amount,
|
|
149
|
+
...tax > 0 ? { "paymentBreakdown.$[methodElem].taxAmount": tax } : {}
|
|
150
|
+
} };
|
|
151
|
+
if (input.cashierId) {
|
|
152
|
+
update.$addToSet = { teamMemberIds: input.cashierId };
|
|
153
|
+
update.$set = {
|
|
154
|
+
endingCashierId: input.cashierId,
|
|
155
|
+
endingCashierName: input.cashierName ?? input.cashierId
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
await this.findOneAndUpdate({
|
|
159
|
+
_id: input.shiftId,
|
|
160
|
+
state: { $in: ["open", "paused"] }
|
|
161
|
+
}, update, {
|
|
162
|
+
arrayFilters: [{ "methodElem.method": input.method }],
|
|
163
|
+
...repoOptionsFromCtx(ctx)
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Lightspeed-style cashier blind-close — counts are recorded but the
|
|
168
|
+
* variance check is deferred to the manager-driven `close()`.
|
|
169
|
+
*/
|
|
170
|
+
async blindClose(input, ctx) {
|
|
171
|
+
const shift = await this.requireActive(input.shiftId, ctx);
|
|
172
|
+
if (shift.state !== "open") throw new IllegalShiftTransitionError(shift.state, "blindClose");
|
|
173
|
+
const updatedBreakdown = this.applyCounts(shift.paymentBreakdown, input.countedByMethod, true);
|
|
174
|
+
const cashRow = updatedBreakdown.find((r) => r.method === "cash");
|
|
175
|
+
const updated = await this.claim(shift._id, {
|
|
176
|
+
field: "state",
|
|
177
|
+
from: "open",
|
|
178
|
+
to: "blind_closed"
|
|
179
|
+
}, {
|
|
180
|
+
blindClosedAt: /* @__PURE__ */ new Date(),
|
|
181
|
+
paymentBreakdown: updatedBreakdown,
|
|
182
|
+
expectedCash: cashRow?.expectedAmount ?? null,
|
|
183
|
+
countedCash: cashRow?.countedAmount ?? null,
|
|
184
|
+
cashDifference: cashRow?.difference ?? null,
|
|
185
|
+
closingCashierId: input.closingCashierId,
|
|
186
|
+
closingCashierName: input.closingCashierName,
|
|
187
|
+
...input.notes ? { notes: input.notes } : {}
|
|
188
|
+
}, repoOptionsFromCtx(ctx));
|
|
189
|
+
if (!updated) throw new IllegalShiftTransitionError(shift.state, "blindClose");
|
|
190
|
+
await this.publishEvent(POS_EVENTS.SHIFT_BLIND_CLOSED, { shiftId: input.shiftId });
|
|
191
|
+
return updated;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Final close — fires the variance gate, the ledger bridge, and the
|
|
195
|
+
* `pos:shift.closed` event in that order. State write happens last; a
|
|
196
|
+
* thrown bridge keeps the shift in its previous state.
|
|
197
|
+
*/
|
|
198
|
+
async close(input, ctx) {
|
|
199
|
+
const shift = await this.requireActive(input.shiftId, ctx);
|
|
200
|
+
if (!canTransition(shift.state, "close")) throw new IllegalShiftTransitionError(shift.state, "close");
|
|
201
|
+
const breakdown = input.countedByMethod ? this.applyCounts(shift.paymentBreakdown, input.countedByMethod, true) : shift.paymentBreakdown;
|
|
202
|
+
const cashRow = breakdown.find((r) => r.method === "cash");
|
|
203
|
+
if (cashRow?.expectedAmount != null && cashRow.countedAmount != null) {
|
|
204
|
+
if (!isWithinVarianceThreshold(cashRow.difference ?? 0, cashRow.expectedAmount, shift.policySnapshot) && shift.policySnapshot.managerOverrideRequired && !input.varianceOverride) throw new VarianceExceededError(cashRow.difference ?? 0, cashRow.expectedAmount);
|
|
205
|
+
}
|
|
206
|
+
const fromState = shift.state;
|
|
207
|
+
let journalEntryId = shift.journalEntryId ?? null;
|
|
208
|
+
if (this.ledgerBridge && !journalEntryId) {
|
|
209
|
+
const projected = {
|
|
210
|
+
...shift.toObject(),
|
|
211
|
+
paymentBreakdown: breakdown
|
|
212
|
+
};
|
|
213
|
+
journalEntryId = (await this.ledgerBridge.onShiftClosed(projected, ctx)).journalEntryId;
|
|
214
|
+
}
|
|
215
|
+
const set = {
|
|
216
|
+
closedAt: /* @__PURE__ */ new Date(),
|
|
217
|
+
closedBy: input.closedBy,
|
|
218
|
+
paymentBreakdown: breakdown,
|
|
219
|
+
expectedCash: cashRow?.expectedAmount ?? null,
|
|
220
|
+
countedCash: cashRow?.countedAmount ?? null,
|
|
221
|
+
cashDifference: cashRow?.difference ?? null,
|
|
222
|
+
...journalEntryId ? { journalEntryId } : {},
|
|
223
|
+
...input.varianceOverride ? { approvals: this.buildVarianceApprovalChain(input.varianceOverride.overriddenBy, input.varianceOverride.reason) } : {}
|
|
224
|
+
};
|
|
225
|
+
const updated = await this.claim(shift._id, {
|
|
226
|
+
field: "state",
|
|
227
|
+
from: fromState,
|
|
228
|
+
to: "closed"
|
|
229
|
+
}, set, repoOptionsFromCtx(ctx));
|
|
230
|
+
if (!updated) throw new IllegalShiftTransitionError(fromState, "close");
|
|
231
|
+
await this.publishEvent(POS_EVENTS.SHIFT_CLOSED, {
|
|
232
|
+
shiftId: input.shiftId,
|
|
233
|
+
journalEntryId,
|
|
234
|
+
closedBy: input.closedBy
|
|
235
|
+
});
|
|
236
|
+
if (input.varianceOverride && this.notificationBridge?.onVarianceOverride) try {
|
|
237
|
+
await this.notificationBridge.onVarianceOverride(updated, ctx);
|
|
238
|
+
} catch (err) {
|
|
239
|
+
this.logger.error("[pos] notificationBridge.onVarianceOverride threw", err);
|
|
240
|
+
}
|
|
241
|
+
return updated;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Find shifts in any active state whose `businessDate` is strictly before
|
|
245
|
+
* `asOf`. Used by the EOD cron backstop to identify orphans the cashier
|
|
246
|
+
* never closed. Returns lean docs (read-only); call `forceClose(id, ctx)`
|
|
247
|
+
* for each.
|
|
248
|
+
*
|
|
249
|
+
* Multi-tenant scoping: this is a CROSS-TENANT helper for the host's
|
|
250
|
+
* batch cron — the package's tenant plugin would block it under a single
|
|
251
|
+
* org context, so we bypass it by reading the model directly.
|
|
252
|
+
*
|
|
253
|
+
* @param asOf Cut-off — typically `new Date()` rounded to today's BD-zone
|
|
254
|
+
* midnight. Shifts strictly before this are stale.
|
|
255
|
+
*/
|
|
256
|
+
async findStaleShifts(asOf) {
|
|
257
|
+
return this.Model.find({
|
|
258
|
+
state: { $in: [
|
|
259
|
+
"open",
|
|
260
|
+
"paused",
|
|
261
|
+
"blind_closed"
|
|
262
|
+
] },
|
|
263
|
+
businessDate: { $lt: asOf }
|
|
264
|
+
}, {
|
|
265
|
+
_id: 1,
|
|
266
|
+
organizationId: 1,
|
|
267
|
+
registerId: 1,
|
|
268
|
+
state: 1,
|
|
269
|
+
businessDate: 1
|
|
270
|
+
}).lean();
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Backstop / EOD-cron path. Defaults counts to expected (zero variance)
|
|
274
|
+
* and routes `closedBy: 'system_auto'`. Result is `orphaned_closed` —
|
|
275
|
+
* a flag for manager review.
|
|
276
|
+
*/
|
|
277
|
+
async forceClose(shiftId, ctx) {
|
|
278
|
+
const shift = await this.requireActive(shiftId, ctx);
|
|
279
|
+
if (!canTransition(shift.state, "forceClose")) throw new IllegalShiftTransitionError(shift.state, "forceClose");
|
|
280
|
+
const breakdown = shift.paymentBreakdown.map((r) => typeof r.toObject === "function" ? r.toObject() : r).map((row) => {
|
|
281
|
+
const expected = row.expectedAmount ?? computeExpected(row);
|
|
282
|
+
return {
|
|
283
|
+
...row,
|
|
284
|
+
expectedAmount: expected,
|
|
285
|
+
countedAmount: expected,
|
|
286
|
+
difference: 0
|
|
287
|
+
};
|
|
288
|
+
});
|
|
289
|
+
const cashRow = breakdown.find((r) => r.method === "cash");
|
|
290
|
+
let journalEntryId = shift.journalEntryId ?? null;
|
|
291
|
+
if (this.ledgerBridge && !journalEntryId) {
|
|
292
|
+
const projected = {
|
|
293
|
+
...shift.toObject(),
|
|
294
|
+
paymentBreakdown: breakdown
|
|
295
|
+
};
|
|
296
|
+
try {
|
|
297
|
+
journalEntryId = (await this.ledgerBridge.onShiftClosed(projected, ctx)).journalEntryId;
|
|
298
|
+
} catch (err) {
|
|
299
|
+
this.logger.error("[pos] ledgerBridge threw on forceClose", err);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const fromState = shift.state;
|
|
303
|
+
const updated = await this.claim(shift._id, {
|
|
304
|
+
field: "state",
|
|
305
|
+
from: fromState,
|
|
306
|
+
to: "orphaned_closed"
|
|
307
|
+
}, {
|
|
308
|
+
closedAt: /* @__PURE__ */ new Date(),
|
|
309
|
+
closedBy: "system_auto",
|
|
310
|
+
paymentBreakdown: breakdown,
|
|
311
|
+
expectedCash: cashRow?.expectedAmount ?? null,
|
|
312
|
+
countedCash: cashRow?.countedAmount ?? null,
|
|
313
|
+
cashDifference: 0,
|
|
314
|
+
...journalEntryId ? { journalEntryId } : {}
|
|
315
|
+
}, repoOptionsFromCtx(ctx));
|
|
316
|
+
if (!updated) throw new IllegalShiftTransitionError(fromState, "forceClose");
|
|
317
|
+
await this.publishEvent(POS_EVENTS.SHIFT_FORCE_CLOSED, {
|
|
318
|
+
shiftId,
|
|
319
|
+
reason: "orphan_eod"
|
|
320
|
+
});
|
|
321
|
+
if (this.notificationBridge?.onOrphanedClose) try {
|
|
322
|
+
await this.notificationBridge.onOrphanedClose(updated, ctx);
|
|
323
|
+
} catch (err) {
|
|
324
|
+
this.logger.error("[pos] notificationBridge.onOrphanedClose threw", err);
|
|
325
|
+
}
|
|
326
|
+
return updated;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Build a single-step approved `ApprovalChain` for a manager's variance
|
|
330
|
+
* override. Uses primitives' `createChain` + `applyDecision` rather than
|
|
331
|
+
* a parallel ad-hoc shape (PACKAGE_RULES P7).
|
|
332
|
+
*
|
|
333
|
+
* If a host wants a full multi-step chain (e.g. shift supervisor → store
|
|
334
|
+
* manager), they construct one externally and pass it in via a future
|
|
335
|
+
* `approvals` input on `CloseShiftInput` — but the common single-override
|
|
336
|
+
* case is already covered without the host having to build the chain
|
|
337
|
+
* manually. The persisted field is `approvals` (P7 canonical).
|
|
338
|
+
*/
|
|
339
|
+
buildVarianceApprovalChain(approverId, reason) {
|
|
340
|
+
return applyDecision(createChain({
|
|
341
|
+
order: "sequential",
|
|
342
|
+
steps: [{
|
|
343
|
+
id: "variance-override",
|
|
344
|
+
name: "Variance override",
|
|
345
|
+
approvers: [{ id: approverId }],
|
|
346
|
+
requiredApprovals: 1
|
|
347
|
+
}]
|
|
348
|
+
}), {
|
|
349
|
+
stepId: "variance-override",
|
|
350
|
+
approverId,
|
|
351
|
+
decision: "approved",
|
|
352
|
+
...reason ? { note: reason } : {}
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
async transitionState(shiftId, verb, extraSet, ctx) {
|
|
356
|
+
const shift = await this.requireActive(shiftId, ctx);
|
|
357
|
+
const target = nextState(shift.state, verb);
|
|
358
|
+
if (!target) throw new IllegalShiftTransitionError(shift.state, verb);
|
|
359
|
+
const updated = await this.claim(shift._id, {
|
|
360
|
+
field: "state",
|
|
361
|
+
from: shift.state,
|
|
362
|
+
to: target
|
|
363
|
+
}, extraSet, repoOptionsFromCtx(ctx));
|
|
364
|
+
if (!updated) throw new IllegalShiftTransitionError(shift.state, verb);
|
|
365
|
+
await this.publishEvent(`pos:shift.${verb}`, {
|
|
366
|
+
shiftId,
|
|
367
|
+
from: shift.state,
|
|
368
|
+
to: target
|
|
369
|
+
});
|
|
370
|
+
return updated;
|
|
371
|
+
}
|
|
372
|
+
async requireActive(shiftId, ctx) {
|
|
373
|
+
const shift = await this.getById(shiftId, repoOptionsFromCtx(ctx));
|
|
374
|
+
if (!shift) throw new ShiftNotFoundError(shiftId);
|
|
375
|
+
if (shift.state === "closed" || shift.state === "orphaned_closed") throw new ShiftFinalizedError(shiftId);
|
|
376
|
+
return shift;
|
|
377
|
+
}
|
|
378
|
+
applyCounts(breakdown, counted, computeAll) {
|
|
379
|
+
return breakdown.map((r) => typeof r.toObject === "function" ? r.toObject() : r).map((row) => {
|
|
380
|
+
const expected = computeAll ? computeExpected(row) : row.expectedAmount;
|
|
381
|
+
const newCounted = counted[row.method] ?? row.countedAmount;
|
|
382
|
+
const diff = expected !== null && newCounted !== null && newCounted !== void 0 ? computeDifference(expected, newCounted) : null;
|
|
383
|
+
return {
|
|
384
|
+
...row,
|
|
385
|
+
expectedAmount: expected,
|
|
386
|
+
countedAmount: newCounted ?? null,
|
|
387
|
+
difference: diff
|
|
388
|
+
};
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
async publishEvent(name, payload) {
|
|
392
|
+
if (!this.eventTransport) return;
|
|
393
|
+
try {
|
|
394
|
+
await this.eventTransport.publish(createPosEvent(name, payload));
|
|
395
|
+
} catch (err) {
|
|
396
|
+
this.logger.error(`[pos] event transport failed for ${name}`, err);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
//#endregion
|
|
401
|
+
export { ShiftRepository };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { blindCloseBody, closeBody, forceCloseBody, objectIdString, openShiftBody, pauseBody, recordCashMovementBody, resumeBody } from "./shift.mjs";
|
|
2
|
+
export { blindCloseBody, closeBody, forceCloseBody, objectIdString, openShiftBody, pauseBody, recordCashMovementBody, resumeBody };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { blindCloseBody, closeBody, forceCloseBody, objectIdString, openShiftBody, pauseBody, recordCashMovementBody, resumeBody } from "./shift.mjs";
|
|
2
|
+
export { blindCloseBody, closeBody, forceCloseBody, objectIdString, openShiftBody, pauseBody, recordCashMovementBody, resumeBody };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
//#region src/schemas/shift.d.ts
|
|
4
|
+
declare const objectIdString: z.ZodString;
|
|
5
|
+
declare const openShiftBody: z.ZodObject<{
|
|
6
|
+
registerId: z.ZodString;
|
|
7
|
+
businessDate: z.ZodUnion<readonly [z.ZodISODateTime, z.ZodISODate]>;
|
|
8
|
+
openingCashierId: z.ZodString;
|
|
9
|
+
openingCashierName: z.ZodString;
|
|
10
|
+
openingCash: z.ZodNumber;
|
|
11
|
+
notes: z.ZodOptional<z.ZodString>;
|
|
12
|
+
}, z.core.$strip>;
|
|
13
|
+
declare const recordCashMovementBody: z.ZodObject<{
|
|
14
|
+
type: z.ZodEnum<{
|
|
15
|
+
in: "in";
|
|
16
|
+
out: "out";
|
|
17
|
+
}>;
|
|
18
|
+
amount: z.ZodNumber;
|
|
19
|
+
reasonCode: z.ZodEnum<{
|
|
20
|
+
safe_drop: "safe_drop";
|
|
21
|
+
petty_cash: "petty_cash";
|
|
22
|
+
owner_withdrawal: "owner_withdrawal";
|
|
23
|
+
correction: "correction";
|
|
24
|
+
bank_deposit: "bank_deposit";
|
|
25
|
+
till_top_up: "till_top_up";
|
|
26
|
+
other: "other";
|
|
27
|
+
}>;
|
|
28
|
+
note: z.ZodDefault<z.ZodString>;
|
|
29
|
+
cashierId: z.ZodString;
|
|
30
|
+
cashierName: z.ZodString;
|
|
31
|
+
timestamp: z.ZodOptional<z.ZodUnion<readonly [z.ZodISODateTime, z.ZodISODate]>>;
|
|
32
|
+
}, z.core.$strip>;
|
|
33
|
+
declare const blindCloseBody: z.ZodObject<{
|
|
34
|
+
countedByMethod: z.ZodRecord<z.ZodEnum<{
|
|
35
|
+
cash: "cash";
|
|
36
|
+
card: "card";
|
|
37
|
+
mfs: "mfs";
|
|
38
|
+
bank_transfer: "bank_transfer";
|
|
39
|
+
}>, z.ZodNumber>;
|
|
40
|
+
closingCashierId: z.ZodString;
|
|
41
|
+
closingCashierName: z.ZodString;
|
|
42
|
+
notes: z.ZodOptional<z.ZodString>;
|
|
43
|
+
}, z.core.$strip>;
|
|
44
|
+
declare const closeBody: z.ZodObject<{
|
|
45
|
+
countedByMethod: z.ZodOptional<z.ZodRecord<z.ZodEnum<{
|
|
46
|
+
cash: "cash";
|
|
47
|
+
card: "card";
|
|
48
|
+
mfs: "mfs";
|
|
49
|
+
bank_transfer: "bank_transfer";
|
|
50
|
+
}>, z.ZodNumber>>;
|
|
51
|
+
varianceOverride: z.ZodOptional<z.ZodObject<{
|
|
52
|
+
overriddenBy: z.ZodString;
|
|
53
|
+
reason: z.ZodString;
|
|
54
|
+
}, z.core.$strip>>;
|
|
55
|
+
closedBy: z.ZodEnum<{
|
|
56
|
+
cashier: "cashier";
|
|
57
|
+
manager: "manager";
|
|
58
|
+
system_auto: "system_auto";
|
|
59
|
+
}>;
|
|
60
|
+
}, z.core.$strip>;
|
|
61
|
+
declare const pauseBody: z.ZodObject<{}, z.core.$strict>;
|
|
62
|
+
declare const resumeBody: z.ZodObject<{}, z.core.$strict>;
|
|
63
|
+
declare const forceCloseBody: z.ZodObject<{
|
|
64
|
+
reason: z.ZodOptional<z.ZodString>;
|
|
65
|
+
}, z.core.$strict>;
|
|
66
|
+
//#endregion
|
|
67
|
+
export { blindCloseBody, closeBody, forceCloseBody, objectIdString, openShiftBody, pauseBody, recordCashMovementBody, resumeBody };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { CASH_MOVEMENT_REASON_CODES } from "../domain/enums/cash-movement-reason.enum.mjs";
|
|
2
|
+
import { CLOSED_BY_VALUES } from "../domain/enums/closed-by.enum.mjs";
|
|
3
|
+
import { SHIFT_PAYMENT_METHODS } from "../domain/enums/payment-method.enum.mjs";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
//#region src/schemas/shift.ts
|
|
6
|
+
/**
|
|
7
|
+
* Zod v4 body / query schemas for the Shift resource.
|
|
8
|
+
*
|
|
9
|
+
* Hosts wiring `@classytic/pos` into arc 2.11 import these from
|
|
10
|
+
* `@classytic/pos/schemas` and pass them to `defineResource({ customSchemas })`.
|
|
11
|
+
*
|
|
12
|
+
* import { openShiftBody, blindCloseBody, closeBody } from '@classytic/pos/schemas';
|
|
13
|
+
*/
|
|
14
|
+
const objectIdString = z.string().regex(/^[a-f0-9]{24}$/i, "invalid ObjectId");
|
|
15
|
+
const isoDate = z.union([z.iso.datetime(), z.iso.date()]);
|
|
16
|
+
const openShiftBody = z.object({
|
|
17
|
+
registerId: z.string().min(1),
|
|
18
|
+
businessDate: isoDate,
|
|
19
|
+
openingCashierId: z.string().min(1),
|
|
20
|
+
openingCashierName: z.string().min(1),
|
|
21
|
+
openingCash: z.number().min(0),
|
|
22
|
+
notes: z.string().optional()
|
|
23
|
+
});
|
|
24
|
+
const recordCashMovementBody = z.object({
|
|
25
|
+
type: z.enum(["in", "out"]),
|
|
26
|
+
amount: z.number().positive(),
|
|
27
|
+
reasonCode: z.enum(CASH_MOVEMENT_REASON_CODES),
|
|
28
|
+
note: z.string().default(""),
|
|
29
|
+
cashierId: z.string().min(1),
|
|
30
|
+
cashierName: z.string().min(1),
|
|
31
|
+
timestamp: isoDate.optional()
|
|
32
|
+
});
|
|
33
|
+
const countedByMethodSchema = z.record(z.enum(SHIFT_PAYMENT_METHODS), z.number().min(0));
|
|
34
|
+
const blindCloseBody = z.object({
|
|
35
|
+
countedByMethod: countedByMethodSchema,
|
|
36
|
+
closingCashierId: z.string().min(1),
|
|
37
|
+
closingCashierName: z.string().min(1),
|
|
38
|
+
notes: z.string().optional()
|
|
39
|
+
});
|
|
40
|
+
const closeBody = z.object({
|
|
41
|
+
countedByMethod: countedByMethodSchema.optional(),
|
|
42
|
+
varianceOverride: z.object({
|
|
43
|
+
overriddenBy: z.string().min(1),
|
|
44
|
+
reason: z.string().min(3)
|
|
45
|
+
}).optional(),
|
|
46
|
+
closedBy: z.enum(CLOSED_BY_VALUES)
|
|
47
|
+
});
|
|
48
|
+
const pauseBody = z.object({}).strict();
|
|
49
|
+
const resumeBody = z.object({}).strict();
|
|
50
|
+
const forceCloseBody = z.object({ reason: z.string().optional() }).strict();
|
|
51
|
+
//#endregion
|
|
52
|
+
export { blindCloseBody, closeBody, forceCloseBody, objectIdString, openShiftBody, pauseBody, recordCashMovementBody, resumeBody };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ShiftPolicy } from "../domain/value-objects/shift-policy.vo.mjs";
|
|
2
|
+
import { OpenShiftInput } from "../repositories/shift.repository.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/testing/fixtures.d.ts
|
|
5
|
+
declare const TEST_ORG_ID: string;
|
|
6
|
+
declare function makePolicy(overrides?: Partial<ShiftPolicy>): ShiftPolicy;
|
|
7
|
+
declare function makeOpenShiftInput(overrides?: Partial<OpenShiftInput>): OpenShiftInput;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { TEST_ORG_ID, makeOpenShiftInput, makePolicy };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { CASH_MOVEMENT_REASON_CODES } from "../domain/enums/cash-movement-reason.enum.mjs";
|
|
2
|
+
import { SHIFT_PAYMENT_METHODS } from "../domain/enums/payment-method.enum.mjs";
|
|
3
|
+
import { Types } from "mongoose";
|
|
4
|
+
//#region src/testing/fixtures.ts
|
|
5
|
+
/**
|
|
6
|
+
* Test fixtures — `make<Entity>()` builders with `Partial<T>` overrides.
|
|
7
|
+
* Importable from `@classytic/pos/testing` so host integration tests reuse
|
|
8
|
+
* the same shapes the package's own tests use.
|
|
9
|
+
*/
|
|
10
|
+
const TEST_ORG_ID = new Types.ObjectId().toString();
|
|
11
|
+
function makePolicy(overrides = {}) {
|
|
12
|
+
return {
|
|
13
|
+
requiredOpeningFloat: null,
|
|
14
|
+
blindCloseRequired: false,
|
|
15
|
+
varianceThresholdAbs: 100,
|
|
16
|
+
varianceThresholdPct: .5,
|
|
17
|
+
managerOverrideRequired: true,
|
|
18
|
+
allowHandover: true,
|
|
19
|
+
requireReasonCode: true,
|
|
20
|
+
allowedReasonCodes: [...CASH_MOVEMENT_REASON_CODES],
|
|
21
|
+
allowedPaymentMethods: [...SHIFT_PAYMENT_METHODS],
|
|
22
|
+
...overrides
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function makeOpenShiftInput(overrides = {}) {
|
|
26
|
+
return {
|
|
27
|
+
registerId: "register-1",
|
|
28
|
+
businessDate: /* @__PURE__ */ new Date("2026-04-25T00:00:00Z"),
|
|
29
|
+
openingCashierId: "cashier-1",
|
|
30
|
+
openingCashierName: "Cashier One",
|
|
31
|
+
openingCash: 1e3,
|
|
32
|
+
...overrides
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
export { TEST_ORG_ID, makeOpenShiftInput, makePolicy };
|