@classytic/pos 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +10 -350
  2. package/dist/commands/index.d.mts +2 -0
  3. package/dist/commands/index.mjs +1 -0
  4. package/dist/commands/pos-commands.d.mts +230 -0
  5. package/dist/commands/pos-commands.mjs +357 -0
  6. package/dist/domain/enums/cash-movement-reason.enum.d.mts +3 -4
  7. package/dist/domain/enums/closed-by.enum.d.mts +3 -4
  8. package/dist/domain/enums/payment-method.enum.d.mts +6 -7
  9. package/dist/domain/enums/payment-method.enum.mjs +2 -2
  10. package/dist/domain/enums/shift-state.enum.d.mts +7 -8
  11. package/dist/domain/errors/pos.errors.d.mts +82 -34
  12. package/dist/domain/errors/pos.errors.mjs +108 -23
  13. package/dist/domain/index.d.mts +11 -3
  14. package/dist/domain/index.mjs +10 -3
  15. package/dist/domain/ports/common.d.mts +2 -3
  16. package/dist/domain/ports/ledger.bridge.d.mts +6 -7
  17. package/dist/domain/ports/notification.bridge.d.mts +5 -6
  18. package/dist/domain/ports/policy.bridge.d.mts +2 -3
  19. package/dist/domain/sale/discount.d.mts +62 -0
  20. package/dist/domain/sale/discount.mjs +58 -0
  21. package/dist/domain/sale/price-override.d.mts +51 -0
  22. package/dist/domain/sale/price-override.mjs +51 -0
  23. package/dist/domain/sale/quick-cash.d.mts +10 -0
  24. package/dist/domain/sale/quick-cash.mjs +27 -0
  25. package/dist/domain/sale/service-line.d.mts +7 -0
  26. package/dist/domain/sale/service-line.mjs +10 -0
  27. package/dist/domain/sale/tender.d.mts +256 -0
  28. package/dist/domain/sale/tender.mjs +242 -0
  29. package/dist/domain/shift/shift-decisions.d.mts +51 -0
  30. package/dist/domain/shift/shift-decisions.mjs +93 -0
  31. package/dist/domain/shift/shift-report.d.mts +127 -0
  32. package/dist/domain/shift/shift-report.mjs +95 -0
  33. package/dist/domain/shift/shift.types.d.mts +107 -0
  34. package/dist/domain/state-machines/shift.fsm.d.mts +6 -7
  35. package/dist/domain/value-objects/cash-movement.vo.d.mts +7 -3
  36. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -5
  37. package/dist/domain/value-objects/shift-policy.vo.d.mts +12 -13
  38. package/dist/domain/value-objects/shift-policy.vo.mjs +13 -7
  39. package/dist/engine/capability.errors.d.mts +23 -0
  40. package/dist/engine/capability.errors.mjs +28 -0
  41. package/dist/engine/define-pos.d.mts +2 -3
  42. package/dist/engine/define-pos.mjs +14 -3
  43. package/dist/engine/engine-types.d.mts +24 -9
  44. package/dist/engine/index.d.mts +2 -1
  45. package/dist/engine/index.mjs +2 -1
  46. package/dist/events/event-catalog.d.mts +18 -14
  47. package/dist/events/event-catalog.mjs +10 -4
  48. package/dist/events/event-constants.d.mts +3 -4
  49. package/dist/events/event-payloads.d.mts +9 -10
  50. package/dist/events/helpers.d.mts +6 -3
  51. package/dist/events/helpers.mjs +12 -2
  52. package/dist/events/in-process-bus.d.mts +3 -4
  53. package/dist/events/index.mjs +1 -1
  54. package/dist/grant/till-grant.d.mts +50 -0
  55. package/dist/grant/till-grant.mjs +47 -0
  56. package/dist/index.d.mts +15 -4
  57. package/dist/index.mjs +13 -4
  58. package/dist/models/create-models.d.mts +10 -6
  59. package/dist/models/create-models.mjs +16 -3
  60. package/dist/models/register.model.d.mts +7 -6
  61. package/dist/models/shift-sale-dedupe.model.d.mts +4 -5
  62. package/dist/models/shift.model.d.mts +4 -111
  63. package/dist/models/shift.model.mjs +27 -3
  64. package/dist/models/till-grant.model.d.mts +19 -0
  65. package/dist/models/till-grant.model.mjs +52 -0
  66. package/dist/repositories/register.repository.d.mts +3 -4
  67. package/dist/repositories/shift.repository.d.mts +90 -60
  68. package/dist/repositories/shift.repository.mjs +323 -150
  69. package/dist/repositories/till-grant.repository.d.mts +22 -0
  70. package/dist/repositories/till-grant.repository.mjs +41 -0
  71. package/dist/schemas/index.mjs +1 -2
  72. package/dist/schemas/shift.d.mts +9 -10
  73. package/dist/testing/fixtures.d.mts +4 -5
  74. package/dist/testing/index.mjs +1 -2
  75. package/package.json +50 -19
@@ -0,0 +1,256 @@
1
+ //#region src/domain/sale/tender.d.ts
2
+ /**
3
+ * TENDER — three amounts, never one:
4
+ *
5
+ * tendered — what the customer handed over
6
+ * applied — what settled the sale
7
+ * change — tendered − applied, handed back
8
+ *
9
+ * **Only APPLIED may reach `order.tenders[].amount`, the shift accrual and
10
+ * revenue.** Persisting the raw tendered amount tells the drawer to expect the
11
+ * ৳500 note against a ৳470 sale — a guaranteed per-sale shortage at close (and a
12
+ * 403 refusal once a variance threshold is set) while revenue records 470 and
13
+ * nothing records the 30 handed back. `tendered` and `change` persist alongside
14
+ * in `PosTenderSummary`, so a receipt reprint and a Z-report share one record.
15
+ *
16
+ * ## Split-tender allocation
17
+ *
18
+ * Change comes only out of a cash drawer — you cannot hand change back on a
19
+ * card, MFS wallet or bank transfer (that is a separate, reversible refund).
20
+ * So:
21
+ *
22
+ * 1. legs that CANNOT give change (`changeCapable: false`) apply in FULL, in
23
+ * submission order. If they alone exceed the due beyond the rounding
24
+ * tolerance, REFUSE (`change-not-possible`) — the alternative is booking a
25
+ * card over-charge as drawer cash;
26
+ * 2. the remaining due goes to cash legs front to back, so change settles on
27
+ * the LAST cash leg.
28
+ *
29
+ * Invariant asserted below: `sum(applied) === appliedMinor` and
30
+ * `sum(change) === changeMinor` — no minor unit invented or lost.
31
+ *
32
+ * **Settlement is a property of the METHOD, never the channel.** `channel ===
33
+ * 'pos'` treats a customer-typed bKash TrxID — an unverified claim — as money in
34
+ * hand. Each method DECLARES how it settles and the resolved value persists
35
+ * (`legs[].settlement`, rolled up as `settlesImmediately`) for the attach side.
36
+ */
37
+ /**
38
+ * When a tender total may differ from the amount due. Each exception is DECLARED, never inferred:
39
+ * a deposit, an account charge and over-tendering have the same arithmetic and different accounting.
40
+ */
41
+ export interface TenderPolicy {
42
+ /** Allow a sale with NO tender (a deferred invoice / account charge). Default false. */
43
+ allowUnpaid?: boolean | undefined;
44
+ /** Allow tenders summing to LESS than due (an authorized deposit). Default false. */
45
+ allowPartial?: boolean | undefined;
46
+ /**
47
+ * Allow tenders summing to MORE than due — cash change. Default true. Only the applied share is
48
+ * money ({@link allocateTender}); over-tender on a leg that cannot give change is refused regardless.
49
+ */
50
+ allowOvertender?: boolean | undefined;
51
+ /** Cash-rounding tolerance in MINOR units, both directions. Default 0. */
52
+ toleranceMinor?: number | undefined;
53
+ }
54
+ /**
55
+ * How a tender becomes money the business can count.
56
+ *
57
+ * - `cash-immediate` — the money is in the drawer NOW, and the only kind that can
58
+ * give change.
59
+ * - `acquirer-captured` — a card the acquirer approved and captured at the counter
60
+ * (its approval code is the reference): settled at the sale into the acquirer's
61
+ * clearing account, never the drawer.
62
+ * - `manual-confirmed` — a human must confirm it against evidence (a wallet
63
+ * statement, a bank line). The cashier's word is the claim, not the confirmation.
64
+ * - `provider-verified` — a payment provider will verify it out of band
65
+ * (`@classytic/revenue` intent → verify → webhook). The drawer learns about it
66
+ * from the gateway subscriber, not from the sale.
67
+ */
68
+ export type TenderSettlement = 'cash-immediate' | 'acquirer-captured' | 'manual-confirmed' | 'provider-verified';
69
+ /** What a deployment declares about one tender method. */
70
+ export interface ResolvedTenderMethod {
71
+ /**
72
+ * Is this method accepted at all? `false` (or a null resolver result) REFUSES
73
+ * the sale.
74
+ *
75
+ * Refuse, never accept: an unknown method (`csah`, `visa-mc`) would land the money in the wrong
76
+ * drawer bucket silently.
77
+ */
78
+ allowed: boolean;
79
+ /**
80
+ * Must the tender carry a `reference` (TrxID, approval code, last 4)?
81
+ *
82
+ * The evidence half of the tender. A non-cash tender with no reference cannot
83
+ * be reconciled against anything later — it is a cashier's assertion that money
84
+ * arrived, indistinguishable from a stolen sale.
85
+ */
86
+ referenceRequired?: boolean | undefined;
87
+ /** How this method settles. Default `manual-confirmed` — never assume immediate. */
88
+ settlement?: TenderSettlement | undefined;
89
+ /** Provider key for `provider-verified` methods (revenue's registry name). */
90
+ provider?: string | undefined;
91
+ /**
92
+ * Can change be handed back on this method? Defaults to
93
+ * `settlement === 'cash-immediate'`.
94
+ *
95
+ * A SEPARATE flag from settlement because they answer different questions: a
96
+ * cash-on-delivery leg settles immediately at the door and still cannot make
97
+ * change at the counter, and a hypothetical prepaid house wallet could give
98
+ * change without being cash. Deriving one from the other is right by default and
99
+ * must remain overridable.
100
+ */
101
+ changeCapable?: boolean | undefined;
102
+ /** What a till shows the cashier for this method. Absent ⇒ the method code. */
103
+ label?: string | undefined;
104
+ }
105
+ /**
106
+ * method string → policy. SYNC on purpose: it is a table lookup, and an async
107
+ * resolver would put an `await` inside the per-leg loop of every sale for no
108
+ * gain. A deployment whose method table lives in a database caches it at boot.
109
+ *
110
+ * Returning `null`/`undefined` means "not in my vocabulary" and is treated as a
111
+ * refusal.
112
+ */
113
+ export type TenderMethodResolver = (method: string) => ResolvedTenderMethod | null | undefined;
114
+ /**
115
+ * The DEFAULT policy: cash is immediate and needs no reference; everything else
116
+ * is `manual-confirmed` and MUST carry a reference.
117
+ *
118
+ * Deliberately permissive about the VOCABULARY and strict about the EVIDENCE. A
119
+ * spine upgrade that refused every method string a live till already sends would
120
+ * stop a shop from selling — a far worse outcome than the defect being fixed. So
121
+ * the default accepts any non-empty method, and the thing it will not accept is a
122
+ * non-cash tender with nothing to reconcile it against.
123
+ *
124
+ * A deployment that wants its vocabulary CLOSED declares it with
125
+ * `createTenderMethodResolver` and gets a 400 on an unknown method.
126
+ */
127
+ export declare const DEFAULT_TENDER_METHOD_RESOLVER: TenderMethodResolver;
128
+ /** One method's declaration in a host-supplied table. */
129
+ export type TenderMethodDeclaration = Omit<ResolvedTenderMethod, 'allowed'>;
130
+ export interface TenderMethodTableOptions {
131
+ /**
132
+ * What to do with a method the table does not name. `'refuse'` by default —
133
+ * declaring a table IS declaring the vocabulary, so anything outside it is a
134
+ * client bug or a typo, and both are better as a 400 than as cash.
135
+ */
136
+ unknownMethod?: 'refuse' | 'manual-confirmed' | undefined;
137
+ }
138
+ /**
139
+ * Build a resolver from a declared table — the shape a deployment should use.
140
+ *
141
+ * ```ts
142
+ * resolveTenderMethod: createTenderMethodResolver({
143
+ * cash: { settlement: 'cash-immediate', changeCapable: true },
144
+ * card: { settlement: 'manual-confirmed', referenceRequired: true },
145
+ * bkash: { settlement: 'provider-verified', provider: 'bkash', referenceRequired: true },
146
+ * })
147
+ * ```
148
+ *
149
+ * Keys are matched case-insensitively on the trimmed method string. This is DATA
150
+ * — adding a method is a config change in the host, never an edit here.
151
+ */
152
+ export declare function createTenderMethodResolver(table: Readonly<Record<string, TenderMethodDeclaration>>, opts?: TenderMethodTableOptions): TenderMethodResolver;
153
+ /** One tender a till may offer on a shift, with the evidence the sale will demand. */
154
+ export interface TillTenderMethod {
155
+ /** The code the tender leg sends (`card`, `bkash`). */
156
+ method: string;
157
+ label: string;
158
+ settlement: TenderSettlement;
159
+ referenceRequired: boolean;
160
+ changeCapable: boolean;
161
+ /** The shift breakdown row the sale accrues to (`bkash` → `mobile_money`). */
162
+ drawerMethod: string;
163
+ }
164
+ /**
165
+ * The tenders a till offers on one shift: each declared method whose drawer row the shift allows.
166
+ * A declared method with no drawer row is left out — selling it would be refused at accrual.
167
+ * Declaration order is kept, so the till's buttons do not reshuffle.
168
+ */
169
+ export declare function tillTenderMethods(table: Readonly<Record<string, TenderMethodDeclaration>>, allowedDrawerMethods: readonly string[], drawerMethodOf: (method: string) => string | null | undefined): TillTenderMethod[];
170
+ /** A tender row as it arrives from the wire, already converted to minor units. */
171
+ export interface TenderLegInput {
172
+ method: string;
173
+ /** MINOR units — the caller owns major→minor so the currency factor lives in one place. */
174
+ tenderedMinor: number;
175
+ reference?: string | undefined;
176
+ }
177
+ /** A tender row that passed method policy: accepted, and with its evidence present. */
178
+ export interface ValidatedTenderLeg extends TenderLegInput {
179
+ settlement: TenderSettlement;
180
+ changeCapable: boolean;
181
+ provider?: string | undefined;
182
+ }
183
+ /** One leg after the three amounts are known. */
184
+ export interface AllocatedTenderLeg extends ValidatedTenderLeg {
185
+ /** What this leg settled of the sale. This — and only this — is drawer/revenue money. */
186
+ appliedMinor: number;
187
+ /** What was handed back on this leg. Non-zero only on a change-capable leg. */
188
+ changeMinor: number;
189
+ }
190
+ /**
191
+ * The persisted tender fact for a sale.
192
+ *
193
+ * `legs[i]` corresponds POSITIONALLY to `order.tenders[i]`, whose `amount` is the
194
+ * leg's APPLIED share. The reference is not duplicated here — it lives on the
195
+ * tender row, and two copies of one fact is how the previous tender shape rotted.
196
+ */
197
+ export interface PosTenderSummary {
198
+ currency: string;
199
+ dueMinor: number;
200
+ tenderedMinor: number;
201
+ appliedMinor: number;
202
+ changeMinor: number;
203
+ /**
204
+ * True only when EVERY leg that settled money is `cash-immediate`.
205
+ *
206
+ * The field `arc-order`'s revenue attach should read instead of inferring
207
+ * settlement from `channel === 'pos'`. False means at least one leg is a claim
208
+ * awaiting confirmation, so the order must NOT be marked fully charged.
209
+ */
210
+ settlesImmediately: boolean;
211
+ legs: Array<{
212
+ method: string;
213
+ tenderedMinor: number;
214
+ appliedMinor: number;
215
+ changeMinor: number;
216
+ settlement: TenderSettlement;
217
+ changeCapable: boolean;
218
+ provider?: string | undefined;
219
+ }>;
220
+ }
221
+ export interface TenderAllocation {
222
+ legs: AllocatedTenderLeg[];
223
+ tenderedMinor: number;
224
+ appliedMinor: number;
225
+ changeMinor: number;
226
+ settlesImmediately: boolean;
227
+ }
228
+ /**
229
+ * Apply method policy to every leg, BEFORE anything is held or written.
230
+ *
231
+ * Runs first in the pipeline deliberately: a refusal here must not leave a stock
232
+ * reservation or a promo hold outstanding, and validating the tender needs no I/O.
233
+ *
234
+ * Throws `TenderMethodRefusedError` naming which requirement failed — a cashier
235
+ * being told "bKash needs the TrxID" can fix the sale; "invalid payment" cannot.
236
+ */
237
+ export declare function validateTenderLegs(legs: readonly TenderLegInput[], resolve: TenderMethodResolver): ValidatedTenderLeg[];
238
+ /**
239
+ * Split the tender into applied + change. See the allocation rule at the top.
240
+ *
241
+ * `toleranceMinor` is the deployment's declared cash-rounding tolerance. Within
242
+ * it, a non-change-capable overage is treated as APPLIED (the customer paid the
243
+ * rounded-up amount by card and nothing is handed back) rather than as change on
244
+ * a card, which is not a thing that can happen at a counter.
245
+ */
246
+ export declare function allocateTender(legs: readonly ValidatedTenderLeg[], dueMinor: number, toleranceMinor?: number): TenderAllocation;
247
+ /** The persisted summary for `order.metadata.tender`. */
248
+ export declare function tenderSummary(allocation: TenderAllocation, dueMinor: number, currency: string): PosTenderSummary;
249
+ /**
250
+ * Refuse a tender that does not settle the sale, unless the deployment declared
251
+ * that exception. Every branch names ONE shape — a mismatch is never interpreted,
252
+ * because a deposit, an account charge and over-tendering produce identical
253
+ * arithmetic and require completely different accounting.
254
+ */
255
+ export declare function assertTenderSettles(dueMinor: number, tenderedMinor: number, tenderCount: number, policy: TenderPolicy): void;
256
+ //#endregion
@@ -0,0 +1,242 @@
1
+ import { TenderMethodRefusedError, TenderMismatchError } from "../errors/pos.errors.mjs";
2
+ //#region src/domain/sale/tender.ts
3
+ /**
4
+ * TENDER — three amounts, never one:
5
+ *
6
+ * tendered — what the customer handed over
7
+ * applied — what settled the sale
8
+ * change — tendered − applied, handed back
9
+ *
10
+ * **Only APPLIED may reach `order.tenders[].amount`, the shift accrual and
11
+ * revenue.** Persisting the raw tendered amount tells the drawer to expect the
12
+ * ৳500 note against a ৳470 sale — a guaranteed per-sale shortage at close (and a
13
+ * 403 refusal once a variance threshold is set) while revenue records 470 and
14
+ * nothing records the 30 handed back. `tendered` and `change` persist alongside
15
+ * in `PosTenderSummary`, so a receipt reprint and a Z-report share one record.
16
+ *
17
+ * ## Split-tender allocation
18
+ *
19
+ * Change comes only out of a cash drawer — you cannot hand change back on a
20
+ * card, MFS wallet or bank transfer (that is a separate, reversible refund).
21
+ * So:
22
+ *
23
+ * 1. legs that CANNOT give change (`changeCapable: false`) apply in FULL, in
24
+ * submission order. If they alone exceed the due beyond the rounding
25
+ * tolerance, REFUSE (`change-not-possible`) — the alternative is booking a
26
+ * card over-charge as drawer cash;
27
+ * 2. the remaining due goes to cash legs front to back, so change settles on
28
+ * the LAST cash leg.
29
+ *
30
+ * Invariant asserted below: `sum(applied) === appliedMinor` and
31
+ * `sum(change) === changeMinor` — no minor unit invented or lost.
32
+ *
33
+ * **Settlement is a property of the METHOD, never the channel.** `channel ===
34
+ * 'pos'` treats a customer-typed bKash TrxID — an unverified claim — as money in
35
+ * hand. Each method DECLARES how it settles and the resolved value persists
36
+ * (`legs[].settlement`, rolled up as `settlesImmediately`) for the attach side.
37
+ */
38
+ /**
39
+ * The DEFAULT policy: cash is immediate and needs no reference; everything else
40
+ * is `manual-confirmed` and MUST carry a reference.
41
+ *
42
+ * Deliberately permissive about the VOCABULARY and strict about the EVIDENCE. A
43
+ * spine upgrade that refused every method string a live till already sends would
44
+ * stop a shop from selling — a far worse outcome than the defect being fixed. So
45
+ * the default accepts any non-empty method, and the thing it will not accept is a
46
+ * non-cash tender with nothing to reconcile it against.
47
+ *
48
+ * A deployment that wants its vocabulary CLOSED declares it with
49
+ * `createTenderMethodResolver` and gets a 400 on an unknown method.
50
+ */
51
+ const DEFAULT_TENDER_METHOD_RESOLVER = (method) => {
52
+ const key = method.trim().toLowerCase();
53
+ if (key.length === 0) return { allowed: false };
54
+ if (key === "cash") return {
55
+ allowed: true,
56
+ referenceRequired: false,
57
+ settlement: "cash-immediate",
58
+ changeCapable: true
59
+ };
60
+ return {
61
+ allowed: true,
62
+ referenceRequired: true,
63
+ settlement: "manual-confirmed"
64
+ };
65
+ };
66
+ /**
67
+ * Build a resolver from a declared table — the shape a deployment should use.
68
+ *
69
+ * ```ts
70
+ * resolveTenderMethod: createTenderMethodResolver({
71
+ * cash: { settlement: 'cash-immediate', changeCapable: true },
72
+ * card: { settlement: 'manual-confirmed', referenceRequired: true },
73
+ * bkash: { settlement: 'provider-verified', provider: 'bkash', referenceRequired: true },
74
+ * })
75
+ * ```
76
+ *
77
+ * Keys are matched case-insensitively on the trimmed method string. This is DATA
78
+ * — adding a method is a config change in the host, never an edit here.
79
+ */
80
+ function createTenderMethodResolver(table, opts = {}) {
81
+ const normalized = /* @__PURE__ */ new Map();
82
+ for (const [key, decl] of Object.entries(table)) normalized.set(key.trim().toLowerCase(), decl);
83
+ const unknown = opts.unknownMethod ?? "refuse";
84
+ return (method) => {
85
+ const decl = normalized.get(method.trim().toLowerCase());
86
+ if (decl) return {
87
+ allowed: true,
88
+ ...decl
89
+ };
90
+ if (unknown === "manual-confirmed") return {
91
+ allowed: true,
92
+ referenceRequired: true,
93
+ settlement: "manual-confirmed"
94
+ };
95
+ return { allowed: false };
96
+ };
97
+ }
98
+ /**
99
+ * The tenders a till offers on one shift: each declared method whose drawer row the shift allows.
100
+ * A declared method with no drawer row is left out — selling it would be refused at accrual.
101
+ * Declaration order is kept, so the till's buttons do not reshuffle.
102
+ */
103
+ function tillTenderMethods(table, allowedDrawerMethods, drawerMethodOf) {
104
+ const allowed = new Set(allowedDrawerMethods);
105
+ const offered = [];
106
+ for (const [method, decl] of Object.entries(table)) {
107
+ const drawerMethod = drawerMethodOf(method);
108
+ if (!drawerMethod || !allowed.has(drawerMethod)) continue;
109
+ const settlement = decl.settlement ?? "manual-confirmed";
110
+ offered.push({
111
+ method,
112
+ label: decl.label ?? method,
113
+ settlement,
114
+ referenceRequired: decl.referenceRequired === true,
115
+ changeCapable: decl.changeCapable ?? settlement === "cash-immediate",
116
+ drawerMethod
117
+ });
118
+ }
119
+ return offered;
120
+ }
121
+ /**
122
+ * Apply method policy to every leg, BEFORE anything is held or written.
123
+ *
124
+ * Runs first in the pipeline deliberately: a refusal here must not leave a stock
125
+ * reservation or a promo hold outstanding, and validating the tender needs no I/O.
126
+ *
127
+ * Throws `TenderMethodRefusedError` naming which requirement failed — a cashier
128
+ * being told "bKash needs the TrxID" can fix the sale; "invalid payment" cannot.
129
+ */
130
+ function validateTenderLegs(legs, resolve) {
131
+ return legs.map((leg) => {
132
+ const resolved = resolve(leg.method);
133
+ if (!resolved?.allowed) throw new TenderMethodRefusedError(leg.method, "not-accepted");
134
+ if (!Number.isFinite(leg.tenderedMinor) || leg.tenderedMinor <= 0) throw new TenderMethodRefusedError(leg.method, "zero-amount");
135
+ const settlement = resolved.settlement ?? "manual-confirmed";
136
+ if (resolved.referenceRequired === true && (leg.reference ?? "").trim().length === 0) throw new TenderMethodRefusedError(leg.method, "reference-required");
137
+ return {
138
+ ...leg,
139
+ settlement,
140
+ changeCapable: resolved.changeCapable ?? settlement === "cash-immediate",
141
+ ...resolved.provider !== void 0 ? { provider: resolved.provider } : {}
142
+ };
143
+ });
144
+ }
145
+ /**
146
+ * Split the tender into applied + change. See the allocation rule at the top.
147
+ *
148
+ * `toleranceMinor` is the deployment's declared cash-rounding tolerance. Within
149
+ * it, a non-change-capable overage is treated as APPLIED (the customer paid the
150
+ * rounded-up amount by card and nothing is handed back) rather than as change on
151
+ * a card, which is not a thing that can happen at a counter.
152
+ */
153
+ function allocateTender(legs, dueMinor, toleranceMinor = 0) {
154
+ const tenderedMinor = legs.reduce((sum, l) => sum + l.tenderedMinor, 0);
155
+ const tolerance = Math.max(0, toleranceMinor);
156
+ let appliedMinor = Math.min(tenderedMinor, Math.max(0, dueMinor));
157
+ const nonChangeMinor = legs.filter((l) => !l.changeCapable).reduce((sum, l) => sum + l.tenderedMinor, 0);
158
+ if (nonChangeMinor > appliedMinor) {
159
+ const over = nonChangeMinor - appliedMinor;
160
+ if (over > tolerance) {
161
+ const offender = legs.find((l) => !l.changeCapable);
162
+ throw new TenderMethodRefusedError(offender.method, "change-not-possible", {
163
+ overMinor: over,
164
+ dueMinor
165
+ });
166
+ }
167
+ appliedMinor = nonChangeMinor;
168
+ }
169
+ const changeMinor = tenderedMinor - appliedMinor;
170
+ let remaining = appliedMinor;
171
+ const take = (leg) => {
172
+ const applied = Math.min(leg.tenderedMinor, remaining);
173
+ remaining -= applied;
174
+ return {
175
+ ...leg,
176
+ appliedMinor: applied,
177
+ changeMinor: leg.tenderedMinor - applied
178
+ };
179
+ };
180
+ const byIndex = /* @__PURE__ */ new Map();
181
+ legs.forEach((leg, i) => {
182
+ if (!leg.changeCapable) byIndex.set(i, take(leg));
183
+ });
184
+ legs.forEach((leg, i) => {
185
+ if (leg.changeCapable) byIndex.set(i, take(leg));
186
+ });
187
+ const allocated = legs.map((_, i) => byIndex.get(i));
188
+ const appliedSum = allocated.reduce((s, l) => s + l.appliedMinor, 0);
189
+ const changeSum = allocated.reduce((s, l) => s + l.changeMinor, 0);
190
+ if (appliedSum !== appliedMinor || changeSum !== changeMinor) throw new Error(`POS tender allocation drift: applied ${appliedSum}≠${appliedMinor}, change ${changeSum}≠${changeMinor}`);
191
+ return {
192
+ legs: allocated,
193
+ tenderedMinor,
194
+ appliedMinor,
195
+ changeMinor,
196
+ settlesImmediately: allocated.some((l) => l.appliedMinor > 0) && allocated.every((l) => l.appliedMinor === 0 || l.settlement === "cash-immediate" || l.settlement === "acquirer-captured")
197
+ };
198
+ }
199
+ /** The persisted summary for `order.metadata.tender`. */
200
+ function tenderSummary(allocation, dueMinor, currency) {
201
+ return {
202
+ currency,
203
+ dueMinor,
204
+ tenderedMinor: allocation.tenderedMinor,
205
+ appliedMinor: allocation.appliedMinor,
206
+ changeMinor: allocation.changeMinor,
207
+ settlesImmediately: allocation.settlesImmediately,
208
+ legs: allocation.legs.map((l) => ({
209
+ method: l.method,
210
+ tenderedMinor: l.tenderedMinor,
211
+ appliedMinor: l.appliedMinor,
212
+ changeMinor: l.changeMinor,
213
+ settlement: l.settlement,
214
+ changeCapable: l.changeCapable,
215
+ ...l.provider !== void 0 ? { provider: l.provider } : {}
216
+ }))
217
+ };
218
+ }
219
+ /**
220
+ * Refuse a tender that does not settle the sale, unless the deployment declared
221
+ * that exception. Every branch names ONE shape — a mismatch is never interpreted,
222
+ * because a deposit, an account charge and over-tendering produce identical
223
+ * arithmetic and require completely different accounting.
224
+ */
225
+ function assertTenderSettles(dueMinor, tenderedMinor, tenderCount, policy) {
226
+ if (dueMinor === 0) return;
227
+ if (tenderCount === 0) {
228
+ if (policy.allowUnpaid === true) return;
229
+ throw new TenderMismatchError(dueMinor, 0, "no tender supplied");
230
+ }
231
+ const tolerance = Math.max(0, policy.toleranceMinor ?? 0);
232
+ const delta = tenderedMinor - dueMinor;
233
+ if (Math.abs(delta) <= tolerance) return;
234
+ if (delta < 0) {
235
+ if (policy.allowPartial === true) return;
236
+ throw new TenderMismatchError(dueMinor, tenderedMinor, `underpaid by ${-delta}`);
237
+ }
238
+ if (policy.allowOvertender !== false) return;
239
+ throw new TenderMismatchError(dueMinor, tenderedMinor, `overpaid by ${delta}`);
240
+ }
241
+ //#endregion
242
+ export { DEFAULT_TENDER_METHOD_RESOLVER, allocateTender, assertTenderSettles, createTenderMethodResolver, tenderSummary, tillTenderMethods, validateTenderLegs };
@@ -0,0 +1,51 @@
1
+ import { ShiftState } from "../enums/shift-state.enum.mjs";
2
+ import { PaymentBreakdown } from "../value-objects/payment-breakdown.vo.mjs";
3
+ import { ShiftPolicy } from "../value-objects/shift-policy.vo.mjs";
4
+ import { PaymentMethodKind } from "@classytic/primitives/payment-method-kind";
5
+ //#region src/domain/shift/shift-decisions.d.ts
6
+ /** The fields of a breakdown row these decisions read and write. */
7
+ export type CountableRow = Pick<PaymentBreakdown, 'method' | 'openingAmount' | 'salesAmount' | 'refundAmount' | 'cashInAmount' | 'cashOutAmount' | 'expectedAmount' | 'countedAmount' | 'difference'> & {
8
+ methodKind: PaymentMethodKind;
9
+ };
10
+ /** The drawer row: keyed on the payment KIND, never on the method's code (`'efectivo'`, `'cash_register_3'`, …). */
11
+ export declare function isCashRow(row: {
12
+ methodKind: string;
13
+ }): boolean;
14
+ /** A new shift's breakdown: one row per allowed method; the opening float sits on the cash row. */
15
+ export declare function seedBreakdown(policy: Pick<ShiftPolicy, 'allowedPaymentMethods' | 'paymentMethodKinds'>, openingCash: number): PaymentBreakdown[];
16
+ /**
17
+ * Apply a count: each counted method gets its counted amount and the difference from expected.
18
+ * `computeAll` recomputes every row's expected amount from its movements (a close); otherwise the
19
+ * stored expected amount stands.
20
+ */
21
+ export declare function applyCounts<T extends CountableRow>(rows: readonly T[], counted: Readonly<Partial<Record<string, number>>>, computeAll: boolean): T[];
22
+ export interface ShiftCloseDecision<T extends CountableRow> {
23
+ breakdown: T[];
24
+ expectedCash: number | null;
25
+ countedCash: number | null;
26
+ cashDifference: number | null;
27
+ /** True when the cash difference is beyond the policy's threshold (and an override was supplied). */
28
+ varianceExceeded: boolean;
29
+ }
30
+ /**
31
+ * May this shift close, and with what figures? Refuses an illegal transition, a close straight from
32
+ * `open` with no count (that would close a drawer nobody counted), and a variance beyond the
33
+ * threshold without an override when the policy requires one.
34
+ *
35
+ * A terminal shift is the caller's concern — closing it again is an idempotent outcome there.
36
+ */
37
+ export declare function decideShiftClose<T extends CountableRow>(input: {
38
+ shiftId: string;
39
+ state: ShiftState;
40
+ breakdown: readonly T[];
41
+ policy: Pick<ShiftPolicy, 'varianceThresholdAbs' | 'varianceThresholdPct' | 'managerOverrideRequired'>;
42
+ countedByMethod?: Readonly<Partial<Record<string, number>>> | undefined;
43
+ hasVarianceOverride: boolean;
44
+ }): ShiftCloseDecision<T>;
45
+ /** A cashier's blind count: only from `open`; records the count and its differences, decides nothing more. */
46
+ export declare function decideBlindClose<T extends CountableRow>(input: {
47
+ state: ShiftState;
48
+ breakdown: readonly T[];
49
+ countedByMethod: Readonly<Partial<Record<string, number>>>;
50
+ }): Omit<ShiftCloseDecision<T>, 'varianceExceeded'>;
51
+ //#endregion
@@ -0,0 +1,93 @@
1
+ import { resolveMethodKind } from "../enums/payment-method.enum.mjs";
2
+ import { IllegalShiftTransitionError, ShiftCountsRequiredError, VarianceExceededError } from "../errors/pos.errors.mjs";
3
+ import { canTransition } from "../state-machines/shift.fsm.mjs";
4
+ import { computeDifference, computeExpected } from "../value-objects/payment-breakdown.vo.mjs";
5
+ import { isWithinVarianceThreshold } from "../value-objects/shift-policy.vo.mjs";
6
+ import { PAYMENT_METHOD_KIND } from "@classytic/primitives/payment-method-kind";
7
+ //#region src/domain/shift/shift-decisions.ts
8
+ /**
9
+ * SHIFT DECISIONS — pure: what a shift looks like when it opens, what a count does to its
10
+ * breakdown, and whether a close may proceed. The repository persists them (CAS, ledger, events);
11
+ * a device till decides through the same functions, so both close the same drawer the same way.
12
+ */
13
+ /** The drawer row: keyed on the payment KIND, never on the method's code (`'efectivo'`, `'cash_register_3'`, …). */
14
+ function isCashRow(row) {
15
+ return row.methodKind === PAYMENT_METHOD_KIND.CASH;
16
+ }
17
+ /** A new shift's breakdown: one row per allowed method; the opening float sits on the cash row. */
18
+ function seedBreakdown(policy, openingCash) {
19
+ return policy.allowedPaymentMethods.map((method) => {
20
+ const methodKind = resolveMethodKind(method, policy.paymentMethodKinds?.[method]);
21
+ return {
22
+ method,
23
+ methodKind,
24
+ openingAmount: methodKind === PAYMENT_METHOD_KIND.CASH ? openingCash : 0,
25
+ salesAmount: 0,
26
+ taxAmount: 0,
27
+ refundAmount: 0,
28
+ refundTaxAmount: 0,
29
+ cashInAmount: 0,
30
+ cashOutAmount: 0,
31
+ expectedAmount: null,
32
+ countedAmount: null,
33
+ difference: null
34
+ };
35
+ });
36
+ }
37
+ /**
38
+ * Apply a count: each counted method gets its counted amount and the difference from expected.
39
+ * `computeAll` recomputes every row's expected amount from its movements (a close); otherwise the
40
+ * stored expected amount stands.
41
+ */
42
+ function applyCounts(rows, counted, computeAll) {
43
+ return rows.map((row) => {
44
+ const expected = computeAll ? computeExpected(row) : row.expectedAmount;
45
+ const nextCounted = counted[row.method] ?? row.countedAmount;
46
+ const difference = expected !== null && nextCounted !== null && nextCounted !== void 0 ? computeDifference(expected, nextCounted) : null;
47
+ return {
48
+ ...row,
49
+ expectedAmount: expected,
50
+ countedAmount: nextCounted ?? null,
51
+ difference
52
+ };
53
+ });
54
+ }
55
+ /**
56
+ * May this shift close, and with what figures? Refuses an illegal transition, a close straight from
57
+ * `open` with no count (that would close a drawer nobody counted), and a variance beyond the
58
+ * threshold without an override when the policy requires one.
59
+ *
60
+ * A terminal shift is the caller's concern — closing it again is an idempotent outcome there.
61
+ */
62
+ function decideShiftClose(input) {
63
+ if (!canTransition(input.state, "close")) throw new IllegalShiftTransitionError(input.state, "close");
64
+ if (input.state === "open" && input.countedByMethod === void 0) throw new ShiftCountsRequiredError(input.shiftId);
65
+ const breakdown = input.countedByMethod ? applyCounts(input.breakdown, input.countedByMethod, true) : [...input.breakdown];
66
+ const cash = breakdown.find(isCashRow);
67
+ let varianceExceeded = false;
68
+ if (cash?.expectedAmount != null && cash.countedAmount != null) {
69
+ varianceExceeded = !isWithinVarianceThreshold(cash.difference ?? 0, cash.expectedAmount, input.policy);
70
+ if (varianceExceeded && input.policy.managerOverrideRequired && !input.hasVarianceOverride) throw new VarianceExceededError(cash.difference ?? 0, cash.expectedAmount);
71
+ }
72
+ return {
73
+ breakdown,
74
+ expectedCash: cash?.expectedAmount ?? null,
75
+ countedCash: cash?.countedAmount ?? null,
76
+ cashDifference: cash?.difference ?? null,
77
+ varianceExceeded
78
+ };
79
+ }
80
+ /** A cashier's blind count: only from `open`; records the count and its differences, decides nothing more. */
81
+ function decideBlindClose(input) {
82
+ if (input.state !== "open") throw new IllegalShiftTransitionError(input.state, "blindClose");
83
+ const breakdown = applyCounts(input.breakdown, input.countedByMethod, true);
84
+ const cash = breakdown.find(isCashRow);
85
+ return {
86
+ breakdown,
87
+ expectedCash: cash?.expectedAmount ?? null,
88
+ countedCash: cash?.countedAmount ?? null,
89
+ cashDifference: cash?.difference ?? null
90
+ };
91
+ }
92
+ //#endregion
93
+ export { applyCounts, decideBlindClose, decideShiftClose, isCashRow, seedBreakdown };