@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.
Files changed (71) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/commands/index.d.mts +2 -0
  3. package/dist/commands/index.mjs +1 -0
  4. package/dist/commands/pos-commands.d.mts +228 -0
  5. package/dist/commands/pos-commands.mjs +355 -0
  6. package/dist/domain/enums/cash-movement-reason.enum.d.mts +3 -4
  7. package/dist/domain/enums/closed-by.enum.d.mts +3 -4
  8. package/dist/domain/enums/payment-method.enum.d.mts +6 -7
  9. package/dist/domain/enums/shift-state.enum.d.mts +7 -8
  10. package/dist/domain/errors/pos.errors.d.mts +82 -13
  11. package/dist/domain/errors/pos.errors.mjs +111 -1
  12. package/dist/domain/index.d.mts +11 -3
  13. package/dist/domain/index.mjs +10 -3
  14. package/dist/domain/ports/common.d.mts +2 -3
  15. package/dist/domain/ports/ledger.bridge.d.mts +6 -7
  16. package/dist/domain/ports/notification.bridge.d.mts +5 -6
  17. package/dist/domain/ports/policy.bridge.d.mts +2 -3
  18. package/dist/domain/sale/discount.d.mts +62 -0
  19. package/dist/domain/sale/discount.mjs +58 -0
  20. package/dist/domain/sale/price-override.d.mts +51 -0
  21. package/dist/domain/sale/price-override.mjs +51 -0
  22. package/dist/domain/sale/quick-cash.d.mts +10 -0
  23. package/dist/domain/sale/quick-cash.mjs +27 -0
  24. package/dist/domain/sale/service-line.d.mts +7 -0
  25. package/dist/domain/sale/service-line.mjs +10 -0
  26. package/dist/domain/sale/tender.d.mts +256 -0
  27. package/dist/domain/sale/tender.mjs +242 -0
  28. package/dist/domain/shift/shift-decisions.d.mts +52 -0
  29. package/dist/domain/shift/shift-decisions.mjs +93 -0
  30. package/dist/domain/shift/shift-report.d.mts +127 -0
  31. package/dist/domain/shift/shift-report.mjs +95 -0
  32. package/dist/domain/shift/shift.types.d.mts +109 -0
  33. package/dist/domain/state-machines/shift.fsm.d.mts +6 -7
  34. package/dist/domain/value-objects/cash-movement.vo.d.mts +7 -3
  35. package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -5
  36. package/dist/domain/value-objects/shift-policy.vo.d.mts +11 -7
  37. package/dist/domain/value-objects/shift-policy.vo.mjs +12 -1
  38. package/dist/engine/define-pos.d.mts +2 -3
  39. package/dist/engine/define-pos.mjs +13 -2
  40. package/dist/engine/engine-types.d.mts +24 -9
  41. package/dist/engine/index.mjs +1 -2
  42. package/dist/events/event-catalog.d.mts +18 -14
  43. package/dist/events/event-catalog.mjs +10 -4
  44. package/dist/events/event-constants.d.mts +3 -4
  45. package/dist/events/event-payloads.d.mts +9 -10
  46. package/dist/events/helpers.d.mts +6 -3
  47. package/dist/events/helpers.mjs +12 -2
  48. package/dist/events/in-process-bus.d.mts +3 -4
  49. package/dist/events/index.mjs +1 -1
  50. package/dist/grant/till-grant.d.mts +50 -0
  51. package/dist/grant/till-grant.mjs +47 -0
  52. package/dist/index.d.mts +14 -4
  53. package/dist/index.mjs +12 -4
  54. package/dist/models/create-models.d.mts +10 -6
  55. package/dist/models/create-models.mjs +16 -3
  56. package/dist/models/register.model.d.mts +7 -6
  57. package/dist/models/shift-sale-dedupe.model.d.mts +4 -5
  58. package/dist/models/shift.model.d.mts +4 -111
  59. package/dist/models/shift.model.mjs +26 -2
  60. package/dist/models/till-grant.model.d.mts +19 -0
  61. package/dist/models/till-grant.model.mjs +52 -0
  62. package/dist/repositories/register.repository.d.mts +3 -4
  63. package/dist/repositories/shift.repository.d.mts +77 -30
  64. package/dist/repositories/shift.repository.mjs +307 -108
  65. package/dist/repositories/till-grant.repository.d.mts +22 -0
  66. package/dist/repositories/till-grant.repository.mjs +41 -0
  67. package/dist/schemas/index.mjs +1 -2
  68. package/dist/schemas/shift.d.mts +9 -10
  69. package/dist/testing/fixtures.d.mts +4 -5
  70. package/dist/testing/index.mjs +1 -2
  71. package/package.json +50 -19
@@ -50,6 +50,19 @@ var ActiveShiftAlreadyOpenError = class extends PosError {
50
50
  this.name = "ActiveShiftAlreadyOpenError";
51
51
  }
52
52
  };
53
+ /**
54
+ * Several registers are active at the branch and the caller named none — picking one would
55
+ * ring the sale into another cashier's drawer. `meta.registers` lists the choices.
56
+ */
57
+ var RegisterRequiredError = class extends PosError {
58
+ status = 409;
59
+ meta;
60
+ constructor(registers) {
61
+ super("POS_REGISTER_REQUIRED", `${registers.length} registers are open at this branch — say which register this till is`);
62
+ this.name = "RegisterRequiredError";
63
+ this.meta = { registers };
64
+ }
65
+ };
53
66
  var VarianceExceededError = class extends PosError {
54
67
  status = 409;
55
68
  difference;
@@ -96,6 +109,14 @@ var ShiftCountsRequiredError = class extends PosError {
96
109
  this.name = "ShiftCountsRequiredError";
97
110
  }
98
111
  };
112
+ /** A cash movement under a key already booked for a DIFFERENT movement — two commands, one key. */
113
+ var CashMovementKeyReusedError = class extends PosError {
114
+ status = 409;
115
+ constructor(movementKey) {
116
+ super("IDEMPOTENCY_KEY_REUSED", `movementKey '${movementKey}' was already used for a different cash movement`);
117
+ this.name = "CashMovementKeyReusedError";
118
+ }
119
+ };
99
120
  var CashMovementInvalidError = class extends PosError {
100
121
  status = 422;
101
122
  constructor(reason) {
@@ -103,6 +124,29 @@ var CashMovementInvalidError = class extends PosError {
103
124
  this.name = "CashMovementInvalidError";
104
125
  }
105
126
  };
127
+ /**
128
+ * A cash-out the drawer cannot cover, refused by the write's own filter — so two
129
+ * concurrent cash-outs that each fit alone cannot both land.
130
+ */
131
+ var CashOutExceedsDrawerError = class extends PosError {
132
+ status = 409;
133
+ amount;
134
+ drawer;
135
+ constructor(amount, drawer) {
136
+ super("CASH_OUT_EXCEEDS_DRAWER", `cash-out ${amount} exceeds drawer balance ${drawer}`);
137
+ this.name = "CashOutExceedsDrawerError";
138
+ this.amount = amount;
139
+ this.drawer = drawer;
140
+ }
141
+ };
142
+ /** A branch policy that allows no cash-movement reason code — `[]` is refused; any-code is `'*'`. */
143
+ var ReasonCodePolicyInvalidError = class extends PosError {
144
+ status = 409;
145
+ constructor() {
146
+ super("REASON_CODE_POLICY_EMPTY", "allowedReasonCodes is empty — list the codes this branch allows, or '*' for any");
147
+ this.name = "ReasonCodePolicyInvalidError";
148
+ }
149
+ };
106
150
  var PosCapabilityError = class extends Error {
107
151
  code = "POS_CAPABILITY";
108
152
  status = 422;
@@ -123,5 +167,71 @@ var PosCapabilityError = class extends Error {
123
167
  this.indeterminate = indeterminate;
124
168
  }
125
169
  };
170
+ /** The tender does not settle the sale, and the deployment's `TenderPolicy` does not permit that shape. */
171
+ var TenderMismatchError = class extends PosError {
172
+ status = 400;
173
+ dueMinor;
174
+ tenderedMinor;
175
+ details;
176
+ constructor(dueMinor, tenderedMinor, detail) {
177
+ super("pos.tender.mismatch", `Tender does not settle the sale: ${tenderedMinor} tendered against ${dueMinor} due (${detail}). Declare the exception on the deployment tender policy if this is intended.`);
178
+ this.name = "TenderMismatchError";
179
+ this.dueMinor = dueMinor;
180
+ this.tenderedMinor = tenderedMinor;
181
+ this.details = {
182
+ dueMinor,
183
+ tenderedMinor
184
+ };
185
+ }
186
+ };
187
+ /** A line price differs from the catalog without authority (403) or without a reason (400). */
188
+ var PriceOverrideRefusedError = class extends PosError {
189
+ status;
190
+ constructor(detail, status = 403) {
191
+ super("pos.price_override.refused", `Price override refused: ${detail}. The catalog price stands unless an authorized actor supplies a reason.`);
192
+ this.name = "PriceOverrideRefusedError";
193
+ this.status = status;
194
+ }
195
+ };
196
+ /** An order-level discount was refused: 400 for a missing reason, 403 for every policy denial. */
197
+ var OrderDiscountRefusedError = class extends PosError {
198
+ status;
199
+ missing;
200
+ details;
201
+ constructor(missing, detail, details = {}) {
202
+ super("pos.order_discount.refused", `Order discount refused (${missing}): ${detail}. An order-level discount requires declared authority, a recorded reason and a declared limit.`);
203
+ this.name = "OrderDiscountRefusedError";
204
+ this.missing = missing;
205
+ this.status = missing === "reason" ? 400 : 403;
206
+ this.details = {
207
+ missing,
208
+ ...details
209
+ };
210
+ }
211
+ };
212
+ const TENDER_REFUSAL_DETAIL = {
213
+ "not-accepted": "This payment method is not accepted at this till",
214
+ "reference-required": "This payment method needs a reference (transaction id, approval code or last 4 digits)",
215
+ "zero-amount": "A payment row must be for more than zero",
216
+ "change-not-possible": "More was tendered on this method than is owed, and change cannot be handed back on it — take the excess in cash or correct the split"
217
+ };
218
+ /** A tender row was refused by the method policy. 400 — every case is one the till can correct. */
219
+ var TenderMethodRefusedError = class extends PosError {
220
+ status = 400;
221
+ method;
222
+ reason;
223
+ details;
224
+ constructor(method, reason, details = {}) {
225
+ super("pos.tender.method_refused", `${TENDER_REFUSAL_DETAIL[reason]} (method: "${method}")`);
226
+ this.name = "TenderMethodRefusedError";
227
+ this.method = method;
228
+ this.reason = reason;
229
+ this.details = {
230
+ method,
231
+ reason,
232
+ ...details
233
+ };
234
+ }
235
+ };
126
236
  //#endregion
127
- export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError };
237
+ export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, OrderDiscountRefusedError, PosCapabilityError, PosError, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, TenderMethodRefusedError, TenderMismatchError, UnmanagedSessionError, VarianceExceededError };
@@ -5,10 +5,18 @@ import { CLOSED_BY_VALUES, ClosedBy } from "./enums/closed-by.enum.mjs";
5
5
  import { SHIFT_VERBS, ShiftVerb, allowedVerbs, canTransition, nextState } from "./state-machines/shift.fsm.mjs";
6
6
  import { CashMovement } from "./value-objects/cash-movement.vo.mjs";
7
7
  import { PaymentBreakdown, computeDifference, computeExpected } from "./value-objects/payment-breakdown.vo.mjs";
8
- import { ShiftPolicy, defaultShiftPolicy, isWithinVarianceThreshold } from "./value-objects/shift-policy.vo.mjs";
9
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError } from "./errors/pos.errors.mjs";
8
+ import { ShiftPolicy, defaultShiftPolicy, isReasonCodeAllowed, isWithinVarianceThreshold } from "./value-objects/shift-policy.vo.mjs";
9
+ import { ActiveRegister, ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, OrderDiscountRefusal, OrderDiscountRefusedError, PosCapabilityError, PosError, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, TenderMethodRefusal, TenderMethodRefusedError, TenderMismatchError, UnmanagedSessionError, VarianceExceededError } from "./errors/pos.errors.mjs";
10
+ import { AllocatedTenderLeg, DEFAULT_TENDER_METHOD_RESOLVER, PosTenderSummary, ResolvedTenderMethod, TenderAllocation, TenderLegInput, TenderMethodDeclaration, TenderMethodResolver, TenderMethodTableOptions, TenderPolicy, TenderSettlement, TillTenderMethod, ValidatedTenderLeg, allocateTender, assertTenderSettles, createTenderMethodResolver, tenderSummary, tillTenderMethods, validateTenderLegs } from "./sale/tender.mjs";
11
+ import { DecideOrderDiscountInput, OrderDiscountDecision, OrderDiscountLimits, PosOrderDiscountRecord, decideOrderDiscount, discountCeilingMinor } from "./sale/discount.mjs";
12
+ import { DecideLinePriceInput, LinePriceDecision, PRICE_OVERRIDE_NOTE_MAX, PRICE_OVERRIDE_REASONS, PRICE_OVERRIDE_REASONS_NEEDING_NOTE, PosPriceOverrideRecord, PriceOverrideReason, decideLinePrice, isPriceOverrideReason } from "./sale/price-override.mjs";
13
+ import { serviceSku, serviceSlug } from "./sale/service-line.mjs";
14
+ import { quickCashAmounts } from "./sale/quick-cash.mjs";
15
+ import { CountableRow, ShiftCloseDecision, applyCounts, decideBlindClose, decideShiftClose, isCashRow, seedBreakdown } from "./shift/shift-decisions.mjs";
16
+ import { ReportOrder, ReportShift, ShiftReport, buildShiftReport } from "./shift/shift-report.mjs";
17
+ import { IShift, PendingLedgerPost, PendingLedgerPostTrigger, ShiftRecord } from "./shift/shift.types.mjs";
10
18
  import { PosContext } from "./ports/common.mjs";
11
19
  import { LedgerBridge, ShiftClosePosting, shiftCloseIdempotencyKey } from "./ports/ledger.bridge.mjs";
12
20
  import { PolicyBridge } from "./ports/policy.bridge.mjs";
13
21
  import { NotificationBridge } from "./ports/notification.bridge.mjs";
14
- export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementReasonCode, ClosedBy, DEFAULT_METHOD_KINDS, FINAL_SHIFT_STATES, IllegalShiftTransitionError, type LedgerBridge, type NotificationBridge, PAYMENT_METHOD_KIND_VALUES, PaymentBreakdown, type PolicyBridge, PosCapabilityError, type PosContext, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, type ShiftClosePosting, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, ShiftPaymentMethod, ShiftPolicy, ShiftState, ShiftVerb, UnmanagedSessionError, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, defaultShiftPolicy, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, resolveMethodKind, shiftCloseIdempotencyKey };
22
+ export { ACTIVE_SHIFT_STATES, ActiveRegister, ActiveShiftAlreadyOpenError, AllocatedTenderLeg, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementKeyReusedError, CashMovementReasonCode, CashOutExceedsDrawerError, ClosedBy, CountableRow, DEFAULT_METHOD_KINDS, DEFAULT_TENDER_METHOD_RESOLVER, DecideLinePriceInput, DecideOrderDiscountInput, FINAL_SHIFT_STATES, type IShift, IllegalShiftTransitionError, type LedgerBridge, LinePriceDecision, type NotificationBridge, OrderDiscountDecision, OrderDiscountLimits, OrderDiscountRefusal, OrderDiscountRefusedError, PAYMENT_METHOD_KIND_VALUES, PRICE_OVERRIDE_NOTE_MAX, PRICE_OVERRIDE_REASONS, PRICE_OVERRIDE_REASONS_NEEDING_NOTE, PaymentBreakdown, type PendingLedgerPost, type PendingLedgerPostTrigger, type PolicyBridge, PosCapabilityError, type PosContext, PosError, PosOrderDiscountRecord, PosPriceOverrideRecord, PosTenderSummary, PriceOverrideReason, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, ReportOrder, ReportShift, ResolvedTenderMethod, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftCloseDecision, type ShiftClosePosting, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, ShiftPaymentMethod, ShiftPolicy, type ShiftRecord, ShiftReport, ShiftState, ShiftVerb, TenderAllocation, TenderLegInput, TenderMethodDeclaration, TenderMethodRefusal, TenderMethodRefusedError, TenderMethodResolver, TenderMethodTableOptions, TenderMismatchError, TenderPolicy, TenderSettlement, TillTenderMethod, UnmanagedSessionError, ValidatedTenderLeg, VarianceExceededError, allocateTender, allowedVerbs, applyCounts, assertTenderSettles, buildShiftReport, canTransition, computeDifference, computeExpected, createTenderMethodResolver, decideBlindClose, decideLinePrice, decideOrderDiscount, decideShiftClose, defaultShiftPolicy, discountCeilingMinor, isActiveShiftState, isCashRow, isFinalShiftState, isPriceOverrideReason, isReasonCodeAllowed, isWithinVarianceThreshold, nextState, quickCashAmounts, resolveMethodKind, seedBreakdown, serviceSku, serviceSlug, shiftCloseIdempotencyKey, tenderSummary, tillTenderMethods, validateTenderLegs };
@@ -1,4 +1,4 @@
1
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError } from "./errors/pos.errors.mjs";
1
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, OrderDiscountRefusedError, PosCapabilityError, PosError, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, TenderMethodRefusedError, TenderMismatchError, UnmanagedSessionError, VarianceExceededError } from "./errors/pos.errors.mjs";
2
2
  import { CASH_MOVEMENT_REASON_CODES } from "./enums/cash-movement-reason.enum.mjs";
3
3
  import { CLOSED_BY_VALUES } from "./enums/closed-by.enum.mjs";
4
4
  import { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS, resolveMethodKind } from "./enums/payment-method.enum.mjs";
@@ -6,5 +6,12 @@ import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, isActiveShiftSta
6
6
  import { shiftCloseIdempotencyKey } from "./ports/ledger.bridge.mjs";
7
7
  import { SHIFT_VERBS, allowedVerbs, canTransition, nextState } from "./state-machines/shift.fsm.mjs";
8
8
  import { computeDifference, computeExpected } from "./value-objects/payment-breakdown.vo.mjs";
9
- import { defaultShiftPolicy, isWithinVarianceThreshold } from "./value-objects/shift-policy.vo.mjs";
10
- export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, DEFAULT_METHOD_KINDS, FINAL_SHIFT_STATES, IllegalShiftTransitionError, PAYMENT_METHOD_KIND_VALUES, PosCapabilityError, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, defaultShiftPolicy, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState, resolveMethodKind, shiftCloseIdempotencyKey };
9
+ import { defaultShiftPolicy, isReasonCodeAllowed, isWithinVarianceThreshold } from "./value-objects/shift-policy.vo.mjs";
10
+ import { applyCounts, decideBlindClose, decideShiftClose, isCashRow, seedBreakdown } from "./shift/shift-decisions.mjs";
11
+ import { DEFAULT_TENDER_METHOD_RESOLVER, allocateTender, assertTenderSettles, createTenderMethodResolver, tenderSummary, tillTenderMethods, validateTenderLegs } from "./sale/tender.mjs";
12
+ import { decideOrderDiscount, discountCeilingMinor } from "./sale/discount.mjs";
13
+ import { PRICE_OVERRIDE_NOTE_MAX, PRICE_OVERRIDE_REASONS, PRICE_OVERRIDE_REASONS_NEEDING_NOTE, decideLinePrice, isPriceOverrideReason } from "./sale/price-override.mjs";
14
+ import { serviceSku, serviceSlug } from "./sale/service-line.mjs";
15
+ import { quickCashAmounts } from "./sale/quick-cash.mjs";
16
+ import { buildShiftReport } from "./shift/shift-report.mjs";
17
+ export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, DEFAULT_METHOD_KINDS, DEFAULT_TENDER_METHOD_RESOLVER, FINAL_SHIFT_STATES, IllegalShiftTransitionError, OrderDiscountRefusedError, PAYMENT_METHOD_KIND_VALUES, PRICE_OVERRIDE_NOTE_MAX, PRICE_OVERRIDE_REASONS, PRICE_OVERRIDE_REASONS_NEEDING_NOTE, PosCapabilityError, PosError, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, TenderMethodRefusedError, TenderMismatchError, UnmanagedSessionError, VarianceExceededError, allocateTender, allowedVerbs, applyCounts, assertTenderSettles, buildShiftReport, canTransition, computeDifference, computeExpected, createTenderMethodResolver, decideBlindClose, decideLinePrice, decideOrderDiscount, decideShiftClose, defaultShiftPolicy, discountCeilingMinor, isActiveShiftState, isCashRow, isFinalShiftState, isPriceOverrideReason, isReasonCodeAllowed, isWithinVarianceThreshold, nextState, quickCashAmounts, resolveMethodKind, seedBreakdown, serviceSku, serviceSlug, shiftCloseIdempotencyKey, tenderSummary, tillTenderMethods, validateTenderLegs };
@@ -1,7 +1,7 @@
1
1
  import { OperationContext } from "@classytic/primitives/context";
2
2
  import { RetryPolicy } from "@classytic/repo-core/repository";
3
3
  //#region src/domain/ports/common.d.ts
4
- interface PosContext extends OperationContext {
4
+ export interface PosContext extends OperationContext {
5
5
  /** Host's local-TZ business date (YYYY-MM-DD) for shifts that derive at open. */
6
6
  businessDate?: string | undefined;
7
7
  /**
@@ -17,5 +17,4 @@ interface PosContext extends OperationContext {
17
17
  */
18
18
  retryPolicy?: RetryPolicy | undefined;
19
19
  }
20
- //#endregion
21
- export { PosContext };
20
+ //#endregion
@@ -1,5 +1,5 @@
1
+ import { PendingLedgerPostTrigger, ShiftRecord } from "../shift/shift.types.mjs";
1
2
  import { PosContext } from "./common.mjs";
2
- import { PendingLedgerPostTrigger, ShiftDocument } from "../../models/shift.model.mjs";
3
3
  //#region src/domain/ports/ledger.bridge.d.ts
4
4
  /**
5
5
  * The deterministic idempotency key for a shift's close posting.
@@ -9,9 +9,9 @@ import { PendingLedgerPostTrigger, ShiftDocument } from "../../models/shift.mode
9
9
  * defeats deduplication while looking correctly wired (AGENTS.md: derive
10
10
  * identifiers deterministically).
11
11
  */
12
- declare function shiftCloseIdempotencyKey(shiftId: string): string;
12
+ export declare function shiftCloseIdempotencyKey(shiftId: string): string;
13
13
  /** The posting request handed to {@link LedgerBridge.onShiftClosed}. */
14
- interface ShiftClosePosting {
14
+ export interface ShiftClosePosting {
15
15
  /**
16
16
  * REQUIRED. `pos:shift:<shiftId>:close` — see
17
17
  * {@link shiftCloseIdempotencyKey}. Dedupe on this or the resume path
@@ -23,7 +23,7 @@ interface ShiftClosePosting {
23
23
  * reconciliation values, `closedAt` / `closedBy` set. Not a projection:
24
24
  * the document the bridge reads is the document the books describe.
25
25
  */
26
- shift: ShiftDocument;
26
+ shift: ShiftRecord;
27
27
  /** Which pipeline claimed the shift. */
28
28
  trigger: PendingLedgerPostTrigger;
29
29
  /**
@@ -34,7 +34,7 @@ interface ShiftClosePosting {
34
34
  */
35
35
  attempt: number;
36
36
  }
37
- interface LedgerBridge {
37
+ export interface LedgerBridge {
38
38
  /**
39
39
  * Post the shift's journal entry. Return the host-side journal entry id;
40
40
  * the package persists it onto the shift and clears the pending marker.
@@ -48,5 +48,4 @@ interface LedgerBridge {
48
48
  journalEntryId: string;
49
49
  }>;
50
50
  }
51
- //#endregion
52
- export { LedgerBridge, ShiftClosePosting, shiftCloseIdempotencyKey };
51
+ //#endregion
@@ -1,11 +1,10 @@
1
+ import { ShiftRecord } from "../shift/shift.types.mjs";
1
2
  import { PosContext } from "./common.mjs";
2
- import { ShiftDocument } from "../../models/shift.model.mjs";
3
3
  //#region src/domain/ports/notification.bridge.d.ts
4
- interface NotificationBridge {
4
+ export interface NotificationBridge {
5
5
  /** Cash variance exceeded the policy threshold and was overridden by a manager. */
6
- onVarianceOverride?(shift: ShiftDocument, ctx: PosContext): Promise<void> | void;
6
+ onVarianceOverride?(shift: ShiftRecord, ctx: PosContext): Promise<void> | void;
7
7
  /** Cron / admin force-closed an orphaned shift. */
8
- onOrphanedClose?(shift: ShiftDocument, ctx: PosContext): Promise<void> | void;
8
+ onOrphanedClose?(shift: ShiftRecord, ctx: PosContext): Promise<void> | void;
9
9
  }
10
- //#endregion
11
- export { NotificationBridge };
10
+ //#endregion
@@ -1,12 +1,11 @@
1
1
  import { ShiftPolicy } from "../value-objects/shift-policy.vo.mjs";
2
2
  import { PosContext } from "./common.mjs";
3
3
  //#region src/domain/ports/policy.bridge.d.ts
4
- interface PolicyBridge {
4
+ export interface PolicyBridge {
5
5
  /**
6
6
  * Resolve the policy snapshot for a new shift. Called once during `open()`;
7
7
  * the result is frozen onto the shift and never re-read.
8
8
  */
9
9
  resolvePolicy(ctx: PosContext): Promise<ShiftPolicy> | ShiftPolicy;
10
10
  }
11
- //#endregion
12
- export { PolicyBridge };
11
+ //#endregion
@@ -0,0 +1,62 @@
1
+ //#region src/domain/sale/discount.d.ts
2
+ /**
3
+ * ORDER-LEVEL DISCOUNT — authorize it, or refuse it naming what is missing. Pure: the caller decides
4
+ * `authorized` (its own permission check, or a verified manager approval) and passes the declared
5
+ * limits. Every server and device that rings a sale decides through {@link decideOrderDiscount}.
6
+ */
7
+ /** What a deployment declares about order-level discounts. */
8
+ export interface OrderDiscountLimits {
9
+ /** Hard ceiling in MINOR units. Absent ⇒ none (the subtotal still bounds it). */
10
+ maxDiscountMinor?: number | undefined;
11
+ /** Hard ceiling as a percentage of the subtotal (0–100). With both, the LOWER wins. */
12
+ maxDiscountPct?: number | undefined;
13
+ /** Allow comping the ENTIRE basket. Default false — a zeroed sale leaves the tender guard nothing to check. */
14
+ allowFullComp?: boolean | undefined;
15
+ }
16
+ /**
17
+ * The discount audit trail, stamped on the order next to `priceOverrides`.
18
+ *
19
+ * Original subtotal → what was asked for → what was granted → who authorized it
20
+ * and why. On the ORDER so it survives independently of log retention: "who
21
+ * discounted this sale and why" must be answerable from the sale itself.
22
+ */
23
+ export interface PosOrderDiscountRecord {
24
+ /** The authoritative subtotal the discount was measured against, minor units. */
25
+ subtotalMinor: number;
26
+ /** What the till asked for, minor units. */
27
+ requestedMinor: number;
28
+ /** What was granted, minor units. Equal to requested — a refusal is not a clamp. */
29
+ grantedMinor: number;
30
+ reason: string;
31
+ /** From the verified scope, never the body — a self-declared approver is not an approval. */
32
+ approvedBy: string;
33
+ /** The declared ceiling that was checked, minor units. Absent when unlimited. */
34
+ limitMinor?: number | undefined;
35
+ /** True when the whole basket was comped (required `allowFullComp`). */
36
+ fullComp?: boolean | undefined;
37
+ }
38
+ export interface DecideOrderDiscountInput {
39
+ /** MINOR units, from the AUTHORITATIVE (catalog-resolved) prices. */
40
+ subtotalMinor: number;
41
+ /** MINOR units, as requested by the till. */
42
+ requestedMinor: number;
43
+ reason: string | undefined;
44
+ /** The caller holds discount authority, or a verified manager approval covers this sale. */
45
+ authorized: boolean;
46
+ /** Who is recorded as approving — the verified approver, never one named in the request body. */
47
+ approvedBy: string;
48
+ limits: OrderDiscountLimits | undefined;
49
+ }
50
+ export interface OrderDiscountDecision {
51
+ grantedMinor: number;
52
+ record?: PosOrderDiscountRecord | undefined;
53
+ }
54
+ /** The declared ceiling in minor units (the lower of the two limits), or `undefined` when none is set. */
55
+ export declare function discountCeilingMinor(limits: OrderDiscountLimits | undefined, subtotalMinor: number): number | undefined;
56
+ /**
57
+ * Authorize an order-level discount, or refuse it naming the missing requirement. An over-limit
58
+ * request is REFUSED, never clamped — a clamp charges a total nobody quoted. Decide it before any
59
+ * stock or promo hold, so a refusal leaves nothing outstanding.
60
+ */
61
+ export declare function decideOrderDiscount(input: DecideOrderDiscountInput): OrderDiscountDecision;
62
+ //#endregion
@@ -0,0 +1,58 @@
1
+ import { OrderDiscountRefusedError } from "../errors/pos.errors.mjs";
2
+ //#region src/domain/sale/discount.ts
3
+ /**
4
+ * ORDER-LEVEL DISCOUNT — authorize it, or refuse it naming what is missing. Pure: the caller decides
5
+ * `authorized` (its own permission check, or a verified manager approval) and passes the declared
6
+ * limits. Every server and device that rings a sale decides through {@link decideOrderDiscount}.
7
+ */
8
+ /** The declared ceiling in minor units (the lower of the two limits), or `undefined` when none is set. */
9
+ function discountCeilingMinor(limits, subtotalMinor) {
10
+ const abs = limits?.maxDiscountMinor;
11
+ const pct = limits?.maxDiscountPct;
12
+ const candidates = [];
13
+ if (typeof abs === "number" && Number.isFinite(abs) && abs >= 0) candidates.push(Math.floor(abs));
14
+ if (typeof pct === "number" && Number.isFinite(pct) && pct >= 0) candidates.push(Math.floor(subtotalMinor * Math.min(pct, 100) / 100));
15
+ if (candidates.length === 0) return void 0;
16
+ return Math.min(...candidates);
17
+ }
18
+ /**
19
+ * Authorize an order-level discount, or refuse it naming the missing requirement. An over-limit
20
+ * request is REFUSED, never clamped — a clamp charges a total nobody quoted. Decide it before any
21
+ * stock or promo hold, so a refusal leaves nothing outstanding.
22
+ */
23
+ function decideOrderDiscount(input) {
24
+ const { subtotalMinor, requestedMinor, limits } = input;
25
+ if (requestedMinor <= 0) return { grantedMinor: 0 };
26
+ if (!input.authorized) throw new OrderDiscountRefusedError("authority", "not authorized to discount a sale", { requestedMinor });
27
+ const reason = (input.reason ?? "").trim();
28
+ if (reason.length === 0) throw new OrderDiscountRefusedError("reason", "no reason given for the discount", { requestedMinor });
29
+ if (requestedMinor > subtotalMinor) throw new OrderDiscountRefusedError("limit", `discount ${requestedMinor} exceeds the subtotal ${subtotalMinor}`, {
30
+ requestedMinor,
31
+ subtotalMinor
32
+ });
33
+ const ceiling = discountCeilingMinor(limits, subtotalMinor);
34
+ if (ceiling !== void 0 && requestedMinor > ceiling) throw new OrderDiscountRefusedError("limit", `discount ${requestedMinor} exceeds the declared limit ${ceiling}`, {
35
+ requestedMinor,
36
+ limitMinor: ceiling,
37
+ subtotalMinor
38
+ });
39
+ const fullComp = requestedMinor >= subtotalMinor && subtotalMinor > 0;
40
+ if (fullComp && limits?.allowFullComp !== true) throw new OrderDiscountRefusedError("full-comp", "discounting the entire sale requires the allowFullComp capability", {
41
+ requestedMinor,
42
+ subtotalMinor
43
+ });
44
+ return {
45
+ grantedMinor: requestedMinor,
46
+ record: {
47
+ subtotalMinor,
48
+ requestedMinor,
49
+ grantedMinor: requestedMinor,
50
+ reason,
51
+ approvedBy: input.approvedBy,
52
+ ...ceiling !== void 0 ? { limitMinor: ceiling } : {},
53
+ ...fullComp ? { fullComp: true } : {}
54
+ }
55
+ };
56
+ }
57
+ //#endregion
58
+ export { decideOrderDiscount, discountCeilingMinor };
@@ -0,0 +1,51 @@
1
+ //#region src/domain/sale/price-override.d.ts
2
+ /**
3
+ * LINE PRICE — the catalog is the only price authority. A requested price that differs from it is an
4
+ * OVERRIDE: it needs authority and a CLOSED reason code, and it is recorded on the order. Never
5
+ * silently repriced back to the catalog, never silently accepted.
6
+ *
7
+ * The reason is a code from {@link PRICE_OVERRIDE_REASONS}, so a report can group overrides; the
8
+ * cashier's own words travel in `note`, which `other` requires.
9
+ */
10
+ /** Why a line price departs from the catalog. Anything else is refused. */
11
+ export declare const PRICE_OVERRIDE_REASONS: readonly ['damaged', 'price_match', 'wrong_label', 'manager_discount', 'other'];
12
+ export type PriceOverrideReason = (typeof PRICE_OVERRIDE_REASONS)[number];
13
+ /** Codes whose override must carry a note — the code alone does not say what happened. */
14
+ export declare const PRICE_OVERRIDE_REASONS_NEEDING_NOTE: readonly PriceOverrideReason[];
15
+ export declare function isPriceOverrideReason(value: unknown): value is PriceOverrideReason;
16
+ /** Longest note a till may attach; the wire schema enforces the same bound. */
17
+ export declare const PRICE_OVERRIDE_NOTE_MAX = 500;
18
+ /** One recorded override, stamped on the order so "who changed this price and why" survives with it. */
19
+ export interface PosPriceOverrideRecord {
20
+ lineId: string;
21
+ offerId: string;
22
+ /** What the catalog said, in minor units. */
23
+ originalMinor: number;
24
+ /** What was charged instead, in minor units. */
25
+ chargedMinor: number;
26
+ reason: PriceOverrideReason;
27
+ /** The cashier's words. Present whenever one was given; always present for `other`. */
28
+ note?: string | undefined;
29
+ /** From the verified actor — never the request body. */
30
+ approvedBy: string;
31
+ }
32
+ export interface DecideLinePriceInput {
33
+ lineId: string;
34
+ offerId: string;
35
+ /** The catalog's unit price, minor units. */
36
+ catalogMinor: number;
37
+ /** The price the till asked for, minor units; absent ⇒ the catalog price. */
38
+ requestedMinor?: number | undefined;
39
+ /** A {@link PRICE_OVERRIDE_REASONS} code, as received. Validated here, so any caller is held to it. */
40
+ reason: string | undefined;
41
+ note?: string | undefined;
42
+ /** The caller may override prices. Consulted only when the price differs. */
43
+ authorized: boolean;
44
+ approvedBy: string;
45
+ }
46
+ export interface LinePriceDecision {
47
+ unitMinor: number;
48
+ override?: PosPriceOverrideRecord | undefined;
49
+ }
50
+ export declare function decideLinePrice(input: DecideLinePriceInput): LinePriceDecision;
51
+ //#endregion
@@ -0,0 +1,51 @@
1
+ import { PriceOverrideRefusedError } from "../errors/pos.errors.mjs";
2
+ //#region src/domain/sale/price-override.ts
3
+ /**
4
+ * LINE PRICE — the catalog is the only price authority. A requested price that differs from it is an
5
+ * OVERRIDE: it needs authority and a CLOSED reason code, and it is recorded on the order. Never
6
+ * silently repriced back to the catalog, never silently accepted.
7
+ *
8
+ * The reason is a code from {@link PRICE_OVERRIDE_REASONS}, so a report can group overrides; the
9
+ * cashier's own words travel in `note`, which `other` requires.
10
+ */
11
+ /** Why a line price departs from the catalog. Anything else is refused. */
12
+ const PRICE_OVERRIDE_REASONS = [
13
+ "damaged",
14
+ "price_match",
15
+ "wrong_label",
16
+ "manager_discount",
17
+ "other"
18
+ ];
19
+ /** Codes whose override must carry a note — the code alone does not say what happened. */
20
+ const PRICE_OVERRIDE_REASONS_NEEDING_NOTE = ["other"];
21
+ function isPriceOverrideReason(value) {
22
+ return typeof value === "string" && PRICE_OVERRIDE_REASONS.includes(value);
23
+ }
24
+ /** Longest note a till may attach; the wire schema enforces the same bound. */
25
+ const PRICE_OVERRIDE_NOTE_MAX = 500;
26
+ function decideLinePrice(input) {
27
+ const { catalogMinor, requestedMinor, offerId } = input;
28
+ if (requestedMinor === void 0 || requestedMinor === catalogMinor) return { unitMinor: catalogMinor };
29
+ if (!Number.isInteger(requestedMinor) || requestedMinor < 0) throw new PriceOverrideRefusedError(`the price of "${offerId}" must be a non-negative amount`, 400);
30
+ if (!input.authorized) throw new PriceOverrideRefusedError(`not authorized to change the price of "${offerId}"`);
31
+ const reason = (input.reason ?? "").trim();
32
+ if (reason.length === 0) throw new PriceOverrideRefusedError(`no reason given for "${offerId}"`, 400);
33
+ if (!isPriceOverrideReason(reason)) throw new PriceOverrideRefusedError(`"${reason}" is not a price override reason for "${offerId}" (one of ${PRICE_OVERRIDE_REASONS.join(", ")})`, 400);
34
+ const note = (input.note ?? "").trim();
35
+ if (note.length > 500) throw new PriceOverrideRefusedError(`the note for "${offerId}" is longer than 500 characters`, 400);
36
+ if (note.length === 0 && PRICE_OVERRIDE_REASONS_NEEDING_NOTE.includes(reason)) throw new PriceOverrideRefusedError(`reason "${reason}" needs a note for "${offerId}"`, 400);
37
+ return {
38
+ unitMinor: requestedMinor,
39
+ override: {
40
+ lineId: input.lineId,
41
+ offerId,
42
+ originalMinor: catalogMinor,
43
+ chargedMinor: requestedMinor,
44
+ reason,
45
+ ...note.length > 0 ? { note } : {},
46
+ approvedBy: input.approvedBy
47
+ }
48
+ };
49
+ }
50
+ //#endregion
51
+ export { PRICE_OVERRIDE_NOTE_MAX, PRICE_OVERRIDE_REASONS, PRICE_OVERRIDE_REASONS_NEEDING_NOTE, decideLinePrice, isPriceOverrideReason };
@@ -0,0 +1,10 @@
1
+ //#region src/domain/sale/quick-cash.d.ts
2
+ /**
3
+ * The amounts a customer is likely to hand over for a sale: the next round sums above what is
4
+ * due, on a 1-2-5 series scaled to the amount — so a $13.23 sale offers $14 · $15 · $20 · $50 and
5
+ * a ¥1,340 one ¥1,400 · ¥1,500 · ¥2,000 · ¥5,000. Currency-aware through its minor unit; no
6
+ * per-country note table.
7
+ */
8
+ /** Up to `count` amounts above `dueMinor`, ascending, in minor units. */
9
+ export declare function quickCashAmounts(dueMinor: number, currency: string, count?: number): number[];
10
+ //#endregion
@@ -0,0 +1,27 @@
1
+ import { minorUnitFactor } from "@classytic/primitives/currency";
2
+ //#region src/domain/sale/quick-cash.ts
3
+ /**
4
+ * The amounts a customer is likely to hand over for a sale: the next round sums above what is
5
+ * due, on a 1-2-5 series scaled to the amount — so a $13.23 sale offers $14 · $15 · $20 · $50 and
6
+ * a ¥1,340 one ¥1,400 · ¥1,500 · ¥2,000 · ¥5,000. Currency-aware through its minor unit; no
7
+ * per-country note table.
8
+ */
9
+ /** Up to `count` amounts above `dueMinor`, ascending, in minor units. */
10
+ function quickCashAmounts(dueMinor, currency, count = 4) {
11
+ const factor = minorUnitFactor(currency);
12
+ const due = dueMinor / factor;
13
+ const base = 10 ** Math.max(0, Math.ceil(Math.log10(Math.max(due, 1) / 50)));
14
+ const amounts = /* @__PURE__ */ new Set();
15
+ for (let i = 0; amounts.size < count && i < 30; i++) {
16
+ const step = base * [
17
+ 1,
18
+ 2,
19
+ 5
20
+ ][i % 3] * 10 ** Math.floor(i / 3);
21
+ const amount = Math.ceil(due / step) * step;
22
+ if (amount > due) amounts.add(amount);
23
+ }
24
+ return [...amounts].sort((a, b) => a - b).map((major) => Math.round(major * factor));
25
+ }
26
+ //#endregion
27
+ export { quickCashAmounts };
@@ -0,0 +1,7 @@
1
+ //#region src/domain/sale/service-line.d.ts
2
+ /** An ad-hoc charge line (gift wrap, delivery fee): no catalog product, so a synthetic SKU. */
3
+ /** A stable service code from the cashier's label. */
4
+ export declare function serviceSlug(label: string | undefined): string;
5
+ /** `service:<slug>` — the charge line's SKU and offer id, on every till and server. */
6
+ export declare const serviceSku: (label: string | undefined) => string;
7
+ //#endregion
@@ -0,0 +1,10 @@
1
+ //#region src/domain/sale/service-line.ts
2
+ /** An ad-hoc charge line (gift wrap, delivery fee): no catalog product, so a synthetic SKU. */
3
+ /** A stable service code from the cashier's label. */
4
+ function serviceSlug(label) {
5
+ return (label ?? "misc").toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "misc";
6
+ }
7
+ /** `service:<slug>` — the charge line's SKU and offer id, on every till and server. */
8
+ const serviceSku = (label) => `service:${serviceSlug(label)}`;
9
+ //#endregion
10
+ export { serviceSku, serviceSlug };