@classytic/supplier-performance 0.1.1 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -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 +80 -111
- package/dist/index.js +115 -205
- package/package.json +15 -6
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
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
|
|
5
|
+
//#region src/models/inject-tenant.ts
|
|
28
6
|
/**
|
|
29
|
-
*
|
|
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.
|
|
30
11
|
*
|
|
31
|
-
* `
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* runtime default — `Pick<TenantConfig, 'fieldType'>` extension preserves
|
|
35
|
-
* type-level alignment without forcing a runtime default change.
|
|
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' }`.
|
|
36
15
|
*/
|
|
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
|
-
};
|
|
46
16
|
/**
|
|
47
|
-
* Resolve
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* - `true` / `undefined` → default field strategy.
|
|
51
|
-
* - Object with `strategy: 'custom'` → `resolve` is required; throws
|
|
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).
|
|
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.
|
|
56
20
|
*/
|
|
57
|
-
function
|
|
58
|
-
|
|
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
|
-
/**
|
|
97
|
-
* Mongoose-specific tenant adapter — mirrors the commission package's
|
|
98
|
-
* pattern so hosts that already configured commission can reuse the same
|
|
99
|
-
* config shape here.
|
|
100
|
-
*
|
|
101
|
-
* Default `fieldType` is `'string'`. Hosts wanting ObjectId storage pass
|
|
102
|
-
* `tenant: { fieldType: 'objectId' }` on `SupplierPerformanceConfig`.
|
|
103
|
-
*/
|
|
104
|
-
function resolveSupplierPerformanceTenant(input = {}) {
|
|
105
|
-
if (typeof input === "boolean") return applyDefaultFieldType(resolveTenantConfig(input));
|
|
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);
|
|
@@ -459,6 +360,33 @@ var SupplierScoreRepository = class extends Repository {
|
|
|
459
360
|
}
|
|
460
361
|
};
|
|
461
362
|
//#endregion
|
|
363
|
+
//#region src/domain/errors/supplier-performance.errors.ts
|
|
364
|
+
var SupplierPerformanceError = class extends Error {
|
|
365
|
+
code;
|
|
366
|
+
status;
|
|
367
|
+
constructor(message, code, status) {
|
|
368
|
+
super(message);
|
|
369
|
+
this.code = code;
|
|
370
|
+
this.status = status;
|
|
371
|
+
this.name = this.constructor.name;
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
/**
|
|
375
|
+
* Thrown when a host passes ctx.session but no OutboxStore is wired —
|
|
376
|
+
* publishing mid-transaction would leak ghost events on rollback (§P8.1).
|
|
377
|
+
*/
|
|
378
|
+
var UnmanagedSessionError = class extends SupplierPerformanceError {
|
|
379
|
+
constructor() {
|
|
380
|
+
super("ctx.session provided but no OutboxStore is wired — events would leak or be lost. Wire an outbox or drop the session.", "supplier_performance.session.unmanaged", 409);
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
/** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
|
|
384
|
+
var SupplierPerformanceValidationError = class extends SupplierPerformanceError {
|
|
385
|
+
constructor(message) {
|
|
386
|
+
super(message, "supplier_performance.validation.invalid_input", 400);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
//#endregion
|
|
462
390
|
//#region src/calc/score-calculator.ts
|
|
463
391
|
const COMPOSITE_WEIGHTS = {
|
|
464
392
|
onTime: .5,
|
|
@@ -529,29 +457,30 @@ function round(value, digits) {
|
|
|
529
457
|
return Math.round(value * factor) / factor;
|
|
530
458
|
}
|
|
531
459
|
//#endregion
|
|
532
|
-
//#region src/
|
|
460
|
+
//#region src/services/score.service.ts
|
|
533
461
|
/**
|
|
534
|
-
*
|
|
462
|
+
* ScoreService — orchestration on top of the two repositories.
|
|
463
|
+
*
|
|
464
|
+
* Service-justified per PACKAGE_RULES §2 (multi-repo orchestration + event
|
|
465
|
+
* emission + pure aggregation algorithm). Pure scoring math lives in
|
|
466
|
+
* `calc/score-calculator.ts`; the service handles persistence + events.
|
|
535
467
|
*
|
|
536
|
-
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
468
|
+
* Verbs:
|
|
469
|
+
* recordEvent(input, ctx) — append to event log + emit `event.recorded`
|
|
470
|
+
* computeScore(input, ctx) — aggregate + upsert + emit `score.computed`
|
|
471
|
+
* getScorecard(supplierId, period?, ctx) — read-or-compute (lazy refresh)
|
|
539
472
|
*/
|
|
540
|
-
const SupplierPerformanceEvents = {
|
|
541
|
-
EVENT_RECORDED: "supplier_performance:event.recorded",
|
|
542
|
-
SCORE_COMPUTED: "supplier_performance:score.computed"
|
|
543
|
-
};
|
|
544
|
-
//#endregion
|
|
545
|
-
//#region src/services/score.service.ts
|
|
546
473
|
var ScoreService = class {
|
|
547
474
|
events;
|
|
548
475
|
scores;
|
|
549
476
|
eventTransport;
|
|
477
|
+
outbox;
|
|
550
478
|
logger;
|
|
551
479
|
constructor(config) {
|
|
552
480
|
this.events = config.events;
|
|
553
481
|
this.scores = config.scores;
|
|
554
482
|
this.eventTransport = config.eventTransport;
|
|
483
|
+
this.outbox = config.outbox;
|
|
555
484
|
this.logger = config.logger ?? console;
|
|
556
485
|
}
|
|
557
486
|
/**
|
|
@@ -561,7 +490,7 @@ var ScoreService = class {
|
|
|
561
490
|
* different keying preferences: PO-line, PO+SKU, etc.).
|
|
562
491
|
*/
|
|
563
492
|
async recordEvent(input, ctx) {
|
|
564
|
-
if (!input.supplierId) throw new
|
|
493
|
+
if (!input.supplierId) throw new SupplierPerformanceValidationError("supplierId is required");
|
|
565
494
|
const occurredAt = input.occurredAt ?? /* @__PURE__ */ new Date();
|
|
566
495
|
const doc = await this.events.create({
|
|
567
496
|
organizationId: ctx.organizationId,
|
|
@@ -573,7 +502,7 @@ var ScoreService = class {
|
|
|
573
502
|
...input.sourceType !== void 0 ? { sourceType: input.sourceType } : {},
|
|
574
503
|
...input.metadata !== void 0 ? { metadata: input.metadata } : {}
|
|
575
504
|
}, repoOptionsFromCtx(ctx));
|
|
576
|
-
this.publish(SupplierPerformanceEvents.EVENT_RECORDED, ctx, {
|
|
505
|
+
await this.publish(SupplierPerformanceEvents.EVENT_RECORDED, ctx, {
|
|
577
506
|
supplierId: input.supplierId,
|
|
578
507
|
type: input.type,
|
|
579
508
|
occurredAt: occurredAt.toISOString(),
|
|
@@ -597,7 +526,7 @@ var ScoreService = class {
|
|
|
597
526
|
metrics,
|
|
598
527
|
eventCount: eventsForCalc.length
|
|
599
528
|
}, ctx);
|
|
600
|
-
this.publish(SupplierPerformanceEvents.SCORE_COMPUTED, ctx, {
|
|
529
|
+
await this.publish(SupplierPerformanceEvents.SCORE_COMPUTED, ctx, {
|
|
601
530
|
supplierId: input.supplierId,
|
|
602
531
|
period: {
|
|
603
532
|
start: period.start.toISOString(),
|
|
@@ -621,16 +550,29 @@ var ScoreService = class {
|
|
|
621
550
|
}, ctx);
|
|
622
551
|
return this.scores.findLatest(supplierId, ctx);
|
|
623
552
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
553
|
+
/**
|
|
554
|
+
* P8 dispatch. Outbox save (when wired) runs first, session-bound, and
|
|
555
|
+
* failures PROPAGATE; the transport publish is best-effort (swallowed)
|
|
556
|
+
* and skipped under a host session — the relay delivers the durable
|
|
557
|
+
* row post-commit (§P8.1). A host session with NO outbox throws
|
|
558
|
+
* `UnmanagedSessionError` before any side effect: the pre-guard
|
|
559
|
+
* fire-and-forget publish could leak ghost events on rollback.
|
|
560
|
+
*/
|
|
561
|
+
async publish(type, ctx, data) {
|
|
562
|
+
if (!this.eventTransport && !this.outbox) return;
|
|
563
|
+
if (ctx.session && !this.outbox) throw new UnmanagedSessionError();
|
|
564
|
+
const event = createEvent(type, data, ctx);
|
|
565
|
+
if (this.outbox) try {
|
|
566
|
+
await this.outbox.save(event, { session: ctx.session });
|
|
567
|
+
} catch (err) {
|
|
568
|
+
this.logger.error(`[supplier-performance] outbox.save failed for ${type}:`, err);
|
|
569
|
+
throw err;
|
|
570
|
+
}
|
|
571
|
+
if (this.eventTransport && !ctx.session) try {
|
|
572
|
+
await this.eventTransport.publish(event);
|
|
573
|
+
} catch (err) {
|
|
632
574
|
this.logger.error(`[supplier-performance] publish failed for ${type}:`, err);
|
|
633
|
-
}
|
|
575
|
+
}
|
|
634
576
|
}
|
|
635
577
|
};
|
|
636
578
|
function toCalcEvent(doc) {
|
|
@@ -649,82 +591,50 @@ function toCalcEvent(doc) {
|
|
|
649
591
|
};
|
|
650
592
|
}
|
|
651
593
|
function normalizePeriod(period) {
|
|
652
|
-
if (period.end.getTime() <= period.start.getTime()) throw new
|
|
594
|
+
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
595
|
return period;
|
|
654
596
|
}
|
|
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
597
|
//#endregion
|
|
705
598
|
//#region src/engine/create-supplier-performance.ts
|
|
706
599
|
async function createSupplierPerformance(config) {
|
|
707
600
|
if (!config.connection) throw new Error("createSupplierPerformance: config.connection is required");
|
|
708
601
|
const logger = config.logger ?? console;
|
|
709
602
|
const events = config.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });
|
|
710
|
-
const tenant =
|
|
603
|
+
const tenant = resolveTenantConfig(config.tenant);
|
|
711
604
|
const models = createSupplierPerformanceModels(config.connection, {
|
|
712
605
|
tenant,
|
|
713
606
|
...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
|
|
714
607
|
...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
|
|
715
608
|
});
|
|
609
|
+
const tenantPlugins = (() => {
|
|
610
|
+
if (!tenant.enabled || tenant.strategy !== "field") return [];
|
|
611
|
+
const extras = typeof config.tenant === "object" ? config.tenant : void 0;
|
|
612
|
+
return [multiTenantPlugin({
|
|
613
|
+
tenantField: tenant.tenantField,
|
|
614
|
+
fieldType: tenant.fieldType,
|
|
615
|
+
contextKey: tenant.contextKey,
|
|
616
|
+
required: tenant.required,
|
|
617
|
+
...extras?.skipOperations !== void 0 ? { skipOperations: extras.skipOperations } : {},
|
|
618
|
+
...extras?.skipWhen !== void 0 ? { skipWhen: extras.skipWhen } : {},
|
|
619
|
+
...extras?.resolveContext !== void 0 ? { resolveContext: extras.resolveContext } : {},
|
|
620
|
+
...extras?.allowDataInjection !== void 0 ? { allowDataInjection: extras.allowDataInjection } : {},
|
|
621
|
+
...extras?.onMismatch !== void 0 ? { onMismatch: extras.onMismatch } : {}
|
|
622
|
+
})];
|
|
623
|
+
})();
|
|
624
|
+
const repoPlugins = config.repositoryPlugins ?? {};
|
|
716
625
|
const performanceEvent = new PerformanceEventRepository({
|
|
717
626
|
model: models.PerformanceEvent,
|
|
718
|
-
|
|
627
|
+
plugins: [...tenantPlugins, ...repoPlugins.performanceEvent ?? []]
|
|
719
628
|
});
|
|
720
629
|
const supplierScore = new SupplierScoreRepository({
|
|
721
630
|
model: models.SupplierScore,
|
|
722
|
-
|
|
631
|
+
plugins: [...tenantPlugins, ...repoPlugins.supplierScore ?? []]
|
|
723
632
|
});
|
|
724
633
|
const score = new ScoreService({
|
|
725
634
|
events: performanceEvent,
|
|
726
635
|
scores: supplierScore,
|
|
727
636
|
eventTransport: events,
|
|
637
|
+
...config.outbox !== void 0 ? { outbox: config.outbox } : {},
|
|
728
638
|
logger
|
|
729
639
|
});
|
|
730
640
|
return {
|
|
@@ -738,10 +648,10 @@ async function createSupplierPerformance(config) {
|
|
|
738
648
|
async syncIndexes() {
|
|
739
649
|
await Promise.all([models.PerformanceEvent.syncIndexes(), models.SupplierScore.syncIndexes()]);
|
|
740
650
|
},
|
|
741
|
-
async destroy() {
|
|
651
|
+
async destroy() {
|
|
652
|
+
await events.close?.();
|
|
653
|
+
}
|
|
742
654
|
};
|
|
743
655
|
}
|
|
744
656
|
//#endregion
|
|
745
|
-
export { InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventModelCollisionError, PerformanceEventRepository, PerformanceEventType,
|
|
746
|
-
|
|
747
|
-
//# sourceMappingURL=index.js.map
|
|
657
|
+
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.1",
|
|
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,SAAiC;;;;EAAjC,UAAA,EAIH,IAJG;EAAyB,OAAA,EAK/B,MAL+B,CAAA,MAAA,EAAA,OAAA,CAAA;WAI5B,CAAA,EAAA,MAAA;YACH,CAAA,EAAA,MAA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.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;;CAEF,OAAO;EACN,GAAG;EACH,GAAG;EACH;EACA,UAAU;EACV,SAAS,OAAO,WAAW;EAC3B;;;;;;;;;;;;AC1CF,SAAgB,iCACd,QAAwC,EAAE,EACpB;CACtB,IAAI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