@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.
Files changed (60) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +152 -0
  4. package/dist/domain/enums/cash-movement-reason.enum.d.mts +12 -0
  5. package/dist/domain/enums/cash-movement-reason.enum.mjs +19 -0
  6. package/dist/domain/enums/closed-by.enum.d.mts +13 -0
  7. package/dist/domain/enums/closed-by.enum.mjs +16 -0
  8. package/dist/domain/enums/payment-method.enum.d.mts +14 -0
  9. package/dist/domain/enums/payment-method.enum.mjs +18 -0
  10. package/dist/domain/enums/shift-state.enum.d.mts +26 -0
  11. package/dist/domain/enums/shift-state.enum.mjs +39 -0
  12. package/dist/domain/errors/pos.errors.d.mts +37 -0
  13. package/dist/domain/errors/pos.errors.mjs +64 -0
  14. package/dist/domain/index.d.mts +14 -0
  15. package/dist/domain/index.mjs +9 -0
  16. package/dist/domain/ports/common.d.mts +9 -0
  17. package/dist/domain/ports/ledger.bridge.d.mts +18 -0
  18. package/dist/domain/ports/notification.bridge.d.mts +12 -0
  19. package/dist/domain/ports/policy.bridge.d.mts +13 -0
  20. package/dist/domain/state-machines/shift.fsm.d.mts +14 -0
  21. package/dist/domain/state-machines/shift.fsm.mjs +41 -0
  22. package/dist/domain/value-objects/cash-movement.vo.d.mts +19 -0
  23. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +24 -0
  24. package/dist/domain/value-objects/payment-breakdown.vo.mjs +11 -0
  25. package/dist/domain/value-objects/shift-policy.vo.d.mts +32 -0
  26. package/dist/domain/value-objects/shift-policy.vo.mjs +14 -0
  27. package/dist/engine/create-pos.d.mts +6 -0
  28. package/dist/engine/create-pos.mjs +65 -0
  29. package/dist/engine/engine-types.d.mts +73 -0
  30. package/dist/engine/index.d.mts +3 -0
  31. package/dist/engine/index.mjs +2 -0
  32. package/dist/events/event-constants.d.mts +21 -0
  33. package/dist/events/event-constants.mjs +20 -0
  34. package/dist/events/event-payloads.d.mts +49 -0
  35. package/dist/events/helpers.d.mts +6 -0
  36. package/dist/events/helpers.mjs +12 -0
  37. package/dist/events/in-process-bus.d.mts +19 -0
  38. package/dist/events/in-process-bus.mjs +38 -0
  39. package/dist/events/index.d.mts +5 -0
  40. package/dist/events/index.mjs +4 -0
  41. package/dist/index.d.mts +23 -0
  42. package/dist/index.mjs +15 -0
  43. package/dist/models/create-models.d.mts +9 -0
  44. package/dist/models/create-models.mjs +20 -0
  45. package/dist/models/inject-tenant.d.mts +2 -0
  46. package/dist/models/inject-tenant.mjs +48 -0
  47. package/dist/models/shift.model.d.mts +68 -0
  48. package/dist/models/shift.model.mjs +267 -0
  49. package/dist/repositories/repo-options.mjs +20 -0
  50. package/dist/repositories/shift.repository.d.mts +153 -0
  51. package/dist/repositories/shift.repository.mjs +401 -0
  52. package/dist/schemas/index.d.mts +2 -0
  53. package/dist/schemas/index.mjs +2 -0
  54. package/dist/schemas/shift.d.mts +67 -0
  55. package/dist/schemas/shift.mjs +52 -0
  56. package/dist/testing/fixtures.d.mts +9 -0
  57. package/dist/testing/fixtures.mjs +36 -0
  58. package/dist/testing/index.d.mts +2 -0
  59. package/dist/testing/index.mjs +2 -0
  60. package/package.json +110 -0
@@ -0,0 +1,267 @@
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 { SHIFT_STATES } from "../domain/enums/shift-state.enum.mjs";
5
+ import { injectTenantField } from "./inject-tenant.mjs";
6
+ import { Schema } from "mongoose";
7
+ //#region src/models/shift.model.ts
8
+ const cashMovementSchema = new Schema({
9
+ type: {
10
+ type: String,
11
+ enum: ["in", "out"],
12
+ required: true
13
+ },
14
+ amount: {
15
+ type: Number,
16
+ required: true,
17
+ min: 0
18
+ },
19
+ reasonCode: {
20
+ type: String,
21
+ enum: CASH_MOVEMENT_REASON_CODES,
22
+ required: true
23
+ },
24
+ note: {
25
+ type: String,
26
+ default: ""
27
+ },
28
+ cashierId: {
29
+ type: String,
30
+ required: true
31
+ },
32
+ cashierName: {
33
+ type: String,
34
+ required: true
35
+ },
36
+ timestamp: {
37
+ type: Date,
38
+ default: () => /* @__PURE__ */ new Date()
39
+ }
40
+ }, { _id: false });
41
+ const paymentBreakdownSchema = new Schema({
42
+ method: {
43
+ type: String,
44
+ enum: SHIFT_PAYMENT_METHODS,
45
+ required: true
46
+ },
47
+ openingAmount: {
48
+ type: Number,
49
+ default: 0,
50
+ min: 0
51
+ },
52
+ salesAmount: {
53
+ type: Number,
54
+ default: 0,
55
+ min: 0
56
+ },
57
+ taxAmount: {
58
+ type: Number,
59
+ default: 0,
60
+ min: 0
61
+ },
62
+ refundAmount: {
63
+ type: Number,
64
+ default: 0,
65
+ min: 0
66
+ },
67
+ refundTaxAmount: {
68
+ type: Number,
69
+ default: 0,
70
+ min: 0
71
+ },
72
+ cashInAmount: {
73
+ type: Number,
74
+ default: 0,
75
+ min: 0
76
+ },
77
+ cashOutAmount: {
78
+ type: Number,
79
+ default: 0,
80
+ min: 0
81
+ },
82
+ expectedAmount: {
83
+ type: Number,
84
+ default: null
85
+ },
86
+ countedAmount: {
87
+ type: Number,
88
+ default: null
89
+ },
90
+ difference: {
91
+ type: Number,
92
+ default: null
93
+ }
94
+ }, { _id: false });
95
+ /**
96
+ * Build the Shift schema. Caller (createPosModels) wires the tenant adapter
97
+ * + register on the connection with the resolved collection name.
98
+ *
99
+ * The schema does NOT call `connection.model(...)` — that's the registrar's
100
+ * job so model-collision detection (PACKAGE_RULES §21) lives in one place.
101
+ */
102
+ function buildShiftSchema(options) {
103
+ const schema = new Schema({
104
+ registerId: {
105
+ type: String,
106
+ required: true
107
+ },
108
+ businessDate: {
109
+ type: Date,
110
+ required: true
111
+ },
112
+ state: {
113
+ type: String,
114
+ enum: SHIFT_STATES,
115
+ default: "open",
116
+ required: true
117
+ },
118
+ openingCashierId: {
119
+ type: String,
120
+ required: true
121
+ },
122
+ openingCashierName: {
123
+ type: String,
124
+ required: true
125
+ },
126
+ endingCashierId: {
127
+ type: String,
128
+ default: null
129
+ },
130
+ endingCashierName: {
131
+ type: String,
132
+ default: null
133
+ },
134
+ closingCashierId: {
135
+ type: String,
136
+ default: null
137
+ },
138
+ closingCashierName: {
139
+ type: String,
140
+ default: null
141
+ },
142
+ teamMemberIds: {
143
+ type: [String],
144
+ default: []
145
+ },
146
+ openedAt: {
147
+ type: Date,
148
+ default: () => /* @__PURE__ */ new Date()
149
+ },
150
+ pausedAt: {
151
+ type: Date,
152
+ default: null
153
+ },
154
+ resumedAt: {
155
+ type: Date,
156
+ default: null
157
+ },
158
+ blindClosedAt: {
159
+ type: Date,
160
+ default: null
161
+ },
162
+ closedAt: {
163
+ type: Date,
164
+ default: null
165
+ },
166
+ openingCash: {
167
+ type: Number,
168
+ default: 0,
169
+ min: 0
170
+ },
171
+ expectedCash: {
172
+ type: Number,
173
+ default: null
174
+ },
175
+ countedCash: {
176
+ type: Number,
177
+ default: null
178
+ },
179
+ cashDifference: {
180
+ type: Number,
181
+ default: null
182
+ },
183
+ paymentBreakdown: {
184
+ type: [paymentBreakdownSchema],
185
+ default: []
186
+ },
187
+ salesCount: {
188
+ type: Number,
189
+ default: 0,
190
+ min: 0
191
+ },
192
+ salesTotal: {
193
+ type: Number,
194
+ default: 0,
195
+ min: 0
196
+ },
197
+ refundCount: {
198
+ type: Number,
199
+ default: 0,
200
+ min: 0
201
+ },
202
+ refundTotal: {
203
+ type: Number,
204
+ default: 0,
205
+ min: 0
206
+ },
207
+ cashMovements: {
208
+ type: [cashMovementSchema],
209
+ default: []
210
+ },
211
+ approvals: {
212
+ type: Schema.Types.Mixed,
213
+ default: null
214
+ },
215
+ policySnapshot: {
216
+ type: Schema.Types.Mixed,
217
+ required: true
218
+ },
219
+ closedBy: {
220
+ type: String,
221
+ enum: CLOSED_BY_VALUES,
222
+ default: null
223
+ },
224
+ notes: {
225
+ type: String,
226
+ default: ""
227
+ },
228
+ journalEntryId: {
229
+ type: String,
230
+ default: null
231
+ }
232
+ }, {
233
+ timestamps: true,
234
+ autoIndex: options.autoIndex
235
+ });
236
+ schema.index({
237
+ registerId: 1,
238
+ state: 1
239
+ }, {
240
+ unique: true,
241
+ partialFilterExpression: { state: { $in: [
242
+ "open",
243
+ "paused",
244
+ "blind_closed"
245
+ ] } },
246
+ name: "uniq_active_shift_per_register"
247
+ });
248
+ schema.index({
249
+ businessDate: 1,
250
+ openedAt: -1
251
+ }, { name: "shifts_by_business_date" });
252
+ schema.index({
253
+ state: 1,
254
+ businessDate: 1
255
+ }, {
256
+ name: "orphan_shift_lookup",
257
+ partialFilterExpression: { state: { $in: [
258
+ "open",
259
+ "paused",
260
+ "blind_closed"
261
+ ] } }
262
+ });
263
+ injectTenantField(schema, options.tenant);
264
+ return schema;
265
+ }
266
+ //#endregion
267
+ export { buildShiftSchema };
@@ -0,0 +1,20 @@
1
+ import { createOptionsExtractor } from "@classytic/mongokit";
2
+ //#region src/repositories/repo-options.ts
3
+ /**
4
+ * Translate a `PosContext` into mongokit `WriteOptions` / `QueryOptions`.
5
+ *
6
+ * Threads `actorId`, `session`, `organizationId` so:
7
+ * - audit hooks see who made the change
8
+ * - transactions span multiple writes (multiTenantPlugin + custom hooks)
9
+ * - tenant policy filter has the right scope
10
+ */
11
+ const extract = createOptionsExtractor([
12
+ "actorId",
13
+ "organizationId",
14
+ "session"
15
+ ]);
16
+ function repoOptionsFromCtx(ctx) {
17
+ return extract(ctx);
18
+ }
19
+ //#endregion
20
+ export { repoOptionsFromCtx };
@@ -0,0 +1,153 @@
1
+ import { ShiftPaymentMethod } from "../domain/enums/payment-method.enum.mjs";
2
+ import { ClosedBy } from "../domain/enums/closed-by.enum.mjs";
3
+ import { CashMovement } from "../domain/value-objects/cash-movement.vo.mjs";
4
+ import { ShiftPolicy } from "../domain/value-objects/shift-policy.vo.mjs";
5
+ import { PosContext } from "../domain/ports/common.mjs";
6
+ import { IShift, ShiftDocument } from "../models/shift.model.mjs";
7
+ import { LedgerBridge } from "../domain/ports/ledger.bridge.mjs";
8
+ import { PolicyBridge } from "../domain/ports/policy.bridge.mjs";
9
+ import { NotificationBridge } from "../domain/ports/notification.bridge.mjs";
10
+ import { PluginType, Repository } from "@classytic/mongokit";
11
+ import { EventTransport } from "@classytic/primitives/events";
12
+ import { Model } from "mongoose";
13
+
14
+ //#region src/repositories/shift.repository.d.ts
15
+ interface OpenShiftInput {
16
+ registerId: string;
17
+ businessDate: Date;
18
+ openingCashierId: string;
19
+ openingCashierName: string;
20
+ openingCash: number;
21
+ /** Optional override for the policy resolver. */
22
+ policy?: ShiftPolicy;
23
+ notes?: string;
24
+ }
25
+ interface RecordCashMovementInput {
26
+ shiftId: string;
27
+ movement: Omit<CashMovement, 'timestamp'> & {
28
+ timestamp?: Date;
29
+ };
30
+ }
31
+ interface BlindCloseInput {
32
+ shiftId: string;
33
+ /** Cashier-counted amounts per method (cash always required; others optional). */
34
+ countedByMethod: Partial<Record<ShiftPaymentMethod, number>>;
35
+ closingCashierId: string;
36
+ closingCashierName: string;
37
+ notes?: string;
38
+ }
39
+ interface CloseShiftInput {
40
+ shiftId: string;
41
+ /** When called after blindClose, host can pass the manager-reconciled counts. */
42
+ countedByMethod?: Partial<Record<ShiftPaymentMethod, number>>;
43
+ /** Manager override row when variance exceeds threshold. */
44
+ varianceOverride?: {
45
+ overriddenBy: string;
46
+ reason: string;
47
+ };
48
+ closedBy: ClosedBy;
49
+ }
50
+ interface IncrementSalesInput {
51
+ shiftId: string;
52
+ method: ShiftPaymentMethod;
53
+ /** Positive minor units (gross, tax-inclusive). */
54
+ amount: number;
55
+ /** Tax portion of `amount` (subset, not additional). Default 0. */
56
+ tax?: number;
57
+ /** Refund = pass true; the tax portion is credited back via refundTaxAmount. */
58
+ refund?: boolean;
59
+ /** Cashier whose order touched the shift — appended to teamMemberIds. */
60
+ cashierId?: string;
61
+ cashierName?: string;
62
+ }
63
+ interface ShiftRepositoryConfig {
64
+ model: Model<IShift>;
65
+ plugins?: PluginType[];
66
+ defaultPolicy: ShiftPolicy;
67
+ ledgerBridge?: LedgerBridge;
68
+ policyBridge?: PolicyBridge;
69
+ notificationBridge?: NotificationBridge;
70
+ eventTransport?: EventTransport;
71
+ logger?: {
72
+ error(message: string, ...args: unknown[]): void;
73
+ };
74
+ }
75
+ declare class ShiftRepository extends Repository<IShift> {
76
+ private readonly defaultPolicy;
77
+ private readonly ledgerBridge?;
78
+ private readonly policyBridge?;
79
+ private readonly notificationBridge?;
80
+ private readonly eventTransport?;
81
+ private readonly logger;
82
+ constructor(config: ShiftRepositoryConfig);
83
+ /**
84
+ * Open a new shift. Throws `ActiveShiftAlreadyOpenError` if one already
85
+ * exists for the (org, register) pair — enforced both by the
86
+ * partial-unique index and a pre-check for a friendlier error.
87
+ */
88
+ open(input: OpenShiftInput, ctx: PosContext): Promise<ShiftDocument>;
89
+ pause(shiftId: string, ctx: PosContext): Promise<ShiftDocument>;
90
+ resume(shiftId: string, ctx: PosContext): Promise<ShiftDocument>;
91
+ recordCashMovement(input: RecordCashMovementInput, ctx: PosContext): Promise<ShiftDocument>;
92
+ /**
93
+ * Atomically increment shift aggregates from an order-create hook in the
94
+ * host. Idempotency is the host's responsibility (don't call twice for
95
+ * the same order). Refunds pass `refund: true`.
96
+ */
97
+ incrementSales(input: IncrementSalesInput, ctx: PosContext): Promise<void>;
98
+ /**
99
+ * Lightspeed-style cashier blind-close — counts are recorded but the
100
+ * variance check is deferred to the manager-driven `close()`.
101
+ */
102
+ blindClose(input: BlindCloseInput, ctx: PosContext): Promise<ShiftDocument>;
103
+ /**
104
+ * Final close — fires the variance gate, the ledger bridge, and the
105
+ * `pos:shift.closed` event in that order. State write happens last; a
106
+ * thrown bridge keeps the shift in its previous state.
107
+ */
108
+ close(input: CloseShiftInput, ctx: PosContext): Promise<ShiftDocument>;
109
+ /**
110
+ * Find shifts in any active state whose `businessDate` is strictly before
111
+ * `asOf`. Used by the EOD cron backstop to identify orphans the cashier
112
+ * never closed. Returns lean docs (read-only); call `forceClose(id, ctx)`
113
+ * for each.
114
+ *
115
+ * Multi-tenant scoping: this is a CROSS-TENANT helper for the host's
116
+ * batch cron — the package's tenant plugin would block it under a single
117
+ * org context, so we bypass it by reading the model directly.
118
+ *
119
+ * @param asOf Cut-off — typically `new Date()` rounded to today's BD-zone
120
+ * midnight. Shifts strictly before this are stale.
121
+ */
122
+ findStaleShifts(asOf: Date): Promise<Array<{
123
+ _id: unknown;
124
+ organizationId: unknown;
125
+ registerId: string;
126
+ state: string;
127
+ businessDate: Date;
128
+ }>>;
129
+ /**
130
+ * Backstop / EOD-cron path. Defaults counts to expected (zero variance)
131
+ * and routes `closedBy: 'system_auto'`. Result is `orphaned_closed` —
132
+ * a flag for manager review.
133
+ */
134
+ forceClose(shiftId: string, ctx: PosContext): Promise<ShiftDocument>;
135
+ /**
136
+ * Build a single-step approved `ApprovalChain` for a manager's variance
137
+ * override. Uses primitives' `createChain` + `applyDecision` rather than
138
+ * a parallel ad-hoc shape (PACKAGE_RULES P7).
139
+ *
140
+ * If a host wants a full multi-step chain (e.g. shift supervisor → store
141
+ * manager), they construct one externally and pass it in via a future
142
+ * `approvals` input on `CloseShiftInput` — but the common single-override
143
+ * case is already covered without the host having to build the chain
144
+ * manually. The persisted field is `approvals` (P7 canonical).
145
+ */
146
+ private buildVarianceApprovalChain;
147
+ private transitionState;
148
+ private requireActive;
149
+ private applyCounts;
150
+ private publishEvent;
151
+ }
152
+ //#endregion
153
+ export { BlindCloseInput, CloseShiftInput, IncrementSalesInput, OpenShiftInput, RecordCashMovementInput, ShiftRepository, ShiftRepositoryConfig };