@classytic/supplier-performance 0.1.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/dist/index.js ADDED
@@ -0,0 +1,675 @@
1
+ import mongoose, { Schema } from "mongoose";
2
+ import { resolveTenantConfig } from "@classytic/primitives/tenant";
3
+ import { Repository, methodRegistryPlugin } from "@classytic/mongokit";
4
+ import { createEvent, matchEventPattern } from "@classytic/primitives/events";
5
+ //#region src/domain/enums/event-type.enum.ts
6
+ /**
7
+ * Performance event types — what happened on a single supplier interaction.
8
+ *
9
+ * The catalog is intentionally small. Each type contributes to one or more
10
+ * scorecard metrics:
11
+ *
12
+ * - `delivery_received` → on-time rate, average delay
13
+ * - `delivery_late` → on-time rate, average delay
14
+ * - `defect_reported` → defect rate
15
+ * - `price_variance` → price variance %
16
+ *
17
+ * Hosts that need a domain-specific signal (e.g. `quality_audit`) can
18
+ * extend by adding a constant + payload. Pure data; no FSM.
19
+ */
20
+ const PerformanceEventType = {
21
+ delivery_received: "delivery_received",
22
+ delivery_late: "delivery_late",
23
+ defect_reported: "defect_reported",
24
+ price_variance: "price_variance"
25
+ };
26
+ const PERFORMANCE_EVENT_TYPE_VALUES = Object.values(PerformanceEventType);
27
+ //#endregion
28
+ //#region src/models/inject-tenant.ts
29
+ /**
30
+ * Mongoose-specific tenant adapter — mirrors the commission package's
31
+ * pattern so hosts that already configured commission can reuse the same
32
+ * config shape here.
33
+ *
34
+ * Default `fieldType` is `'string'`. Hosts wanting ObjectId storage pass
35
+ * `tenant: { fieldType: 'objectId' }` on `SupplierPerformanceConfig`.
36
+ */
37
+ function resolveSupplierPerformanceTenant(input = {}) {
38
+ if (typeof input === "boolean") return applyDefaultFieldType(resolveTenantConfig(input));
39
+ if ("tenantFieldType" in input || "multiTenant" in input) {
40
+ const legacy = input;
41
+ return resolveTenantConfig({
42
+ enabled: legacy.multiTenant !== false,
43
+ fieldType: legacy.tenantFieldType ?? "string"
44
+ });
45
+ }
46
+ const cfg = input;
47
+ if (cfg.fieldType === void 0) return resolveTenantConfig({
48
+ ...cfg,
49
+ fieldType: "string"
50
+ });
51
+ return resolveTenantConfig(cfg);
52
+ }
53
+ function applyDefaultFieldType(resolved) {
54
+ return {
55
+ ...resolved,
56
+ fieldType: "string"
57
+ };
58
+ }
59
+ /**
60
+ * Inject the tenant field into a Mongoose schema and prepend it to every
61
+ * existing compound index (so queries are index-efficient under
62
+ * multi-tenant scoping). Identical algorithm to commission's helper.
63
+ */
64
+ function injectTenantField(schema, tenant) {
65
+ const isFieldStrategy = tenant.strategy === "field";
66
+ const isObjectId = tenant.fieldType === "objectId";
67
+ schema.add({ [tenant.tenantField]: {
68
+ type: isObjectId ? mongoose.Schema.Types.ObjectId : String,
69
+ ...tenant.enabled && tenant.required ? { required: true } : {},
70
+ index: true,
71
+ ...isObjectId && tenant.ref ? { ref: tenant.ref } : {}
72
+ } });
73
+ if (!tenant.enabled || !isFieldStrategy) return;
74
+ const existingIndexes = schema._indexes;
75
+ if (existingIndexes && existingIndexes.length > 0) for (const indexEntry of existingIndexes) {
76
+ const fields = indexEntry[0];
77
+ if (fields[tenant.tenantField] !== void 0) continue;
78
+ const newFields = { [tenant.tenantField]: 1 };
79
+ for (const [key, val] of Object.entries(fields)) newFields[key] = val;
80
+ indexEntry[0] = newFields;
81
+ }
82
+ }
83
+ //#endregion
84
+ //#region src/models/performance-event.model.ts
85
+ const metricsSchema$1 = new Schema({
86
+ quantity: {
87
+ type: Number,
88
+ min: 0
89
+ },
90
+ expectedAt: Date,
91
+ actualAt: Date,
92
+ delayDays: Number,
93
+ expectedUnitCost: {
94
+ type: Number,
95
+ min: 0
96
+ },
97
+ actualUnitCost: {
98
+ type: Number,
99
+ min: 0
100
+ },
101
+ variancePct: Number
102
+ }, {
103
+ _id: false,
104
+ strict: false
105
+ });
106
+ function buildPerformanceEventSchema(tenant) {
107
+ const schema = new Schema({
108
+ supplierId: {
109
+ type: String,
110
+ required: true
111
+ },
112
+ type: {
113
+ type: String,
114
+ required: true,
115
+ enum: PERFORMANCE_EVENT_TYPE_VALUES
116
+ },
117
+ occurredAt: {
118
+ type: Date,
119
+ required: true
120
+ },
121
+ metrics: {
122
+ type: metricsSchema$1,
123
+ required: true,
124
+ default: {}
125
+ },
126
+ sourceRef: String,
127
+ sourceType: String,
128
+ metadata: { type: Schema.Types.Mixed }
129
+ }, {
130
+ timestamps: true,
131
+ collection: "supplier_performance_events"
132
+ });
133
+ schema.index({
134
+ supplierId: 1,
135
+ occurredAt: 1
136
+ });
137
+ schema.index({
138
+ sourceRef: 1,
139
+ type: 1
140
+ }, { partialFilterExpression: { sourceRef: { $exists: true } } });
141
+ injectTenantField(schema, tenant);
142
+ return schema;
143
+ }
144
+ var PerformanceEventModelCollisionError = class extends Error {
145
+ constructor(name) {
146
+ super(`[supplier-performance] Mongoose model "${name}" already exists on this connection. Pass \`forceRecreate: true\` for hot-reload, or use two Mongoose connections.`);
147
+ this.name = "PerformanceEventModelCollisionError";
148
+ }
149
+ };
150
+ function createPerformanceEventModel(connection, tenant, config = {}) {
151
+ if (connection.models.PerformanceEvent) if (config.forceRecreate) connection.deleteModel("PerformanceEvent");
152
+ else throw new PerformanceEventModelCollisionError("PerformanceEvent");
153
+ const collection = (config.collectionPrefix ?? "") + "supplier_performance_events";
154
+ return connection.model("PerformanceEvent", buildPerformanceEventSchema(tenant), collection);
155
+ }
156
+ //#endregion
157
+ //#region src/models/supplier-score.model.ts
158
+ const periodSchema = new Schema({
159
+ start: {
160
+ type: Date,
161
+ required: true
162
+ },
163
+ end: {
164
+ type: Date,
165
+ required: true
166
+ },
167
+ label: String
168
+ }, { _id: false });
169
+ const metricsSchema = new Schema({
170
+ deliveryCount: {
171
+ type: Number,
172
+ default: 0,
173
+ min: 0
174
+ },
175
+ onTimeCount: {
176
+ type: Number,
177
+ default: 0,
178
+ min: 0
179
+ },
180
+ onTimeRate: {
181
+ type: Number,
182
+ default: 0,
183
+ min: 0,
184
+ max: 1
185
+ },
186
+ avgDelayDays: {
187
+ type: Number,
188
+ default: 0
189
+ },
190
+ unitsReceived: {
191
+ type: Number,
192
+ default: 0,
193
+ min: 0
194
+ },
195
+ defectiveUnits: {
196
+ type: Number,
197
+ default: 0,
198
+ min: 0
199
+ },
200
+ defectRate: {
201
+ type: Number,
202
+ default: 0,
203
+ min: 0,
204
+ max: 1
205
+ },
206
+ priceVarianceCount: {
207
+ type: Number,
208
+ default: 0,
209
+ min: 0
210
+ },
211
+ avgPriceVariance: {
212
+ type: Number,
213
+ default: 0
214
+ },
215
+ compositeScore: {
216
+ type: Number,
217
+ default: 0,
218
+ min: 0,
219
+ max: 100
220
+ }
221
+ }, { _id: false });
222
+ function buildSupplierScoreSchema(tenant) {
223
+ const schema = new Schema({
224
+ supplierId: {
225
+ type: String,
226
+ required: true
227
+ },
228
+ period: {
229
+ type: periodSchema,
230
+ required: true
231
+ },
232
+ metrics: {
233
+ type: metricsSchema,
234
+ required: true,
235
+ default: {}
236
+ },
237
+ computedAt: {
238
+ type: Date,
239
+ required: true
240
+ },
241
+ eventCount: {
242
+ type: Number,
243
+ required: true,
244
+ default: 0,
245
+ min: 0
246
+ }
247
+ }, {
248
+ timestamps: true,
249
+ collection: "supplier_scores"
250
+ });
251
+ schema.index({
252
+ supplierId: 1,
253
+ "period.start": 1,
254
+ "period.end": 1
255
+ }, { unique: true });
256
+ schema.index({
257
+ "period.end": -1,
258
+ "metrics.compositeScore": -1
259
+ });
260
+ injectTenantField(schema, tenant);
261
+ return schema;
262
+ }
263
+ var SupplierScoreModelCollisionError = class extends Error {
264
+ constructor(name) {
265
+ super(`[supplier-performance] Mongoose model "${name}" already exists on this connection. Pass \`forceRecreate: true\` for hot-reload, or use two Mongoose connections.`);
266
+ this.name = "SupplierScoreModelCollisionError";
267
+ }
268
+ };
269
+ function createSupplierScoreModel(connection, tenant, config = {}) {
270
+ if (connection.models.SupplierScore) if (config.forceRecreate) connection.deleteModel("SupplierScore");
271
+ else throw new SupplierScoreModelCollisionError("SupplierScore");
272
+ const collection = (config.collectionPrefix ?? "") + "supplier_scores";
273
+ return connection.model("SupplierScore", buildSupplierScoreSchema(tenant), collection);
274
+ }
275
+ //#endregion
276
+ //#region src/models/create-models.ts
277
+ function createSupplierPerformanceModels(connection, options = {}) {
278
+ const tenant = (() => {
279
+ if (typeof options.tenant === "object" && options.tenant !== null && "strategy" in options.tenant && "tenantField" in options.tenant) return options.tenant;
280
+ if (options.tenant !== void 0) return resolveSupplierPerformanceTenant(options.tenant);
281
+ return resolveSupplierPerformanceTenant();
282
+ })();
283
+ const modelConfig = {
284
+ ...options.collectionPrefix !== void 0 ? { collectionPrefix: options.collectionPrefix } : {},
285
+ ...options.forceRecreate !== void 0 ? { forceRecreate: options.forceRecreate } : {}
286
+ };
287
+ return {
288
+ PerformanceEvent: createPerformanceEventModel(connection, tenant, modelConfig),
289
+ SupplierScore: createSupplierScoreModel(connection, tenant, modelConfig)
290
+ };
291
+ }
292
+ //#endregion
293
+ //#region src/repositories/repo-options.ts
294
+ function repoOptionsFromCtx(ctx) {
295
+ const opts = {
296
+ organizationId: ctx.organizationId,
297
+ actorRef: ctx.actorRef,
298
+ actorKind: ctx.actorKind,
299
+ correlationId: ctx.correlationId
300
+ };
301
+ if (ctx.session !== void 0) opts.session = ctx.session;
302
+ if (ctx.idempotencyKey !== void 0) opts.idempotencyKey = ctx.idempotencyKey;
303
+ return opts;
304
+ }
305
+ //#endregion
306
+ //#region src/repositories/performance-event.repository.ts
307
+ /**
308
+ * PerformanceEventRepository — append-only event log.
309
+ *
310
+ * No mutation verbs beyond mongokit's inherited `create` / `findAll` /
311
+ * `getByQuery`. Aggregation lives in `ScoreService` — this repo's only
312
+ * job is "store one row per supplier signal".
313
+ */
314
+ var PerformanceEventRepository = class extends Repository {
315
+ constructor(config) {
316
+ super(config.model, [methodRegistryPlugin(), ...config.plugins ?? []]);
317
+ }
318
+ /**
319
+ * Range query for one supplier — `[start, end)`. The (supplierId,
320
+ * occurredAt) compound index serves this directly. Returned lean for
321
+ * cheap aggregation in the service layer.
322
+ */
323
+ async findInWindow(supplierId, start, end, ctx) {
324
+ return this.findAll({
325
+ supplierId,
326
+ occurredAt: {
327
+ $gte: start,
328
+ $lt: end
329
+ }
330
+ }, {
331
+ ...repoOptionsFromCtx(ctx),
332
+ lean: true
333
+ });
334
+ }
335
+ };
336
+ //#endregion
337
+ //#region src/repositories/supplier-score.repository.ts
338
+ /**
339
+ * SupplierScoreRepository — cached scorecard upserts.
340
+ *
341
+ * `upsertForPeriod` is the only domain verb — it replaces any prior
342
+ * computation for the same (supplierId, period.start, period.end) tuple
343
+ * (enforced by the unique index on the model). Pure CRUD beyond that.
344
+ */
345
+ var SupplierScoreRepository = class extends Repository {
346
+ constructor(config) {
347
+ super(config.model, [methodRegistryPlugin(), ...config.plugins ?? []]);
348
+ }
349
+ /**
350
+ * Atomic upsert keyed on (supplierId, period). Replaces an existing
351
+ * snapshot in place — `computeScore` is idempotent. The unique index
352
+ * on `(supplierId, period.start, period.end)` enforces that only one
353
+ * row per (tenant, supplier, window) ever exists.
354
+ */
355
+ async upsertForPeriod(input, ctx) {
356
+ const computedAt = input.computedAt ?? /* @__PURE__ */ new Date();
357
+ const updated = await this.findOneAndUpdate({
358
+ supplierId: input.supplierId,
359
+ "period.start": input.period.start,
360
+ "period.end": input.period.end
361
+ }, { $set: {
362
+ period: input.period,
363
+ metrics: input.metrics,
364
+ eventCount: input.eventCount,
365
+ computedAt
366
+ } }, {
367
+ ...repoOptionsFromCtx(ctx),
368
+ upsert: true,
369
+ returnDocument: "after",
370
+ lean: false
371
+ });
372
+ if (!updated) throw new Error(`[supplier-performance] upsertForPeriod returned null for ${input.supplierId} ${input.period.start.toISOString()}`);
373
+ return updated;
374
+ }
375
+ /**
376
+ * Latest snapshot whose period contains `asOf` (or covers it via
377
+ * `period.end`). Useful for dashboard reads — pick the most recent
378
+ * computed scorecard for this supplier.
379
+ */
380
+ async findLatest(supplierId, ctx) {
381
+ return (await this.findAll({ supplierId }, {
382
+ ...repoOptionsFromCtx(ctx),
383
+ lean: true,
384
+ sort: { "period.end": -1 },
385
+ limit: 1
386
+ }))[0] ?? null;
387
+ }
388
+ };
389
+ //#endregion
390
+ //#region src/calc/score-calculator.ts
391
+ const COMPOSITE_WEIGHTS = {
392
+ onTime: .5,
393
+ defectFree: .4,
394
+ pricedToPlan: .1
395
+ };
396
+ /**
397
+ * Aggregate raw performance events into a scorecard. Events outside the
398
+ * `period` window are filtered out (defensive — callers should already
399
+ * have queried within the window).
400
+ */
401
+ function scoreFromEvents(events, period) {
402
+ const inWindow = events.filter((e) => e.occurredAt >= period.start && e.occurredAt < period.end);
403
+ let deliveryCount = 0;
404
+ let onTimeCount = 0;
405
+ let totalDelayDays = 0;
406
+ let lateCount = 0;
407
+ let unitsReceived = 0;
408
+ let defectiveUnits = 0;
409
+ let priceVarianceCount = 0;
410
+ let totalVariancePct = 0;
411
+ for (const event of inWindow) {
412
+ const metrics = event.metrics ?? {};
413
+ const qty = Number(metrics.quantity ?? 1);
414
+ switch (event.type) {
415
+ case "delivery_received":
416
+ deliveryCount++;
417
+ onTimeCount++;
418
+ unitsReceived += qty;
419
+ break;
420
+ case "delivery_late": {
421
+ deliveryCount++;
422
+ lateCount++;
423
+ unitsReceived += qty;
424
+ const delay = Number(metrics.delayDays ?? 0);
425
+ if (delay > 0) totalDelayDays += delay;
426
+ break;
427
+ }
428
+ case "defect_reported":
429
+ defectiveUnits += qty;
430
+ break;
431
+ case "price_variance":
432
+ priceVarianceCount++;
433
+ totalVariancePct += Number(metrics.variancePct ?? 0);
434
+ break;
435
+ }
436
+ }
437
+ const onTimeRate = deliveryCount > 0 ? onTimeCount / deliveryCount : 0;
438
+ const avgDelayDays = lateCount > 0 ? totalDelayDays / lateCount : 0;
439
+ const defectRate = unitsReceived > 0 ? defectiveUnits / unitsReceived : 0;
440
+ const avgPriceVariance = priceVarianceCount > 0 ? totalVariancePct / priceVarianceCount : 0;
441
+ const composite = onTimeRate * COMPOSITE_WEIGHTS.onTime + (1 - defectRate) * COMPOSITE_WEIGHTS.defectFree + (1 - Math.min(Math.abs(avgPriceVariance), 1)) * COMPOSITE_WEIGHTS.pricedToPlan;
442
+ return {
443
+ deliveryCount,
444
+ onTimeCount,
445
+ onTimeRate: round(onTimeRate, 4),
446
+ avgDelayDays: round(avgDelayDays, 2),
447
+ unitsReceived,
448
+ defectiveUnits,
449
+ defectRate: round(defectRate, 4),
450
+ priceVarianceCount,
451
+ avgPriceVariance: round(avgPriceVariance, 4),
452
+ compositeScore: round(Math.max(0, Math.min(100, composite * 100)), 2)
453
+ };
454
+ }
455
+ function round(value, digits) {
456
+ const factor = 10 ** digits;
457
+ return Math.round(value * factor) / factor;
458
+ }
459
+ //#endregion
460
+ //#region src/events/event-constants.ts
461
+ /**
462
+ * Canonical event names emitted by `@classytic/supplier-performance`.
463
+ *
464
+ * Prefix `supplier_performance:` matches the sibling-package convention
465
+ * (`order:...`, `commission:...`). Hosts wiring an Arc transport can
466
+ * pattern-match on `supplier_performance:*`.
467
+ */
468
+ const SupplierPerformanceEvents = {
469
+ EVENT_RECORDED: "supplier_performance:event.recorded",
470
+ SCORE_COMPUTED: "supplier_performance:score.computed"
471
+ };
472
+ //#endregion
473
+ //#region src/services/score.service.ts
474
+ var ScoreService = class {
475
+ events;
476
+ scores;
477
+ eventTransport;
478
+ logger;
479
+ constructor(config) {
480
+ this.events = config.events;
481
+ this.scores = config.scores;
482
+ this.eventTransport = config.eventTransport;
483
+ this.logger = config.logger ?? console;
484
+ }
485
+ /**
486
+ * Append a single performance event to the log. Idempotent on the
487
+ * caller's side via `metadata.idempotencyKey` if hosts wire their own
488
+ * dedup index — this kernel doesn't enforce it (different hosts have
489
+ * different keying preferences: PO-line, PO+SKU, etc.).
490
+ */
491
+ async recordEvent(input, ctx) {
492
+ if (!input.supplierId) throw new RecordEventValidationError("supplierId is required");
493
+ const occurredAt = input.occurredAt ?? /* @__PURE__ */ new Date();
494
+ const doc = await this.events.create({
495
+ organizationId: ctx.organizationId,
496
+ supplierId: input.supplierId,
497
+ type: input.type,
498
+ occurredAt,
499
+ metrics: input.metrics ?? {},
500
+ ...input.sourceRef !== void 0 ? { sourceRef: input.sourceRef } : {},
501
+ ...input.sourceType !== void 0 ? { sourceType: input.sourceType } : {},
502
+ ...input.metadata !== void 0 ? { metadata: input.metadata } : {}
503
+ }, repoOptionsFromCtx(ctx));
504
+ this.publish(SupplierPerformanceEvents.EVENT_RECORDED, ctx, {
505
+ supplierId: input.supplierId,
506
+ type: input.type,
507
+ occurredAt: occurredAt.toISOString(),
508
+ sourceRef: input.sourceRef
509
+ });
510
+ return doc;
511
+ }
512
+ /**
513
+ * Compute (or recompute) a scorecard for one (supplier, period) pair.
514
+ * Pulls all events in window, runs the pure calculator, persists the
515
+ * snapshot. Idempotent — calling twice with the same period upserts in
516
+ * place.
517
+ */
518
+ async computeScore(input, ctx) {
519
+ const period = normalizePeriod(input.period);
520
+ const eventsForCalc = (await this.events.findInWindow(input.supplierId, period.start, period.end, ctx)).map(toCalcEvent);
521
+ const metrics = scoreFromEvents(eventsForCalc, period);
522
+ const doc = await this.scores.upsertForPeriod({
523
+ supplierId: input.supplierId,
524
+ period,
525
+ metrics,
526
+ eventCount: eventsForCalc.length
527
+ }, ctx);
528
+ this.publish(SupplierPerformanceEvents.SCORE_COMPUTED, ctx, {
529
+ supplierId: input.supplierId,
530
+ period: {
531
+ start: period.start.toISOString(),
532
+ end: period.end.toISOString()
533
+ },
534
+ compositeScore: metrics.compositeScore,
535
+ eventCount: eventsForCalc.length
536
+ });
537
+ return doc;
538
+ }
539
+ /**
540
+ * Read-or-compute. Returns the latest cached scorecard for the supplier;
541
+ * if `period` is supplied, recomputes for that exact window before
542
+ * returning. Pure read otherwise — won't refresh stale snapshots
543
+ * implicitly (callers know when their data has changed).
544
+ */
545
+ async getScorecard(supplierId, ctx, period) {
546
+ if (period) return this.computeScore({
547
+ supplierId,
548
+ period
549
+ }, ctx);
550
+ return this.scores.findLatest(supplierId, ctx);
551
+ }
552
+ publish(type, ctx, data) {
553
+ if (!this.eventTransport) return;
554
+ const event = createEvent(type, data, {
555
+ organizationId: ctx.organizationId,
556
+ userId: ctx.actorRef,
557
+ correlationId: ctx.correlationId
558
+ });
559
+ this.eventTransport.publish(event).catch((err) => {
560
+ this.logger.error(`[supplier-performance] publish failed for ${type}:`, err);
561
+ });
562
+ }
563
+ };
564
+ function toCalcEvent(doc) {
565
+ return {
566
+ _id: doc._id,
567
+ organizationId: String(doc.organizationId),
568
+ supplierId: doc.supplierId,
569
+ type: doc.type,
570
+ occurredAt: doc.occurredAt,
571
+ metrics: doc.metrics ?? {},
572
+ ...doc.sourceRef !== void 0 ? { sourceRef: doc.sourceRef } : {},
573
+ ...doc.sourceType !== void 0 ? { sourceType: doc.sourceType } : {},
574
+ ...doc.metadata !== void 0 ? { metadata: doc.metadata } : {},
575
+ createdAt: doc.createdAt,
576
+ updatedAt: doc.updatedAt
577
+ };
578
+ }
579
+ function normalizePeriod(period) {
580
+ if (period.end.getTime() <= period.start.getTime()) throw new RecordEventValidationError(`period.end (${period.end.toISOString()}) must be strictly after period.start (${period.start.toISOString()})`);
581
+ return period;
582
+ }
583
+ var RecordEventValidationError = class extends Error {
584
+ name = "RecordEventValidationError";
585
+ code = "SUPPLIER_PERFORMANCE_VALIDATION";
586
+ constructor(message) {
587
+ super(message);
588
+ }
589
+ };
590
+ //#endregion
591
+ //#region src/events/in-process-bus.ts
592
+ /**
593
+ * Zero-dep in-process event bus. Subscribers can use glob patterns
594
+ * (`supplier_performance:*`, `*`, exact type). Subscriber errors are
595
+ * caught and logged — they never break the emitter or sibling
596
+ * subscribers.
597
+ *
598
+ * Drop-in compatible with any `EventTransport` — hosts replace it by
599
+ * passing their own at `createSupplierPerformance({ eventTransport })`.
600
+ */
601
+ var InProcessSupplierPerformanceBus = class {
602
+ name = "in-process-supplier-performance";
603
+ patterns = /* @__PURE__ */ new Map();
604
+ logger;
605
+ constructor(options = {}) {
606
+ this.logger = options.logger ?? console;
607
+ }
608
+ async publish(event) {
609
+ for (const [pattern, handlers] of this.patterns) {
610
+ if (!matchEventPattern(pattern, event.type)) continue;
611
+ for (const fn of handlers) try {
612
+ await fn(event);
613
+ } catch (err) {
614
+ this.logger.error(`[supplier-performance] subscriber threw on ${event.type}: ${err.message}`, err);
615
+ }
616
+ }
617
+ }
618
+ async subscribe(pattern, handler) {
619
+ let set = this.patterns.get(pattern);
620
+ if (!set) {
621
+ set = /* @__PURE__ */ new Set();
622
+ this.patterns.set(pattern, set);
623
+ }
624
+ set.add(handler);
625
+ return () => {
626
+ const s = this.patterns.get(pattern);
627
+ s?.delete(handler);
628
+ if (s && s.size === 0) this.patterns.delete(pattern);
629
+ };
630
+ }
631
+ };
632
+ //#endregion
633
+ //#region src/engine/create-supplier-performance.ts
634
+ async function createSupplierPerformance(config) {
635
+ if (!config.connection) throw new Error("createSupplierPerformance: config.connection is required");
636
+ const logger = config.logger ?? console;
637
+ const events = config.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });
638
+ const tenant = resolveSupplierPerformanceTenant(config.tenant);
639
+ const models = createSupplierPerformanceModels(config.connection, {
640
+ tenant,
641
+ ...config.collectionPrefix !== void 0 ? { collectionPrefix: config.collectionPrefix } : {},
642
+ ...config.forceRecreate !== void 0 ? { forceRecreate: config.forceRecreate } : {}
643
+ });
644
+ const performanceEvent = new PerformanceEventRepository({
645
+ model: models.PerformanceEvent,
646
+ ...config.repositoryPlugins?.performanceEvent !== void 0 ? { plugins: config.repositoryPlugins.performanceEvent } : {}
647
+ });
648
+ const supplierScore = new SupplierScoreRepository({
649
+ model: models.SupplierScore,
650
+ ...config.repositoryPlugins?.supplierScore !== void 0 ? { plugins: config.repositoryPlugins.supplierScore } : {}
651
+ });
652
+ const score = new ScoreService({
653
+ events: performanceEvent,
654
+ scores: supplierScore,
655
+ eventTransport: events,
656
+ logger
657
+ });
658
+ return {
659
+ models,
660
+ repositories: {
661
+ performanceEvent,
662
+ supplierScore
663
+ },
664
+ services: { score },
665
+ events,
666
+ async syncIndexes() {
667
+ await Promise.all([models.PerformanceEvent.syncIndexes(), models.SupplierScore.syncIndexes()]);
668
+ },
669
+ async destroy() {}
670
+ };
671
+ }
672
+ //#endregion
673
+ export { InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventModelCollisionError, PerformanceEventRepository, PerformanceEventType, RecordEventValidationError, ScoreService, SupplierPerformanceEvents, SupplierScoreModelCollisionError, SupplierScoreRepository, createPerformanceEventModel, createSupplierPerformance, createSupplierPerformanceModels, createSupplierScoreModel, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents };
674
+
675
+ //# sourceMappingURL=index.js.map