@classytic/pos 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +152 -0
- package/dist/domain/enums/cash-movement-reason.enum.d.mts +12 -0
- package/dist/domain/enums/cash-movement-reason.enum.mjs +19 -0
- package/dist/domain/enums/closed-by.enum.d.mts +13 -0
- package/dist/domain/enums/closed-by.enum.mjs +16 -0
- package/dist/domain/enums/payment-method.enum.d.mts +14 -0
- package/dist/domain/enums/payment-method.enum.mjs +18 -0
- package/dist/domain/enums/shift-state.enum.d.mts +26 -0
- package/dist/domain/enums/shift-state.enum.mjs +39 -0
- package/dist/domain/errors/pos.errors.d.mts +37 -0
- package/dist/domain/errors/pos.errors.mjs +64 -0
- package/dist/domain/index.d.mts +14 -0
- package/dist/domain/index.mjs +9 -0
- package/dist/domain/ports/common.d.mts +9 -0
- package/dist/domain/ports/ledger.bridge.d.mts +18 -0
- package/dist/domain/ports/notification.bridge.d.mts +12 -0
- package/dist/domain/ports/policy.bridge.d.mts +13 -0
- package/dist/domain/state-machines/shift.fsm.d.mts +14 -0
- package/dist/domain/state-machines/shift.fsm.mjs +41 -0
- package/dist/domain/value-objects/cash-movement.vo.d.mts +19 -0
- package/dist/domain/value-objects/payment-breakdown.vo.d.mts +24 -0
- package/dist/domain/value-objects/payment-breakdown.vo.mjs +11 -0
- package/dist/domain/value-objects/shift-policy.vo.d.mts +32 -0
- package/dist/domain/value-objects/shift-policy.vo.mjs +14 -0
- package/dist/engine/create-pos.d.mts +6 -0
- package/dist/engine/create-pos.mjs +65 -0
- package/dist/engine/engine-types.d.mts +73 -0
- package/dist/engine/index.d.mts +3 -0
- package/dist/engine/index.mjs +2 -0
- package/dist/events/event-constants.d.mts +21 -0
- package/dist/events/event-constants.mjs +20 -0
- package/dist/events/event-payloads.d.mts +49 -0
- package/dist/events/helpers.d.mts +6 -0
- package/dist/events/helpers.mjs +12 -0
- package/dist/events/in-process-bus.d.mts +19 -0
- package/dist/events/in-process-bus.mjs +38 -0
- package/dist/events/index.d.mts +5 -0
- package/dist/events/index.mjs +4 -0
- package/dist/index.d.mts +23 -0
- package/dist/index.mjs +15 -0
- package/dist/models/create-models.d.mts +9 -0
- package/dist/models/create-models.mjs +20 -0
- package/dist/models/inject-tenant.d.mts +2 -0
- package/dist/models/inject-tenant.mjs +48 -0
- package/dist/models/shift.model.d.mts +68 -0
- package/dist/models/shift.model.mjs +267 -0
- package/dist/repositories/repo-options.mjs +20 -0
- package/dist/repositories/shift.repository.d.mts +153 -0
- package/dist/repositories/shift.repository.mjs +401 -0
- package/dist/schemas/index.d.mts +2 -0
- package/dist/schemas/index.mjs +2 -0
- package/dist/schemas/shift.d.mts +67 -0
- package/dist/schemas/shift.mjs +52 -0
- package/dist/testing/fixtures.d.mts +9 -0
- package/dist/testing/fixtures.mjs +36 -0
- package/dist/testing/index.d.mts +2 -0
- package/dist/testing/index.mjs +2 -0
- package/package.json +110 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region src/domain/value-objects/payment-breakdown.vo.ts
|
|
2
|
+
/** Pure compute — `expectedAmount` from inputs. Lives in VO so tests don't need a DB. */
|
|
3
|
+
function computeExpected(b) {
|
|
4
|
+
return b.openingAmount + b.salesAmount - b.refundAmount + b.cashInAmount - b.cashOutAmount;
|
|
5
|
+
}
|
|
6
|
+
/** Pure compute — variance from a counted reading. Returns null if counted is null. */
|
|
7
|
+
function computeDifference(expected, counted) {
|
|
8
|
+
return counted === null ? null : counted - expected;
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
export { computeDifference, computeExpected };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { ShiftPaymentMethod } from "../enums/payment-method.enum.mjs";
|
|
2
|
+
import { CashMovementReasonCode } from "../enums/cash-movement-reason.enum.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/domain/value-objects/shift-policy.vo.d.ts
|
|
5
|
+
interface ShiftPolicy {
|
|
6
|
+
/** Null = cashier chooses opening float. Number = required exact match at open. */
|
|
7
|
+
requiredOpeningFloat: number | null;
|
|
8
|
+
/** Lightspeed-style — cashier blind-counts, manager reconciles. */
|
|
9
|
+
blindCloseRequired: boolean;
|
|
10
|
+
/** Variance gate (absolute, minor units). */
|
|
11
|
+
varianceThresholdAbs: number;
|
|
12
|
+
/** Variance gate as percent of expected cash. OR-combined with abs. */
|
|
13
|
+
varianceThresholdPct: number;
|
|
14
|
+
/** When variance exceeds threshold, manager override row is required to close. */
|
|
15
|
+
managerOverrideRequired: boolean;
|
|
16
|
+
/** Toast-style pause/resume. */
|
|
17
|
+
allowHandover: boolean;
|
|
18
|
+
/** Shopify 2025: require reason code on every cash-in / cash-out. */
|
|
19
|
+
requireReasonCode: boolean;
|
|
20
|
+
/** Subset of reason codes valid at this branch. */
|
|
21
|
+
allowedReasonCodes: readonly CashMovementReasonCode[];
|
|
22
|
+
/** Subset of payment methods accepted at this branch. */
|
|
23
|
+
allowedPaymentMethods: readonly ShiftPaymentMethod[];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Variance check — pure function so tests don't need a shift document.
|
|
27
|
+
* Returns `withinThreshold: true` if EITHER bound is satisfied (whichever is
|
|
28
|
+
* looser). Threshold semantics: a |diff| of exactly threshold is permitted.
|
|
29
|
+
*/
|
|
30
|
+
declare function isWithinVarianceThreshold(difference: number, expected: number, policy: Pick<ShiftPolicy, 'varianceThresholdAbs' | 'varianceThresholdPct'>): boolean;
|
|
31
|
+
//#endregion
|
|
32
|
+
export { ShiftPolicy, isWithinVarianceThreshold };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/domain/value-objects/shift-policy.vo.ts
|
|
2
|
+
/**
|
|
3
|
+
* Variance check — pure function so tests don't need a shift document.
|
|
4
|
+
* Returns `withinThreshold: true` if EITHER bound is satisfied (whichever is
|
|
5
|
+
* looser). Threshold semantics: a |diff| of exactly threshold is permitted.
|
|
6
|
+
*/
|
|
7
|
+
function isWithinVarianceThreshold(difference, expected, policy) {
|
|
8
|
+
const abs = Math.abs(difference);
|
|
9
|
+
if (abs <= policy.varianceThresholdAbs) return true;
|
|
10
|
+
if (expected <= 0) return false;
|
|
11
|
+
return abs <= policy.varianceThresholdPct / 100 * expected;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
export { isWithinVarianceThreshold };
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { InProcessPosBus } from "../events/in-process-bus.mjs";
|
|
2
|
+
import { resolvePosTenant } from "../models/inject-tenant.mjs";
|
|
3
|
+
import { createPosModels } from "../models/create-models.mjs";
|
|
4
|
+
import { ShiftRepository } from "../repositories/shift.repository.mjs";
|
|
5
|
+
import { multiTenantPlugin } from "@classytic/mongokit";
|
|
6
|
+
//#region src/engine/create-pos.ts
|
|
7
|
+
/**
|
|
8
|
+
* createPosEngine — factory entry point.
|
|
9
|
+
*
|
|
10
|
+
* import { createPosEngine } from '@classytic/pos';
|
|
11
|
+
* const pos = createPosEngine({ connection, defaultPolicy });
|
|
12
|
+
* await pos.repositories.shift.open({ ... }, ctx);
|
|
13
|
+
*
|
|
14
|
+
* The engine returns a closed-over object — no class, no inheritance.
|
|
15
|
+
* Hosts wire arc adapters directly off `pos.repositories.shift` (auto-CRUD)
|
|
16
|
+
* and call domain verbs for state changes.
|
|
17
|
+
*
|
|
18
|
+
* Multi-tenant scoping is ON by default. The mongokit `multiTenantPlugin`
|
|
19
|
+
* runs at `policy` priority on every read/write; cross-tenant leakage is
|
|
20
|
+
* impossible to forget. Hosts that genuinely need single-tenant deployments
|
|
21
|
+
* pass `multiTenant: false`.
|
|
22
|
+
*/
|
|
23
|
+
function createPosEngine(config) {
|
|
24
|
+
if (!config.connection) throw new Error("createPosEngine: config.connection is required");
|
|
25
|
+
if (!config.defaultPolicy) throw new Error("createPosEngine: config.defaultPolicy is required");
|
|
26
|
+
const logger = config.logger ?? console;
|
|
27
|
+
const events = config.eventTransport ?? new InProcessPosBus({ logger });
|
|
28
|
+
const bridges = config.bridges ?? {};
|
|
29
|
+
const tenant = resolvePosTenant({
|
|
30
|
+
multiTenant: config.multiTenant === false ? false : true,
|
|
31
|
+
tenantFieldType: config.tenantFieldType ?? "objectId",
|
|
32
|
+
...typeof config.multiTenant === "object" ? config.multiTenant : {}
|
|
33
|
+
});
|
|
34
|
+
const models = createPosModels({
|
|
35
|
+
connection: config.connection,
|
|
36
|
+
tenant,
|
|
37
|
+
...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
|
|
38
|
+
...config.autoIndex !== void 0 ? { autoIndex: config.autoIndex } : {},
|
|
39
|
+
...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
|
|
40
|
+
});
|
|
41
|
+
const tenantPlugins = config.multiTenant === false ? [] : [multiTenantPlugin({
|
|
42
|
+
...typeof config.multiTenant === "object" ? config.multiTenant : {},
|
|
43
|
+
fieldType: tenant.fieldType
|
|
44
|
+
})];
|
|
45
|
+
const shiftRepo = new ShiftRepository({
|
|
46
|
+
model: models.Shift,
|
|
47
|
+
plugins: tenantPlugins,
|
|
48
|
+
defaultPolicy: config.defaultPolicy,
|
|
49
|
+
...bridges.ledger ? { ledgerBridge: bridges.ledger } : {},
|
|
50
|
+
...bridges.policy ? { policyBridge: bridges.policy } : {},
|
|
51
|
+
...bridges.notification ? { notificationBridge: bridges.notification } : {},
|
|
52
|
+
eventTransport: events,
|
|
53
|
+
logger
|
|
54
|
+
});
|
|
55
|
+
return {
|
|
56
|
+
config: Object.freeze({ ...config }),
|
|
57
|
+
bridges: Object.freeze({ ...bridges }),
|
|
58
|
+
events,
|
|
59
|
+
models,
|
|
60
|
+
repositories: { shift: shiftRepo },
|
|
61
|
+
defaultPolicy: config.defaultPolicy
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
export { createPosEngine };
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { ShiftPolicy } from "../domain/value-objects/shift-policy.vo.mjs";
|
|
2
|
+
import { IShift } from "../models/shift.model.mjs";
|
|
3
|
+
import { LedgerBridge } from "../domain/ports/ledger.bridge.mjs";
|
|
4
|
+
import { PolicyBridge } from "../domain/ports/policy.bridge.mjs";
|
|
5
|
+
import { NotificationBridge } from "../domain/ports/notification.bridge.mjs";
|
|
6
|
+
import { ShiftRepository } from "../repositories/shift.repository.mjs";
|
|
7
|
+
import { EventTransport } from "@classytic/primitives/events";
|
|
8
|
+
import { Connection, Model } from "mongoose";
|
|
9
|
+
import { TenantConfig } from "@classytic/repo-core/tenant";
|
|
10
|
+
|
|
11
|
+
//#region src/engine/engine-types.d.ts
|
|
12
|
+
interface PosBridges {
|
|
13
|
+
/**
|
|
14
|
+
* Ledger bridge — host implements `onShiftClosed(shift, ctx)` to emit a
|
|
15
|
+
* JournalEntry and return the resulting `journalEntryId`. Without this
|
|
16
|
+
* bridge, `close()` runs the variance gate and writes state but does not
|
|
17
|
+
* post any accounting record (you can wire one later).
|
|
18
|
+
*/
|
|
19
|
+
ledger?: LedgerBridge;
|
|
20
|
+
/** Override `defaultPolicy` per shift open. Default: use `defaultPolicy` verbatim. */
|
|
21
|
+
policy?: PolicyBridge;
|
|
22
|
+
/** Variance + orphan-close notifications. Best-effort; failures don't block state. */
|
|
23
|
+
notification?: NotificationBridge;
|
|
24
|
+
}
|
|
25
|
+
interface PosLogger {
|
|
26
|
+
error(message: string, ...args: unknown[]): void;
|
|
27
|
+
}
|
|
28
|
+
interface PosConfig {
|
|
29
|
+
/** Mongoose connection (or `mongoose.connection`). */
|
|
30
|
+
connection: Connection;
|
|
31
|
+
/** Default shift policy when neither `bridges.policy` nor a per-call override is supplied. */
|
|
32
|
+
defaultPolicy: ShiftPolicy;
|
|
33
|
+
/** Bridges — every method is opt-in, package degrades gracefully without them. */
|
|
34
|
+
bridges?: PosBridges | undefined;
|
|
35
|
+
/** Inject your own event bus; otherwise an in-process bus is used. */
|
|
36
|
+
eventTransport?: EventTransport | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Multi-tenant scoping. `true` (default) wires the mongokit
|
|
39
|
+
* `multiTenantPlugin` and prepends `organizationId` to every compound
|
|
40
|
+
* index. `false` disables the plugin (host enforces scope at its own
|
|
41
|
+
* framework layer); the field is still added.
|
|
42
|
+
*/
|
|
43
|
+
multiTenant?: boolean | TenantConfig | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Legacy shorthand — `'objectId' | 'string'`. Most hosts pass `'objectId'`
|
|
46
|
+
* (the Better Auth org id is an ObjectId).
|
|
47
|
+
*/
|
|
48
|
+
tenantFieldType?: 'objectId' | 'string' | undefined;
|
|
49
|
+
/** Optional collection-name namespace. See PACKAGE_RULES §20.1. */
|
|
50
|
+
collectionPrefix?: string | undefined;
|
|
51
|
+
/** Disable Mongoose autoIndex in production; run `Shift.syncIndexes()` explicitly. */
|
|
52
|
+
autoIndex?: boolean | undefined;
|
|
53
|
+
/** Hot-reload escape hatch for test fixtures. Default false. */
|
|
54
|
+
forceRecreate?: boolean | undefined;
|
|
55
|
+
/** Custom logger; defaults to `console`. */
|
|
56
|
+
logger?: PosLogger | undefined;
|
|
57
|
+
}
|
|
58
|
+
interface PosModels {
|
|
59
|
+
Shift: Model<IShift>;
|
|
60
|
+
}
|
|
61
|
+
interface PosRepositories {
|
|
62
|
+
shift: ShiftRepository;
|
|
63
|
+
}
|
|
64
|
+
interface PosEngine {
|
|
65
|
+
readonly config: Readonly<PosConfig>;
|
|
66
|
+
readonly bridges: Readonly<PosBridges>;
|
|
67
|
+
readonly events: EventTransport;
|
|
68
|
+
readonly models: PosModels;
|
|
69
|
+
readonly repositories: PosRepositories;
|
|
70
|
+
readonly defaultPolicy: ShiftPolicy;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
export { PosBridges, PosConfig, PosEngine, PosLogger, PosModels, PosRepositories };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { PosBridges, PosConfig, PosEngine, PosLogger, PosModels, PosRepositories } from "./engine-types.mjs";
|
|
2
|
+
import { createPosEngine } from "./create-pos.mjs";
|
|
3
|
+
export { type PosBridges, type PosConfig, type PosEngine, type PosLogger, type PosModels, type PosRepositories, createPosEngine };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region src/events/event-constants.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Event names emitted by `@classytic/pos`. Use string constants — not
|
|
4
|
+
* enums — so consumers can subscribe via glob patterns and we keep the
|
|
5
|
+
* payload typing in `event-payloads.ts`.
|
|
6
|
+
*
|
|
7
|
+
* Naming follows PACKAGE_RULES §12: `package:resource.verb`.
|
|
8
|
+
*/
|
|
9
|
+
declare const POS_EVENTS: {
|
|
10
|
+
readonly SHIFT_OPENED: "pos:shift.opened";
|
|
11
|
+
readonly SHIFT_PAUSED: "pos:shift.paused";
|
|
12
|
+
readonly SHIFT_RESUMED: "pos:shift.resumed";
|
|
13
|
+
readonly SHIFT_BLIND_CLOSED: "pos:shift.blind_closed";
|
|
14
|
+
readonly SHIFT_CLOSED: "pos:shift.closed";
|
|
15
|
+
readonly SHIFT_FORCE_CLOSED: "pos:shift.force_closed";
|
|
16
|
+
readonly CASH_MOVEMENT_RECORDED: "pos:cash_movement.recorded";
|
|
17
|
+
readonly VARIANCE_DETECTED: "pos:shift.variance.detected";
|
|
18
|
+
};
|
|
19
|
+
type PosEventName = (typeof POS_EVENTS)[keyof typeof POS_EVENTS];
|
|
20
|
+
//#endregion
|
|
21
|
+
export { POS_EVENTS, PosEventName };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region src/events/event-constants.ts
|
|
2
|
+
/**
|
|
3
|
+
* Event names emitted by `@classytic/pos`. Use string constants — not
|
|
4
|
+
* enums — so consumers can subscribe via glob patterns and we keep the
|
|
5
|
+
* payload typing in `event-payloads.ts`.
|
|
6
|
+
*
|
|
7
|
+
* Naming follows PACKAGE_RULES §12: `package:resource.verb`.
|
|
8
|
+
*/
|
|
9
|
+
const POS_EVENTS = {
|
|
10
|
+
SHIFT_OPENED: "pos:shift.opened",
|
|
11
|
+
SHIFT_PAUSED: "pos:shift.paused",
|
|
12
|
+
SHIFT_RESUMED: "pos:shift.resumed",
|
|
13
|
+
SHIFT_BLIND_CLOSED: "pos:shift.blind_closed",
|
|
14
|
+
SHIFT_CLOSED: "pos:shift.closed",
|
|
15
|
+
SHIFT_FORCE_CLOSED: "pos:shift.force_closed",
|
|
16
|
+
CASH_MOVEMENT_RECORDED: "pos:cash_movement.recorded",
|
|
17
|
+
VARIANCE_DETECTED: "pos:shift.variance.detected"
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
export { POS_EVENTS };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { CashMovementReasonCode } from "../domain/enums/cash-movement-reason.enum.mjs";
|
|
2
|
+
import { ClosedBy } from "../domain/enums/closed-by.enum.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/events/event-payloads.d.ts
|
|
5
|
+
interface ShiftOpenedPayload {
|
|
6
|
+
shiftId: string;
|
|
7
|
+
registerId: string;
|
|
8
|
+
openingCashierId: string;
|
|
9
|
+
}
|
|
10
|
+
interface ShiftClosedPayload {
|
|
11
|
+
shiftId: string;
|
|
12
|
+
journalEntryId: string | null;
|
|
13
|
+
closedBy: ClosedBy;
|
|
14
|
+
}
|
|
15
|
+
interface ShiftBlindClosedPayload {
|
|
16
|
+
shiftId: string;
|
|
17
|
+
}
|
|
18
|
+
interface ShiftForceClosedPayload {
|
|
19
|
+
shiftId: string;
|
|
20
|
+
reason: 'orphan_eod' | 'admin_override';
|
|
21
|
+
}
|
|
22
|
+
interface ShiftStateChangedPayload {
|
|
23
|
+
shiftId: string;
|
|
24
|
+
from: string;
|
|
25
|
+
to: string;
|
|
26
|
+
}
|
|
27
|
+
interface CashMovementRecordedPayload {
|
|
28
|
+
shiftId: string;
|
|
29
|
+
type: 'in' | 'out';
|
|
30
|
+
amount: number;
|
|
31
|
+
reasonCode: CashMovementReasonCode;
|
|
32
|
+
}
|
|
33
|
+
interface VarianceDetectedPayload {
|
|
34
|
+
shiftId: string;
|
|
35
|
+
difference: number;
|
|
36
|
+
expected: number;
|
|
37
|
+
}
|
|
38
|
+
interface PosEventPayloads {
|
|
39
|
+
'pos:shift.opened': ShiftOpenedPayload;
|
|
40
|
+
'pos:shift.paused': ShiftStateChangedPayload;
|
|
41
|
+
'pos:shift.resumed': ShiftStateChangedPayload;
|
|
42
|
+
'pos:shift.blind_closed': ShiftBlindClosedPayload;
|
|
43
|
+
'pos:shift.closed': ShiftClosedPayload;
|
|
44
|
+
'pos:shift.force_closed': ShiftForceClosedPayload;
|
|
45
|
+
'pos:cash_movement.recorded': CashMovementRecordedPayload;
|
|
46
|
+
'pos:shift.variance.detected': VarianceDetectedPayload;
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
export { CashMovementRecordedPayload, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createEvent } from "@classytic/primitives/events";
|
|
2
|
+
//#region src/events/helpers.ts
|
|
3
|
+
/**
|
|
4
|
+
* Thin typed wrapper around primitives' `createEvent` so the event id /
|
|
5
|
+
* timestamp / version live in one place. Internal — the package's domain
|
|
6
|
+
* verbs call this.
|
|
7
|
+
*/
|
|
8
|
+
function createPosEvent(name, payload) {
|
|
9
|
+
return createEvent(name, payload, { source: "@classytic/pos" });
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
export { createPosEvent };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { DomainEvent, EventHandler, EventTransport } from "@classytic/primitives/events";
|
|
2
|
+
|
|
3
|
+
//#region src/events/in-process-bus.d.ts
|
|
4
|
+
interface InProcessPosBusOptions {
|
|
5
|
+
logger?: {
|
|
6
|
+
error(message: string, ...args: unknown[]): void;
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
declare class InProcessPosBus implements EventTransport {
|
|
10
|
+
readonly name = "in-process-pos";
|
|
11
|
+
private handlers;
|
|
12
|
+
private logger;
|
|
13
|
+
constructor(options?: InProcessPosBusOptions);
|
|
14
|
+
publish(event: DomainEvent): Promise<void>;
|
|
15
|
+
subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
export { InProcessPosBus };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { matchEventPattern } from "@classytic/primitives/events";
|
|
2
|
+
//#region src/events/in-process-bus.ts
|
|
3
|
+
var InProcessPosBus = class {
|
|
4
|
+
name = "in-process-pos";
|
|
5
|
+
handlers = /* @__PURE__ */ new Map();
|
|
6
|
+
logger;
|
|
7
|
+
constructor(options = {}) {
|
|
8
|
+
this.logger = options.logger ?? console;
|
|
9
|
+
}
|
|
10
|
+
async publish(event) {
|
|
11
|
+
const matched = /* @__PURE__ */ new Set();
|
|
12
|
+
for (const [pattern, handlers] of this.handlers.entries()) if (matchEventPattern(pattern, event.type)) for (const h of handlers) matched.add(h);
|
|
13
|
+
for (const handler of matched) try {
|
|
14
|
+
await handler(event);
|
|
15
|
+
} catch (err) {
|
|
16
|
+
this.logger.error(`[pos] handler error for ${event.type}:`, err);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
async subscribe(pattern, handler) {
|
|
20
|
+
let set = this.handlers.get(pattern);
|
|
21
|
+
if (!set) {
|
|
22
|
+
set = /* @__PURE__ */ new Set();
|
|
23
|
+
this.handlers.set(pattern, set);
|
|
24
|
+
}
|
|
25
|
+
set.add(handler);
|
|
26
|
+
return () => {
|
|
27
|
+
const s = this.handlers.get(pattern);
|
|
28
|
+
if (!s) return;
|
|
29
|
+
s.delete(handler);
|
|
30
|
+
if (s.size === 0) this.handlers.delete(pattern);
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
async close() {
|
|
34
|
+
this.handlers.clear();
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
//#endregion
|
|
38
|
+
export { InProcessPosBus };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { POS_EVENTS, PosEventName } from "./event-constants.mjs";
|
|
2
|
+
import { CashMovementRecordedPayload, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload } from "./event-payloads.mjs";
|
|
3
|
+
import { createPosEvent } from "./helpers.mjs";
|
|
4
|
+
import { InProcessPosBus } from "./in-process-bus.mjs";
|
|
5
|
+
export { CashMovementRecordedPayload, InProcessPosBus, POS_EVENTS, PosEventName, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload, createPosEvent };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, ShiftState, isActiveShiftState, isFinalShiftState } from "./domain/enums/shift-state.enum.mjs";
|
|
2
|
+
import { SHIFT_PAYMENT_METHODS, ShiftPaymentMethod } from "./domain/enums/payment-method.enum.mjs";
|
|
3
|
+
import { CASH_MOVEMENT_REASON_CODES, CashMovementReasonCode } from "./domain/enums/cash-movement-reason.enum.mjs";
|
|
4
|
+
import { CLOSED_BY_VALUES, ClosedBy } from "./domain/enums/closed-by.enum.mjs";
|
|
5
|
+
import { SHIFT_VERBS, ShiftVerb, allowedVerbs, canTransition, nextState } from "./domain/state-machines/shift.fsm.mjs";
|
|
6
|
+
import { CashMovement } from "./domain/value-objects/cash-movement.vo.mjs";
|
|
7
|
+
import { PaymentBreakdown, computeDifference, computeExpected } from "./domain/value-objects/payment-breakdown.vo.mjs";
|
|
8
|
+
import { ShiftPolicy, isWithinVarianceThreshold } from "./domain/value-objects/shift-policy.vo.mjs";
|
|
9
|
+
import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
|
|
10
|
+
import { PosContext } from "./domain/ports/common.mjs";
|
|
11
|
+
import { IShift, ShiftDocument, ShiftModel } from "./models/shift.model.mjs";
|
|
12
|
+
import { LedgerBridge } from "./domain/ports/ledger.bridge.mjs";
|
|
13
|
+
import { PolicyBridge } from "./domain/ports/policy.bridge.mjs";
|
|
14
|
+
import { NotificationBridge } from "./domain/ports/notification.bridge.mjs";
|
|
15
|
+
import { BlindCloseInput, CloseShiftInput, IncrementSalesInput, OpenShiftInput, RecordCashMovementInput, ShiftRepository, ShiftRepositoryConfig } from "./repositories/shift.repository.mjs";
|
|
16
|
+
import { PosBridges, PosConfig, PosEngine, PosLogger, PosModels, PosRepositories } from "./engine/engine-types.mjs";
|
|
17
|
+
import { createPosEngine } from "./engine/create-pos.mjs";
|
|
18
|
+
import { POS_EVENTS, PosEventName } from "./events/event-constants.mjs";
|
|
19
|
+
import { CashMovementRecordedPayload, PosEventPayloads, ShiftBlindClosedPayload, ShiftClosedPayload, ShiftForceClosedPayload, ShiftOpenedPayload, ShiftStateChangedPayload, VarianceDetectedPayload } from "./events/event-payloads.mjs";
|
|
20
|
+
import { createPosEvent } from "./events/helpers.mjs";
|
|
21
|
+
import { InProcessPosBus } from "./events/in-process-bus.mjs";
|
|
22
|
+
import { DEFAULT_COLLECTIONS } from "./models/create-models.mjs";
|
|
23
|
+
export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, type BlindCloseInput, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovement, CashMovementInvalidError, CashMovementReasonCode, CashMovementRecordedPayload, type CloseShiftInput, ClosedBy, DEFAULT_COLLECTIONS, FINAL_SHIFT_STATES, type IShift, IllegalShiftTransitionError, InProcessPosBus, type IncrementSalesInput, LedgerBridge, NotificationBridge, type OpenShiftInput, POS_EVENTS, PaymentBreakdown, PolicyBridge, type PosBridges, type PosConfig, PosContext, type PosEngine, PosError, PosEventName, PosEventPayloads, type PosLogger, type PosModels, type PosRepositories, type RecordCashMovementInput, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftBlindClosedPayload, ShiftClosedPayload, type ShiftDocument, ShiftFinalizedError, ShiftForceClosedPayload, type ShiftModel, ShiftModelCollisionError, ShiftNotFoundError, ShiftOpenedPayload, ShiftPaymentMethod, ShiftPolicy, ShiftRepository, type ShiftRepositoryConfig, ShiftState, ShiftStateChangedPayload, ShiftVerb, VarianceDetectedPayload, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { InProcessPosBus } from "./events/in-process-bus.mjs";
|
|
2
|
+
import { ActiveShiftAlreadyOpenError, CashMovementInvalidError, IllegalShiftTransitionError, PosError, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, VarianceExceededError } from "./domain/errors/pos.errors.mjs";
|
|
3
|
+
import { CASH_MOVEMENT_REASON_CODES } from "./domain/enums/cash-movement-reason.enum.mjs";
|
|
4
|
+
import { CLOSED_BY_VALUES } from "./domain/enums/closed-by.enum.mjs";
|
|
5
|
+
import { SHIFT_PAYMENT_METHODS } from "./domain/enums/payment-method.enum.mjs";
|
|
6
|
+
import { ACTIVE_SHIFT_STATES, FINAL_SHIFT_STATES, SHIFT_STATES, isActiveShiftState, isFinalShiftState } from "./domain/enums/shift-state.enum.mjs";
|
|
7
|
+
import { DEFAULT_COLLECTIONS } from "./models/create-models.mjs";
|
|
8
|
+
import { SHIFT_VERBS, allowedVerbs, canTransition, nextState } from "./domain/state-machines/shift.fsm.mjs";
|
|
9
|
+
import { computeDifference, computeExpected } from "./domain/value-objects/payment-breakdown.vo.mjs";
|
|
10
|
+
import { isWithinVarianceThreshold } from "./domain/value-objects/shift-policy.vo.mjs";
|
|
11
|
+
import { POS_EVENTS } from "./events/event-constants.mjs";
|
|
12
|
+
import { createPosEvent } from "./events/helpers.mjs";
|
|
13
|
+
import { ShiftRepository } from "./repositories/shift.repository.mjs";
|
|
14
|
+
import { createPosEngine } from "./engine/create-pos.mjs";
|
|
15
|
+
export { ACTIVE_SHIFT_STATES, ActiveShiftAlreadyOpenError, CASH_MOVEMENT_REASON_CODES, CLOSED_BY_VALUES, CashMovementInvalidError, DEFAULT_COLLECTIONS, FINAL_SHIFT_STATES, IllegalShiftTransitionError, InProcessPosBus, POS_EVENTS, PosError, SHIFT_PAYMENT_METHODS, SHIFT_STATES, SHIFT_VERBS, ShiftFinalizedError, ShiftModelCollisionError, ShiftNotFoundError, ShiftRepository, VarianceExceededError, allowedVerbs, canTransition, computeDifference, computeExpected, createPosEngine, createPosEvent, isActiveShiftState, isFinalShiftState, isWithinVarianceThreshold, nextState };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Connection } from "mongoose";
|
|
2
|
+
|
|
3
|
+
//#region src/models/create-models.d.ts
|
|
4
|
+
/** Single source of truth for collection names. Renaming = breaking change. */
|
|
5
|
+
declare const DEFAULT_COLLECTIONS: {
|
|
6
|
+
readonly Shift: "pos_shifts";
|
|
7
|
+
};
|
|
8
|
+
//#endregion
|
|
9
|
+
export { DEFAULT_COLLECTIONS };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ShiftModelCollisionError } from "../domain/errors/pos.errors.mjs";
|
|
2
|
+
import { buildShiftSchema } from "./shift.model.mjs";
|
|
3
|
+
//#region src/models/create-models.ts
|
|
4
|
+
/** Single source of truth for collection names. Renaming = breaking change. */
|
|
5
|
+
const DEFAULT_COLLECTIONS = { Shift: "pos_shifts" };
|
|
6
|
+
const POS_MODEL_NAMES = ["Shift"];
|
|
7
|
+
function createPosModels(options) {
|
|
8
|
+
const { connection, tenant, collectionPrefix, autoIndex, forceRecreate } = options;
|
|
9
|
+
if (forceRecreate) {
|
|
10
|
+
for (const name of POS_MODEL_NAMES) if (connection.models[name]) connection.deleteModel(name);
|
|
11
|
+
} else for (const name of POS_MODEL_NAMES) if (connection.models[name]) throw new ShiftModelCollisionError(name);
|
|
12
|
+
const prefix = collectionPrefix ?? "";
|
|
13
|
+
const shiftSchema = buildShiftSchema({
|
|
14
|
+
tenant,
|
|
15
|
+
autoIndex
|
|
16
|
+
});
|
|
17
|
+
return { Shift: connection.model("Shift", shiftSchema, prefix + DEFAULT_COLLECTIONS.Shift) };
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
export { DEFAULT_COLLECTIONS, createPosModels };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import mongoose from "mongoose";
|
|
2
|
+
import { resolveTenantConfig } from "@classytic/repo-core/tenant";
|
|
3
|
+
//#region src/models/inject-tenant.ts
|
|
4
|
+
/**
|
|
5
|
+
* Mongoose-specific tenant adapter — wraps `resolveTenantConfig()` from
|
|
6
|
+
* `@classytic/repo-core/tenant`. The pure resolution lives in primitives
|
|
7
|
+
* (zero runtime deps); this file handles schema mutations (add field +
|
|
8
|
+
* prepend tenant to compound indexes) that primitives cannot own without a
|
|
9
|
+
* mongoose dependency. Mirrors the @classytic/order convention.
|
|
10
|
+
*/
|
|
11
|
+
function resolvePosTenant(input = {}) {
|
|
12
|
+
if (typeof input === "boolean" || input === void 0) return resolveTenantConfig(input);
|
|
13
|
+
if ("tenantFieldType" in input || "multiTenant" in input) {
|
|
14
|
+
const legacy = input;
|
|
15
|
+
return resolveTenantConfig({
|
|
16
|
+
enabled: legacy.multiTenant !== false,
|
|
17
|
+
fieldType: legacy.tenantFieldType ?? "objectId"
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
return resolveTenantConfig(input);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Inject the tenant field on a schema and prepend it to every existing
|
|
24
|
+
* compound index so the multi-tenant plugin's policy filter rides on the
|
|
25
|
+
* primary index column. Idempotent — never adds a second field if one is
|
|
26
|
+
* already there.
|
|
27
|
+
*/
|
|
28
|
+
function injectTenantField(schema, tenant) {
|
|
29
|
+
const isFieldStrategy = tenant.strategy === "field";
|
|
30
|
+
const isObjectId = tenant.fieldType === "objectId";
|
|
31
|
+
schema.add({ [tenant.tenantField]: {
|
|
32
|
+
type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
|
|
33
|
+
...tenant.enabled && tenant.required ? { required: true } : {},
|
|
34
|
+
index: true,
|
|
35
|
+
...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
|
|
36
|
+
} });
|
|
37
|
+
if (!tenant.enabled || !isFieldStrategy) return;
|
|
38
|
+
const existingIndexes = schema._indexes;
|
|
39
|
+
if (existingIndexes && existingIndexes.length > 0) for (const indexEntry of existingIndexes) {
|
|
40
|
+
const fields = indexEntry[0];
|
|
41
|
+
if (fields[tenant.tenantField] !== void 0) continue;
|
|
42
|
+
const newFields = { [tenant.tenantField]: 1 };
|
|
43
|
+
for (const [key, val] of Object.entries(fields)) newFields[key] = val;
|
|
44
|
+
indexEntry[0] = newFields;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
export { injectTenantField, resolvePosTenant };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { ShiftState } from "../domain/enums/shift-state.enum.mjs";
|
|
2
|
+
import { ClosedBy } from "../domain/enums/closed-by.enum.mjs";
|
|
3
|
+
import { CashMovement } from "../domain/value-objects/cash-movement.vo.mjs";
|
|
4
|
+
import { PaymentBreakdown } from "../domain/value-objects/payment-breakdown.vo.mjs";
|
|
5
|
+
import { ShiftPolicy } from "../domain/value-objects/shift-policy.vo.mjs";
|
|
6
|
+
import { HydratedDocument, Model, Schema } from "mongoose";
|
|
7
|
+
import { ApprovalChain } from "@classytic/primitives/approval";
|
|
8
|
+
|
|
9
|
+
//#region src/models/shift.model.d.ts
|
|
10
|
+
interface IShift {
|
|
11
|
+
/** Tenant scope (organizationId / branchId). Type set by tenant config. */
|
|
12
|
+
organizationId: unknown;
|
|
13
|
+
/**
|
|
14
|
+
* Register / terminal id within the branch. Hosts that have only one
|
|
15
|
+
* register per branch can pass a constant string. Unique-active-shift is
|
|
16
|
+
* enforced per (organizationId, registerId).
|
|
17
|
+
*/
|
|
18
|
+
registerId: string;
|
|
19
|
+
/** Business day this shift belongs to (host's local TZ; YYYY-MM-DD UTC midnight). */
|
|
20
|
+
businessDate: Date;
|
|
21
|
+
state: ShiftState;
|
|
22
|
+
openingCashierId: string;
|
|
23
|
+
openingCashierName: string;
|
|
24
|
+
endingCashierId: string | null;
|
|
25
|
+
endingCashierName: string | null;
|
|
26
|
+
closingCashierId: string | null;
|
|
27
|
+
closingCashierName: string | null;
|
|
28
|
+
teamMemberIds: string[];
|
|
29
|
+
openedAt: Date;
|
|
30
|
+
pausedAt: Date | null;
|
|
31
|
+
resumedAt: Date | null;
|
|
32
|
+
blindClosedAt: Date | null;
|
|
33
|
+
closedAt: Date | null;
|
|
34
|
+
openingCash: number;
|
|
35
|
+
expectedCash: number | null;
|
|
36
|
+
countedCash: number | null;
|
|
37
|
+
cashDifference: number | null;
|
|
38
|
+
paymentBreakdown: PaymentBreakdown[];
|
|
39
|
+
salesCount: number;
|
|
40
|
+
salesTotal: number;
|
|
41
|
+
refundCount: number;
|
|
42
|
+
refundTotal: number;
|
|
43
|
+
cashMovements: CashMovement[];
|
|
44
|
+
/**
|
|
45
|
+
* Approval chain — primitives' `ApprovalChain` (PACKAGE_RULES §P7:
|
|
46
|
+
* canonical field name is `approvals`; never build a parallel
|
|
47
|
+
* review-workflow shape). On a Shift document this carries the
|
|
48
|
+
* **variance approval** — the single-step `ApprovalChain` constructed
|
|
49
|
+
* when a manager overrides a variance during close, or any multi-step
|
|
50
|
+
* chain a host attaches via a future `approvals` input on
|
|
51
|
+
* `CloseShiftInput`. Null when no variance override / no chain attached.
|
|
52
|
+
*
|
|
53
|
+
* Renamed from `varianceApproval` (2026-05-06) to align with P7.
|
|
54
|
+
*/
|
|
55
|
+
approvals: ApprovalChain | null;
|
|
56
|
+
/** Policy frozen at open time. Reconciliation reads from here, never live. */
|
|
57
|
+
policySnapshot: ShiftPolicy;
|
|
58
|
+
closedBy: ClosedBy | null;
|
|
59
|
+
notes: string;
|
|
60
|
+
/** Set by the close pipeline after the ledger bridge returns the JE id. */
|
|
61
|
+
journalEntryId: string | null;
|
|
62
|
+
createdAt?: Date;
|
|
63
|
+
updatedAt?: Date;
|
|
64
|
+
}
|
|
65
|
+
type ShiftDocument = HydratedDocument<IShift>;
|
|
66
|
+
type ShiftModel = Model<IShift>;
|
|
67
|
+
//#endregion
|
|
68
|
+
export { IShift, ShiftDocument, ShiftModel };
|