@classytic/supplier-performance 0.1.1 → 0.2.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 +68 -0
- package/README.md +37 -5
- package/dist/event-catalog.js +170 -0
- package/dist/events.d.ts +2 -0
- package/dist/events.js +2 -0
- package/dist/in-process-bus.d.ts +163 -0
- package/dist/index.d.ts +65 -111
- package/dist/index.js +75 -199
- package/package.json +15 -6
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
Stack upgrade + tenant-isolation fix + PACKAGE_RULES compliance + real test
|
|
6
|
+
coverage. No new features.
|
|
7
|
+
|
|
8
|
+
### Fixed (security)
|
|
9
|
+
|
|
10
|
+
- **Cross-tenant leak — `multiTenantPlugin` was never wired.** Both
|
|
11
|
+
repositories were constructed with only `methodRegistryPlugin()`, so reads
|
|
12
|
+
and writes were NOT tenant-scoped despite the schema carrying an
|
|
13
|
+
`organizationId` field. The engine now derives one resolved tenant config
|
|
14
|
+
(via repo-core's `resolveTenantConfig`) and wires `multiTenantPlugin` on
|
|
15
|
+
every repo — scoping is enforced at POLICY priority and missing
|
|
16
|
+
`organizationId` throws (fail-closed). A `tenant-plugin-probe` integration
|
|
17
|
+
test plus an end-to-end isolation test guard this.
|
|
18
|
+
|
|
19
|
+
### Changed (breaking)
|
|
20
|
+
|
|
21
|
+
- **Peers:** `@classytic/mongokit` `>=3.13.0` → `>=3.16.0`; **added**
|
|
22
|
+
`@classytic/repo-core >=0.6.0` (rule 11 — the code imports
|
|
23
|
+
`@classytic/repo-core/tenant` and `/errors`); **added** `zod >=4.0.0`
|
|
24
|
+
(event catalog). `@classytic/primitives` stays `>=0.5.0` (devDep bumped to
|
|
25
|
+
`^0.7.2`).
|
|
26
|
+
- **Tenant config clean break.** Dropped the legacy
|
|
27
|
+
`{ tenantFieldType, multiTenant }` shape and the `'string'` default. Tenant
|
|
28
|
+
config is now a repo-core `TenantConfig` (or boolean), defaulting to
|
|
29
|
+
repo-core's standard `fieldType: 'objectId'`, `required: true`. Hosts with
|
|
30
|
+
string/UUID org ids pass `{ fieldType: 'string' }`. Mongokit-runtime knobs
|
|
31
|
+
(`skipWhen`, `resolveContext`, `allowDataInjection`, `onMismatch`,
|
|
32
|
+
`skipOperations`) forward through the `tenant` object.
|
|
33
|
+
- **Errors.** Removed `RecordEventValidationError extends Error`. Validation now
|
|
34
|
+
throws `SupplierPerformanceValidationError implements HttpError` (status 400,
|
|
35
|
+
code `supplier_performance.validation.invalid_input`) so arc serializes it
|
|
36
|
+
correctly.
|
|
37
|
+
|
|
38
|
+
### Added
|
|
39
|
+
|
|
40
|
+
- **Zod event catalog (rule 18):** `supplierPerformanceEventDefinitions`
|
|
41
|
+
exported from the package root AND the new `./events` subpath; per-event Zod
|
|
42
|
+
schemas (`z.iso.datetime()` timestamps), a no-drift invariant test, and
|
|
43
|
+
safeParse happy/rejection tests.
|
|
44
|
+
- **Cancellation / retry threading:** `SupplierPerformanceContext` now carries
|
|
45
|
+
`signal` / `retryPolicy`, forwarded to repo calls via `repoOptionsFromCtx`.
|
|
46
|
+
- **Test coverage** raised from one unit file to five files / 21 tests:
|
|
47
|
+
event-catalog no-drift, tenant probe + isolation, computeScore aggregation +
|
|
48
|
+
idempotency (re-run does not double-aggregate, exactly one snapshot row),
|
|
49
|
+
model-collision policy.
|
|
50
|
+
|
|
51
|
+
### Build hygiene
|
|
52
|
+
|
|
53
|
+
- `tsconfig.json`: enabled `exactOptionalPropertyTypes`; disabled
|
|
54
|
+
`declarationMap` and `sourceMap` (no source leaks). `InProcessSupplierPerformanceBus`
|
|
55
|
+
gained `close()`. `CHANGELOG.md` added to published `files`.
|
|
56
|
+
|
|
57
|
+
### Notes (verified, intentionally NOT changed)
|
|
58
|
+
|
|
59
|
+
- **No outbox / P8 dispatch machinery.** Durable delivery is host-composed
|
|
60
|
+
(§5.5 / §16); only a transport is wired, so publish failures are swallowed
|
|
61
|
+
(rule 14). Not a gap.
|
|
62
|
+
- **No capabilities boot gate.** The package uses no transactions — every verb
|
|
63
|
+
is a single-doc read/write/upsert — so the gate (transactions-only) does not
|
|
64
|
+
apply.
|
|
65
|
+
- **No rating-state CAS.** Scorecards are recomputable snapshots, not a state
|
|
66
|
+
machine; `computeScore` idempotency rests on the unique index + upsert.
|
|
67
|
+
- **`recordEvent` dedup stays host-owned** by design (hosts key differently:
|
|
68
|
+
PO-line vs PO+SKU). The kernel does not enforce a metric-dedup unique index.
|
package/README.md
CHANGED
|
@@ -27,9 +27,11 @@ Peer deps:
|
|
|
27
27
|
|
|
28
28
|
| | |
|
|
29
29
|
|---|---|
|
|
30
|
-
| `@classytic/mongokit` | `>=3.
|
|
31
|
-
| `@classytic/
|
|
30
|
+
| `@classytic/mongokit` | `>=3.16.0` |
|
|
31
|
+
| `@classytic/repo-core` | `>=0.6.0` |
|
|
32
|
+
| `@classytic/primitives` | `>=0.5.0` |
|
|
32
33
|
| `mongoose` | `>=9.4.1` |
|
|
34
|
+
| `zod` | `>=4.0.0` |
|
|
33
35
|
|
|
34
36
|
## Quick start
|
|
35
37
|
|
|
@@ -140,17 +142,43 @@ supplier_performance:score.computed
|
|
|
140
142
|
|
|
141
143
|
Use any `EventTransport`-shaped bus (Arc's MemoryEventTransport, Redis, Kafka, …). The bundled `InProcessSupplierPerformanceBus` is a zero-dep default.
|
|
142
144
|
|
|
145
|
+
A Zod event catalog ships at the `@classytic/supplier-performance/events`
|
|
146
|
+
subpath (`supplierPerformanceEventDefinitions`) — hosts register it with arc's
|
|
147
|
+
`EventRegistry` for publish-time validation and OpenAPI introspection:
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import { supplierPerformanceEventDefinitions } from '@classytic/supplier-performance/events';
|
|
151
|
+
for (const def of supplierPerformanceEventDefinitions) registry.register(def);
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
There is no package-owned outbox — durable delivery is host-composed
|
|
155
|
+
(`PACKAGE_RULES §5.5 / §16`). A transport publish failure is logged and
|
|
156
|
+
swallowed; hosts wanting at-least-once wire their own transport + relay.
|
|
157
|
+
|
|
143
158
|
### Multi-tenant
|
|
144
159
|
|
|
145
|
-
|
|
160
|
+
Every repository is wired with `multiTenantPlugin` — reads and writes are
|
|
161
|
+
tenant-scoped at POLICY priority, so cross-tenant access is impossible (the
|
|
162
|
+
plugin throws when `organizationId` is missing from the call context).
|
|
163
|
+
Resolution drives off `@classytic/repo-core/tenant`; defaults follow repo-core:
|
|
164
|
+
`tenantField: 'organizationId'`, `fieldType: 'objectId'`, required.
|
|
146
165
|
|
|
147
166
|
```ts
|
|
167
|
+
// ObjectId org ids (Better Auth) — the default:
|
|
168
|
+
const engine = await createSupplierPerformance({ connection });
|
|
169
|
+
|
|
170
|
+
// String / UUID org ids:
|
|
148
171
|
const engine = await createSupplierPerformance({
|
|
149
172
|
connection,
|
|
150
|
-
tenant: { fieldType: '
|
|
173
|
+
tenant: { fieldType: 'string' },
|
|
151
174
|
});
|
|
152
175
|
```
|
|
153
176
|
|
|
177
|
+
Mongokit 3.16 plugin defaults are fail-closed (`onMismatch: 'throw'`,
|
|
178
|
+
`allowDataInjection: false`); a host can forward `skipWhen` / `resolveContext` /
|
|
179
|
+
`allowDataInjection` / `onMismatch` through the `tenant` object when its trust
|
|
180
|
+
model justifies it.
|
|
181
|
+
|
|
154
182
|
### Indexes
|
|
155
183
|
|
|
156
184
|
| Collection | Index | Purpose |
|
|
@@ -164,7 +192,11 @@ The tenant field is prepended to compound indexes via `injectTenantField` when s
|
|
|
164
192
|
|
|
165
193
|
### Soft delete
|
|
166
194
|
|
|
167
|
-
|
|
195
|
+
Not wired by default — soft delete is host policy, not package policy
|
|
196
|
+
(`PACKAGE_RULES §10`). The event log is append-only and scorecards are
|
|
197
|
+
recomputable, so neither collection needs reversible delete out of the box.
|
|
198
|
+
Hosts that want it pass a `softDeletePlugin()` instance through
|
|
199
|
+
`repositoryPlugins.performanceEvent` / `repositoryPlugins.supplierScore`.
|
|
168
200
|
|
|
169
201
|
## Why a service (and not just repos)?
|
|
170
202
|
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { createEvent, matchEventPattern } from "@classytic/primitives/events";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
//#region src/domain/enums/event-type.enum.ts
|
|
4
|
+
/**
|
|
5
|
+
* Performance event types — what happened on a single supplier interaction.
|
|
6
|
+
*
|
|
7
|
+
* The catalog is intentionally small. Each type contributes to one or more
|
|
8
|
+
* scorecard metrics:
|
|
9
|
+
*
|
|
10
|
+
* - `delivery_received` → on-time rate, average delay
|
|
11
|
+
* - `delivery_late` → on-time rate, average delay
|
|
12
|
+
* - `defect_reported` → defect rate
|
|
13
|
+
* - `price_variance` → price variance %
|
|
14
|
+
*
|
|
15
|
+
* Hosts that need a domain-specific signal (e.g. `quality_audit`) can
|
|
16
|
+
* extend by adding a constant + payload. Pure data; no FSM.
|
|
17
|
+
*/
|
|
18
|
+
const PerformanceEventType = {
|
|
19
|
+
delivery_received: "delivery_received",
|
|
20
|
+
delivery_late: "delivery_late",
|
|
21
|
+
defect_reported: "defect_reported",
|
|
22
|
+
price_variance: "price_variance"
|
|
23
|
+
};
|
|
24
|
+
const PERFORMANCE_EVENT_TYPE_VALUES = Object.values(PerformanceEventType);
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/events/event-constants.ts
|
|
27
|
+
/**
|
|
28
|
+
* Canonical event names emitted by `@classytic/supplier-performance`.
|
|
29
|
+
*
|
|
30
|
+
* Prefix `supplier_performance:` matches the sibling-package convention
|
|
31
|
+
* (`order:...`, `commission:...`). Hosts wiring an Arc transport can
|
|
32
|
+
* pattern-match on `supplier_performance:*`.
|
|
33
|
+
*/
|
|
34
|
+
const SupplierPerformanceEvents = {
|
|
35
|
+
EVENT_RECORDED: "supplier_performance:event.recorded",
|
|
36
|
+
SCORE_COMPUTED: "supplier_performance:score.computed"
|
|
37
|
+
};
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/events/helpers.ts
|
|
40
|
+
/**
|
|
41
|
+
* Thin typed wrapper around `@classytic/primitives/events.createEvent`
|
|
42
|
+
* (PACKAGE_RULES rule 14 shape: `createEvent(type, payload, ctx?, meta?)`).
|
|
43
|
+
*
|
|
44
|
+
* Value-add over primitives:
|
|
45
|
+
* - narrows `type` to `SupplierPerformanceEventName`
|
|
46
|
+
* - fills `meta.userId` / `meta.organizationId` / `meta.correlationId`
|
|
47
|
+
* from the supplier-performance context so every event stays scoped to
|
|
48
|
+
* the originating actor and tenant.
|
|
49
|
+
*
|
|
50
|
+
* Shape, id generation, timestamp — all owned by primitives / arc.
|
|
51
|
+
*/
|
|
52
|
+
function createEvent$1(type, payload, ctx, meta) {
|
|
53
|
+
return createEvent(type, payload, {
|
|
54
|
+
...ctx !== void 0 && ctx.actorKind === "user" ? { userId: String(ctx.actorRef) } : {},
|
|
55
|
+
...ctx?.organizationId !== void 0 ? { organizationId: String(ctx.organizationId) } : {},
|
|
56
|
+
...ctx?.correlationId !== void 0 ? { correlationId: ctx.correlationId } : {},
|
|
57
|
+
...meta
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
//#endregion
|
|
61
|
+
//#region src/events/in-process-bus.ts
|
|
62
|
+
/**
|
|
63
|
+
* Zero-dep in-process event bus. Subscribers can use glob patterns
|
|
64
|
+
* (`supplier_performance:*`, `*`, exact type). Subscriber errors are
|
|
65
|
+
* caught and logged — they never break the emitter or sibling
|
|
66
|
+
* subscribers.
|
|
67
|
+
*
|
|
68
|
+
* Drop-in compatible with any `EventTransport` — hosts replace it by
|
|
69
|
+
* passing their own at `createSupplierPerformance({ eventTransport })`.
|
|
70
|
+
*/
|
|
71
|
+
var InProcessSupplierPerformanceBus = class {
|
|
72
|
+
name = "in-process-supplier-performance";
|
|
73
|
+
patterns = /* @__PURE__ */ new Map();
|
|
74
|
+
logger;
|
|
75
|
+
constructor(options = {}) {
|
|
76
|
+
this.logger = options.logger ?? console;
|
|
77
|
+
}
|
|
78
|
+
async publish(event) {
|
|
79
|
+
for (const [pattern, handlers] of this.patterns) {
|
|
80
|
+
if (!matchEventPattern(pattern, event.type)) continue;
|
|
81
|
+
for (const fn of handlers) try {
|
|
82
|
+
await fn(event);
|
|
83
|
+
} catch (err) {
|
|
84
|
+
this.logger.error(`[supplier-performance] subscriber threw on ${event.type}: ${err.message}`, err);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async subscribe(pattern, handler) {
|
|
89
|
+
let set = this.patterns.get(pattern);
|
|
90
|
+
if (!set) {
|
|
91
|
+
set = /* @__PURE__ */ new Set();
|
|
92
|
+
this.patterns.set(pattern, set);
|
|
93
|
+
}
|
|
94
|
+
set.add(handler);
|
|
95
|
+
return () => {
|
|
96
|
+
const s = this.patterns.get(pattern);
|
|
97
|
+
s?.delete(handler);
|
|
98
|
+
if (s && s.size === 0) this.patterns.delete(pattern);
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
async close() {
|
|
102
|
+
this.patterns.clear();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/events/event-catalog.ts
|
|
107
|
+
/**
|
|
108
|
+
* Zod-source event catalog (PACKAGE_RULES rule 18).
|
|
109
|
+
*
|
|
110
|
+
* One Zod schema per event is the source of truth — runtime validation,
|
|
111
|
+
* static types, and Arc introspection all derive from it. Hosts wire the
|
|
112
|
+
* definitions into arc's `EventRegistry`:
|
|
113
|
+
*
|
|
114
|
+
* ```ts
|
|
115
|
+
* for (const def of supplierPerformanceEventDefinitions) registry.register(def);
|
|
116
|
+
* ```
|
|
117
|
+
*
|
|
118
|
+
* which lights up publish-time validation (`eventPlugin({ registry,
|
|
119
|
+
* validateMode: 'reject' })`), OpenAPI event introspection, and
|
|
120
|
+
* `arc describe` output — with zero arc imports here (the definition shape
|
|
121
|
+
* is structurally identical to arc's `EventDefinitionOutput`).
|
|
122
|
+
*
|
|
123
|
+
* Timestamps are `z.iso.datetime()` (rule 25): `z.toJSONSchema()` throws on
|
|
124
|
+
* `z.coerce.date()`, and events serialize to JSON over the wire anyway.
|
|
125
|
+
*/
|
|
126
|
+
function defineSupplierPerformanceEvent(input) {
|
|
127
|
+
const { name, description, version = 1, zodSchema } = input;
|
|
128
|
+
return {
|
|
129
|
+
name,
|
|
130
|
+
version,
|
|
131
|
+
description,
|
|
132
|
+
zodSchema,
|
|
133
|
+
schema: z.toJSONSchema(zodSchema),
|
|
134
|
+
create(payload, meta) {
|
|
135
|
+
return createEvent(name, payload, {
|
|
136
|
+
resource: "supplier-performance",
|
|
137
|
+
source: "supplier-performance",
|
|
138
|
+
...meta
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const eventRecordedSchema = z.object({
|
|
144
|
+
supplierId: z.string(),
|
|
145
|
+
type: z.enum(PERFORMANCE_EVENT_TYPE_VALUES),
|
|
146
|
+
occurredAt: z.iso.datetime(),
|
|
147
|
+
sourceRef: z.string().optional()
|
|
148
|
+
});
|
|
149
|
+
const EventRecorded = defineSupplierPerformanceEvent({
|
|
150
|
+
name: SupplierPerformanceEvents.EVENT_RECORDED,
|
|
151
|
+
description: "recordEvent() appended one supplier signal to the event log.",
|
|
152
|
+
zodSchema: eventRecordedSchema
|
|
153
|
+
});
|
|
154
|
+
const scoreComputedSchema = z.object({
|
|
155
|
+
supplierId: z.string(),
|
|
156
|
+
period: z.object({
|
|
157
|
+
start: z.iso.datetime(),
|
|
158
|
+
end: z.iso.datetime()
|
|
159
|
+
}),
|
|
160
|
+
compositeScore: z.number(),
|
|
161
|
+
eventCount: z.number().int().min(0)
|
|
162
|
+
});
|
|
163
|
+
const ScoreComputed = defineSupplierPerformanceEvent({
|
|
164
|
+
name: SupplierPerformanceEvents.SCORE_COMPUTED,
|
|
165
|
+
description: "computeScore() aggregated the window and upserted a scorecard snapshot.",
|
|
166
|
+
zodSchema: scoreComputedSchema
|
|
167
|
+
});
|
|
168
|
+
const supplierPerformanceEventDefinitions = [EventRecorded, ScoreComputed];
|
|
169
|
+
//#endregion
|
|
170
|
+
export { createEvent$1 as a, PerformanceEventType as c, InProcessSupplierPerformanceBus as i, ScoreComputed as n, SupplierPerformanceEvents as o, supplierPerformanceEventDefinitions as r, PERFORMANCE_EVENT_TYPE_VALUES as s, EventRecorded as t };
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as ScoreComputed, c as supplierPerformanceEventDefinitions, i as EventRecorded, l as SupplierPerformanceEventPayloads, m as SupplierPerformanceEvents, n as createEvent, o as SupplierPerformanceEventDefinition, p as SupplierPerformanceEventName, s as SupplierPerformanceEventSchema, t as InProcessSupplierPerformanceBus } from "./in-process-bus.js";
|
|
2
|
+
export { EventRecorded, InProcessSupplierPerformanceBus, ScoreComputed, type SupplierPerformanceEventDefinition, type SupplierPerformanceEventName, type SupplierPerformanceEventPayloads, type SupplierPerformanceEventSchema, SupplierPerformanceEvents, createEvent, supplierPerformanceEventDefinitions };
|
package/dist/events.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as createEvent, i as InProcessSupplierPerformanceBus, n as ScoreComputed, o as SupplierPerformanceEvents, r as supplierPerformanceEventDefinitions, t as EventRecorded } from "./event-catalog.js";
|
|
2
|
+
export { EventRecorded, InProcessSupplierPerformanceBus, ScoreComputed, SupplierPerformanceEvents, createEvent, supplierPerformanceEventDefinitions };
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { DomainEvent, EventHandler, EventMeta, EventTransport } from "@classytic/primitives/events";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/events/event-constants.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Canonical event names emitted by `@classytic/supplier-performance`.
|
|
8
|
+
*
|
|
9
|
+
* Prefix `supplier_performance:` matches the sibling-package convention
|
|
10
|
+
* (`order:...`, `commission:...`). Hosts wiring an Arc transport can
|
|
11
|
+
* pattern-match on `supplier_performance:*`.
|
|
12
|
+
*/
|
|
13
|
+
declare const SupplierPerformanceEvents: {
|
|
14
|
+
readonly EVENT_RECORDED: "supplier_performance:event.recorded";
|
|
15
|
+
readonly SCORE_COMPUTED: "supplier_performance:score.computed";
|
|
16
|
+
};
|
|
17
|
+
type SupplierPerformanceEventName = (typeof SupplierPerformanceEvents)[keyof typeof SupplierPerformanceEvents];
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/domain/enums/event-type.enum.d.ts
|
|
20
|
+
/**
|
|
21
|
+
* Performance event types — what happened on a single supplier interaction.
|
|
22
|
+
*
|
|
23
|
+
* The catalog is intentionally small. Each type contributes to one or more
|
|
24
|
+
* scorecard metrics:
|
|
25
|
+
*
|
|
26
|
+
* - `delivery_received` → on-time rate, average delay
|
|
27
|
+
* - `delivery_late` → on-time rate, average delay
|
|
28
|
+
* - `defect_reported` → defect rate
|
|
29
|
+
* - `price_variance` → price variance %
|
|
30
|
+
*
|
|
31
|
+
* Hosts that need a domain-specific signal (e.g. `quality_audit`) can
|
|
32
|
+
* extend by adding a constant + payload. Pure data; no FSM.
|
|
33
|
+
*/
|
|
34
|
+
declare const PerformanceEventType: {
|
|
35
|
+
readonly delivery_received: "delivery_received";
|
|
36
|
+
readonly delivery_late: "delivery_late";
|
|
37
|
+
readonly defect_reported: "defect_reported";
|
|
38
|
+
readonly price_variance: "price_variance";
|
|
39
|
+
};
|
|
40
|
+
type PerformanceEventTypeValue = (typeof PerformanceEventType)[keyof typeof PerformanceEventType];
|
|
41
|
+
declare const PERFORMANCE_EVENT_TYPE_VALUES: readonly PerformanceEventTypeValue[];
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/events/event-payloads.d.ts
|
|
44
|
+
/**
|
|
45
|
+
* Payload shapes for every `supplier_performance:*` event. Subscribers
|
|
46
|
+
* type-narrow on `eventType` and read `payload` as the matching entry.
|
|
47
|
+
*
|
|
48
|
+
* Timestamps are ISO-8601 strings on the wire (rule 25). Subscribers
|
|
49
|
+
* wanting a `Date` call `new Date(payload.occurredAt)`.
|
|
50
|
+
*/
|
|
51
|
+
interface SupplierPerformanceEventPayloads {
|
|
52
|
+
'supplier_performance:event.recorded': {
|
|
53
|
+
supplierId: string;
|
|
54
|
+
type: PerformanceEventTypeValue;
|
|
55
|
+
/** ISO-8601 — when the signal happened in the real world. */
|
|
56
|
+
occurredAt: string;
|
|
57
|
+
sourceRef?: string;
|
|
58
|
+
};
|
|
59
|
+
'supplier_performance:score.computed': {
|
|
60
|
+
supplierId: string;
|
|
61
|
+
period: {
|
|
62
|
+
/** ISO-8601 inclusive start. */
|
|
63
|
+
start: string;
|
|
64
|
+
/** ISO-8601 exclusive end. */
|
|
65
|
+
end: string;
|
|
66
|
+
};
|
|
67
|
+
compositeScore: number;
|
|
68
|
+
eventCount: number;
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/events/event-catalog.d.ts
|
|
73
|
+
/** JSON-Schema object produced by `z.toJSONSchema` — what arc's registry consumes. */
|
|
74
|
+
type SupplierPerformanceEventSchema = Record<string, unknown>;
|
|
75
|
+
/** Structurally identical to arc's `EventDefinitionOutput` — do NOT import arc. */
|
|
76
|
+
interface SupplierPerformanceEventDefinition<TSchema extends z.ZodType = z.ZodType> {
|
|
77
|
+
name: SupplierPerformanceEventName;
|
|
78
|
+
version: number;
|
|
79
|
+
description: string;
|
|
80
|
+
zodSchema: TSchema;
|
|
81
|
+
schema: SupplierPerformanceEventSchema;
|
|
82
|
+
create(payload: z.infer<TSchema>, meta?: Partial<EventMeta>): DomainEvent<z.infer<TSchema>>;
|
|
83
|
+
}
|
|
84
|
+
declare const EventRecorded: SupplierPerformanceEventDefinition<z.ZodObject<{
|
|
85
|
+
supplierId: z.ZodString;
|
|
86
|
+
type: z.ZodEnum<{
|
|
87
|
+
[x: string]: string;
|
|
88
|
+
}>;
|
|
89
|
+
occurredAt: z.ZodISODateTime;
|
|
90
|
+
sourceRef: z.ZodOptional<z.ZodString>;
|
|
91
|
+
}, z.core.$strip>>;
|
|
92
|
+
declare const ScoreComputed: SupplierPerformanceEventDefinition<z.ZodObject<{
|
|
93
|
+
supplierId: z.ZodString;
|
|
94
|
+
period: z.ZodObject<{
|
|
95
|
+
start: z.ZodISODateTime;
|
|
96
|
+
end: z.ZodISODateTime;
|
|
97
|
+
}, z.core.$strip>;
|
|
98
|
+
compositeScore: z.ZodNumber;
|
|
99
|
+
eventCount: z.ZodNumber;
|
|
100
|
+
}, z.core.$strip>>;
|
|
101
|
+
declare const supplierPerformanceEventDefinitions: ReadonlyArray<SupplierPerformanceEventDefinition>;
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region src/domain/ports/common.d.ts
|
|
104
|
+
/**
|
|
105
|
+
* Per-call context. Carries tenant, actor, and tracing signals. Opaque
|
|
106
|
+
* `session` slot avoids importing mongoose here so this port file stays
|
|
107
|
+
* framework-agnostic.
|
|
108
|
+
*/
|
|
109
|
+
interface SupplierPerformanceContext {
|
|
110
|
+
/** Tenant scope. */
|
|
111
|
+
organizationId: string;
|
|
112
|
+
/** Actor reference (user id, system id, cron id). */
|
|
113
|
+
actorRef: string;
|
|
114
|
+
/** Actor kind. */
|
|
115
|
+
actorKind: 'user' | 'system' | 'integration';
|
|
116
|
+
/** Correlation id propagated through events. */
|
|
117
|
+
correlationId: string;
|
|
118
|
+
/** Optional mongoose ClientSession — narrowed at the repo boundary. */
|
|
119
|
+
session?: unknown;
|
|
120
|
+
/** Optional idempotency key for the operation. */
|
|
121
|
+
idempotencyKey?: string;
|
|
122
|
+
/**
|
|
123
|
+
* Optional cancellation signal. Threaded to repo calls via
|
|
124
|
+
* `repoOptionsFromCtx`; mongokit checks it at every op boundary and
|
|
125
|
+
* stops before the next round-trip.
|
|
126
|
+
*/
|
|
127
|
+
signal?: AbortSignal;
|
|
128
|
+
/**
|
|
129
|
+
* Optional retry policy forwarded to repo calls. Mongokit wraps driver
|
|
130
|
+
* round-trips in `withRetry` when present.
|
|
131
|
+
*/
|
|
132
|
+
retryPolicy?: unknown;
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/events/helpers.d.ts
|
|
136
|
+
declare function createEvent$1<T>(type: SupplierPerformanceEventName, payload: T, ctx?: SupplierPerformanceContext, meta?: Partial<EventMeta>): DomainEvent<T>;
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/events/in-process-bus.d.ts
|
|
139
|
+
interface InProcessBusOptions {
|
|
140
|
+
logger?: {
|
|
141
|
+
error(message: string, ...args: unknown[]): void;
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Zero-dep in-process event bus. Subscribers can use glob patterns
|
|
146
|
+
* (`supplier_performance:*`, `*`, exact type). Subscriber errors are
|
|
147
|
+
* caught and logged — they never break the emitter or sibling
|
|
148
|
+
* subscribers.
|
|
149
|
+
*
|
|
150
|
+
* Drop-in compatible with any `EventTransport` — hosts replace it by
|
|
151
|
+
* passing their own at `createSupplierPerformance({ eventTransport })`.
|
|
152
|
+
*/
|
|
153
|
+
declare class InProcessSupplierPerformanceBus implements EventTransport {
|
|
154
|
+
readonly name = "in-process-supplier-performance";
|
|
155
|
+
private patterns;
|
|
156
|
+
private logger;
|
|
157
|
+
constructor(options?: InProcessBusOptions);
|
|
158
|
+
publish(event: DomainEvent): Promise<void>;
|
|
159
|
+
subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
|
|
160
|
+
close(): Promise<void>;
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
export { ScoreComputed as a, supplierPerformanceEventDefinitions as c, PerformanceEventType as d, PerformanceEventTypeValue as f, EventRecorded as i, SupplierPerformanceEventPayloads as l, SupplierPerformanceEvents as m, createEvent$1 as n, SupplierPerformanceEventDefinition as o, SupplierPerformanceEventName as p, SupplierPerformanceContext as r, SupplierPerformanceEventSchema as s, InProcessSupplierPerformanceBus as t, PERFORMANCE_EVENT_TYPE_VALUES as u };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { PluginType, Repository } from "@classytic/mongokit";
|
|
3
|
-
import { DomainEvent, EventHandler, EventTransport } from "@classytic/primitives/events";
|
|
1
|
+
import { a as ScoreComputed, c as supplierPerformanceEventDefinitions, d as PerformanceEventType, f as PerformanceEventTypeValue, i as EventRecorded, l as SupplierPerformanceEventPayloads, m as SupplierPerformanceEvents, n as createEvent, o as SupplierPerformanceEventDefinition, p as SupplierPerformanceEventName, r as SupplierPerformanceContext, s as SupplierPerformanceEventSchema, t as InProcessSupplierPerformanceBus, u as PERFORMANCE_EVENT_TYPE_VALUES } from "./in-process-bus.js";
|
|
2
|
+
import { PluginType, Repository, RepositoryContext } from "@classytic/mongokit";
|
|
4
3
|
import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
|
|
4
|
+
import { ClientSession, Connection, Document, Model, Schema, Types } from "mongoose";
|
|
5
|
+
import { EventTransport } from "@classytic/primitives/events";
|
|
6
|
+
import { HttpError } from "@classytic/repo-core/errors";
|
|
5
7
|
|
|
6
8
|
//#region src/models/performance-event.model.d.ts
|
|
7
9
|
interface PerformanceEventDocument extends Document {
|
|
@@ -49,51 +51,19 @@ declare class SupplierScoreModelCollisionError extends Error {
|
|
|
49
51
|
}
|
|
50
52
|
declare function createSupplierScoreModel(connection: Connection, tenant: ResolvedTenantConfig, config?: SupplierScoreModelConfig): Model<SupplierScoreDocument>;
|
|
51
53
|
//#endregion
|
|
52
|
-
//#region src/models/inject-tenant.d.ts
|
|
53
|
-
type SupplierPerformanceTenantInput = TenantConfig | boolean | {
|
|
54
|
-
tenantFieldType?: 'objectId' | 'string';
|
|
55
|
-
multiTenant?: boolean;
|
|
56
|
-
};
|
|
57
|
-
declare function resolveSupplierPerformanceTenant(input?: SupplierPerformanceTenantInput): ResolvedTenantConfig;
|
|
58
|
-
/**
|
|
59
|
-
* Inject the tenant field into a Mongoose schema and prepend it to every
|
|
60
|
-
* existing compound index (so queries are index-efficient under
|
|
61
|
-
* multi-tenant scoping). Identical algorithm to commission's helper.
|
|
62
|
-
*/
|
|
63
|
-
//#endregion
|
|
64
54
|
//#region src/models/create-models.d.ts
|
|
65
55
|
interface SupplierPerformanceModelBundle {
|
|
66
56
|
PerformanceEvent: ReturnType<typeof createPerformanceEventModel>;
|
|
67
57
|
SupplierScore: ReturnType<typeof createSupplierScoreModel>;
|
|
68
58
|
}
|
|
69
59
|
interface CreateSupplierPerformanceModelsOptions {
|
|
70
|
-
tenant
|
|
60
|
+
/** Resolved tenant config, or a `TenantConfig` / boolean to resolve. */
|
|
61
|
+
tenant?: ResolvedTenantConfig | TenantConfig | boolean;
|
|
71
62
|
collectionPrefix?: string | undefined;
|
|
72
63
|
forceRecreate?: boolean | undefined;
|
|
73
64
|
}
|
|
74
65
|
declare function createSupplierPerformanceModels(connection: Connection, options?: CreateSupplierPerformanceModelsOptions): SupplierPerformanceModelBundle;
|
|
75
66
|
//#endregion
|
|
76
|
-
//#region src/domain/ports/common.d.ts
|
|
77
|
-
/**
|
|
78
|
-
* Per-call context. Carries tenant, actor, and tracing signals. Opaque
|
|
79
|
-
* `session` slot avoids importing mongoose here so this port file stays
|
|
80
|
-
* framework-agnostic.
|
|
81
|
-
*/
|
|
82
|
-
interface SupplierPerformanceContext {
|
|
83
|
-
/** Tenant scope. */
|
|
84
|
-
organizationId: string;
|
|
85
|
-
/** Actor reference (user id, system id, cron id). */
|
|
86
|
-
actorRef: string;
|
|
87
|
-
/** Actor kind. */
|
|
88
|
-
actorKind: 'user' | 'system' | 'integration';
|
|
89
|
-
/** Correlation id propagated through events. */
|
|
90
|
-
correlationId: string;
|
|
91
|
-
/** Optional mongoose ClientSession — narrowed at the repo boundary. */
|
|
92
|
-
session?: unknown;
|
|
93
|
-
/** Optional idempotency key for the operation. */
|
|
94
|
-
idempotencyKey?: string;
|
|
95
|
-
}
|
|
96
|
-
//#endregion
|
|
97
67
|
//#region src/repositories/performance-event.repository.d.ts
|
|
98
68
|
interface PerformanceEventRepositoryConfig {
|
|
99
69
|
model: Model<PerformanceEventDocument>;
|
|
@@ -197,30 +167,6 @@ declare class SupplierScoreRepository extends Repository<SupplierScoreDocument>
|
|
|
197
167
|
findLatest(supplierId: string, ctx: SupplierPerformanceContext): Promise<SupplierScoreDocument | null>;
|
|
198
168
|
}
|
|
199
169
|
//#endregion
|
|
200
|
-
//#region src/domain/enums/event-type.enum.d.ts
|
|
201
|
-
/**
|
|
202
|
-
* Performance event types — what happened on a single supplier interaction.
|
|
203
|
-
*
|
|
204
|
-
* The catalog is intentionally small. Each type contributes to one or more
|
|
205
|
-
* scorecard metrics:
|
|
206
|
-
*
|
|
207
|
-
* - `delivery_received` → on-time rate, average delay
|
|
208
|
-
* - `delivery_late` → on-time rate, average delay
|
|
209
|
-
* - `defect_reported` → defect rate
|
|
210
|
-
* - `price_variance` → price variance %
|
|
211
|
-
*
|
|
212
|
-
* Hosts that need a domain-specific signal (e.g. `quality_audit`) can
|
|
213
|
-
* extend by adding a constant + payload. Pure data; no FSM.
|
|
214
|
-
*/
|
|
215
|
-
declare const PerformanceEventType: {
|
|
216
|
-
readonly delivery_received: "delivery_received";
|
|
217
|
-
readonly delivery_late: "delivery_late";
|
|
218
|
-
readonly defect_reported: "defect_reported";
|
|
219
|
-
readonly price_variance: "price_variance";
|
|
220
|
-
};
|
|
221
|
-
type PerformanceEventTypeValue = (typeof PerformanceEventType)[keyof typeof PerformanceEventType];
|
|
222
|
-
declare const PERFORMANCE_EVENT_TYPE_VALUES: readonly PerformanceEventTypeValue[];
|
|
223
|
-
//#endregion
|
|
224
170
|
//#region src/domain/entities/performance-event.entity.d.ts
|
|
225
171
|
interface PerformanceEvent {
|
|
226
172
|
_id: Types.ObjectId;
|
|
@@ -297,12 +243,12 @@ interface ScoreServiceConfig {
|
|
|
297
243
|
eventTransport?: EventTransport | undefined;
|
|
298
244
|
logger?: {
|
|
299
245
|
error(message: string, ...args: unknown[]): void;
|
|
300
|
-
};
|
|
246
|
+
} | undefined;
|
|
301
247
|
}
|
|
302
248
|
declare class ScoreService {
|
|
303
249
|
private events;
|
|
304
250
|
private scores;
|
|
305
|
-
private eventTransport
|
|
251
|
+
private eventTransport;
|
|
306
252
|
private logger;
|
|
307
253
|
constructor(config: ScoreServiceConfig);
|
|
308
254
|
/**
|
|
@@ -326,18 +272,33 @@ declare class ScoreService {
|
|
|
326
272
|
* implicitly (callers know when their data has changed).
|
|
327
273
|
*/
|
|
328
274
|
getScorecard(supplierId: string, ctx: SupplierPerformanceContext, period?: ScorePeriod): Promise<SupplierScoreDocument | null>;
|
|
275
|
+
/**
|
|
276
|
+
* Publish a domain event via the injected transport (rule 14). There is
|
|
277
|
+
* no outbox in this package (host-composed per §5.5 / §16), so a publish
|
|
278
|
+
* failure is logged and swallowed — there is no durable row to roll back
|
|
279
|
+
* and no transaction in flight. Hosts wanting at-least-once delivery wire
|
|
280
|
+
* their own transport (Redis/Kafka) + relay.
|
|
281
|
+
*/
|
|
329
282
|
private publish;
|
|
330
283
|
}
|
|
331
|
-
declare class RecordEventValidationError extends Error {
|
|
332
|
-
readonly name = "RecordEventValidationError";
|
|
333
|
-
readonly code: "SUPPLIER_PERFORMANCE_VALIDATION";
|
|
334
|
-
constructor(message: string);
|
|
335
|
-
}
|
|
336
284
|
//#endregion
|
|
337
285
|
//#region src/engine/engine-types.d.ts
|
|
338
286
|
interface SupplierPerformanceLogger {
|
|
339
287
|
error(message: string, ...args: unknown[]): void;
|
|
340
288
|
}
|
|
289
|
+
/**
|
|
290
|
+
* Tenant scoping config. Extends repo-core's `TenantConfig` with the
|
|
291
|
+
* mongokit-runtime knobs `multiTenantPlugin` accepts beyond the static
|
|
292
|
+
* vocabulary (forwarded only when the host sets them — the fail-closed
|
|
293
|
+
* 3.16 defaults stay in charge otherwise, rule 9.3 / 9.5).
|
|
294
|
+
*/
|
|
295
|
+
interface SupplierPerformanceTenantOptions extends TenantConfig {
|
|
296
|
+
skipOperations?: string[] | undefined;
|
|
297
|
+
skipWhen?: ((context: RepositoryContext, operation: string) => boolean) | undefined;
|
|
298
|
+
resolveContext?: (() => string | undefined) | undefined;
|
|
299
|
+
allowDataInjection?: boolean | undefined;
|
|
300
|
+
onMismatch?: 'throw' | 'overwrite' | undefined;
|
|
301
|
+
}
|
|
341
302
|
interface SupplierPerformanceConfig {
|
|
342
303
|
/** Shared mongoose connection. */
|
|
343
304
|
connection: Connection;
|
|
@@ -349,9 +310,15 @@ interface SupplierPerformanceConfig {
|
|
|
349
310
|
*/
|
|
350
311
|
eventTransport?: EventTransport | undefined;
|
|
351
312
|
/**
|
|
352
|
-
* Tenant scoping config
|
|
313
|
+
* Tenant scoping config — `TenantConfig` from `@classytic/repo-core/tenant`
|
|
314
|
+
* (plus mongokit-runtime knobs) or a boolean shorthand. One resolved value
|
|
315
|
+
* drives BOTH the model factory (schema field type + index prefixing) and
|
|
316
|
+
* `multiTenantPlugin` (query casting + fail-closed scoping), so they can't
|
|
317
|
+
* drift (rule 9.2). Defaults follow repo-core: `tenantField: 'organizationId'`,
|
|
318
|
+
* `fieldType: 'objectId'`, required. Hosts with string/UUID org ids pass
|
|
319
|
+
* `{ fieldType: 'string' }`.
|
|
353
320
|
*/
|
|
354
|
-
tenant?:
|
|
321
|
+
tenant?: SupplierPerformanceTenantOptions | boolean | undefined;
|
|
355
322
|
/** Optional collection name prefix (PACKAGE_RULES §20.1). */
|
|
356
323
|
collectionPrefix?: string | undefined;
|
|
357
324
|
/** Hot-reload / test fixtures only. Default `false`. */
|
|
@@ -373,7 +340,7 @@ interface SupplierPerformanceEngine {
|
|
|
373
340
|
services: {
|
|
374
341
|
score: ScoreService;
|
|
375
342
|
};
|
|
376
|
-
events
|
|
343
|
+
events: EventTransport;
|
|
377
344
|
syncIndexes(): Promise<void>;
|
|
378
345
|
destroy(): Promise<void>;
|
|
379
346
|
}
|
|
@@ -381,6 +348,17 @@ interface SupplierPerformanceEngine {
|
|
|
381
348
|
//#region src/engine/create-supplier-performance.d.ts
|
|
382
349
|
declare function createSupplierPerformance(config: SupplierPerformanceConfig): Promise<SupplierPerformanceEngine>;
|
|
383
350
|
//#endregion
|
|
351
|
+
//#region src/domain/errors/supplier-performance.errors.d.ts
|
|
352
|
+
declare class SupplierPerformanceError extends Error implements HttpError {
|
|
353
|
+
readonly code: string;
|
|
354
|
+
readonly status: number;
|
|
355
|
+
constructor(message: string, code: string, status: number);
|
|
356
|
+
}
|
|
357
|
+
/** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
|
|
358
|
+
declare class SupplierPerformanceValidationError extends SupplierPerformanceError {
|
|
359
|
+
constructor(message: string);
|
|
360
|
+
}
|
|
361
|
+
//#endregion
|
|
384
362
|
//#region src/calc/score-calculator.d.ts
|
|
385
363
|
/**
|
|
386
364
|
* Aggregate raw performance events into a scorecard. Events outside the
|
|
@@ -389,6 +367,19 @@ declare function createSupplierPerformance(config: SupplierPerformanceConfig): P
|
|
|
389
367
|
*/
|
|
390
368
|
declare function scoreFromEvents(events: ReadonlyArray<PerformanceEvent>, period: ScorePeriod): ScoreMetrics;
|
|
391
369
|
//#endregion
|
|
370
|
+
//#region src/models/inject-tenant.d.ts
|
|
371
|
+
/**
|
|
372
|
+
* Resolve the package's tenant config. Accepts a repo-core `TenantConfig`
|
|
373
|
+
* or boolean shorthand — no package-local shapes. Pure passthrough to
|
|
374
|
+
* `resolveTenantConfig` so defaults can't drift from the org standard.
|
|
375
|
+
*/
|
|
376
|
+
declare function resolveSupplierPerformanceTenant(input?: TenantConfig | boolean): ResolvedTenantConfig;
|
|
377
|
+
/**
|
|
378
|
+
* Inject the tenant field into a Mongoose schema and prepend it to every
|
|
379
|
+
* existing compound index (so queries are index-efficient under
|
|
380
|
+
* multi-tenant scoping, rule 36).
|
|
381
|
+
*/
|
|
382
|
+
//#endregion
|
|
392
383
|
//#region src/repositories/repo-options.d.ts
|
|
393
384
|
interface RepoOptions {
|
|
394
385
|
organizationId: string;
|
|
@@ -397,47 +388,10 @@ interface RepoOptions {
|
|
|
397
388
|
correlationId: string;
|
|
398
389
|
session?: ClientSession;
|
|
399
390
|
idempotencyKey?: string;
|
|
391
|
+
signal?: AbortSignal;
|
|
392
|
+
retryPolicy?: unknown;
|
|
400
393
|
[key: string]: unknown;
|
|
401
394
|
}
|
|
402
395
|
declare function repoOptionsFromCtx(ctx: SupplierPerformanceContext): RepoOptions;
|
|
403
396
|
//#endregion
|
|
404
|
-
|
|
405
|
-
/**
|
|
406
|
-
* Canonical event names emitted by `@classytic/supplier-performance`.
|
|
407
|
-
*
|
|
408
|
-
* Prefix `supplier_performance:` matches the sibling-package convention
|
|
409
|
-
* (`order:...`, `commission:...`). Hosts wiring an Arc transport can
|
|
410
|
-
* pattern-match on `supplier_performance:*`.
|
|
411
|
-
*/
|
|
412
|
-
declare const SupplierPerformanceEvents: {
|
|
413
|
-
readonly EVENT_RECORDED: "supplier_performance:event.recorded";
|
|
414
|
-
readonly SCORE_COMPUTED: "supplier_performance:score.computed";
|
|
415
|
-
};
|
|
416
|
-
type SupplierPerformanceEventName = (typeof SupplierPerformanceEvents)[keyof typeof SupplierPerformanceEvents];
|
|
417
|
-
//#endregion
|
|
418
|
-
//#region src/events/in-process-bus.d.ts
|
|
419
|
-
interface InProcessBusOptions {
|
|
420
|
-
logger?: {
|
|
421
|
-
error(message: string, ...args: unknown[]): void;
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
/**
|
|
425
|
-
* Zero-dep in-process event bus. Subscribers can use glob patterns
|
|
426
|
-
* (`supplier_performance:*`, `*`, exact type). Subscriber errors are
|
|
427
|
-
* caught and logged — they never break the emitter or sibling
|
|
428
|
-
* subscribers.
|
|
429
|
-
*
|
|
430
|
-
* Drop-in compatible with any `EventTransport` — hosts replace it by
|
|
431
|
-
* passing their own at `createSupplierPerformance({ eventTransport })`.
|
|
432
|
-
*/
|
|
433
|
-
declare class InProcessSupplierPerformanceBus implements EventTransport {
|
|
434
|
-
readonly name = "in-process-supplier-performance";
|
|
435
|
-
private patterns;
|
|
436
|
-
private logger;
|
|
437
|
-
constructor(options?: InProcessBusOptions);
|
|
438
|
-
publish(event: DomainEvent): Promise<void>;
|
|
439
|
-
subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
|
|
440
|
-
}
|
|
441
|
-
//#endregion
|
|
442
|
-
export { type ComputeScoreInput, type CreateSupplierPerformanceModelsOptions, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, type PerformanceEvent, type PerformanceEventDocument, PerformanceEventModelCollisionError, PerformanceEventRepository, type PerformanceEventRepositoryConfig, PerformanceEventType, type PerformanceEventTypeValue, type PerformanceMetrics, type RecordEventInput, RecordEventValidationError, type RepoOptions, type ScoreMetrics, type ScorePeriod, ScoreService, type ScoreServiceConfig, type SupplierPerformanceConfig, type SupplierPerformanceContext, type SupplierPerformanceEngine, type SupplierPerformanceEventName, SupplierPerformanceEvents, type SupplierPerformanceLogger, type SupplierPerformanceModelBundle, type SupplierPerformanceRepositories, type SupplierPerformanceTenantInput, type SupplierScore, type SupplierScoreDocument, SupplierScoreModelCollisionError, SupplierScoreRepository, type SupplierScoreRepositoryConfig, type UpsertScoreInput, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents };
|
|
443
|
-
//# sourceMappingURL=index.d.ts.map
|
|
397
|
+
export { type ComputeScoreInput, type CreateSupplierPerformanceModelsOptions, EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, type PerformanceEvent, type PerformanceEventDocument, PerformanceEventModelCollisionError, PerformanceEventRepository, type PerformanceEventRepositoryConfig, PerformanceEventType, type PerformanceEventTypeValue, type PerformanceMetrics, type RecordEventInput, type RepoOptions, ScoreComputed, type ScoreMetrics, type ScorePeriod, ScoreService, type ScoreServiceConfig, type SupplierPerformanceConfig, type SupplierPerformanceContext, type SupplierPerformanceEngine, SupplierPerformanceError, type SupplierPerformanceEventDefinition, type SupplierPerformanceEventName, type SupplierPerformanceEventPayloads, type SupplierPerformanceEventSchema, SupplierPerformanceEvents, type SupplierPerformanceLogger, type SupplierPerformanceModelBundle, type SupplierPerformanceRepositories, type SupplierPerformanceTenantOptions, SupplierPerformanceValidationError, type SupplierScore, type SupplierScoreDocument, SupplierScoreModelCollisionError, SupplierScoreRepository, type SupplierScoreRepositoryConfig, type UpsertScoreInput, createEvent, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
|
package/dist/index.js
CHANGED
|
@@ -1,132 +1,30 @@
|
|
|
1
|
+
import { a as createEvent, c as PerformanceEventType, i as InProcessSupplierPerformanceBus, n as ScoreComputed, o as SupplierPerformanceEvents, r as supplierPerformanceEventDefinitions, s as PERFORMANCE_EVENT_TYPE_VALUES, t as EventRecorded } from "./event-catalog.js";
|
|
2
|
+
import { Repository, createOptionsExtractor, methodRegistryPlugin, multiTenantPlugin } from "@classytic/mongokit";
|
|
3
|
+
import { resolveTenantConfig } from "@classytic/repo-core/tenant";
|
|
1
4
|
import mongoose, { Schema } from "mongoose";
|
|
2
|
-
|
|
3
|
-
import { createEvent, matchEventPattern } from "@classytic/primitives/events";
|
|
4
|
-
//#region src/domain/enums/event-type.enum.ts
|
|
5
|
-
/**
|
|
6
|
-
* Performance event types — what happened on a single supplier interaction.
|
|
7
|
-
*
|
|
8
|
-
* The catalog is intentionally small. Each type contributes to one or more
|
|
9
|
-
* scorecard metrics:
|
|
10
|
-
*
|
|
11
|
-
* - `delivery_received` → on-time rate, average delay
|
|
12
|
-
* - `delivery_late` → on-time rate, average delay
|
|
13
|
-
* - `defect_reported` → defect rate
|
|
14
|
-
* - `price_variance` → price variance %
|
|
15
|
-
*
|
|
16
|
-
* Hosts that need a domain-specific signal (e.g. `quality_audit`) can
|
|
17
|
-
* extend by adding a constant + payload. Pure data; no FSM.
|
|
18
|
-
*/
|
|
19
|
-
const PerformanceEventType = {
|
|
20
|
-
delivery_received: "delivery_received",
|
|
21
|
-
delivery_late: "delivery_late",
|
|
22
|
-
defect_reported: "defect_reported",
|
|
23
|
-
price_variance: "price_variance"
|
|
24
|
-
};
|
|
25
|
-
const PERFORMANCE_EVENT_TYPE_VALUES = Object.values(PerformanceEventType);
|
|
26
|
-
//#endregion
|
|
27
|
-
//#region node_modules/@classytic/repo-core/dist/tenant/resolve.mjs
|
|
28
|
-
/**
|
|
29
|
-
* Sensible defaults for a freshly-built package (field strategy).
|
|
30
|
-
*
|
|
31
|
-
* `fieldType: 'objectId'` is the recommended default for new Mongo-shaped
|
|
32
|
-
* kits because it enables `$lookup` / `.populate()`. Existing kits that
|
|
33
|
-
* historically defaulted to `'string'` (mongokit pre-3.x) keep their own
|
|
34
|
-
* runtime default — `Pick<TenantConfig, 'fieldType'>` extension preserves
|
|
35
|
-
* type-level alignment without forcing a runtime default change.
|
|
36
|
-
*/
|
|
37
|
-
const DEFAULT_TENANT_CONFIG = {
|
|
38
|
-
strategy: "field",
|
|
39
|
-
enabled: true,
|
|
40
|
-
tenantField: "organizationId",
|
|
41
|
-
fieldType: "objectId",
|
|
42
|
-
ref: "organization",
|
|
43
|
-
contextKey: "organizationId",
|
|
44
|
-
required: true
|
|
45
|
-
};
|
|
5
|
+
//#region src/models/inject-tenant.ts
|
|
46
6
|
/**
|
|
47
|
-
*
|
|
7
|
+
* Mongoose-specific tenant adapter — thin layer over repo-core's
|
|
8
|
+
* `resolveTenantConfig()` (P11). All tenant-config defaulting and
|
|
9
|
+
* validation belongs to repo-core; only the Mongoose schema mutation
|
|
10
|
+
* (field add + compound-index prefix) lives here.
|
|
48
11
|
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* otherwise so the misconfiguration surfaces at boot, not runtime.
|
|
53
|
-
* - Object with `strategy: 'none'` → `enabled: false` (preserves
|
|
54
|
-
* user-supplied `tenantField` / `fieldType` / `ref` so the doc field
|
|
55
|
-
* stays correctly typed even with scoping off).
|
|
12
|
+
* Defaults follow repo-core: `tenantField: 'organizationId'`,
|
|
13
|
+
* `fieldType: 'objectId'`, `required: true`, `enabled: true`. Hosts whose
|
|
14
|
+
* org ids are strings/UUIDs pass `tenant: { fieldType: 'string' }`.
|
|
56
15
|
*/
|
|
57
|
-
function resolveTenantConfig(config) {
|
|
58
|
-
if (config === false) return {
|
|
59
|
-
...DEFAULT_TENANT_CONFIG,
|
|
60
|
-
strategy: "none",
|
|
61
|
-
enabled: false,
|
|
62
|
-
required: false
|
|
63
|
-
};
|
|
64
|
-
if (config === true || config === void 0) return { ...DEFAULT_TENANT_CONFIG };
|
|
65
|
-
const strategy = config.strategy ?? (config.enabled === false ? "none" : "field");
|
|
66
|
-
const contextKey = config.contextKey ?? config.tenantField ?? DEFAULT_TENANT_CONFIG.contextKey;
|
|
67
|
-
if (strategy === "none") return {
|
|
68
|
-
...DEFAULT_TENANT_CONFIG,
|
|
69
|
-
...config,
|
|
70
|
-
contextKey,
|
|
71
|
-
strategy: "none",
|
|
72
|
-
enabled: false,
|
|
73
|
-
required: false
|
|
74
|
-
};
|
|
75
|
-
if (strategy === "custom") {
|
|
76
|
-
if (typeof config.resolve !== "function") throw new Error("[repo-core] TenantConfig.strategy 'custom' requires a 'resolve' function");
|
|
77
|
-
return {
|
|
78
|
-
...DEFAULT_TENANT_CONFIG,
|
|
79
|
-
...config,
|
|
80
|
-
contextKey,
|
|
81
|
-
strategy: "custom",
|
|
82
|
-
enabled: config.enabled ?? true,
|
|
83
|
-
resolve: config.resolve
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
return {
|
|
87
|
-
...DEFAULT_TENANT_CONFIG,
|
|
88
|
-
...config,
|
|
89
|
-
contextKey,
|
|
90
|
-
strategy: "field",
|
|
91
|
-
enabled: config.enabled ?? true
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
//#endregion
|
|
95
|
-
//#region src/models/inject-tenant.ts
|
|
96
16
|
/**
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
* Default `fieldType` is `'string'`. Hosts wanting ObjectId storage pass
|
|
102
|
-
* `tenant: { fieldType: 'objectId' }` on `SupplierPerformanceConfig`.
|
|
17
|
+
* Resolve the package's tenant config. Accepts a repo-core `TenantConfig`
|
|
18
|
+
* or boolean shorthand — no package-local shapes. Pure passthrough to
|
|
19
|
+
* `resolveTenantConfig` so defaults can't drift from the org standard.
|
|
103
20
|
*/
|
|
104
|
-
function resolveSupplierPerformanceTenant(input
|
|
105
|
-
|
|
106
|
-
if ("tenantFieldType" in input || "multiTenant" in input) {
|
|
107
|
-
const legacy = input;
|
|
108
|
-
return resolveTenantConfig({
|
|
109
|
-
enabled: legacy.multiTenant !== false,
|
|
110
|
-
fieldType: legacy.tenantFieldType ?? "string"
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
const cfg = input;
|
|
114
|
-
if (cfg.fieldType === void 0) return resolveTenantConfig({
|
|
115
|
-
...cfg,
|
|
116
|
-
fieldType: "string"
|
|
117
|
-
});
|
|
118
|
-
return resolveTenantConfig(cfg);
|
|
119
|
-
}
|
|
120
|
-
function applyDefaultFieldType(resolved) {
|
|
121
|
-
return {
|
|
122
|
-
...resolved,
|
|
123
|
-
fieldType: "string"
|
|
124
|
-
};
|
|
21
|
+
function resolveSupplierPerformanceTenant(input) {
|
|
22
|
+
return resolveTenantConfig(input);
|
|
125
23
|
}
|
|
126
24
|
/**
|
|
127
25
|
* Inject the tenant field into a Mongoose schema and prepend it to every
|
|
128
26
|
* existing compound index (so queries are index-efficient under
|
|
129
|
-
* multi-tenant scoping
|
|
27
|
+
* multi-tenant scoping, rule 36).
|
|
130
28
|
*/
|
|
131
29
|
function injectTenantField(schema, tenant) {
|
|
132
30
|
const isFieldStrategy = tenant.strategy === "field";
|
|
@@ -341,12 +239,13 @@ function createSupplierScoreModel(connection, tenant, config = {}) {
|
|
|
341
239
|
}
|
|
342
240
|
//#endregion
|
|
343
241
|
//#region src/models/create-models.ts
|
|
242
|
+
function toResolved(tenant) {
|
|
243
|
+
if (typeof tenant === "object" && tenant !== null && "strategy" in tenant && "enabled" in tenant && "tenantField" in tenant) return tenant;
|
|
244
|
+
if (tenant !== void 0) return resolveSupplierPerformanceTenant(tenant);
|
|
245
|
+
return resolveSupplierPerformanceTenant();
|
|
246
|
+
}
|
|
344
247
|
function createSupplierPerformanceModels(connection, options = {}) {
|
|
345
|
-
const tenant = (
|
|
346
|
-
if (typeof options.tenant === "object" && options.tenant !== null && "strategy" in options.tenant && "tenantField" in options.tenant) return options.tenant;
|
|
347
|
-
if (options.tenant !== void 0) return resolveSupplierPerformanceTenant(options.tenant);
|
|
348
|
-
return resolveSupplierPerformanceTenant();
|
|
349
|
-
})();
|
|
248
|
+
const tenant = toResolved(options.tenant);
|
|
350
249
|
const modelConfig = {
|
|
351
250
|
...options.collectionPrefix !== void 0 ? { collectionPrefix: options.collectionPrefix } : {},
|
|
352
251
|
...options.forceRecreate !== void 0 ? { forceRecreate: options.forceRecreate } : {}
|
|
@@ -364,7 +263,9 @@ const extract = createOptionsExtractor([
|
|
|
364
263
|
"actorKind",
|
|
365
264
|
"correlationId",
|
|
366
265
|
"session",
|
|
367
|
-
"idempotencyKey"
|
|
266
|
+
"idempotencyKey",
|
|
267
|
+
"signal",
|
|
268
|
+
"retryPolicy"
|
|
368
269
|
]);
|
|
369
270
|
function repoOptionsFromCtx(ctx) {
|
|
370
271
|
return extract(ctx);
|
|
@@ -529,17 +430,22 @@ function round(value, digits) {
|
|
|
529
430
|
return Math.round(value * factor) / factor;
|
|
530
431
|
}
|
|
531
432
|
//#endregion
|
|
532
|
-
//#region src/
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
433
|
+
//#region src/domain/errors/supplier-performance.errors.ts
|
|
434
|
+
var SupplierPerformanceError = class extends Error {
|
|
435
|
+
code;
|
|
436
|
+
status;
|
|
437
|
+
constructor(message, code, status) {
|
|
438
|
+
super(message);
|
|
439
|
+
this.code = code;
|
|
440
|
+
this.status = status;
|
|
441
|
+
this.name = this.constructor.name;
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
/** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
|
|
445
|
+
var SupplierPerformanceValidationError = class extends SupplierPerformanceError {
|
|
446
|
+
constructor(message) {
|
|
447
|
+
super(message, "supplier_performance.validation.invalid_input", 400);
|
|
448
|
+
}
|
|
543
449
|
};
|
|
544
450
|
//#endregion
|
|
545
451
|
//#region src/services/score.service.ts
|
|
@@ -561,7 +467,7 @@ var ScoreService = class {
|
|
|
561
467
|
* different keying preferences: PO-line, PO+SKU, etc.).
|
|
562
468
|
*/
|
|
563
469
|
async recordEvent(input, ctx) {
|
|
564
|
-
if (!input.supplierId) throw new
|
|
470
|
+
if (!input.supplierId) throw new SupplierPerformanceValidationError("supplierId is required");
|
|
565
471
|
const occurredAt = input.occurredAt ?? /* @__PURE__ */ new Date();
|
|
566
472
|
const doc = await this.events.create({
|
|
567
473
|
organizationId: ctx.organizationId,
|
|
@@ -621,13 +527,16 @@ var ScoreService = class {
|
|
|
621
527
|
}, ctx);
|
|
622
528
|
return this.scores.findLatest(supplierId, ctx);
|
|
623
529
|
}
|
|
530
|
+
/**
|
|
531
|
+
* Publish a domain event via the injected transport (rule 14). There is
|
|
532
|
+
* no outbox in this package (host-composed per §5.5 / §16), so a publish
|
|
533
|
+
* failure is logged and swallowed — there is no durable row to roll back
|
|
534
|
+
* and no transaction in flight. Hosts wanting at-least-once delivery wire
|
|
535
|
+
* their own transport (Redis/Kafka) + relay.
|
|
536
|
+
*/
|
|
624
537
|
publish(type, ctx, data) {
|
|
625
538
|
if (!this.eventTransport) return;
|
|
626
|
-
const event = createEvent(type, data,
|
|
627
|
-
organizationId: ctx.organizationId,
|
|
628
|
-
userId: ctx.actorRef,
|
|
629
|
-
correlationId: ctx.correlationId
|
|
630
|
-
});
|
|
539
|
+
const event = createEvent(type, data, ctx);
|
|
631
540
|
this.eventTransport.publish(event).catch((err) => {
|
|
632
541
|
this.logger.error(`[supplier-performance] publish failed for ${type}:`, err);
|
|
633
542
|
});
|
|
@@ -649,77 +558,44 @@ function toCalcEvent(doc) {
|
|
|
649
558
|
};
|
|
650
559
|
}
|
|
651
560
|
function normalizePeriod(period) {
|
|
652
|
-
if (period.end.getTime() <= period.start.getTime()) throw new
|
|
561
|
+
if (period.end.getTime() <= period.start.getTime()) throw new SupplierPerformanceValidationError(`period.end (${period.end.toISOString()}) must be strictly after period.start (${period.start.toISOString()})`);
|
|
653
562
|
return period;
|
|
654
563
|
}
|
|
655
|
-
var RecordEventValidationError = class extends Error {
|
|
656
|
-
name = "RecordEventValidationError";
|
|
657
|
-
code = "SUPPLIER_PERFORMANCE_VALIDATION";
|
|
658
|
-
constructor(message) {
|
|
659
|
-
super(message);
|
|
660
|
-
}
|
|
661
|
-
};
|
|
662
|
-
//#endregion
|
|
663
|
-
//#region src/events/in-process-bus.ts
|
|
664
|
-
/**
|
|
665
|
-
* Zero-dep in-process event bus. Subscribers can use glob patterns
|
|
666
|
-
* (`supplier_performance:*`, `*`, exact type). Subscriber errors are
|
|
667
|
-
* caught and logged — they never break the emitter or sibling
|
|
668
|
-
* subscribers.
|
|
669
|
-
*
|
|
670
|
-
* Drop-in compatible with any `EventTransport` — hosts replace it by
|
|
671
|
-
* passing their own at `createSupplierPerformance({ eventTransport })`.
|
|
672
|
-
*/
|
|
673
|
-
var InProcessSupplierPerformanceBus = class {
|
|
674
|
-
name = "in-process-supplier-performance";
|
|
675
|
-
patterns = /* @__PURE__ */ new Map();
|
|
676
|
-
logger;
|
|
677
|
-
constructor(options = {}) {
|
|
678
|
-
this.logger = options.logger ?? console;
|
|
679
|
-
}
|
|
680
|
-
async publish(event) {
|
|
681
|
-
for (const [pattern, handlers] of this.patterns) {
|
|
682
|
-
if (!matchEventPattern(pattern, event.type)) continue;
|
|
683
|
-
for (const fn of handlers) try {
|
|
684
|
-
await fn(event);
|
|
685
|
-
} catch (err) {
|
|
686
|
-
this.logger.error(`[supplier-performance] subscriber threw on ${event.type}: ${err.message}`, err);
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
async subscribe(pattern, handler) {
|
|
691
|
-
let set = this.patterns.get(pattern);
|
|
692
|
-
if (!set) {
|
|
693
|
-
set = /* @__PURE__ */ new Set();
|
|
694
|
-
this.patterns.set(pattern, set);
|
|
695
|
-
}
|
|
696
|
-
set.add(handler);
|
|
697
|
-
return () => {
|
|
698
|
-
const s = this.patterns.get(pattern);
|
|
699
|
-
s?.delete(handler);
|
|
700
|
-
if (s && s.size === 0) this.patterns.delete(pattern);
|
|
701
|
-
};
|
|
702
|
-
}
|
|
703
|
-
};
|
|
704
564
|
//#endregion
|
|
705
565
|
//#region src/engine/create-supplier-performance.ts
|
|
706
566
|
async function createSupplierPerformance(config) {
|
|
707
567
|
if (!config.connection) throw new Error("createSupplierPerformance: config.connection is required");
|
|
708
568
|
const logger = config.logger ?? console;
|
|
709
569
|
const events = config.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });
|
|
710
|
-
const tenant =
|
|
570
|
+
const tenant = resolveTenantConfig(config.tenant);
|
|
711
571
|
const models = createSupplierPerformanceModels(config.connection, {
|
|
712
572
|
tenant,
|
|
713
573
|
...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
|
|
714
574
|
...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
|
|
715
575
|
});
|
|
576
|
+
const tenantPlugins = (() => {
|
|
577
|
+
if (!tenant.enabled || tenant.strategy !== "field") return [];
|
|
578
|
+
const extras = typeof config.tenant === "object" ? config.tenant : void 0;
|
|
579
|
+
return [multiTenantPlugin({
|
|
580
|
+
tenantField: tenant.tenantField,
|
|
581
|
+
fieldType: tenant.fieldType,
|
|
582
|
+
contextKey: tenant.contextKey,
|
|
583
|
+
required: tenant.required,
|
|
584
|
+
...extras?.skipOperations !== void 0 ? { skipOperations: extras.skipOperations } : {},
|
|
585
|
+
...extras?.skipWhen !== void 0 ? { skipWhen: extras.skipWhen } : {},
|
|
586
|
+
...extras?.resolveContext !== void 0 ? { resolveContext: extras.resolveContext } : {},
|
|
587
|
+
...extras?.allowDataInjection !== void 0 ? { allowDataInjection: extras.allowDataInjection } : {},
|
|
588
|
+
...extras?.onMismatch !== void 0 ? { onMismatch: extras.onMismatch } : {}
|
|
589
|
+
})];
|
|
590
|
+
})();
|
|
591
|
+
const repoPlugins = config.repositoryPlugins ?? {};
|
|
716
592
|
const performanceEvent = new PerformanceEventRepository({
|
|
717
593
|
model: models.PerformanceEvent,
|
|
718
|
-
|
|
594
|
+
plugins: [...tenantPlugins, ...repoPlugins.performanceEvent ?? []]
|
|
719
595
|
});
|
|
720
596
|
const supplierScore = new SupplierScoreRepository({
|
|
721
597
|
model: models.SupplierScore,
|
|
722
|
-
|
|
598
|
+
plugins: [...tenantPlugins, ...repoPlugins.supplierScore ?? []]
|
|
723
599
|
});
|
|
724
600
|
const score = new ScoreService({
|
|
725
601
|
events: performanceEvent,
|
|
@@ -738,10 +614,10 @@ async function createSupplierPerformance(config) {
|
|
|
738
614
|
async syncIndexes() {
|
|
739
615
|
await Promise.all([models.PerformanceEvent.syncIndexes(), models.SupplierScore.syncIndexes()]);
|
|
740
616
|
},
|
|
741
|
-
async destroy() {
|
|
617
|
+
async destroy() {
|
|
618
|
+
await events.close?.();
|
|
619
|
+
}
|
|
742
620
|
};
|
|
743
621
|
}
|
|
744
622
|
//#endregion
|
|
745
|
-
export { InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventModelCollisionError, PerformanceEventRepository, PerformanceEventType,
|
|
746
|
-
|
|
747
|
-
//# sourceMappingURL=index.js.map
|
|
623
|
+
export { EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventModelCollisionError, PerformanceEventRepository, PerformanceEventType, ScoreComputed, ScoreService, SupplierPerformanceError, SupplierPerformanceEvents, SupplierPerformanceValidationError, SupplierScoreModelCollisionError, SupplierScoreRepository, createEvent, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@classytic/supplier-performance",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Framework-agnostic supplier performance engine — on-time-delivery, defect, and price-variance tracking with append-only event log + cached scorecards. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
|
|
5
5
|
"author": "Classytic",
|
|
6
6
|
"license": "MIT",
|
|
@@ -36,6 +36,10 @@
|
|
|
36
36
|
".": {
|
|
37
37
|
"types": "./dist/index.d.ts",
|
|
38
38
|
"default": "./dist/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./events": {
|
|
41
|
+
"types": "./dist/events.d.ts",
|
|
42
|
+
"default": "./dist/events.js"
|
|
39
43
|
}
|
|
40
44
|
},
|
|
41
45
|
"main": "./dist/index.js",
|
|
@@ -43,6 +47,7 @@
|
|
|
43
47
|
"files": [
|
|
44
48
|
"dist",
|
|
45
49
|
"README.md",
|
|
50
|
+
"CHANGELOG.md",
|
|
46
51
|
"LICENSE"
|
|
47
52
|
],
|
|
48
53
|
"scripts": {
|
|
@@ -55,19 +60,23 @@
|
|
|
55
60
|
"release": "npm run push -- main && npm run release:tag && npm publish"
|
|
56
61
|
},
|
|
57
62
|
"peerDependencies": {
|
|
58
|
-
"@classytic/mongokit": ">=3.
|
|
63
|
+
"@classytic/mongokit": ">=3.16.0",
|
|
64
|
+
"@classytic/repo-core": ">=0.6.0",
|
|
59
65
|
"@classytic/primitives": ">=0.5.0",
|
|
60
|
-
"mongoose": ">=9.4.1"
|
|
66
|
+
"mongoose": ">=9.4.1",
|
|
67
|
+
"zod": ">=4.0.0"
|
|
61
68
|
},
|
|
62
69
|
"devDependencies": {
|
|
63
70
|
"@classytic/dev-tools": "^0.2.0",
|
|
64
|
-
"@classytic/mongokit": ">=3.
|
|
65
|
-
"@classytic/
|
|
71
|
+
"@classytic/mongokit": ">=3.16.0",
|
|
72
|
+
"@classytic/repo-core": ">=0.6.0",
|
|
73
|
+
"@classytic/primitives": "^0.7.2",
|
|
66
74
|
"@types/node": "^25.5.0",
|
|
67
75
|
"mongodb-memory-server": "^10.2.3",
|
|
68
76
|
"mongoose": "^9.4.1",
|
|
69
77
|
"tsdown": "^0.14.2",
|
|
70
78
|
"typescript": "^5.8.2",
|
|
71
|
-
"vitest": "^3.2.4"
|
|
79
|
+
"vitest": "^3.2.4",
|
|
80
|
+
"zod": "^4.0.0"
|
|
72
81
|
}
|
|
73
82
|
}
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/models/performance-event.model.ts","../src/models/supplier-score.model.ts","../src/models/inject-tenant.ts","../src/models/create-models.ts","../src/domain/ports/common.ts","../src/repositories/performance-event.repository.ts","../src/domain/entities/supplier-score.entity.ts","../src/repositories/supplier-score.repository.ts","../src/domain/enums/event-type.enum.ts","../src/domain/entities/performance-event.entity.ts","../src/services/score.service.ts","../src/engine/engine-types.ts","../src/engine/create-supplier-performance.ts","../src/calc/score-calculator.ts","../src/repositories/repo-options.ts","../src/events/event-constants.ts","../src/events/in-process-bus.ts"],"mappings":";;;;;;UAKiB,wBAAA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AAA,GAAA,GAAA,IAAA,CAAA"}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["metricsSchema"],"sources":["../src/domain/enums/event-type.enum.ts","../node_modules/@classytic/repo-core/dist/tenant/resolve.mjs","../src/models/inject-tenant.ts","../src/models/performance-event.model.ts","../src/models/supplier-score.model.ts","../src/models/create-models.ts","../src/repositories/repo-options.ts","../src/repositories/performance-event.repository.ts","../src/repositories/supplier-score.repository.ts","../src/calc/score-calculator.ts","../src/events/event-constants.ts","../src/services/score.service.ts","../src/events/in-process-bus.ts","../src/engine/create-supplier-performance.ts"],"sourcesContent":["/**\n * Performance event types — what happened on a single supplier interaction.\n *\n * The catalog is intentionally small. Each type contributes to one or more\n * scorecard metrics:\n *\n * - `delivery_received` → on-time rate, average delay\n * - `delivery_late` → on-time rate, average delay\n * - `defect_reported` → defect rate\n * - `price_variance` → price variance %\n *\n * Hosts that need a domain-specific signal (e.g. `quality_audit`) can\n * extend by adding a constant + payload. Pure data; no FSM.\n */\nexport const PerformanceEventType = {\n delivery_received: 'delivery_received',\n delivery_late: 'delivery_late',\n defect_reported: 'defect_reported',\n price_variance: 'price_variance',\n} as const;\n\nexport type PerformanceEventTypeValue =\n (typeof PerformanceEventType)[keyof typeof PerformanceEventType];\n\nexport const PERFORMANCE_EVENT_TYPE_VALUES = Object.values(\n PerformanceEventType,\n) as readonly PerformanceEventTypeValue[];\n","//#region src/tenant/resolve.ts\n/**\n* Sensible defaults for a freshly-built package (field strategy).\n*\n* `fieldType: 'objectId'` is the recommended default for new Mongo-shaped\n* kits because it enables `$lookup` / `.populate()`. Existing kits that\n* historically defaulted to `'string'` (mongokit pre-3.x) keep their own\n* runtime default — `Pick<TenantConfig, 'fieldType'>` extension preserves\n* type-level alignment without forcing a runtime default change.\n*/\nconst DEFAULT_TENANT_CONFIG = {\n\tstrategy: \"field\",\n\tenabled: true,\n\ttenantField: \"organizationId\",\n\tfieldType: \"objectId\",\n\tref: \"organization\",\n\tcontextKey: \"organizationId\",\n\trequired: true\n};\n/**\n* Resolve a possibly-partial {@link TenantConfig} against the defaults.\n*\n* - `false` → `enabled: false`, `strategy: 'none'`, `required: false`.\n* - `true` / `undefined` → default field strategy.\n* - Object with `strategy: 'custom'` → `resolve` is required; throws\n* otherwise so the misconfiguration surfaces at boot, not runtime.\n* - Object with `strategy: 'none'` → `enabled: false` (preserves\n* user-supplied `tenantField` / `fieldType` / `ref` so the doc field\n* stays correctly typed even with scoping off).\n*/\nfunction resolveTenantConfig(config) {\n\tif (config === false) return {\n\t\t...DEFAULT_TENANT_CONFIG,\n\t\tstrategy: \"none\",\n\t\tenabled: false,\n\t\trequired: false\n\t};\n\tif (config === true || config === void 0) return { ...DEFAULT_TENANT_CONFIG };\n\tconst strategy = config.strategy ?? (config.enabled === false ? \"none\" : \"field\");\n\tconst contextKey = config.contextKey ?? config.tenantField ?? DEFAULT_TENANT_CONFIG.contextKey;\n\tif (strategy === \"none\") return {\n\t\t...DEFAULT_TENANT_CONFIG,\n\t\t...config,\n\t\tcontextKey,\n\t\tstrategy: \"none\",\n\t\tenabled: false,\n\t\trequired: false\n\t};\n\tif (strategy === \"custom\") {\n\t\tif (typeof config.resolve !== \"function\") throw new Error(\"[repo-core] TenantConfig.strategy 'custom' requires a 'resolve' function\");\n\t\treturn {\n\t\t\t...DEFAULT_TENANT_CONFIG,\n\t\t\t...config,\n\t\t\tcontextKey,\n\t\t\tstrategy: \"custom\",\n\t\t\tenabled: config.enabled ?? true,\n\t\t\tresolve: config.resolve\n\t\t};\n\t}\n\treturn {\n\t\t...DEFAULT_TENANT_CONFIG,\n\t\t...config,\n\t\tcontextKey,\n\t\tstrategy: \"field\",\n\t\tenabled: config.enabled ?? true\n\t};\n}\n//#endregion\nexport { DEFAULT_TENANT_CONFIG, resolveTenantConfig };\n","/**\n * Mongoose-specific tenant adapter — mirrors the commission package's\n * pattern so hosts that already configured commission can reuse the same\n * config shape here.\n *\n * Default `fieldType` is `'string'`. Hosts wanting ObjectId storage pass\n * `tenant: { fieldType: 'objectId' }` on `SupplierPerformanceConfig`.\n */\nimport mongoose, { type Schema } from 'mongoose';\nimport {\n resolveTenantConfig,\n type ResolvedTenantConfig,\n type TenantConfig,\n} from '@classytic/repo-core/tenant';\n\nexport type SupplierPerformanceTenantInput =\n | TenantConfig\n | boolean\n | {\n tenantFieldType?: 'objectId' | 'string';\n multiTenant?: boolean;\n };\n\nexport function resolveSupplierPerformanceTenant(\n input: SupplierPerformanceTenantInput = {},\n): ResolvedTenantConfig {\n if (typeof input === 'boolean') {\n return applyDefaultFieldType(resolveTenantConfig(input));\n }\n if ('tenantFieldType' in input || 'multiTenant' in input) {\n const legacy = input as { tenantFieldType?: 'objectId' | 'string'; multiTenant?: boolean };\n return resolveTenantConfig({\n enabled: legacy.multiTenant !== false,\n fieldType: legacy.tenantFieldType ?? 'string',\n });\n }\n const cfg = input as TenantConfig;\n if (cfg.fieldType === undefined) {\n return resolveTenantConfig({ ...cfg, fieldType: 'string' });\n }\n return resolveTenantConfig(cfg);\n}\n\nfunction applyDefaultFieldType(resolved: ResolvedTenantConfig): ResolvedTenantConfig {\n return { ...resolved, fieldType: 'string' };\n}\n\n/**\n * Inject the tenant field into a Mongoose schema and prepend it to every\n * existing compound index (so queries are index-efficient under\n * multi-tenant scoping). Identical algorithm to commission's helper.\n */\nexport function injectTenantField(schema: Schema, tenant: ResolvedTenantConfig): void {\n const isFieldStrategy = tenant.strategy === 'field';\n const isObjectId = tenant.fieldType === 'objectId';\n\n schema.add({\n [tenant.tenantField]: {\n type: isObjectId ? mongoose.Schema.Types.ObjectId : String,\n ...(tenant.enabled && tenant.required ? { required: true } : {}),\n index: true,\n ...(isObjectId && tenant.ref ? { ref: tenant.ref } : {}),\n },\n });\n\n if (!tenant.enabled || !isFieldStrategy) return;\n\n const existingIndexes = (\n schema as unknown as {\n _indexes: Array<[Record<string, unknown>, Record<string, unknown>]>;\n }\n )._indexes;\n if (existingIndexes && existingIndexes.length > 0) {\n for (const indexEntry of existingIndexes) {\n const fields = indexEntry[0];\n if (fields[tenant.tenantField] !== undefined) continue;\n const newFields: Record<string, unknown> = { [tenant.tenantField]: 1 };\n for (const [key, val] of Object.entries(fields)) {\n newFields[key] = val;\n }\n indexEntry[0] = newFields;\n }\n }\n}\n","import { Schema, type Connection, type Document, type Model } from 'mongoose';\nimport type { ResolvedTenantConfig } from '@classytic/repo-core/tenant';\nimport { PERFORMANCE_EVENT_TYPE_VALUES } from '../domain/enums/event-type.enum.js';\nimport { injectTenantField } from './inject-tenant.js';\n\nexport interface PerformanceEventDocument extends Document {\n organizationId: unknown;\n supplierId: string;\n type: string;\n occurredAt: Date;\n metrics: Record<string, unknown>;\n sourceRef?: string;\n sourceType?: string;\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\nconst metricsSchema = new Schema(\n {\n quantity: { type: Number, min: 0 },\n expectedAt: Date,\n actualAt: Date,\n delayDays: Number,\n expectedUnitCost: { type: Number, min: 0 },\n actualUnitCost: { type: Number, min: 0 },\n variancePct: Number,\n },\n { _id: false, strict: false },\n);\n\nexport interface PerformanceEventModelConfig {\n collectionPrefix?: string | undefined;\n forceRecreate?: boolean;\n}\n\nfunction buildPerformanceEventSchema(tenant: ResolvedTenantConfig): Schema {\n const schema = new Schema<PerformanceEventDocument>(\n {\n supplierId: { type: String, required: true },\n type: { type: String, required: true, enum: PERFORMANCE_EVENT_TYPE_VALUES },\n occurredAt: { type: Date, required: true },\n metrics: { type: metricsSchema, required: true, default: {} },\n sourceRef: String,\n sourceType: String,\n metadata: { type: Schema.Types.Mixed },\n },\n { timestamps: true, collection: 'supplier_performance_events' },\n );\n\n // Primary scorecard query — events for a supplier in a time window.\n // Tenant prefix added by `injectTenantField` per PACKAGE_RULES §P11.\n schema.index({ supplierId: 1, occurredAt: 1 });\n\n // Source drill-down — \"why did this PO show up in the late bucket?\"\n schema.index(\n { sourceRef: 1, type: 1 },\n { partialFilterExpression: { sourceRef: { $exists: true } } },\n );\n\n injectTenantField(schema, tenant);\n return schema;\n}\n\nexport class PerformanceEventModelCollisionError extends Error {\n constructor(name: string) {\n super(\n `[supplier-performance] Mongoose model \"${name}\" already exists on this connection. ` +\n `Pass \\`forceRecreate: true\\` for hot-reload, or use two Mongoose connections.`,\n );\n this.name = 'PerformanceEventModelCollisionError';\n }\n}\n\nexport function createPerformanceEventModel(\n connection: Connection,\n tenant: ResolvedTenantConfig,\n config: PerformanceEventModelConfig = {},\n): Model<PerformanceEventDocument> {\n if (connection.models.PerformanceEvent) {\n if (config.forceRecreate) {\n connection.deleteModel('PerformanceEvent');\n } else {\n throw new PerformanceEventModelCollisionError('PerformanceEvent');\n }\n }\n const collection = (config.collectionPrefix ?? '') + 'supplier_performance_events';\n return connection.model<PerformanceEventDocument>(\n 'PerformanceEvent',\n buildPerformanceEventSchema(tenant),\n collection,\n );\n}\n","import { Schema, type Connection, type Document, type Model } from 'mongoose';\nimport type { ResolvedTenantConfig } from '@classytic/repo-core/tenant';\nimport { injectTenantField } from './inject-tenant.js';\n\nexport interface SupplierScoreDocument extends Document {\n organizationId: unknown;\n supplierId: string;\n period: { start: Date; end: Date; label?: string };\n metrics: Record<string, unknown>;\n computedAt: Date;\n eventCount: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\nconst periodSchema = new Schema(\n {\n start: { type: Date, required: true },\n end: { type: Date, required: true },\n label: String,\n },\n { _id: false },\n);\n\nconst metricsSchema = new Schema(\n {\n deliveryCount: { type: Number, default: 0, min: 0 },\n onTimeCount: { type: Number, default: 0, min: 0 },\n onTimeRate: { type: Number, default: 0, min: 0, max: 1 },\n avgDelayDays: { type: Number, default: 0 },\n unitsReceived: { type: Number, default: 0, min: 0 },\n defectiveUnits: { type: Number, default: 0, min: 0 },\n defectRate: { type: Number, default: 0, min: 0, max: 1 },\n priceVarianceCount: { type: Number, default: 0, min: 0 },\n avgPriceVariance: { type: Number, default: 0 },\n compositeScore: { type: Number, default: 0, min: 0, max: 100 },\n },\n { _id: false },\n);\n\nexport interface SupplierScoreModelConfig {\n collectionPrefix?: string | undefined;\n forceRecreate?: boolean;\n}\n\nfunction buildSupplierScoreSchema(tenant: ResolvedTenantConfig): Schema {\n const schema = new Schema<SupplierScoreDocument>(\n {\n supplierId: { type: String, required: true },\n period: { type: periodSchema, required: true },\n metrics: { type: metricsSchema, required: true, default: {} },\n computedAt: { type: Date, required: true },\n eventCount: { type: Number, required: true, default: 0, min: 0 },\n },\n { timestamps: true, collection: 'supplier_scores' },\n );\n\n // One score per (supplier, period.start, period.end). Re-computing the\n // same window upserts in place — tenant scoping prepended by\n // `injectTenantField`.\n schema.index({ supplierId: 1, 'period.start': 1, 'period.end': 1 }, { unique: true });\n\n // Dashboard query — \"list all suppliers' scores for the latest period\".\n schema.index({ 'period.end': -1, 'metrics.compositeScore': -1 });\n\n injectTenantField(schema, tenant);\n return schema;\n}\n\nexport class SupplierScoreModelCollisionError extends Error {\n constructor(name: string) {\n super(\n `[supplier-performance] Mongoose model \"${name}\" already exists on this connection. ` +\n `Pass \\`forceRecreate: true\\` for hot-reload, or use two Mongoose connections.`,\n );\n this.name = 'SupplierScoreModelCollisionError';\n }\n}\n\nexport function createSupplierScoreModel(\n connection: Connection,\n tenant: ResolvedTenantConfig,\n config: SupplierScoreModelConfig = {},\n): Model<SupplierScoreDocument> {\n if (connection.models.SupplierScore) {\n if (config.forceRecreate) {\n connection.deleteModel('SupplierScore');\n } else {\n throw new SupplierScoreModelCollisionError('SupplierScore');\n }\n }\n const collection = (config.collectionPrefix ?? '') + 'supplier_scores';\n return connection.model<SupplierScoreDocument>(\n 'SupplierScore',\n buildSupplierScoreSchema(tenant),\n collection,\n );\n}\n","import type { Connection } from 'mongoose';\nimport type { ResolvedTenantConfig, TenantConfig } from '@classytic/repo-core/tenant';\nimport {\n createPerformanceEventModel,\n type PerformanceEventDocument,\n} from './performance-event.model.js';\nimport {\n createSupplierScoreModel,\n type SupplierScoreDocument,\n} from './supplier-score.model.js';\nimport {\n resolveSupplierPerformanceTenant,\n type SupplierPerformanceTenantInput,\n} from './inject-tenant.js';\n\nexport interface SupplierPerformanceModelBundle {\n PerformanceEvent: ReturnType<typeof createPerformanceEventModel>;\n SupplierScore: ReturnType<typeof createSupplierScoreModel>;\n}\n\nexport type { PerformanceEventDocument, SupplierScoreDocument };\n\nexport interface CreateSupplierPerformanceModelsOptions {\n tenant?: ResolvedTenantConfig | TenantConfig | boolean | SupplierPerformanceTenantInput;\n collectionPrefix?: string | undefined;\n forceRecreate?: boolean | undefined;\n}\n\nexport function createSupplierPerformanceModels(\n connection: Connection,\n options: CreateSupplierPerformanceModelsOptions = {},\n): SupplierPerformanceModelBundle {\n const tenant: ResolvedTenantConfig = (() => {\n if (\n typeof options.tenant === 'object' &&\n options.tenant !== null &&\n 'strategy' in options.tenant &&\n 'tenantField' in options.tenant\n ) {\n return options.tenant as ResolvedTenantConfig;\n }\n if (options.tenant !== undefined) {\n return resolveSupplierPerformanceTenant(options.tenant as SupplierPerformanceTenantInput);\n }\n return resolveSupplierPerformanceTenant();\n })();\n\n const modelConfig = {\n ...(options.collectionPrefix !== undefined ? { collectionPrefix: options.collectionPrefix } : {}),\n ...(options.forceRecreate !== undefined ? { forceRecreate: options.forceRecreate } : {}),\n };\n\n return {\n PerformanceEvent: createPerformanceEventModel(connection, tenant, modelConfig),\n SupplierScore: createSupplierScoreModel(connection, tenant, modelConfig),\n };\n}\n","import { createOptionsExtractor } from '@classytic/mongokit';\nimport type { ClientSession } from 'mongoose';\nimport type { SupplierPerformanceContext } from '../domain/ports/common.js';\n\nexport interface RepoOptions {\n organizationId: string;\n actorRef: string;\n actorKind: SupplierPerformanceContext['actorKind'];\n correlationId: string;\n session?: ClientSession;\n idempotencyKey?: string;\n [key: string]: unknown;\n}\n\nconst extract = createOptionsExtractor<SupplierPerformanceContext & Record<string, unknown>>([\n 'organizationId',\n 'actorRef',\n 'actorKind',\n 'correlationId',\n 'session',\n 'idempotencyKey',\n]);\n\nexport function repoOptionsFromCtx(ctx: SupplierPerformanceContext): RepoOptions {\n return extract(ctx as SupplierPerformanceContext & Record<string, unknown>) as RepoOptions;\n}\n","/**\n * PerformanceEventRepository — append-only event log.\n *\n * No mutation verbs beyond mongokit's inherited `create` / `findAll` /\n * `getByQuery`. Aggregation lives in `ScoreService` — this repo's only\n * job is \"store one row per supplier signal\".\n */\nimport { Repository, type PluginType, methodRegistryPlugin } from '@classytic/mongokit';\nimport type { Model } from 'mongoose';\nimport type { PerformanceEventDocument } from '../models/performance-event.model.js';\nimport type { SupplierPerformanceContext } from '../domain/ports/common.js';\nimport { repoOptionsFromCtx } from './repo-options.js';\n\nexport interface PerformanceEventRepositoryConfig {\n model: Model<PerformanceEventDocument>;\n plugins?: PluginType[];\n}\n\nexport class PerformanceEventRepository extends Repository<PerformanceEventDocument> {\n constructor(config: PerformanceEventRepositoryConfig) {\n super(config.model, [methodRegistryPlugin(), ...(config.plugins ?? [])]);\n }\n\n /**\n * Range query for one supplier — `[start, end)`. The (supplierId,\n * occurredAt) compound index serves this directly. Returned lean for\n * cheap aggregation in the service layer.\n */\n async findInWindow(\n supplierId: string,\n start: Date,\n end: Date,\n ctx: SupplierPerformanceContext,\n ): Promise<PerformanceEventDocument[]> {\n return this.findAll(\n {\n supplierId,\n occurredAt: { $gte: start, $lt: end },\n },\n { ...repoOptionsFromCtx(ctx), lean: true },\n ) as unknown as Promise<PerformanceEventDocument[]>;\n }\n}\n","/**\n * SupplierScoreRepository — cached scorecard upserts.\n *\n * `upsertForPeriod` is the only domain verb — it replaces any prior\n * computation for the same (supplierId, period.start, period.end) tuple\n * (enforced by the unique index on the model). Pure CRUD beyond that.\n */\nimport { Repository, type PluginType, methodRegistryPlugin } from '@classytic/mongokit';\nimport type { Model } from 'mongoose';\nimport type { SupplierScoreDocument } from '../models/supplier-score.model.js';\nimport type { SupplierPerformanceContext } from '../domain/ports/common.js';\nimport type { ScoreMetrics, ScorePeriod } from '../domain/entities/supplier-score.entity.js';\nimport { repoOptionsFromCtx } from './repo-options.js';\n\nexport interface SupplierScoreRepositoryConfig {\n model: Model<SupplierScoreDocument>;\n plugins?: PluginType[];\n}\n\nexport interface UpsertScoreInput {\n supplierId: string;\n period: ScorePeriod;\n metrics: ScoreMetrics;\n eventCount: number;\n computedAt?: Date;\n}\n\nexport class SupplierScoreRepository extends Repository<SupplierScoreDocument> {\n constructor(config: SupplierScoreRepositoryConfig) {\n super(config.model, [methodRegistryPlugin(), ...(config.plugins ?? [])]);\n }\n\n /**\n * Atomic upsert keyed on (supplierId, period). Replaces an existing\n * snapshot in place — `computeScore` is idempotent. The unique index\n * on `(supplierId, period.start, period.end)` enforces that only one\n * row per (tenant, supplier, window) ever exists.\n *\n * INTENTIONAL BYPASS: This is an idempotent data-refresh upsert, not\n * a state-machine transition. Per migration rules, upserts that refresh\n * computed data (not CAS transitions) are excluded from claim() migration.\n * Stays as `findOneAndUpdate` with explicit upsert: true.\n */\n async upsertForPeriod(\n input: UpsertScoreInput,\n ctx: SupplierPerformanceContext,\n ): Promise<SupplierScoreDocument> {\n const computedAt = input.computedAt ?? new Date();\n const updated = await this.findOneAndUpdate<SupplierScoreDocument>(\n {\n supplierId: input.supplierId,\n 'period.start': input.period.start,\n 'period.end': input.period.end,\n },\n {\n $set: {\n period: input.period,\n metrics: input.metrics,\n eventCount: input.eventCount,\n computedAt,\n },\n },\n {\n ...repoOptionsFromCtx(ctx),\n upsert: true,\n returnDocument: 'after',\n lean: false,\n },\n );\n if (!updated) {\n throw new Error(\n `[supplier-performance] upsertForPeriod returned null for ${input.supplierId} ${input.period.start.toISOString()}`,\n );\n }\n return updated;\n }\n\n /**\n * Latest snapshot whose period contains `asOf` (or covers it via\n * `period.end`). Useful for dashboard reads — pick the most recent\n * computed scorecard for this supplier.\n */\n async findLatest(\n supplierId: string,\n ctx: SupplierPerformanceContext,\n ): Promise<SupplierScoreDocument | null> {\n const docs = await this.findAll(\n { supplierId },\n {\n ...repoOptionsFromCtx(ctx),\n lean: true,\n sort: { 'period.end': -1 },\n limit: 1,\n },\n );\n return (docs[0] as SupplierScoreDocument | undefined) ?? null;\n }\n}\n","/**\n * Pure scorecard aggregation. No I/O, no side effects, no `Date.now()`.\n *\n * Hosts that need different weights / scoring formulas write their own\n * roll-up over the same `PerformanceEvent` array — this module ships\n * one sane default.\n */\nimport type {\n PerformanceEvent,\n PerformanceMetrics,\n} from '../domain/entities/performance-event.entity.js';\nimport type {\n ScoreMetrics,\n ScorePeriod,\n} from '../domain/entities/supplier-score.entity.js';\n\nconst COMPOSITE_WEIGHTS = {\n onTime: 0.5,\n defectFree: 0.4,\n pricedToPlan: 0.1,\n} as const;\n\n/**\n * Aggregate raw performance events into a scorecard. Events outside the\n * `period` window are filtered out (defensive — callers should already\n * have queried within the window).\n */\nexport function scoreFromEvents(\n events: ReadonlyArray<PerformanceEvent>,\n period: ScorePeriod,\n): ScoreMetrics {\n const inWindow = events.filter(\n (e) => e.occurredAt >= period.start && e.occurredAt < period.end,\n );\n\n let deliveryCount = 0;\n let onTimeCount = 0;\n let totalDelayDays = 0;\n let lateCount = 0;\n\n let unitsReceived = 0;\n let defectiveUnits = 0;\n\n let priceVarianceCount = 0;\n let totalVariancePct = 0;\n\n for (const event of inWindow) {\n const metrics = (event.metrics ?? {}) as PerformanceMetrics;\n const qty = Number(metrics.quantity ?? 1);\n\n switch (event.type) {\n case 'delivery_received': {\n deliveryCount++;\n onTimeCount++;\n unitsReceived += qty;\n break;\n }\n case 'delivery_late': {\n deliveryCount++;\n lateCount++;\n unitsReceived += qty;\n const delay = Number(metrics.delayDays ?? 0);\n if (delay > 0) totalDelayDays += delay;\n break;\n }\n case 'defect_reported': {\n defectiveUnits += qty;\n break;\n }\n case 'price_variance': {\n priceVarianceCount++;\n totalVariancePct += Number(metrics.variancePct ?? 0);\n break;\n }\n }\n }\n\n const onTimeRate = deliveryCount > 0 ? onTimeCount / deliveryCount : 0;\n const avgDelayDays = lateCount > 0 ? totalDelayDays / lateCount : 0;\n const defectRate = unitsReceived > 0 ? defectiveUnits / unitsReceived : 0;\n const avgPriceVariance =\n priceVarianceCount > 0 ? totalVariancePct / priceVarianceCount : 0;\n\n // Composite: higher = better. Bounds at 0..100. Variance flips sign so\n // both over- and under-billing reduce the score.\n const composite =\n onTimeRate * COMPOSITE_WEIGHTS.onTime +\n (1 - defectRate) * COMPOSITE_WEIGHTS.defectFree +\n (1 - Math.min(Math.abs(avgPriceVariance), 1)) * COMPOSITE_WEIGHTS.pricedToPlan;\n\n return {\n deliveryCount,\n onTimeCount,\n onTimeRate: round(onTimeRate, 4),\n avgDelayDays: round(avgDelayDays, 2),\n unitsReceived,\n defectiveUnits,\n defectRate: round(defectRate, 4),\n priceVarianceCount,\n avgPriceVariance: round(avgPriceVariance, 4),\n compositeScore: round(Math.max(0, Math.min(100, composite * 100)), 2),\n };\n}\n\nfunction round(value: number, digits: number): number {\n const factor = 10 ** digits;\n return Math.round(value * factor) / factor;\n}\n","/**\n * Canonical event names emitted by `@classytic/supplier-performance`.\n *\n * Prefix `supplier_performance:` matches the sibling-package convention\n * (`order:...`, `commission:...`). Hosts wiring an Arc transport can\n * pattern-match on `supplier_performance:*`.\n */\nexport const SupplierPerformanceEvents = {\n EVENT_RECORDED: 'supplier_performance:event.recorded',\n SCORE_COMPUTED: 'supplier_performance:score.computed',\n} as const;\n\nexport type SupplierPerformanceEventName =\n (typeof SupplierPerformanceEvents)[keyof typeof SupplierPerformanceEvents];\n","/**\n * ScoreService — orchestration on top of the two repositories.\n *\n * Service-justified per PACKAGE_RULES §2 (multi-repo orchestration + event\n * emission + pure aggregation algorithm). Pure scoring math lives in\n * `calc/score-calculator.ts`; the service handles persistence + events.\n *\n * Verbs:\n * recordEvent(input, ctx) — append to event log + emit `event.recorded`\n * computeScore(input, ctx) — aggregate + upsert + emit `score.computed`\n * getScorecard(supplierId, period?, ctx) — read-or-compute (lazy refresh)\n */\nimport type { EventTransport } from '@classytic/primitives/events';\nimport { createEvent } from '@classytic/primitives/events';\nimport type { SupplierPerformanceContext } from '../domain/ports/common.js';\nimport type {\n PerformanceEvent,\n RecordEventInput,\n} from '../domain/entities/performance-event.entity.js';\nimport type {\n ComputeScoreInput,\n ScorePeriod,\n SupplierScore,\n} from '../domain/entities/supplier-score.entity.js';\nimport type { PerformanceEventDocument } from '../models/performance-event.model.js';\nimport type { SupplierScoreDocument } from '../models/supplier-score.model.js';\nimport type { PerformanceEventRepository } from '../repositories/performance-event.repository.js';\nimport type { SupplierScoreRepository } from '../repositories/supplier-score.repository.js';\nimport { repoOptionsFromCtx } from '../repositories/repo-options.js';\nimport { scoreFromEvents } from '../calc/score-calculator.js';\nimport { SupplierPerformanceEvents } from '../events/event-constants.js';\n\nexport interface ScoreServiceConfig {\n events: PerformanceEventRepository;\n scores: SupplierScoreRepository;\n eventTransport?: EventTransport | undefined;\n logger?: { error(message: string, ...args: unknown[]): void };\n}\n\nexport class ScoreService {\n private events: PerformanceEventRepository;\n private scores: SupplierScoreRepository;\n private eventTransport?: EventTransport;\n private logger: NonNullable<ScoreServiceConfig['logger']>;\n\n constructor(config: ScoreServiceConfig) {\n this.events = config.events;\n this.scores = config.scores;\n this.eventTransport = config.eventTransport;\n this.logger = config.logger ?? console;\n }\n\n /**\n * Append a single performance event to the log. Idempotent on the\n * caller's side via `metadata.idempotencyKey` if hosts wire their own\n * dedup index — this kernel doesn't enforce it (different hosts have\n * different keying preferences: PO-line, PO+SKU, etc.).\n */\n async recordEvent(\n input: RecordEventInput,\n ctx: SupplierPerformanceContext,\n ): Promise<PerformanceEventDocument> {\n if (!input.supplierId) throw new RecordEventValidationError('supplierId is required');\n\n const occurredAt = input.occurredAt ?? new Date();\n const doc = (await this.events.create(\n {\n organizationId: ctx.organizationId,\n supplierId: input.supplierId,\n type: input.type,\n occurredAt,\n metrics: input.metrics ?? {},\n ...(input.sourceRef !== undefined ? { sourceRef: input.sourceRef } : {}),\n ...(input.sourceType !== undefined ? { sourceType: input.sourceType } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n },\n repoOptionsFromCtx(ctx),\n )) as PerformanceEventDocument;\n\n this.publish(SupplierPerformanceEvents.EVENT_RECORDED, ctx, {\n supplierId: input.supplierId,\n type: input.type,\n occurredAt: occurredAt.toISOString(),\n sourceRef: input.sourceRef,\n });\n\n return doc;\n }\n\n /**\n * Compute (or recompute) a scorecard for one (supplier, period) pair.\n * Pulls all events in window, runs the pure calculator, persists the\n * snapshot. Idempotent — calling twice with the same period upserts in\n * place.\n */\n async computeScore(\n input: ComputeScoreInput,\n ctx: SupplierPerformanceContext,\n ): Promise<SupplierScoreDocument> {\n const period = normalizePeriod(input.period);\n const rawEvents = await this.events.findInWindow(\n input.supplierId,\n period.start,\n period.end,\n ctx,\n );\n const eventsForCalc = rawEvents.map(toCalcEvent);\n const metrics = scoreFromEvents(eventsForCalc, period);\n\n const doc = await this.scores.upsertForPeriod(\n {\n supplierId: input.supplierId,\n period,\n metrics,\n eventCount: eventsForCalc.length,\n },\n ctx,\n );\n\n this.publish(SupplierPerformanceEvents.SCORE_COMPUTED, ctx, {\n supplierId: input.supplierId,\n period: { start: period.start.toISOString(), end: period.end.toISOString() },\n compositeScore: metrics.compositeScore,\n eventCount: eventsForCalc.length,\n });\n\n return doc;\n }\n\n /**\n * Read-or-compute. Returns the latest cached scorecard for the supplier;\n * if `period` is supplied, recomputes for that exact window before\n * returning. Pure read otherwise — won't refresh stale snapshots\n * implicitly (callers know when their data has changed).\n */\n async getScorecard(\n supplierId: string,\n ctx: SupplierPerformanceContext,\n period?: ScorePeriod,\n ): Promise<SupplierScoreDocument | null> {\n if (period) {\n return this.computeScore({ supplierId, period }, ctx);\n }\n return this.scores.findLatest(supplierId, ctx);\n }\n\n // ── Internals ────────────────────────────────────────────────────\n\n private publish(\n type: string,\n ctx: SupplierPerformanceContext,\n data: Record<string, unknown>,\n ): void {\n if (!this.eventTransport) return;\n const event = createEvent(type, data, {\n organizationId: ctx.organizationId,\n userId: ctx.actorRef,\n correlationId: ctx.correlationId,\n });\n this.eventTransport.publish(event).catch((err) => {\n this.logger.error(`[supplier-performance] publish failed for ${type}:`, err);\n });\n }\n}\n\n// ── Adapters ───────────────────────────────────────────────────────────\n\nfunction toCalcEvent(doc: PerformanceEventDocument): PerformanceEvent {\n return {\n _id: doc._id as PerformanceEvent['_id'],\n organizationId: String(doc.organizationId),\n supplierId: doc.supplierId,\n type: doc.type as PerformanceEvent['type'],\n occurredAt: doc.occurredAt,\n metrics: (doc.metrics ?? {}) as PerformanceEvent['metrics'],\n ...(doc.sourceRef !== undefined ? { sourceRef: doc.sourceRef } : {}),\n ...(doc.sourceType !== undefined ? { sourceType: doc.sourceType } : {}),\n ...(doc.metadata !== undefined ? { metadata: doc.metadata } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n };\n}\n\nfunction normalizePeriod(period: ScorePeriod): ScorePeriod {\n if (period.end.getTime() <= period.start.getTime()) {\n throw new RecordEventValidationError(\n `period.end (${period.end.toISOString()}) must be strictly after period.start (${period.start.toISOString()})`,\n );\n }\n return period;\n}\n\n// ── Errors ─────────────────────────────────────────────────────────────\n\nexport class RecordEventValidationError extends Error {\n override readonly name = 'RecordEventValidationError';\n readonly code = 'SUPPLIER_PERFORMANCE_VALIDATION' as const;\n constructor(message: string) {\n super(message);\n }\n}\n","import type {\n DomainEvent,\n EventHandler,\n EventTransport,\n} from '@classytic/primitives/events';\nimport { matchEventPattern } from '@classytic/primitives/events';\n\nexport interface InProcessBusOptions {\n logger?: { error(message: string, ...args: unknown[]): void };\n}\n\n/**\n * Zero-dep in-process event bus. Subscribers can use glob patterns\n * (`supplier_performance:*`, `*`, exact type). Subscriber errors are\n * caught and logged — they never break the emitter or sibling\n * subscribers.\n *\n * Drop-in compatible with any `EventTransport` — hosts replace it by\n * passing their own at `createSupplierPerformance({ eventTransport })`.\n */\nexport class InProcessSupplierPerformanceBus implements EventTransport {\n readonly name = 'in-process-supplier-performance';\n private patterns = new Map<string, Set<EventHandler>>();\n private logger: NonNullable<InProcessBusOptions['logger']>;\n\n constructor(options: InProcessBusOptions = {}) {\n this.logger = options.logger ?? console;\n }\n\n async publish(event: DomainEvent): Promise<void> {\n for (const [pattern, handlers] of this.patterns) {\n if (!matchEventPattern(pattern, event.type)) continue;\n for (const fn of handlers) {\n try {\n await fn(event);\n } catch (err) {\n this.logger.error(\n `[supplier-performance] subscriber threw on ${event.type}: ${(err as Error).message}`,\n err,\n );\n }\n }\n }\n }\n\n async subscribe(pattern: string, handler: EventHandler): Promise<() => void> {\n let set = this.patterns.get(pattern);\n if (!set) {\n set = new Set();\n this.patterns.set(pattern, set);\n }\n set.add(handler);\n return () => {\n const s = this.patterns.get(pattern);\n s?.delete(handler);\n if (s && s.size === 0) this.patterns.delete(pattern);\n };\n }\n}\n","import { createSupplierPerformanceModels } from '../models/create-models.js';\nimport { resolveSupplierPerformanceTenant } from '../models/inject-tenant.js';\nimport { PerformanceEventRepository } from '../repositories/performance-event.repository.js';\nimport { SupplierScoreRepository } from '../repositories/supplier-score.repository.js';\nimport { ScoreService } from '../services/score.service.js';\nimport { InProcessSupplierPerformanceBus } from '../events/in-process-bus.js';\nimport type {\n SupplierPerformanceConfig,\n SupplierPerformanceEngine,\n} from './engine-types.js';\n\nexport async function createSupplierPerformance(\n config: SupplierPerformanceConfig,\n): Promise<SupplierPerformanceEngine> {\n if (!config.connection) {\n throw new Error('createSupplierPerformance: config.connection is required');\n }\n\n const logger = config.logger ?? console;\n const events = config.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });\n\n const tenant = resolveSupplierPerformanceTenant(config.tenant);\n const models = createSupplierPerformanceModels(config.connection, {\n tenant,\n ...(config.collectionPrefix !== undefined ? { collectionPrefix: config.collectionPrefix } : {}),\n ...(config.forceRecreate !== undefined ? { forceRecreate: config.forceRecreate } : {}),\n });\n\n const performanceEvent = new PerformanceEventRepository({\n model: models.PerformanceEvent,\n ...(config.repositoryPlugins?.performanceEvent !== undefined\n ? { plugins: config.repositoryPlugins.performanceEvent }\n : {}),\n });\n const supplierScore = new SupplierScoreRepository({\n model: models.SupplierScore,\n ...(config.repositoryPlugins?.supplierScore !== undefined\n ? { plugins: config.repositoryPlugins.supplierScore }\n : {}),\n });\n\n const score = new ScoreService({\n events: performanceEvent,\n scores: supplierScore,\n eventTransport: events,\n logger,\n });\n\n return {\n models,\n repositories: { performanceEvent, supplierScore },\n services: { score },\n events,\n async syncIndexes() {\n await Promise.all([\n models.PerformanceEvent.syncIndexes(),\n models.SupplierScore.syncIndexes(),\n ]);\n },\n async destroy() {\n // No-op — host owns the connection lifecycle.\n },\n };\n}\n"],"x_google_ignoreList":[1],"mappings":";;;;;;;;;;;;;;;;;;AAcA,MAAa,uBAAuB;CAClC,mBAAmB;CACnB,eAAe;CACf,iBAAiB;CACjB,gBAAgB;CACjB;AAKD,MAAa,gCAAgC,OAAO,OAClD,qBACD;;;;;;;;;;;;AChBD,MAAM,wBAAwB;CAC7B,UAAU;CACV,SAAS;CACT,aAAa;CACb,WAAW;CACX,KAAK;CACL,YAAY;CACZ,UAAU;CACV;;;;;;;;;;;;AAYD,SAAS,oBAAoB,QAAQ;CACpC,IAAI,WAAW,OAAO,OAAO;EAC5B,GAAG;EACH,UAAU;EACV,SAAS;EACT,UAAU;EACV;CACD,IAAI,WAAW,QAAQ,WAAW,KAAK,GAAG,OAAO,EAAE,GAAG,uBAAuB;CAC7E,MAAM,WAAW,OAAO,aAAa,OAAO,YAAY,QAAQ,SAAS;CACzE,MAAM,aAAa,OAAO,cAAc,OAAO,eAAe,sBAAsB;CACpF,IAAI,aAAa,QAAQ,OAAO;EAC/B,GAAG;EACH,GAAG;EACH;EACA,UAAU;EACV,SAAS;EACT,UAAU;EACV;CACD,IAAI,aAAa,UAAU;EAC1B,IAAI,OAAO,OAAO,YAAY,YAAY,MAAM,IAAI,MAAM,2EAA2E;EACrI,OAAO;GACN,GAAG;GACH,GAAG;GACH;GACA,UAAU;GACV,SAAS,OAAO,WAAW;GAC3B,SAAS,OAAO;GAChB;;CA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