@classytic/pos 0.7.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.
@@ -1,8 +1,8 @@
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
1
  import { CASH_MOVEMENT_REASON_CODES } from "./enums/cash-movement-reason.enum.mjs";
3
2
  import { CLOSED_BY_VALUES } from "./enums/closed-by.enum.mjs";
4
3
  import { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS, resolveMethodKind } from "./enums/payment-method.enum.mjs";
5
4
  import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, isActiveShiftState, isFinalShiftState } from "./enums/shift-state.enum.mjs";
5
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, OrderDiscountRefusedError, PosError, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, TenderMethodRefusedError, TenderMismatchError, UnmanagedSessionError, VarianceExceededError } from "./errors/pos.errors.mjs";
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";
@@ -14,4 +14,4 @@ import { PRICE_OVERRIDE_NOTE_MAX, PRICE_OVERRIDE_REASONS, PRICE_OVERRIDE_REASONS
14
14
  import { serviceSku, serviceSlug } from "./sale/service-line.mjs";
15
15
  import { quickCashAmounts } from "./sale/quick-cash.mjs";
16
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 };
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, 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 };
@@ -54,26 +54,26 @@ export interface TenderPolicy {
54
54
  /**
55
55
  * How a tender becomes money the business can count.
56
56
  *
57
- * - `cash-immediate` — the money is in the drawer NOW. The only inherently
58
- * immediate kind, and the only one that can give change.
59
- * - `manual-confirmed` — a human must confirm it against evidence (a terminal
60
- * slip, a wallet statement, a bank line). The cashier's word is the claim, not
61
- * the confirmation.
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.
62
64
  * - `provider-verified` — a payment provider will verify it out of band
63
65
  * (`@classytic/revenue` intent → verify → webhook). The drawer learns about it
64
66
  * from the gateway subscriber, not from the sale.
65
67
  */
66
- export type TenderSettlement = 'cash-immediate' | 'manual-confirmed' | 'provider-verified';
68
+ export type TenderSettlement = 'cash-immediate' | 'acquirer-captured' | 'manual-confirmed' | 'provider-verified';
67
69
  /** What a deployment declares about one tender method. */
68
70
  export interface ResolvedTenderMethod {
69
71
  /**
70
72
  * Is this method accepted at all? `false` (or a null resolver result) REFUSES
71
73
  * the sale.
72
74
  *
73
- * Refusing beats accepting: an unrecognised method string used to persist
74
- * verbatim, then fail the accrual's alias lookup, and the whole sale was
75
- * bucketed to CASH with a warning nobody reads. A typo (`csah`, `visa-mc`)
76
- * therefore moved real money into the wrong drawer bucket silently.
75
+ * Refuse, never accept: an unknown method (`csah`, `visa-mc`) would land the money in the wrong
76
+ * drawer bucket silently.
77
77
  */
78
78
  allowed: boolean;
79
79
  /**
@@ -158,7 +158,7 @@ export interface TillTenderMethod {
158
158
  settlement: TenderSettlement;
159
159
  referenceRequired: boolean;
160
160
  changeCapable: boolean;
161
- /** The shift breakdown row the sale accrues to (`bkash` → `mfs`). */
161
+ /** The shift breakdown row the sale accrues to (`bkash` → `mobile_money`). */
162
162
  drawerMethod: string;
163
163
  }
164
164
  /**
@@ -193,7 +193,7 @@ function allocateTender(legs, dueMinor, toleranceMinor = 0) {
193
193
  tenderedMinor,
194
194
  appliedMinor,
195
195
  changeMinor,
196
- settlesImmediately: allocated.some((l) => l.appliedMinor > 0) && allocated.every((l) => l.appliedMinor === 0 || l.settlement === "cash-immediate")
196
+ settlesImmediately: allocated.some((l) => l.appliedMinor > 0) && allocated.every((l) => l.appliedMinor === 0 || l.settlement === "cash-immediate" || l.settlement === "acquirer-captured")
197
197
  };
198
198
  }
199
199
  /** The persisted summary for `order.metadata.tender`. */
@@ -5,12 +5,11 @@ import { PaymentMethodKind } from "@classytic/primitives/payment-method-kind";
5
5
  //#region src/domain/shift/shift-decisions.d.ts
6
6
  /** The fields of a breakdown row these decisions read and write. */
7
7
  export type CountableRow = Pick<PaymentBreakdown, 'method' | 'openingAmount' | 'salesAmount' | 'refundAmount' | 'cashInAmount' | 'cashOutAmount' | 'expectedAmount' | 'countedAmount' | 'difference'> & {
8
- methodKind?: PaymentMethodKind;
8
+ methodKind: PaymentMethodKind;
9
9
  };
10
- /** The drawer row: keyed on the payment KIND, never on the method's spelling. */
10
+ /** The drawer row: keyed on the payment KIND, never on the method's code (`'efectivo'`, `'cash_register_3'`, …). */
11
11
  export declare function isCashRow(row: {
12
- method?: string;
13
- methodKind?: string;
12
+ methodKind: string;
14
13
  }): boolean;
15
14
  /** A new shift's breakdown: one row per allowed method; the opening float sits on the cash row. */
16
15
  export declare function seedBreakdown(policy: Pick<ShiftPolicy, 'allowedPaymentMethods' | 'paymentMethodKinds'>, openingCash: number): PaymentBreakdown[];
@@ -1,5 +1,5 @@
1
- import { IllegalShiftTransitionError, ShiftCountsRequiredError, VarianceExceededError } from "../errors/pos.errors.mjs";
2
1
  import { resolveMethodKind } from "../enums/payment-method.enum.mjs";
2
+ import { IllegalShiftTransitionError, ShiftCountsRequiredError, VarianceExceededError } from "../errors/pos.errors.mjs";
3
3
  import { canTransition } from "../state-machines/shift.fsm.mjs";
4
4
  import { computeDifference, computeExpected } from "../value-objects/payment-breakdown.vo.mjs";
5
5
  import { isWithinVarianceThreshold } from "../value-objects/shift-policy.vo.mjs";
@@ -10,9 +10,9 @@ import { PAYMENT_METHOD_KIND } from "@classytic/primitives/payment-method-kind";
10
10
  * breakdown, and whether a close may proceed. The repository persists them (CAS, ledger, events);
11
11
  * a device till decides through the same functions, so both close the same drawer the same way.
12
12
  */
13
- /** The drawer row: keyed on the payment KIND, never on the method's spelling. */
13
+ /** The drawer row: keyed on the payment KIND, never on the method's code (`'efectivo'`, `'cash_register_3'`, …). */
14
14
  function isCashRow(row) {
15
- return row.methodKind === PAYMENT_METHOD_KIND.CASH || row.methodKind === void 0 && row.method === "cash";
15
+ return row.methodKind === PAYMENT_METHOD_KIND.CASH;
16
16
  }
17
17
  /** A new shift's breakdown: one row per allowed method; the opening float sits on the cash row. */
18
18
  function seedBreakdown(policy, openingCash) {
@@ -79,8 +79,6 @@ export interface IShift {
79
79
  * when a manager overrides a variance during close, or any multi-step
80
80
  * chain a host attaches via a future `approvals` input on
81
81
  * `CloseShiftInput`. Null when no variance override / no chain attached.
82
- *
83
- * Renamed from `varianceApproval` (2026-05-06) to align with P7.
84
82
  */
85
83
  approvals: ApprovalChain | null;
86
84
  /** Policy frozen at open time. Reconciliation reads from here, never live. */
@@ -32,12 +32,7 @@ export interface ShiftPolicy {
32
32
  paymentMethodKinds?: Readonly<Record<string, PaymentMethodKind>>;
33
33
  }
34
34
  /**
35
- * A sane starting policy, so a HOST never hardcodes one.
36
- *
37
- * Every deployment used to carry its own literal — be-prod's
38
- * `shift.constants.ts`, and a copy in every fork of it. That is business policy
39
- * living in composition code: it drifts, and a fix in one host reaches none of
40
- * the others. The kernel owns `ShiftPolicy`, so the kernel owns its default.
35
+ * A sane starting policy, so a HOST never hardcodes one: the kernel owns `ShiftPolicy`, so it owns the default.
41
36
  *
42
37
  * The values are the conservative reading of the research the FSM is modelled
43
38
  * on: blind-close OFF (a single-operator shop must not be forced into a
@@ -1,14 +1,9 @@
1
- import { ReasonCodePolicyInvalidError } from "../errors/pos.errors.mjs";
2
1
  import { CASH_MOVEMENT_REASON_CODES } from "../enums/cash-movement-reason.enum.mjs";
3
2
  import { SHIFT_PAYMENT_METHODS } from "../enums/payment-method.enum.mjs";
3
+ import { ReasonCodePolicyInvalidError } from "../errors/pos.errors.mjs";
4
4
  //#region src/domain/value-objects/shift-policy.vo.ts
5
5
  /**
6
- * A sane starting policy, so a HOST never hardcodes one.
7
- *
8
- * Every deployment used to carry its own literal — be-prod's
9
- * `shift.constants.ts`, and a copy in every fork of it. That is business policy
10
- * living in composition code: it drifts, and a fix in one host reaches none of
11
- * the others. The kernel owns `ShiftPolicy`, so the kernel owns its default.
6
+ * A sane starting policy, so a HOST never hardcodes one: the kernel owns `ShiftPolicy`, so it owns the default.
12
7
  *
13
8
  * The values are the conservative reading of the research the FSM is modelled
14
9
  * on: blind-close OFF (a single-operator shop must not be forced into a
@@ -0,0 +1,23 @@
1
+ //#region src/engine/capability.errors.d.ts
2
+ /**
3
+ * Bind-time refusals: the engine's backend cannot honour what POS needs. Server-only, so it lives in
4
+ * the engine and never ships in the browser-safe `./domain`. Pinned by
5
+ * `tests/integration/capability-gate.test.ts`.
6
+ */
7
+ export declare class PosCapabilityError extends Error {
8
+ readonly code = "POS_CAPABILITY";
9
+ readonly status = 422;
10
+ readonly missing: readonly string[];
11
+ /**
12
+ * `true` when the backend never ANSWERED (the connection was not open at
13
+ * bind, or the driver exposed no topology) rather than answering "no".
14
+ * Both refuse — an unobserved outcome is never a positive one (AGENTS.md
15
+ * FAIL LOUD rule 3) — but the operator's fix is completely different, so
16
+ * the message has to distinguish them.
17
+ */
18
+ readonly indeterminate: boolean;
19
+ constructor(missing: readonly string[], opts?: {
20
+ indeterminate?: boolean;
21
+ });
22
+ }
23
+ //#endregion
@@ -0,0 +1,28 @@
1
+ //#region src/engine/capability.errors.ts
2
+ /**
3
+ * Bind-time refusals: the engine's backend cannot honour what POS needs. Server-only, so it lives in
4
+ * the engine and never ships in the browser-safe `./domain`. Pinned by
5
+ * `tests/integration/capability-gate.test.ts`.
6
+ */
7
+ var PosCapabilityError = class extends Error {
8
+ code = "POS_CAPABILITY";
9
+ status = 422;
10
+ missing;
11
+ /**
12
+ * `true` when the backend never ANSWERED (the connection was not open at
13
+ * bind, or the driver exposed no topology) rather than answering "no".
14
+ * Both refuse — an unobserved outcome is never a positive one (AGENTS.md
15
+ * FAIL LOUD rule 3) — but the operator's fix is completely different, so
16
+ * the message has to distinguish them.
17
+ */
18
+ indeterminate;
19
+ constructor(missing, opts = {}) {
20
+ const indeterminate = opts.indeterminate === true;
21
+ super(indeterminate ? `[pos] could NOT determine whether the backend supports: ${missing.join(", ")}. An unconfirmed answer is treated as unsupported — the close / forceClose pipelines run through CAS and are transactional. Bind AFTER \`await mongoose.connect(...)\`, or \`await probeMongoCapabilities(connection)\` first, or pass \`allowNonTransactional: true\`.` : `[pos] missing required capabilities: ${missing.join(", ")}. POS fails loud at bind rather than posting a Z-report for cash nobody counted.` + (missing.some((flag) => !flag.startsWith("outbox.")) ? " The close / forceClose pipelines run through CAS and are transactional — MongoDB must run as a replica set (repo-core 0.6 / mongokit 3.16+). Pass `allowNonTransactional: true` for standalone-Mongo local dev." : ""));
22
+ this.name = "PosCapabilityError";
23
+ this.missing = missing;
24
+ this.indeterminate = indeterminate;
25
+ }
26
+ };
27
+ //#endregion
28
+ export { PosCapabilityError };
@@ -1,4 +1,4 @@
1
- import { PosCapabilityError } from "../domain/errors/pos.errors.mjs";
1
+ import { PosCapabilityError } from "./capability.errors.mjs";
2
2
  import { InProcessPosBus } from "../events/in-process-bus.mjs";
3
3
  import { resolvePosTenant } from "../models/inject-tenant.mjs";
4
4
  import { definePosModels } from "../models/create-models.mjs";
@@ -1,4 +1,5 @@
1
1
  import { PosModels } from "../models/create-models.mjs";
2
2
  import { PosBlueprint, PosBridges, PosEngine, PosLogger, PosRepositories, PosRuntime, PosShape, ResolvedPosConfig } from "./engine-types.mjs";
3
3
  import { definePos } from "./define-pos.mjs";
4
- export { type PosBlueprint, type PosBridges, type PosEngine, type PosLogger, type PosModels, type PosRepositories, type PosRuntime, type PosShape, type ResolvedPosConfig, definePos };
4
+ import { PosCapabilityError } from "./capability.errors.mjs";
5
+ export { type PosBlueprint, type PosBridges, PosCapabilityError, type PosEngine, type PosLogger, type PosModels, type PosRepositories, type PosRuntime, type PosShape, type ResolvedPosConfig, definePos };
@@ -1 +1,3 @@
1
- export { definePos } from "./define-pos.mjs";
1
+ import { PosCapabilityError } from "./capability.errors.mjs";
2
+ import { definePos } from "./define-pos.mjs";
3
+ export { PosCapabilityError, definePos };
package/dist/index.d.mts CHANGED
@@ -6,7 +6,7 @@ import { SHIFT_VERBS, ShiftVerb, allowedVerbs, canTransition, nextState } from "
6
6
  import { CashMovement } from "./domain/value-objects/cash-movement.vo.mjs";
7
7
  import { PaymentBreakdown, computeDifference, computeExpected } from "./domain/value-objects/payment-breakdown.vo.mjs";
8
8
  import { ShiftPolicy, defaultShiftPolicy, isReasonCodeAllowed, isWithinVarianceThreshold } from "./domain/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 "./domain/errors/pos.errors.mjs";
9
+ import { ActiveRegister, ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, OrderDiscountRefusal, OrderDiscountRefusedError, PosError, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, TenderMethodRefusal, TenderMethodRefusedError, TenderMismatchError, UnmanagedSessionError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
10
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 "./domain/sale/tender.mjs";
11
11
  import { DecideOrderDiscountInput, OrderDiscountDecision, OrderDiscountLimits, PosOrderDiscountRecord, decideOrderDiscount, discountCeilingMinor } from "./domain/sale/discount.mjs";
12
12
  import { DecideLinePriceInput, LinePriceDecision, PRICE_OVERRIDE_NOTE_MAX, PRICE_OVERRIDE_REASONS, PRICE_OVERRIDE_REASONS_NEEDING_NOTE, PosPriceOverrideRecord, PriceOverrideReason, decideLinePrice, isPriceOverrideReason } from "./domain/sale/price-override.mjs";
@@ -31,6 +31,7 @@ import { BlindCloseInput, CloseShiftInput, CloseShiftResult, IncrementSalesInput
31
31
  import { TillGrantRepository } from "./repositories/till-grant.repository.mjs";
32
32
  import { PosBlueprint, PosBridges, PosEngine, PosLogger, PosRepositories, PosRuntime, PosShape, ResolvedPosConfig } from "./engine/engine-types.mjs";
33
33
  import { definePos } from "./engine/define-pos.mjs";
34
+ import { PosCapabilityError } from "./engine/capability.errors.mjs";
34
35
  import { POS_EVENTS, PosEventName } from "./events/event-constants.mjs";
35
36
  import { CashMovementRecordedPayload, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload } from "./events/event-payloads.mjs";
36
37
  import { createPosEvent } from "./events/helpers.mjs";
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, OrderDiscountRefusedError, PosCapabilityError, PosError, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, TenderMethodRefusedError, TenderMismatchError, UnmanagedSessionError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
1
+ import { PosCapabilityError } from "./engine/capability.errors.mjs";
2
2
  import { InProcessPosBus } from "./events/in-process-bus.mjs";
3
3
  import { CASH_MOVEMENT_REASON_CODES } from "./domain/enums/cash-movement-reason.enum.mjs";
4
4
  import { CLOSED_BY_VALUES } from "./domain/enums/closed-by.enum.mjs";
@@ -6,6 +6,7 @@ import { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS
6
6
  import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, isActiveShiftState, isFinalShiftState } from "./domain/enums/shift-state.enum.mjs";
7
7
  import { DEFAULT_COLLECTIONS, POS_MODEL_NAMES } from "./models/create-models.mjs";
8
8
  import { RegisterRepository } from "./repositories/register.repository.mjs";
9
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, OrderDiscountRefusedError, PosError, PriceOverrideRefusedError, ReasonCodePolicyInvalidError, RegisterRequiredError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, TenderMethodRefusedError, TenderMismatchError, UnmanagedSessionError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
9
10
  import { shiftCloseIdempotencyKey } from "./domain/ports/ledger.bridge.mjs";
10
11
  import { SHIFT_VERBS, allowedVerbs, canTransition, nextState } from "./domain/state-machines/shift.fsm.mjs";
11
12
  import { computeDifference, computeExpected } from "./domain/value-objects/payment-breakdown.vo.mjs";
@@ -72,7 +72,7 @@ const paymentBreakdownSchema = new Schema({
72
72
  methodKind: {
73
73
  type: String,
74
74
  enum: PAYMENT_METHOD_KIND_VALUES,
75
- default: "other"
75
+ required: true
76
76
  },
77
77
  openingAmount: {
78
78
  type: Number,
@@ -76,18 +76,17 @@ export interface IncrementSalesInput {
76
76
  cashierId?: string;
77
77
  cashierName?: string;
78
78
  /**
79
- * Optional claim-first dedupe key. When set, the repo insert-first claims
80
- * `(shiftId, dedupeRef)` in the `pos_shift_sale_dedupe` collection BEFORE
81
- * applying the `$inc`; a duplicate claim means the increment was already
82
- * applied (e.g. a host transaction retry re-ran the order-create hook) and
83
- * the call returns `{ applied: false }` without touching the shift.
84
- *
85
- * MUST be a retry-stable identity — e.g. `shift-sale:{orderNumber}:{method}`
86
- * (orderNumber survives a Mongo transient-txn retry; a per-attempt `_id`
87
- * does not and would defeat the dedupe). Omit to keep the legacy
88
- * "idempotency is the host's responsibility" behavior.
79
+ * Claim-first dedupe key: the repo claims `(shiftId, dedupeRef)` in `pos_shift_sale_dedupe` before the
80
+ * `$inc`, so a retried call returns `{ applied: false }`. Must be retry-stable, e.g.
81
+ * `shift-sale:{orderNumber}:{method}`; a per-attempt id defeats it.
82
+ */
83
+ dedupeRef: string;
84
+ /**
85
+ * Whether this call counts toward `salesCount` / `refundCount`. Default true. A sale or refund
86
+ * split across methods is one call per leg: pass false for every leg after the first, so the count
87
+ * is transactions, not legs.
89
88
  */
90
- dedupeRef?: string;
89
+ countsTransaction?: boolean;
91
90
  }
92
91
  /** Result of `incrementSales` — `applied: false` = dedupe hit or zero amount. */
93
92
  export interface IncrementSalesResult {
@@ -105,11 +104,8 @@ export interface IncrementSalesResult {
105
104
  * post (a crash between the CAS and the ledger write);
106
105
  * this call converged it.
107
106
  *
108
- * `already-closed` is a legitimate IDEMPOTENT RESULT, not an error. It used to
109
- * be an `IllegalShiftTransitionError` thrown after the loser had already
110
- * posted its journal entry — which every host caught and logged, turning a
111
- * double-post into a log line. Returning it as an outcome is what lets the
112
- * lazy-close / cron / oversight triggers stop swallowing exceptions.
107
+ * `already-closed` is an IDEMPOTENT RESULT, not an error, so the lazy-close / cron / oversight
108
+ * triggers never need to swallow exceptions.
113
109
  *
114
110
  * **Counts submitted by a losing caller are NOT applied** — the shift was
115
111
  * reconciled by whoever won. Check `outcome` before reporting success to a
@@ -139,12 +135,8 @@ export interface CloseShiftResult {
139
135
  }
140
136
  export interface ShiftRepositoryConfig {
141
137
  model: Model<IShift>;
142
- /**
143
- * Claim ledger backing `incrementSales({ dedupeRef })`. Optional so tests /
144
- * legacy constructions without the model keep working — a `dedupeRef` call
145
- * without the model throws (fail loud, never silently double-count).
146
- */
147
- dedupeModel?: Model<IShiftSaleDedupe> | undefined;
138
+ /** Claim ledger backing `incrementSales({ dedupeRef })`. */
139
+ dedupeModel: Model<IShiftSaleDedupe>;
148
140
  plugins?: PluginType[] | undefined;
149
141
  /**
150
142
  * Soft-delete policy. `{ ttlDays }` (default 2555 = 7yr) wires
@@ -204,12 +196,8 @@ export declare class ShiftRepository extends Repository<IShift> {
204
196
  * Atomically increment shift aggregates from an order-create hook in the
205
197
  * host. Refunds pass `refund: true`.
206
198
  *
207
- * Idempotency: pass `dedupeRef` (a retry-stable order identity, e.g.
208
- * `shift-sale:{orderNumber}:{method}`) to make the call exactly-once — the
209
- * repo claims `(shiftId, dedupeRef)` insert-first in the dedupe ledger and
210
- * skips the `$inc` on a duplicate claim (`{ applied: false }`). Without
211
- * `dedupeRef` the legacy contract applies: idempotency is the host's
212
- * responsibility (don't call twice for the same order).
199
+ * Exactly-once on `dedupeRef`: the repo claims `(shiftId, dedupeRef)` insert-first in the dedupe
200
+ * ledger and skips the `$inc` on a duplicate claim (`{ applied: false }`).
213
201
  */
214
202
  incrementSales(input: IncrementSalesInput, ctx: PosContext): Promise<IncrementSalesResult>;
215
203
  /**
@@ -247,6 +235,8 @@ export declare class ShiftRepository extends Repository<IShift> {
247
235
  registerId: string;
248
236
  state: string;
249
237
  businessDate: Date;
238
+ salesCount: number;
239
+ salesTotal: number;
250
240
  }>>;
251
241
  /**
252
242
  * The currently ACTIVE shift (`open | paused | blind_closed`), or `null`.
@@ -346,8 +336,7 @@ export declare class ShiftRepository extends Repository<IShift> {
346
336
  * on-disk state says another caller finalized the shift; returns null when
347
337
  * the failure is a genuine illegal transition the caller should throw.
348
338
  *
349
- * The LOSER NEVER POSTS. That is the entire fix: previously the loser had
350
- * already committed its journal entry by the time it got here.
339
+ * The LOSER NEVER POSTS: it reaches here before any journal entry.
351
340
  */
352
341
  private diagnoseLostClaim;
353
342
  /**
@@ -413,7 +402,7 @@ export declare class ShiftRepository extends Repository<IShift> {
413
402
  /**
414
403
  * Write one event inside `unit`. Under a session the row commits with the unit through `dispatchDomainEvent`
415
404
  * (a durable type REFUSES to write anywhere else); returns the event for {@link announceCommitted}. With no
416
- * session (the waived fallback) the legacy save-then-publish runs and `null` says it already published.
405
+ * session (`allowNonTransactional`) it saves then publishes, and `null` says it already published.
417
406
  */
418
407
  private dispatchInUnit;
419
408
  /** After the unit committed: wake the transport (the relay nudge). A caller-owned session flushes for itself. */
@@ -1,5 +1,5 @@
1
- import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, RegisterRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError } from "../domain/errors/pos.errors.mjs";
2
1
  import { ACTIVE_SHIFT_STATES, isFinalShiftState } from "../domain/enums/shift-state.enum.mjs";
2
+ import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, CashMovementKeyReusedError, CashOutExceedsDrawerError, IllegalShiftTransitionError, RegisterRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError } from "../domain/errors/pos.errors.mjs";
3
3
  import { shiftCloseIdempotencyKey } from "../domain/ports/ledger.bridge.mjs";
4
4
  import { canTransition, nextState } from "../domain/state-machines/shift.fsm.mjs";
5
5
  import { computeExpected } from "../domain/value-objects/payment-breakdown.vo.mjs";
@@ -32,17 +32,11 @@ import { dispatchDomainEvent } from "@classytic/primitives/durable-events";
32
32
  * 5. Persist `journalEntryId` + clear `pendingLedgerPost`
33
33
  * 6. Publish `pos:shift.closed`
34
34
  *
35
- * ## Why this order (the defect it fixes)
35
+ * ## Why claim first
36
36
  *
37
- * The bridge used to run BEFORE the CAS, outside any transaction, and the
38
- * loser's `IllegalShiftTransitionError` was thrown AFTER its journal entry had
39
- * already committed — which hosts caught and logged. Three shipped triggers
40
- * close the same shift (lazy-close at register open, the oversight endpoint,
41
- * the EOD cron), so at 08:00 a cashier opening a till and the cron sweeping
42
- * yesterday's orphan would BOTH read `state: 'open'`, BOTH pass `canTransition`
43
- * and BOTH post a Z-report for one day's cash. One shift document, two journal
44
- * entries, no error surfaced. Claiming first makes the bridge unreachable to
45
- * every caller but one.
37
+ * Three triggers close the same shift (lazy-close at register open, the oversight endpoint, the EOD
38
+ * cron) and can race. Claiming before the bridge makes the bridge reachable by exactly one caller, so
39
+ * one shift posts one journal entry.
46
40
  *
47
41
  * ## Crash convergence
48
42
  *
@@ -51,11 +45,7 @@ import { dispatchDomainEvent } from "@classytic/primitives/durable-events";
51
45
  * `forceClose()` RESUMES from that state — same deterministic
52
46
  * `idempotencyKey`, so a durable bridge returns the existing entry instead of
53
47
  * posting a second one. `findShiftsWithPendingLedgerPost()` lists anything
54
- * stuck there. On the old ordering the same crash re-posted a fresh JE on
55
- * every retry, forever.
56
- *
57
- * Idempotency is no longer prose: `ShiftClosePosting.idempotencyKey` is a
58
- * required field the compiler enforces on every implementation.
48
+ * stuck there. `ShiftClosePosting.idempotencyKey` is required by the type, so every bridge receives it.
59
49
  *
60
50
  * ## `ledgerPost: 'deferred'`
61
51
  *
@@ -148,7 +138,7 @@ var ShiftRepository = class extends Repository {
148
138
  }, ctx);
149
139
  return shift;
150
140
  } catch (err) {
151
- if (this.isDuplicateKeyError(err) || err.code === 11e3) throw new ActiveShiftAlreadyOpenError(`${input.registerId}`);
141
+ if (this.isDuplicateKeyError(err)) throw new ActiveShiftAlreadyOpenError(`${input.registerId}`);
152
142
  throw err;
153
143
  }
154
144
  }
@@ -212,12 +202,8 @@ var ShiftRepository = class extends Repository {
212
202
  * Atomically increment shift aggregates from an order-create hook in the
213
203
  * host. Refunds pass `refund: true`.
214
204
  *
215
- * Idempotency: pass `dedupeRef` (a retry-stable order identity, e.g.
216
- * `shift-sale:{orderNumber}:{method}`) to make the call exactly-once — the
217
- * repo claims `(shiftId, dedupeRef)` insert-first in the dedupe ledger and
218
- * skips the `$inc` on a duplicate claim (`{ applied: false }`). Without
219
- * `dedupeRef` the legacy contract applies: idempotency is the host's
220
- * responsibility (don't call twice for the same order).
205
+ * Exactly-once on `dedupeRef`: the repo claims `(shiftId, dedupeRef)` insert-first in the dedupe
206
+ * ledger and skips the `$inc` on a duplicate claim (`{ applied: false }`).
221
207
  */
222
208
  async incrementSales(input, ctx) {
223
209
  if (input.amount <= 0) return {
@@ -231,28 +217,27 @@ var ShiftRepository = class extends Repository {
231
217
  const tax = Math.max(0, rawTax);
232
218
  if (tax > input.amount) throw new CashMovementInvalidError(`tax (${tax}) cannot exceed amount (${input.amount})`);
233
219
  const txnSession = repoOptionsFromCtx(ctx).session;
234
- if (input.dedupeRef !== void 0) {
235
- if (!this.dedupeModel) throw new CashMovementInvalidError("incrementSales dedupeRef requires the ShiftSaleDedupe model — construct the engine via definePos().bind (or pass dedupeModel)");
236
- try {
237
- await this.dedupeModel.create([{
238
- shiftId: input.shiftId,
239
- orderRef: input.dedupeRef
240
- }], txnSession ? { session: txnSession } : {});
241
- } catch (err) {
242
- if (err.code === 11e3) return {
243
- applied: false,
244
- reason: "duplicate"
245
- };
246
- throw err;
247
- }
220
+ if (typeof input.dedupeRef !== "string" || !input.dedupeRef) throw new CashMovementInvalidError("incrementSales requires a retry-stable dedupeRef");
221
+ try {
222
+ await this.dedupeModel.create([{
223
+ shiftId: input.shiftId,
224
+ orderRef: input.dedupeRef
225
+ }], txnSession ? { session: txnSession } : {});
226
+ } catch (err) {
227
+ if (err.code === 11e3) return {
228
+ applied: false,
229
+ reason: "duplicate"
230
+ };
231
+ throw err;
248
232
  }
233
+ const countsTransaction = input.countsTransaction !== false;
249
234
  const update = { $inc: refund ? {
250
- refundCount: 1,
235
+ ...countsTransaction ? { refundCount: 1 } : {},
251
236
  refundTotal: input.amount,
252
237
  "paymentBreakdown.$[methodElem].refundAmount": input.amount,
253
238
  ...tax > 0 ? { "paymentBreakdown.$[methodElem].refundTaxAmount": tax } : {}
254
239
  } : {
255
- salesCount: 1,
240
+ ...countsTransaction ? { salesCount: 1 } : {},
256
241
  salesTotal: input.amount,
257
242
  "paymentBreakdown.$[methodElem].salesAmount": input.amount,
258
243
  ...tax > 0 ? { "paymentBreakdown.$[methodElem].taxAmount": tax } : {}
@@ -273,7 +258,7 @@ var ShiftRepository = class extends Repository {
273
258
  arrayFilters: [{ "methodElem.method": input.method }],
274
259
  ...repoOptionsFromCtx(ctx)
275
260
  })) {
276
- if (input.dedupeRef !== void 0 && this.dedupeModel) await this.dedupeModel.deleteOne({
261
+ await this.dedupeModel.deleteOne({
277
262
  shiftId: input.shiftId,
278
263
  orderRef: input.dedupeRef
279
264
  }, txnSession ? { session: txnSession } : {});
@@ -485,7 +470,9 @@ var ShiftRepository = class extends Repository {
485
470
  organizationId: 1,
486
471
  registerId: 1,
487
472
  state: 1,
488
- businessDate: 1
473
+ businessDate: 1,
474
+ salesCount: 1,
475
+ salesTotal: 1
489
476
  }).lean();
490
477
  }
491
478
  /**
@@ -779,8 +766,7 @@ var ShiftRepository = class extends Repository {
779
766
  * on-disk state says another caller finalized the shift; returns null when
780
767
  * the failure is a genuine illegal transition the caller should throw.
781
768
  *
782
- * The LOSER NEVER POSTS. That is the entire fix: previously the loser had
783
- * already committed its journal entry by the time it got here.
769
+ * The LOSER NEVER POSTS: it reaches here before any journal entry.
784
770
  */
785
771
  async diagnoseLostClaim(err, shiftId, fromState, verb, ctx) {
786
772
  if (!(err instanceof IllegalShiftTransitionError) && !isTransitionRace(err)) return null;
@@ -1001,7 +987,7 @@ var ShiftRepository = class extends Repository {
1001
987
  /**
1002
988
  * Write one event inside `unit`. Under a session the row commits with the unit through `dispatchDomainEvent`
1003
989
  * (a durable type REFUSES to write anywhere else); returns the event for {@link announceCommitted}. With no
1004
- * session (the waived fallback) the legacy save-then-publish runs and `null` says it already published.
990
+ * session (`allowNonTransactional`) it saves then publishes, and `null` says it already published.
1005
991
  */
1006
992
  async dispatchInUnit(name, payload, unit) {
1007
993
  if (unit.session === void 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/pos",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Multi-vertical POS / register-session kernel for MongoDB — shift lifecycle, cash-drawer reconciliation, payment-method breakdown, variance detection, FSM. Works for retail, restaurant, clinic, service-booking, car-wash and any vertical with a 'shift opens, shift closes, money is reconciled' workflow.",
5
5
  "author": "Classytic",
6
6
  "type": "module",
@@ -87,13 +87,13 @@
87
87
  "release": "npm run push -- main && npm run release:tag && npm publish"
88
88
  },
89
89
  "peerDependencies": {
90
- "@classytic/mongokit": ">=3.41.0",
91
- "@classytic/order": ">=0.19.0",
92
- "@classytic/primitives": ">=0.32.0",
93
- "@classytic/repo-core": ">=0.31.0",
94
- "@classytic/tax-core": ">=0.6.0",
90
+ "@classytic/mongokit": ">=3.47.0",
91
+ "@classytic/order": ">=0.24.0",
92
+ "@classytic/primitives": ">=0.39.0",
93
+ "@classytic/repo-core": ">=0.39.0",
94
+ "@classytic/tax-core": ">=0.7.0",
95
95
  "@classytic/validation": ">=0.6.0",
96
- "mongoose": ">=9.11.0",
96
+ "mongoose": ">=9.13.1",
97
97
  "zod": ">=4.0.0"
98
98
  },
99
99
  "peerDependenciesMeta": {
@@ -109,16 +109,16 @@
109
109
  },
110
110
  "devDependencies": {
111
111
  "@classytic/dev-tools": "^0.2.1",
112
- "@classytic/mongokit": "^3.43.0",
113
- "@classytic/order": "^0.19.0",
114
- "@classytic/primitives": "^0.34.0",
115
- "@classytic/repo-core": "^0.31.1",
116
- "@classytic/tax-core": "^0.6.0",
112
+ "@classytic/mongokit": "^3.47.0",
113
+ "@classytic/order": "^0.24.0",
114
+ "@classytic/primitives": "^0.39.0",
115
+ "@classytic/repo-core": "^0.39.0",
116
+ "@classytic/tax-core": "^0.7.0",
117
117
  "@classytic/validation": "^0.6.0",
118
118
  "@types/node": "^26.6.5",
119
119
  "@vitest/coverage-v8": "^5.0.5",
120
120
  "mongodb-memory-server": "^11.3.0",
121
- "mongoose": "^9.11.2",
121
+ "mongoose": "^9.13.1",
122
122
  "publint": "^0.3.25",
123
123
  "tsdown": "^0.23.1",
124
124
  "typescript": "^7.0.2",