@classytic/pos 0.3.1 → 0.4.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.
- package/CHANGELOG.md +236 -10
- package/LICENSE +75 -21
- package/README.md +11 -4
- package/dist/domain/enums/cash-movement-reason.enum.d.mts +15 -1
- package/dist/domain/enums/closed-by.enum.d.mts +1 -1
- package/dist/domain/enums/payment-method.enum.d.mts +23 -9
- package/dist/domain/enums/payment-method.enum.mjs +27 -7
- package/dist/domain/enums/shift-state.enum.d.mts +1 -1
- package/dist/domain/errors/pos.errors.d.mts +53 -10
- package/dist/domain/errors/pos.errors.mjs +58 -13
- package/dist/domain/index.d.mts +5 -5
- package/dist/domain/index.mjs +5 -4
- package/dist/domain/ports/common.d.mts +0 -1
- package/dist/domain/ports/ledger.bridge.d.mts +42 -8
- package/dist/domain/ports/ledger.bridge.mjs +14 -0
- package/dist/domain/ports/notification.bridge.d.mts +0 -1
- package/dist/domain/ports/policy.bridge.d.mts +0 -1
- package/dist/domain/state-machines/shift.fsm.d.mts +1 -2
- package/dist/domain/value-objects/cash-movement.vo.d.mts +0 -1
- package/dist/domain/value-objects/payment-breakdown.vo.d.mts +4 -1
- package/dist/domain/value-objects/shift-policy.vo.d.mts +31 -3
- package/dist/domain/value-objects/shift-policy.vo.mjs +35 -1
- package/dist/engine/define-pos.d.mts +9 -0
- package/dist/engine/define-pos.mjs +126 -0
- package/dist/engine/engine-types.d.mts +84 -36
- package/dist/engine/index.d.mts +4 -3
- package/dist/engine/index.mjs +2 -2
- package/dist/events/event-catalog.d.mts +6 -7
- package/dist/events/event-constants.d.mts +8 -8
- package/dist/events/event-payloads.d.mts +0 -1
- package/dist/events/helpers.d.mts +0 -1
- package/dist/events/helpers.mjs +5 -5
- package/dist/events/in-process-bus.d.mts +4 -15
- package/dist/events/in-process-bus.mjs +14 -32
- package/dist/events/outbox-store.d.mts +3 -19
- package/dist/events/outbox-store.mjs +1 -27
- package/dist/index.d.mts +15 -10
- package/dist/index.mjs +8 -6
- package/dist/models/create-models.d.mts +31 -4
- package/dist/models/create-models.mjs +80 -13
- package/dist/models/hide-soft-delete.mjs +11 -0
- package/dist/models/inject-tenant.d.mts +2 -2
- package/dist/models/inject-tenant.mjs +4 -10
- package/dist/models/register.model.d.mts +37 -0
- package/dist/models/register.model.mjs +82 -0
- package/dist/models/shift-sale-dedupe.model.d.mts +16 -0
- package/dist/models/shift-sale-dedupe.model.mjs +57 -0
- package/dist/models/shift.model.d.mts +48 -2
- package/dist/models/shift.model.mjs +88 -25
- package/dist/repositories/register.repository.d.mts +22 -0
- package/dist/repositories/register.repository.mjs +25 -0
- package/dist/repositories/shift.repository.d.mts +217 -12
- package/dist/repositories/shift.repository.mjs +480 -85
- package/dist/schemas/shift.d.mts +7 -18
- package/dist/schemas/shift.mjs +1 -2
- package/dist/testing/fixtures.d.mts +0 -1
- package/package.json +13 -10
- package/dist/engine/create-pos.d.mts +0 -6
- package/dist/engine/create-pos.mjs +0 -82
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
//#region src/domain/errors/pos.errors.ts
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* `status` makes every POS throwable satisfy `HttpError` from
|
|
4
|
+
* `@classytic/repo-core/errors`, so arc's global handler serializes it with
|
|
5
|
+
* the correct status natively — no per-host `errorMapper`. Without it every
|
|
6
|
+
* POS error reached the client as `arc.internal_error` / 500, including
|
|
7
|
+
* `ShiftNotFoundError` (404) and `ActiveShiftAlreadyOpenError` (409).
|
|
4
8
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* stable `code` for log-mining and i18n.
|
|
9
|
+
* Defaults to 422; subclasses override with `readonly status = N` (a subclass
|
|
10
|
+
* field initializer runs after this constructor, so it wins).
|
|
8
11
|
*/
|
|
9
12
|
var PosError = class extends Error {
|
|
10
13
|
code;
|
|
14
|
+
status = 422;
|
|
11
15
|
constructor(code, message) {
|
|
12
16
|
super(message);
|
|
13
17
|
this.name = "PosError";
|
|
@@ -20,29 +24,34 @@ var PosError = class extends Error {
|
|
|
20
24
|
* Session + outbox is legal durable-relay-only mode.
|
|
21
25
|
*/
|
|
22
26
|
var UnmanagedSessionError = class extends PosError {
|
|
27
|
+
status = 500;
|
|
23
28
|
constructor() {
|
|
24
29
|
super("POS_SESSION_UNMANAGED", "ctx.session provided but no OutboxStore is wired — events would leak or be lost. Wire an outbox or drop the session.");
|
|
25
30
|
}
|
|
26
31
|
};
|
|
27
32
|
var ShiftNotFoundError = class extends PosError {
|
|
33
|
+
status = 404;
|
|
28
34
|
constructor(id) {
|
|
29
35
|
super("SHIFT_NOT_FOUND", `Shift not found: ${id}`);
|
|
30
36
|
this.name = "ShiftNotFoundError";
|
|
31
37
|
}
|
|
32
38
|
};
|
|
33
39
|
var IllegalShiftTransitionError = class extends PosError {
|
|
40
|
+
status = 422;
|
|
34
41
|
constructor(from, verb) {
|
|
35
42
|
super("ILLEGAL_SHIFT_TRANSITION", `Cannot ${verb} a shift in state '${from}'`);
|
|
36
43
|
this.name = "IllegalShiftTransitionError";
|
|
37
44
|
}
|
|
38
45
|
};
|
|
39
46
|
var ActiveShiftAlreadyOpenError = class extends PosError {
|
|
47
|
+
status = 409;
|
|
40
48
|
constructor(scope) {
|
|
41
49
|
super("ACTIVE_SHIFT_ALREADY_OPEN", `An active shift already exists for scope '${scope}'`);
|
|
42
50
|
this.name = "ActiveShiftAlreadyOpenError";
|
|
43
51
|
}
|
|
44
52
|
};
|
|
45
53
|
var VarianceExceededError = class extends PosError {
|
|
54
|
+
status = 409;
|
|
46
55
|
difference;
|
|
47
56
|
expected;
|
|
48
57
|
constructor(difference, expected) {
|
|
@@ -53,30 +62,66 @@ var VarianceExceededError = class extends PosError {
|
|
|
53
62
|
}
|
|
54
63
|
};
|
|
55
64
|
var ShiftFinalizedError = class extends PosError {
|
|
65
|
+
status = 409;
|
|
56
66
|
constructor(id) {
|
|
57
67
|
super("SHIFT_FINALIZED", `Shift ${id} is final and cannot be mutated`);
|
|
58
68
|
this.name = "ShiftFinalizedError";
|
|
59
69
|
}
|
|
60
70
|
};
|
|
71
|
+
/**
|
|
72
|
+
* Thrown when a NEW SALE is attempted against a paused shift. A paused till
|
|
73
|
+
* takes no new sales until it is resumed (refunds and cash movements are
|
|
74
|
+
* corrections and remain allowed). Distinct from {@link ShiftFinalizedError}:
|
|
75
|
+
* the shift is recoverable — resume it and retry.
|
|
76
|
+
*/
|
|
77
|
+
var ShiftPausedError = class extends PosError {
|
|
78
|
+
status = 409;
|
|
79
|
+
constructor(id) {
|
|
80
|
+
super("SHIFT_PAUSED", `Shift ${id} is paused — resume it before recording new sales`);
|
|
81
|
+
this.name = "ShiftPausedError";
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Thrown when a shift is closed directly from `open` (no prior blind-close
|
|
86
|
+
* reading) without any counted amounts. There is no expected-vs-counted
|
|
87
|
+
* reconciliation to perform, so the drawer would close with a null variance
|
|
88
|
+
* regardless of policy — closing a till you never counted. The caller must
|
|
89
|
+
* pass `countedByMethod` (cash always, plus any non-cash tender being
|
|
90
|
+
* reconciled) or blind-close first.
|
|
91
|
+
*/
|
|
92
|
+
var ShiftCountsRequiredError = class extends PosError {
|
|
93
|
+
status = 422;
|
|
94
|
+
constructor(id) {
|
|
95
|
+
super("SHIFT_COUNTS_REQUIRED", `Shift ${id} is being closed directly from 'open' with no counted amounts — pass countedByMethod (or blind-close first) so the drawer can be reconciled`);
|
|
96
|
+
this.name = "ShiftCountsRequiredError";
|
|
97
|
+
}
|
|
98
|
+
};
|
|
61
99
|
var CashMovementInvalidError = class extends PosError {
|
|
100
|
+
status = 422;
|
|
62
101
|
constructor(reason) {
|
|
63
102
|
super("CASH_MOVEMENT_INVALID", reason);
|
|
64
103
|
this.name = "CashMovementInvalidError";
|
|
65
104
|
}
|
|
66
105
|
};
|
|
67
106
|
var PosCapabilityError = class extends Error {
|
|
107
|
+
code = "POS_CAPABILITY";
|
|
108
|
+
status = 422;
|
|
68
109
|
missing;
|
|
69
|
-
|
|
70
|
-
|
|
110
|
+
/**
|
|
111
|
+
* `true` when the backend never ANSWERED (the connection was not open at
|
|
112
|
+
* bind, or the driver exposed no topology) rather than answering "no".
|
|
113
|
+
* Both refuse — an unobserved outcome is never a positive one (AGENTS.md
|
|
114
|
+
* FAIL LOUD rule 3) — but the operator's fix is completely different, so
|
|
115
|
+
* the message has to distinguish them.
|
|
116
|
+
*/
|
|
117
|
+
indeterminate;
|
|
118
|
+
constructor(missing, opts = {}) {
|
|
119
|
+
const indeterminate = opts.indeterminate === true;
|
|
120
|
+
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." : ""));
|
|
71
121
|
this.name = "PosCapabilityError";
|
|
72
122
|
this.missing = missing;
|
|
73
|
-
|
|
74
|
-
};
|
|
75
|
-
var ShiftModelCollisionError = class extends Error {
|
|
76
|
-
constructor(name) {
|
|
77
|
-
super(`[pos] Mongoose model "${name}" already exists on this connection. For hot-reload / test fixtures, pass \`forceRecreate: true\` to clobber. For two pos engines in one process, use two Mongoose connections (\`mongoose.createConnection(...)\`) — each has its own model registry.`);
|
|
78
|
-
this.name = "ShiftModelCollisionError";
|
|
123
|
+
this.indeterminate = indeterminate;
|
|
79
124
|
}
|
|
80
125
|
};
|
|
81
126
|
//#endregion
|
|
82
|
-
export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError,
|
|
127
|
+
export { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, UnmanagedSessionError, VarianceExceededError };
|
package/dist/domain/index.d.mts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, ShiftState, isActiveShiftState, isFinalShiftState } from "./enums/shift-state.enum.mjs";
|
|
2
|
-
import { SHIFT_PAYMENT_METHODS, ShiftPaymentMethod } from "./enums/payment-method.enum.mjs";
|
|
2
|
+
import { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS, ShiftPaymentMethod, resolveMethodKind } from "./enums/payment-method.enum.mjs";
|
|
3
3
|
import { CASH_MOVEMENT_REASON_CODES, CashMovementReasonCode } from "./enums/cash-movement-reason.enum.mjs";
|
|
4
4
|
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, isWithinVarianceThreshold } from "./value-objects/shift-policy.vo.mjs";
|
|
9
|
-
import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError,
|
|
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";
|
|
10
10
|
import { PosContext } from "./ports/common.mjs";
|
|
11
|
-
import { LedgerBridge } from "./ports/ledger.bridge.mjs";
|
|
11
|
+
import { LedgerBridge, ShiftClosePosting, shiftCloseIdempotencyKey } from "./ports/ledger.bridge.mjs";
|
|
12
12
|
import { PolicyBridge } from "./ports/policy.bridge.mjs";
|
|
13
13
|
import { NotificationBridge } from "./ports/notification.bridge.mjs";
|
|
14
|
-
export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementReasonCode, ClosedBy, FINAL_SHIFT_STATES, IllegalShiftTransitionError, type LedgerBridge, type NotificationBridge, PaymentBreakdown, type PolicyBridge, PosCapabilityError, type PosContext, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS,
|
|
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 };
|
package/dist/domain/index.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError,
|
|
1
|
+
import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosCapabilityError, PosError, ShiftCountsRequiredError, ShiftFinalizedError, ShiftNotFoundError, ShiftPausedError, 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
|
-
import { SHIFT_PAYMENT_METHODS } from "./enums/payment-method.enum.mjs";
|
|
4
|
+
import { DEFAULT_METHOD_KINDS, PAYMENT_METHOD_KIND_VALUES, SHIFT_PAYMENT_METHODS, resolveMethodKind } from "./enums/payment-method.enum.mjs";
|
|
5
5
|
import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, isActiveShiftState, isFinalShiftState } from "./enums/shift-state.enum.mjs";
|
|
6
|
+
import { shiftCloseIdempotencyKey } from "./ports/ledger.bridge.mjs";
|
|
6
7
|
import { SHIFT_VERBS, allowedVerbs, canTransition, nextState } from "./state-machines/shift.fsm.mjs";
|
|
7
8
|
import { computeDifference, computeExpected } from "./value-objects/payment-breakdown.vo.mjs";
|
|
8
|
-
import { isWithinVarianceThreshold } from "./value-objects/shift-policy.vo.mjs";
|
|
9
|
-
export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, FINAL_SHIFT_STATES, IllegalShiftTransitionError, PosCapabilityError, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS,
|
|
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 };
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { OperationContext } from "@classytic/primitives/context";
|
|
2
2
|
import { RetryPolicy } from "@classytic/repo-core/repository";
|
|
3
|
-
|
|
4
3
|
//#region src/domain/ports/common.d.ts
|
|
5
4
|
interface PosContext extends OperationContext {
|
|
6
5
|
/** Host's local-TZ business date (YYYY-MM-DD) for shifts that derive at open. */
|
|
@@ -1,18 +1,52 @@
|
|
|
1
1
|
import { PosContext } from "./common.mjs";
|
|
2
|
-
import { ShiftDocument } from "../../models/shift.model.mjs";
|
|
3
|
-
|
|
2
|
+
import { PendingLedgerPostTrigger, ShiftDocument } from "../../models/shift.model.mjs";
|
|
4
3
|
//#region src/domain/ports/ledger.bridge.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The deterministic idempotency key for a shift's close posting.
|
|
6
|
+
*
|
|
7
|
+
* Derived from the shift id ALONE — never the clock, never a random
|
|
8
|
+
* fallback, never the attempt number. A key that varies per attempt
|
|
9
|
+
* defeats deduplication while looking correctly wired (AGENTS.md: derive
|
|
10
|
+
* identifiers deterministically).
|
|
11
|
+
*/
|
|
12
|
+
declare function shiftCloseIdempotencyKey(shiftId: string): string;
|
|
13
|
+
/** The posting request handed to {@link LedgerBridge.onShiftClosed}. */
|
|
14
|
+
interface ShiftClosePosting {
|
|
15
|
+
/**
|
|
16
|
+
* REQUIRED. `pos:shift:<shiftId>:close` — see
|
|
17
|
+
* {@link shiftCloseIdempotencyKey}. Dedupe on this or the resume path
|
|
18
|
+
* double-posts.
|
|
19
|
+
*/
|
|
20
|
+
idempotencyKey: string;
|
|
21
|
+
/**
|
|
22
|
+
* The shift AS PERSISTED after the CAS — terminal state, final
|
|
23
|
+
* reconciliation values, `closedAt` / `closedBy` set. Not a projection:
|
|
24
|
+
* the document the bridge reads is the document the books describe.
|
|
25
|
+
*/
|
|
26
|
+
shift: ShiftDocument;
|
|
27
|
+
/** Which pipeline claimed the shift. */
|
|
28
|
+
trigger: PendingLedgerPostTrigger;
|
|
29
|
+
/**
|
|
30
|
+
* 1 on the first post; >1 when a crashed close is being converged. A
|
|
31
|
+
* `> 1` attempt means a prior invocation MAY have committed a JE the
|
|
32
|
+
* package never recorded — this is exactly when `idempotencyKey`
|
|
33
|
+
* earns its keep.
|
|
34
|
+
*/
|
|
35
|
+
attempt: number;
|
|
36
|
+
}
|
|
5
37
|
interface LedgerBridge {
|
|
6
38
|
/**
|
|
7
|
-
*
|
|
8
|
-
* the package persists it onto the shift.
|
|
39
|
+
* Post the shift's journal entry. Return the host-side journal entry id;
|
|
40
|
+
* the package persists it onto the shift and clears the pending marker.
|
|
9
41
|
*
|
|
10
|
-
* Throw on validation / chart-of-accounts errors
|
|
11
|
-
*
|
|
42
|
+
* Throw on validation / chart-of-accounts errors. During `close()` the
|
|
43
|
+
* package compensates the CAS and rethrows; during `forceClose()` it logs
|
|
44
|
+
* and leaves the orphan converge-able. Use a domain error class with a
|
|
45
|
+
* stable `code`.
|
|
12
46
|
*/
|
|
13
|
-
onShiftClosed(
|
|
47
|
+
onShiftClosed(request: ShiftClosePosting, ctx: PosContext): Promise<{
|
|
14
48
|
journalEntryId: string;
|
|
15
49
|
}>;
|
|
16
50
|
}
|
|
17
51
|
//#endregion
|
|
18
|
-
export { LedgerBridge };
|
|
52
|
+
export { LedgerBridge, ShiftClosePosting, shiftCloseIdempotencyKey };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/domain/ports/ledger.bridge.ts
|
|
2
|
+
/**
|
|
3
|
+
* The deterministic idempotency key for a shift's close posting.
|
|
4
|
+
*
|
|
5
|
+
* Derived from the shift id ALONE — never the clock, never a random
|
|
6
|
+
* fallback, never the attempt number. A key that varies per attempt
|
|
7
|
+
* defeats deduplication while looking correctly wired (AGENTS.md: derive
|
|
8
|
+
* identifiers deterministically).
|
|
9
|
+
*/
|
|
10
|
+
function shiftCloseIdempotencyKey(shiftId) {
|
|
11
|
+
return `pos:shift:${shiftId}:close`;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
export { shiftCloseIdempotencyKey };
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { PosContext } from "./common.mjs";
|
|
2
2
|
import { ShiftDocument } from "../../models/shift.model.mjs";
|
|
3
|
-
|
|
4
3
|
//#region src/domain/ports/notification.bridge.d.ts
|
|
5
4
|
interface NotificationBridge {
|
|
6
5
|
/** Cash variance exceeded the policy threshold and was overridden by a manager. */
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { ShiftState } from "../enums/shift-state.enum.mjs";
|
|
2
|
-
|
|
3
2
|
//#region src/domain/state-machines/shift.fsm.d.ts
|
|
4
3
|
/** Domain verbs that drive transitions. */
|
|
5
|
-
declare const SHIFT_VERBS: readonly [
|
|
4
|
+
declare const SHIFT_VERBS: readonly ['pause', 'resume', 'blindClose', 'close', 'forceClose'];
|
|
6
5
|
type ShiftVerb = (typeof SHIFT_VERBS)[number];
|
|
7
6
|
/** Resolve the target state for a verb from a given state, or `null` if disallowed. */
|
|
8
7
|
declare function nextState(from: ShiftState, verb: ShiftVerb): ShiftState | null;
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { ShiftPaymentMethod } from "../enums/payment-method.enum.mjs";
|
|
2
|
-
|
|
2
|
+
import { PaymentMethodKind } from "@classytic/primitives/payment-method-kind";
|
|
3
3
|
//#region src/domain/value-objects/payment-breakdown.vo.d.ts
|
|
4
4
|
interface PaymentBreakdown {
|
|
5
|
+
/** Deployment/provider-specific method code (open string). */
|
|
5
6
|
method: ShiftPaymentMethod;
|
|
7
|
+
/** Universal category for reconciliation/reporting (resolved from the code). */
|
|
8
|
+
methodKind: PaymentMethodKind;
|
|
6
9
|
openingAmount: number;
|
|
7
10
|
salesAmount: number;
|
|
8
11
|
/** Tax portion of salesAmount (subset, not additional). 0 when no tax applied. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ShiftPaymentMethod } from "../enums/payment-method.enum.mjs";
|
|
2
2
|
import { CashMovementReasonCode } from "../enums/cash-movement-reason.enum.mjs";
|
|
3
|
-
|
|
3
|
+
import { PaymentMethodKind } from "@classytic/primitives/payment-method-kind";
|
|
4
4
|
//#region src/domain/value-objects/shift-policy.vo.d.ts
|
|
5
5
|
interface ShiftPolicy {
|
|
6
6
|
/** Null = cashier chooses opening float. Number = required exact match at open. */
|
|
@@ -19,9 +19,37 @@ interface ShiftPolicy {
|
|
|
19
19
|
requireReasonCode: boolean;
|
|
20
20
|
/** Subset of reason codes valid at this branch. */
|
|
21
21
|
allowedReasonCodes: readonly CashMovementReasonCode[];
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Method CODES accepted at this branch — the closed table for the shift. Any
|
|
24
|
+
* open string (baseline `cash`/`card`/… or provider codes `bkash`/`nagad`/…).
|
|
25
|
+
*/
|
|
23
26
|
allowedPaymentMethods: readonly ShiftPaymentMethod[];
|
|
27
|
+
/**
|
|
28
|
+
* Explicit code → universal kind overrides for non-baseline codes (e.g.
|
|
29
|
+
* `{ bkash: 'mobile_money', gift_card: 'gift_card' }`). Baseline codes
|
|
30
|
+
* resolve automatically; absent codes fall back to `other`.
|
|
31
|
+
*/
|
|
32
|
+
paymentMethodKinds?: Readonly<Record<string, PaymentMethodKind>>;
|
|
24
33
|
}
|
|
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.
|
|
41
|
+
*
|
|
42
|
+
* The values are the conservative reading of the research the FSM is modelled
|
|
43
|
+
* on: blind-close OFF (a single-operator shop must not be forced into a
|
|
44
|
+
* two-person flow), variance gated at 100 major units OR 0.5% of expected
|
|
45
|
+
* (whichever is looser — they are OR-combined), and a manager override REQUIRED
|
|
46
|
+
* past that, because an unexplained till difference is the one thing a cash
|
|
47
|
+
* audit exists to surface.
|
|
48
|
+
*
|
|
49
|
+
* Per-branch variation belongs in DATA, resolved through the policy bridge —
|
|
50
|
+
* not in a second literal.
|
|
51
|
+
*/
|
|
52
|
+
declare function defaultShiftPolicy(overrides?: Partial<ShiftPolicy>): ShiftPolicy;
|
|
25
53
|
/**
|
|
26
54
|
* Variance check — pure function so tests don't need a shift document.
|
|
27
55
|
* Returns `withinThreshold: true` if EITHER bound is satisfied (whichever is
|
|
@@ -29,4 +57,4 @@ interface ShiftPolicy {
|
|
|
29
57
|
*/
|
|
30
58
|
declare function isWithinVarianceThreshold(difference: number, expected: number, policy: Pick<ShiftPolicy, 'varianceThresholdAbs' | 'varianceThresholdPct'>): boolean;
|
|
31
59
|
//#endregion
|
|
32
|
-
export { ShiftPolicy, isWithinVarianceThreshold };
|
|
60
|
+
export { ShiftPolicy, defaultShiftPolicy, isWithinVarianceThreshold };
|
|
@@ -1,5 +1,39 @@
|
|
|
1
|
+
import { CASH_MOVEMENT_REASON_CODES } from "../enums/cash-movement-reason.enum.mjs";
|
|
2
|
+
import { SHIFT_PAYMENT_METHODS } from "../enums/payment-method.enum.mjs";
|
|
1
3
|
//#region src/domain/value-objects/shift-policy.vo.ts
|
|
2
4
|
/**
|
|
5
|
+
* A sane starting policy, so a HOST never hardcodes one.
|
|
6
|
+
*
|
|
7
|
+
* Every deployment used to carry its own literal — be-prod's
|
|
8
|
+
* `shift.constants.ts`, and a copy in every fork of it. That is business policy
|
|
9
|
+
* living in composition code: it drifts, and a fix in one host reaches none of
|
|
10
|
+
* the others. The kernel owns `ShiftPolicy`, so the kernel owns its default.
|
|
11
|
+
*
|
|
12
|
+
* The values are the conservative reading of the research the FSM is modelled
|
|
13
|
+
* on: blind-close OFF (a single-operator shop must not be forced into a
|
|
14
|
+
* two-person flow), variance gated at 100 major units OR 0.5% of expected
|
|
15
|
+
* (whichever is looser — they are OR-combined), and a manager override REQUIRED
|
|
16
|
+
* past that, because an unexplained till difference is the one thing a cash
|
|
17
|
+
* audit exists to surface.
|
|
18
|
+
*
|
|
19
|
+
* Per-branch variation belongs in DATA, resolved through the policy bridge —
|
|
20
|
+
* not in a second literal.
|
|
21
|
+
*/
|
|
22
|
+
function defaultShiftPolicy(overrides = {}) {
|
|
23
|
+
return {
|
|
24
|
+
requiredOpeningFloat: null,
|
|
25
|
+
blindCloseRequired: false,
|
|
26
|
+
varianceThresholdAbs: 1e4,
|
|
27
|
+
varianceThresholdPct: .5,
|
|
28
|
+
managerOverrideRequired: true,
|
|
29
|
+
allowHandover: true,
|
|
30
|
+
requireReasonCode: true,
|
|
31
|
+
allowedReasonCodes: [...CASH_MOVEMENT_REASON_CODES],
|
|
32
|
+
allowedPaymentMethods: [...SHIFT_PAYMENT_METHODS],
|
|
33
|
+
...overrides
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
3
37
|
* Variance check — pure function so tests don't need a shift document.
|
|
4
38
|
* Returns `withinThreshold: true` if EITHER bound is satisfied (whichever is
|
|
5
39
|
* looser). Threshold semantics: a |diff| of exactly threshold is permitted.
|
|
@@ -11,4 +45,4 @@ function isWithinVarianceThreshold(difference, expected, policy) {
|
|
|
11
45
|
return abs <= policy.varianceThresholdPct / 100 * expected;
|
|
12
46
|
}
|
|
13
47
|
//#endregion
|
|
14
|
-
export { isWithinVarianceThreshold };
|
|
48
|
+
export { defaultShiftPolicy, isWithinVarianceThreshold };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { PosBlueprint, PosShape } from "./engine-types.mjs";
|
|
2
|
+
//#region src/engine/define-pos.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Describe the POS engine. Pure — registers no model, builds no schema,
|
|
5
|
+
* performs no I/O.
|
|
6
|
+
*/
|
|
7
|
+
declare function definePos(shape: PosShape): PosBlueprint;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { definePos };
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { PosCapabilityError } from "../domain/errors/pos.errors.mjs";
|
|
2
|
+
import { InProcessPosBus } from "../events/in-process-bus.mjs";
|
|
3
|
+
import { resolvePosTenant } from "../models/inject-tenant.mjs";
|
|
4
|
+
import { definePosModels } from "../models/create-models.mjs";
|
|
5
|
+
import { RegisterRepository } from "../repositories/register.repository.mjs";
|
|
6
|
+
import { ShiftRepository } from "../repositories/shift.repository.mjs";
|
|
7
|
+
import { multiTenantPlugin, transactionResolutionOf } from "@classytic/mongokit";
|
|
8
|
+
import { assertNoLegacyTenantKeys } from "@classytic/repo-core/tenant";
|
|
9
|
+
//#region src/engine/define-pos.ts
|
|
10
|
+
/** Repository capabilities asserted at bind. */
|
|
11
|
+
const REQUIRED_CAPABILITIES = ["transactions"];
|
|
12
|
+
/**
|
|
13
|
+
* Describe the POS engine. Pure — registers no model, builds no schema,
|
|
14
|
+
* performs no I/O.
|
|
15
|
+
*/
|
|
16
|
+
function definePos(shape) {
|
|
17
|
+
assertNoLegacyTenantKeys(shape, "definePos", [["tenantFieldType", "tenant.fieldType"]]);
|
|
18
|
+
if (!shape || !shape.defaultPolicy) throw new Error("definePos: shape.defaultPolicy is required");
|
|
19
|
+
const defaultPolicy = shape.defaultPolicy;
|
|
20
|
+
const tenant = resolvePosTenant(shape.tenant ?? true);
|
|
21
|
+
const softDelete = shape.softDelete === false ? false : { ttlDays: typeof shape.softDelete === "object" && typeof shape.softDelete.ttlDays === "number" ? shape.softDelete.ttlDays : 2555 };
|
|
22
|
+
const modelBlueprint = definePosModels({
|
|
23
|
+
tenant,
|
|
24
|
+
...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
|
|
25
|
+
...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
|
|
26
|
+
...shape.forceRecreate !== void 0 ? { forceRecreate: shape.forceRecreate } : {}
|
|
27
|
+
});
|
|
28
|
+
return {
|
|
29
|
+
id: "pos",
|
|
30
|
+
modelNames: modelBlueprint.modelNames,
|
|
31
|
+
bind(connection, runtime = {}) {
|
|
32
|
+
/**
|
|
33
|
+
* VERIFY (boot gate) — an injected outbox MUST enlist `ctx.session`.
|
|
34
|
+
*
|
|
35
|
+
* FIRST, before the model blueprint binds: a cheaper error should report before a
|
|
36
|
+
* costlier one, and a bind refused here must leave the connection's model registry
|
|
37
|
+
* untouched.
|
|
38
|
+
*
|
|
39
|
+
* `OutboxWriteOptions.session` is best-effort BY CONTRACT (see
|
|
40
|
+
* `@classytic/primitives/outbox`), so a hand-rolled store satisfies `OutboxStore`
|
|
41
|
+
* and then keeps the row when the host's transaction aborts. POS's dispatch saves
|
|
42
|
+
* under `ctx.session` for the opposite reason: a till checkout runs the sale, the
|
|
43
|
+
* `incrementSales` and the event in ONE host transaction. A store that drops the
|
|
44
|
+
* session emits `pos:shift.closed` — the Z-report event the ledger bridge posts a
|
|
45
|
+
* journal entry from — for a close that rolled back, so the GL carries a day's cash
|
|
46
|
+
* the shift document says was never counted. Nothing throws on either side.
|
|
47
|
+
*
|
|
48
|
+
* This is NOT the `transactions` requirement (the capability gate below owns that)
|
|
49
|
+
* — it is about the STORE's contract, and `allowNonTransactional` does not waive it.
|
|
50
|
+
*/
|
|
51
|
+
if (runtime.outbox && runtime.outbox.transactionalSave !== true) throw new PosCapabilityError(["outbox.transactionalSave (the configured OutboxStore does not declare that save() enlists ctx.session — see @classytic/primitives/outbox)"]);
|
|
52
|
+
const models = modelBlueprint.bind(connection);
|
|
53
|
+
const logger = runtime.logger ?? console;
|
|
54
|
+
const bridges = runtime.bridges ?? {};
|
|
55
|
+
const allowNonTransactional = runtime.allowNonTransactional ?? false;
|
|
56
|
+
const ownsTransport = runtime.eventTransport === void 0;
|
|
57
|
+
const events = runtime.eventTransport ?? new InProcessPosBus({ logger });
|
|
58
|
+
const tenantPlugins = !tenant.enabled ? [] : [multiTenantPlugin({
|
|
59
|
+
tenantField: tenant.tenantField,
|
|
60
|
+
contextKey: tenant.contextKey,
|
|
61
|
+
required: tenant.required,
|
|
62
|
+
fieldType: tenant.fieldType
|
|
63
|
+
})];
|
|
64
|
+
const shiftRepo = new ShiftRepository({
|
|
65
|
+
model: models.Shift,
|
|
66
|
+
dedupeModel: models.ShiftSaleDedupe,
|
|
67
|
+
plugins: tenantPlugins,
|
|
68
|
+
softDelete,
|
|
69
|
+
defaultPolicy,
|
|
70
|
+
...bridges.ledger ? { ledgerBridge: bridges.ledger } : {},
|
|
71
|
+
...bridges.policy ? { policyBridge: bridges.policy } : {},
|
|
72
|
+
...bridges.notification ? { notificationBridge: bridges.notification } : {},
|
|
73
|
+
eventTransport: events,
|
|
74
|
+
...runtime.outbox ? { outbox: runtime.outbox } : {},
|
|
75
|
+
logger
|
|
76
|
+
});
|
|
77
|
+
const registerRepo = new RegisterRepository({
|
|
78
|
+
model: models.Register,
|
|
79
|
+
plugins: tenantPlugins,
|
|
80
|
+
softDelete
|
|
81
|
+
});
|
|
82
|
+
{
|
|
83
|
+
const caps = shiftRepo.capabilities;
|
|
84
|
+
if (!caps) throw new PosCapabilityError(["capabilities descriptor (repo-core 0.6 / mongokit 3.16+)"]);
|
|
85
|
+
const missing = REQUIRED_CAPABILITIES.filter((flag) => caps[flag] !== true);
|
|
86
|
+
if (missing.length > 0) {
|
|
87
|
+
const indeterminate = transactionResolutionOf(caps) === "unknown";
|
|
88
|
+
if (allowNonTransactional) logger.warn?.(`[pos] the backend ${indeterminate ? "could NOT be confirmed to support" : "does NOT support"}: ${missing.join(", ")}. allowNonTransactional=true: the close / forceClose pipelines run WITHOUT atomicity — a crash mid-close can leave a shift closed with no outbox row (or the reverse). Development only.`);
|
|
89
|
+
else throw new PosCapabilityError(missing, { indeterminate });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const resolved = Object.freeze({
|
|
93
|
+
defaultPolicy,
|
|
94
|
+
tenant,
|
|
95
|
+
softDelete,
|
|
96
|
+
collectionPrefix: shape.collectionPrefix,
|
|
97
|
+
autoIndex: shape.autoIndex,
|
|
98
|
+
forceRecreate: shape.forceRecreate ?? false,
|
|
99
|
+
allowNonTransactional
|
|
100
|
+
});
|
|
101
|
+
let closed = false;
|
|
102
|
+
return Object.freeze({
|
|
103
|
+
config: resolved,
|
|
104
|
+
bridges: Object.freeze({ ...bridges }),
|
|
105
|
+
events,
|
|
106
|
+
outbox: runtime.outbox,
|
|
107
|
+
models,
|
|
108
|
+
repositories: {
|
|
109
|
+
shift: shiftRepo,
|
|
110
|
+
register: registerRepo
|
|
111
|
+
},
|
|
112
|
+
defaultPolicy,
|
|
113
|
+
async syncIndexes() {
|
|
114
|
+
return Promise.all(Object.values(models).map((m) => m.syncIndexes()));
|
|
115
|
+
},
|
|
116
|
+
async close() {
|
|
117
|
+
if (closed) return;
|
|
118
|
+
closed = true;
|
|
119
|
+
if (ownsTransport) await events.close?.();
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
export { definePos };
|