@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Classytic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,208 @@
1
+ # @classytic/supplier-performance
2
+
3
+ > Framework-agnostic supplier performance engine — on-time-delivery, defect, and price-variance tracking with an append-only event log and cached scorecards. Powered by MongoDB via `@classytic/mongokit`.
4
+
5
+ ```
6
+ flow.procurement.received
7
+ │
8
+ ▼
9
+ recordEvent(supplierId, type, metrics) ──▶ performance_event (append-only log)
10
+ │
11
+ ▼
12
+ computeScore(supplierId, period)
13
+ │
14
+ ▼
15
+ supplier_score (cached, upsert per period)
16
+ ```
17
+
18
+ Zero framework dependencies — usable from Arc, Express, Nest, Next.js, or raw Node.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ npm install @classytic/supplier-performance @classytic/mongokit @classytic/primitives mongoose
24
+ ```
25
+
26
+ Peer deps:
27
+
28
+ | | |
29
+ |---|---|
30
+ | `@classytic/mongokit` | `>=3.11.0` |
31
+ | `@classytic/primitives` | `>=0.1.0` |
32
+ | `mongoose` | `>=9.4.1` |
33
+
34
+ ## Quick start
35
+
36
+ ```ts
37
+ import mongoose from 'mongoose';
38
+ import { createSupplierPerformance } from '@classytic/supplier-performance';
39
+
40
+ await mongoose.connect('mongodb://localhost/myapp');
41
+
42
+ const engine = await createSupplierPerformance({ connection: mongoose.connection });
43
+ await engine.syncIndexes();
44
+
45
+ // Host bridges sibling events. Example: turn `flow.procurement.received`
46
+ // into a delivery_received event on the supplier's record.
47
+ const ctx = {
48
+ organizationId: 'org_42',
49
+ actorRef: 'system:cron',
50
+ actorKind: 'system' as const,
51
+ correlationId: 'req_xyz',
52
+ };
53
+
54
+ await engine.services.score.recordEvent(
55
+ {
56
+ supplierId: 'SUP-001',
57
+ type: 'delivery_received',
58
+ occurredAt: new Date(),
59
+ metrics: { quantity: 100 },
60
+ sourceRef: 'PO-2026-0042',
61
+ sourceType: 'procurement_order',
62
+ },
63
+ ctx,
64
+ );
65
+
66
+ // Compute (and cache) a scorecard for a window
67
+ const scorecard = await engine.services.score.computeScore(
68
+ {
69
+ supplierId: 'SUP-001',
70
+ period: {
71
+ start: new Date('2026-01-01'),
72
+ end: new Date('2026-04-01'),
73
+ label: '2026-Q1',
74
+ },
75
+ },
76
+ ctx,
77
+ );
78
+
79
+ console.log(scorecard.metrics);
80
+ // {
81
+ // deliveryCount: 10,
82
+ // onTimeCount: 8,
83
+ // onTimeRate: 0.8,
84
+ // avgDelayDays: 0.6,
85
+ // unitsReceived: 1000,
86
+ // defectiveUnits: 5,
87
+ // defectRate: 0.005,
88
+ // priceVarianceCount: 2,
89
+ // avgPriceVariance: 0.04,
90
+ // compositeScore: 89.5
91
+ // }
92
+ ```
93
+
94
+ ## Architecture
95
+
96
+ ### Event types
97
+
98
+ The catalog ships 4 event types — extend by recording additional `metadata` fields, not new types (kernel-level enum changes break consumers).
99
+
100
+ | Type | Drives | Required metrics |
101
+ |---|---|---|
102
+ | `delivery_received` | on-time rate, units received | `quantity` |
103
+ | `delivery_late` | on-time rate, average delay | `quantity`, `delayDays` |
104
+ | `defect_reported` | defect rate, defective units | `quantity` |
105
+ | `price_variance` | average variance % | `expectedUnitCost`, `actualUnitCost`, `variancePct` |
106
+
107
+ ### Score formula
108
+
109
+ The default composite score is bounded `0..100` (higher = better):
110
+
111
+ ```
112
+ score = onTimeRate × 50
113
+ + (1 − defectRate) × 40
114
+ + (1 − |variance|) × 10
115
+ ```
116
+
117
+ Hosts that need different weights re-rank `events` directly via the `scoreFromEvents` pure helper or write their own roll-up.
118
+
119
+ ### Repositories
120
+
121
+ | Repo | Verbs |
122
+ |---|---|
123
+ | `performanceEvent` | inherited mongokit CRUD + `findInWindow(supplierId, start, end, ctx)` |
124
+ | `supplierScore` | inherited CRUD + `upsertForPeriod(input, ctx)`, `findLatest(supplierId, ctx)` |
125
+
126
+ ### Service
127
+
128
+ | Verb | Behavior |
129
+ |---|---|
130
+ | `recordEvent(input, ctx)` | Append one row to the event log; emit `supplier_performance:event.recorded`. |
131
+ | `computeScore({ supplierId, period }, ctx)` | Load events in window → run `scoreFromEvents` → upsert score. Idempotent. Emits `supplier_performance:score.computed`. |
132
+ | `getScorecard(supplierId, ctx, period?)` | When `period` is supplied, recompute. Otherwise return the latest persisted snapshot. |
133
+
134
+ ### Events
135
+
136
+ ```
137
+ supplier_performance:event.recorded
138
+ supplier_performance:score.computed
139
+ ```
140
+
141
+ Use any `EventTransport`-shaped bus (Arc's MemoryEventTransport, Redis, Kafka, …). The bundled `InProcessSupplierPerformanceBus` is a zero-dep default.
142
+
143
+ ### Multi-tenant
144
+
145
+ Drives off `@classytic/primitives/tenant`. Default field type is `'string'` (matches the legacy convention shared by sibling packages):
146
+
147
+ ```ts
148
+ const engine = await createSupplierPerformance({
149
+ connection,
150
+ tenant: { fieldType: 'objectId' }, // when org IDs are stored as ObjectId
151
+ });
152
+ ```
153
+
154
+ ### Indexes
155
+
156
+ | Collection | Index | Purpose |
157
+ |---|---|---|
158
+ | `supplier_performance_events` | `{ supplierId, occurredAt }` | Range query for scoring window |
159
+ | `supplier_performance_events` | `{ sourceRef, type }` (partial) | Drill-down from PO / RMA into the events that fired |
160
+ | `supplier_scores` | `{ supplierId, period.start, period.end }` (unique) | One snapshot per (supplier, period) |
161
+ | `supplier_scores` | `{ period.end ↓, metrics.compositeScore ↓ }` | Dashboard "top suppliers this month" |
162
+
163
+ The tenant field is prepended to compound indexes via `injectTenantField` when scoping is enabled.
164
+
165
+ ### Soft delete
166
+
167
+ Every collection wires `softDeletePlugin` with a default 7-year retention. Hosts override via `retentionDays` on the engine config.
168
+
169
+ ## Why a service (and not just repos)?
170
+
171
+ Per `PACKAGE_RULES §2`, a service is justified when it does ≥1 of:
172
+
173
+ - multi-repo orchestration ✅ (event log + score cache)
174
+ - pure domain algorithm ✅ (`scoreFromEvents` is in `calc/`, called by the service)
175
+ - event emission ✅
176
+
177
+ So `ScoreService` exists. Pure scoring is testable in isolation via `scoreFromEvents`.
178
+
179
+ ## Bridges (host-side)
180
+
181
+ This package never imports `@classytic/flow`, `@classytic/order`, or any sibling — supplier-performance is downstream. The host wires whatever signals it cares about:
182
+
183
+ ```ts
184
+ import { subscribe } from '#lib/events/arcEvents.js';
185
+
186
+ subscribe('flow.procurement.received', async (event) => {
187
+ const order = await flow.repositories.procurement.getByQuery(/* … */);
188
+ const onTime = order.expectedAt && new Date() <= order.expectedAt;
189
+ await engine.services.score.recordEvent(
190
+ {
191
+ supplierId: order.vendorRef,
192
+ type: onTime ? 'delivery_received' : 'delivery_late',
193
+ occurredAt: new Date(),
194
+ metrics: {
195
+ quantity: totalReceived,
196
+ ...(order.expectedAt ? { expectedAt: order.expectedAt, actualAt: new Date() } : {}),
197
+ },
198
+ sourceRef: order.orderNumber,
199
+ sourceType: 'procurement_order',
200
+ },
201
+ ctx,
202
+ );
203
+ });
204
+ ```
205
+
206
+ ## License
207
+
208
+ MIT
@@ -0,0 +1,438 @@
1
+ import { ClientSession, Connection, Document, Model, Schema, Types } from "mongoose";
2
+ import { ResolvedTenantConfig, TenantConfig } from "@classytic/primitives/tenant";
3
+ import { PluginType, Repository } from "@classytic/mongokit";
4
+ import { DomainEvent, EventHandler, EventTransport } from "@classytic/primitives/events";
5
+
6
+ //#region src/models/performance-event.model.d.ts
7
+ interface PerformanceEventDocument extends Document {
8
+ organizationId: unknown;
9
+ supplierId: string;
10
+ type: string;
11
+ occurredAt: Date;
12
+ metrics: Record<string, unknown>;
13
+ sourceRef?: string;
14
+ sourceType?: string;
15
+ metadata?: Record<string, unknown>;
16
+ createdAt: Date;
17
+ updatedAt: Date;
18
+ }
19
+ interface PerformanceEventModelConfig {
20
+ collectionPrefix?: string | undefined;
21
+ forceRecreate?: boolean;
22
+ }
23
+ declare class PerformanceEventModelCollisionError extends Error {
24
+ constructor(name: string);
25
+ }
26
+ declare function createPerformanceEventModel(connection: Connection, tenant: ResolvedTenantConfig, config?: PerformanceEventModelConfig): Model<PerformanceEventDocument>;
27
+ //#endregion
28
+ //#region src/models/supplier-score.model.d.ts
29
+ interface SupplierScoreDocument extends Document {
30
+ organizationId: unknown;
31
+ supplierId: string;
32
+ period: {
33
+ start: Date;
34
+ end: Date;
35
+ label?: string;
36
+ };
37
+ metrics: Record<string, unknown>;
38
+ computedAt: Date;
39
+ eventCount: number;
40
+ createdAt: Date;
41
+ updatedAt: Date;
42
+ }
43
+ interface SupplierScoreModelConfig {
44
+ collectionPrefix?: string | undefined;
45
+ forceRecreate?: boolean;
46
+ }
47
+ declare class SupplierScoreModelCollisionError extends Error {
48
+ constructor(name: string);
49
+ }
50
+ declare function createSupplierScoreModel(connection: Connection, tenant: ResolvedTenantConfig, config?: SupplierScoreModelConfig): Model<SupplierScoreDocument>;
51
+ //#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
+ //#region src/models/create-models.d.ts
65
+ interface SupplierPerformanceModelBundle {
66
+ PerformanceEvent: ReturnType<typeof createPerformanceEventModel>;
67
+ SupplierScore: ReturnType<typeof createSupplierScoreModel>;
68
+ }
69
+ interface CreateSupplierPerformanceModelsOptions {
70
+ tenant?: ResolvedTenantConfig | TenantConfig | boolean | SupplierPerformanceTenantInput;
71
+ collectionPrefix?: string | undefined;
72
+ forceRecreate?: boolean | undefined;
73
+ }
74
+ declare function createSupplierPerformanceModels(connection: Connection, options?: CreateSupplierPerformanceModelsOptions): SupplierPerformanceModelBundle;
75
+ //#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
+ //#region src/repositories/performance-event.repository.d.ts
98
+ interface PerformanceEventRepositoryConfig {
99
+ model: Model<PerformanceEventDocument>;
100
+ plugins?: PluginType[];
101
+ }
102
+ declare class PerformanceEventRepository extends Repository<PerformanceEventDocument> {
103
+ constructor(config: PerformanceEventRepositoryConfig);
104
+ /**
105
+ * Range query for one supplier — `[start, end)`. The (supplierId,
106
+ * occurredAt) compound index serves this directly. Returned lean for
107
+ * cheap aggregation in the service layer.
108
+ */
109
+ findInWindow(supplierId: string, start: Date, end: Date, ctx: SupplierPerformanceContext): Promise<PerformanceEventDocument[]>;
110
+ }
111
+ //#endregion
112
+ //#region src/domain/entities/supplier-score.entity.d.ts
113
+ interface SupplierScore {
114
+ _id: Types.ObjectId;
115
+ organizationId: string;
116
+ supplierId: string;
117
+ period: ScorePeriod;
118
+ /** Aggregated metrics. Counts are integers; rates are 0..1 fractions. */
119
+ metrics: ScoreMetrics;
120
+ /** When this snapshot was last computed. */
121
+ computedAt: Date;
122
+ /** Number of source events contributing to this score. */
123
+ eventCount: number;
124
+ createdAt: Date;
125
+ updatedAt: Date;
126
+ }
127
+ interface ScorePeriod {
128
+ /** Inclusive. */
129
+ start: Date;
130
+ /** Exclusive. */
131
+ end: Date;
132
+ /** Optional human label (e.g. `2026-Q1`, `2026-04`). */
133
+ label?: string;
134
+ }
135
+ interface ScoreMetrics {
136
+ /** Total deliveries observed (delivery_received + delivery_late). */
137
+ deliveryCount: number;
138
+ /** On-time count (delivery_received). */
139
+ onTimeCount: number;
140
+ /** Fraction in [0, 1]. `0` when `deliveryCount === 0`. */
141
+ onTimeRate: number;
142
+ /** Average delay in days across late deliveries (0 when none). */
143
+ avgDelayDays: number;
144
+ /** Total received units across deliveries (sum of `metrics.quantity`). */
145
+ unitsReceived: number;
146
+ /** Total defective units (sum of `metrics.quantity` on defect events). */
147
+ defectiveUnits: number;
148
+ /** Fraction in [0, 1]. `defectiveUnits / unitsReceived`. */
149
+ defectRate: number;
150
+ /** Number of price-variance events in window. */
151
+ priceVarianceCount: number;
152
+ /** Average variance fraction (e.g. 0.04 = 4% over expected). */
153
+ avgPriceVariance: number;
154
+ /**
155
+ * Composite score 0..100. Higher is better. Default formula:
156
+ * 100 × (onTimeRate × 0.5 + (1 − defectRate) × 0.4 + (1 − |avgPriceVariance|) × 0.1)
157
+ * Pure roll-up; hosts with custom weights re-score from the rates.
158
+ */
159
+ compositeScore: number;
160
+ }
161
+ interface ComputeScoreInput {
162
+ supplierId: string;
163
+ period: ScorePeriod;
164
+ }
165
+ //#endregion
166
+ //#region src/repositories/supplier-score.repository.d.ts
167
+ interface SupplierScoreRepositoryConfig {
168
+ model: Model<SupplierScoreDocument>;
169
+ plugins?: PluginType[];
170
+ }
171
+ interface UpsertScoreInput {
172
+ supplierId: string;
173
+ period: ScorePeriod;
174
+ metrics: ScoreMetrics;
175
+ eventCount: number;
176
+ computedAt?: Date;
177
+ }
178
+ declare class SupplierScoreRepository extends Repository<SupplierScoreDocument> {
179
+ constructor(config: SupplierScoreRepositoryConfig);
180
+ /**
181
+ * Atomic upsert keyed on (supplierId, period). Replaces an existing
182
+ * snapshot in place — `computeScore` is idempotent. The unique index
183
+ * on `(supplierId, period.start, period.end)` enforces that only one
184
+ * row per (tenant, supplier, window) ever exists.
185
+ */
186
+ upsertForPeriod(input: UpsertScoreInput, ctx: SupplierPerformanceContext): Promise<SupplierScoreDocument>;
187
+ /**
188
+ * Latest snapshot whose period contains `asOf` (or covers it via
189
+ * `period.end`). Useful for dashboard reads — pick the most recent
190
+ * computed scorecard for this supplier.
191
+ */
192
+ findLatest(supplierId: string, ctx: SupplierPerformanceContext): Promise<SupplierScoreDocument | null>;
193
+ }
194
+ //#endregion
195
+ //#region src/domain/enums/event-type.enum.d.ts
196
+ /**
197
+ * Performance event types — what happened on a single supplier interaction.
198
+ *
199
+ * The catalog is intentionally small. Each type contributes to one or more
200
+ * scorecard metrics:
201
+ *
202
+ * - `delivery_received` → on-time rate, average delay
203
+ * - `delivery_late` → on-time rate, average delay
204
+ * - `defect_reported` → defect rate
205
+ * - `price_variance` → price variance %
206
+ *
207
+ * Hosts that need a domain-specific signal (e.g. `quality_audit`) can
208
+ * extend by adding a constant + payload. Pure data; no FSM.
209
+ */
210
+ declare const PerformanceEventType: {
211
+ readonly delivery_received: "delivery_received";
212
+ readonly delivery_late: "delivery_late";
213
+ readonly defect_reported: "defect_reported";
214
+ readonly price_variance: "price_variance";
215
+ };
216
+ type PerformanceEventTypeValue = (typeof PerformanceEventType)[keyof typeof PerformanceEventType];
217
+ declare const PERFORMANCE_EVENT_TYPE_VALUES: readonly PerformanceEventTypeValue[];
218
+ //#endregion
219
+ //#region src/domain/entities/performance-event.entity.d.ts
220
+ interface PerformanceEvent {
221
+ _id: Types.ObjectId;
222
+ organizationId: string;
223
+ /** Supplier reference. Free-form — host decides format (vendorRef, ObjectId, etc.). */
224
+ supplierId: string;
225
+ type: PerformanceEventTypeValue;
226
+ /**
227
+ * When this event happened in the real world. Distinct from `createdAt`
228
+ * (when the row was inserted) so a backdated import or a delayed
229
+ * inspection lands in the correct period bucket.
230
+ */
231
+ occurredAt: Date;
232
+ /**
233
+ * Per-type metric payload. Only fields relevant to the type need be set:
234
+ *
235
+ * delivery_received → expectedAt? actualAt
236
+ * delivery_late → expectedAt + actualAt + delayDays
237
+ * defect_reported → quantity (defective units)
238
+ * price_variance → expectedUnitCost + actualUnitCost + variancePct
239
+ *
240
+ * Quantity-bearing types include `quantity` so per-unit defect / on-time
241
+ * rates can roll up properly without re-fetching the source PO.
242
+ */
243
+ metrics: PerformanceMetrics;
244
+ /**
245
+ * Reference back to the source document that triggered this event (PO
246
+ * number, invoice number, return number). Lets ops drill from a low
247
+ * scorecard down to the underlying receipt.
248
+ */
249
+ sourceRef?: string;
250
+ sourceType?: string;
251
+ /**
252
+ * Optional free-form context. Examples: severity tag from QA, category
253
+ * dimension for slicing reports.
254
+ */
255
+ metadata?: Record<string, unknown>;
256
+ createdAt: Date;
257
+ updatedAt: Date;
258
+ }
259
+ interface PerformanceMetrics {
260
+ /** Quantity of units this event covers. Defaults to 1 when omitted. */
261
+ quantity?: number;
262
+ /** Expected delivery time (for delivery_* events). */
263
+ expectedAt?: Date;
264
+ /** Actual delivery time (for delivery_* events). */
265
+ actualAt?: Date;
266
+ /** Days late — denormalized for cheap aggregates. Negative ⇒ early. */
267
+ delayDays?: number;
268
+ /** Expected unit cost (for price_variance). */
269
+ expectedUnitCost?: number;
270
+ /** Actual unit cost (for price_variance). */
271
+ actualUnitCost?: number;
272
+ /**
273
+ * Variance as a fraction of expected — e.g. 0.05 = 5% over, -0.02 = 2%
274
+ * under. Denormalized at write so reports don't recompute per row.
275
+ */
276
+ variancePct?: number;
277
+ }
278
+ interface RecordEventInput {
279
+ supplierId: string;
280
+ type: PerformanceEventTypeValue;
281
+ occurredAt?: Date;
282
+ metrics?: PerformanceMetrics;
283
+ sourceRef?: string;
284
+ sourceType?: string;
285
+ metadata?: Record<string, unknown>;
286
+ }
287
+ //#endregion
288
+ //#region src/services/score.service.d.ts
289
+ interface ScoreServiceConfig {
290
+ events: PerformanceEventRepository;
291
+ scores: SupplierScoreRepository;
292
+ eventTransport?: EventTransport | undefined;
293
+ logger?: {
294
+ error(message: string, ...args: unknown[]): void;
295
+ };
296
+ }
297
+ declare class ScoreService {
298
+ private events;
299
+ private scores;
300
+ private eventTransport?;
301
+ private logger;
302
+ constructor(config: ScoreServiceConfig);
303
+ /**
304
+ * Append a single performance event to the log. Idempotent on the
305
+ * caller's side via `metadata.idempotencyKey` if hosts wire their own
306
+ * dedup index — this kernel doesn't enforce it (different hosts have
307
+ * different keying preferences: PO-line, PO+SKU, etc.).
308
+ */
309
+ recordEvent(input: RecordEventInput, ctx: SupplierPerformanceContext): Promise<PerformanceEventDocument>;
310
+ /**
311
+ * Compute (or recompute) a scorecard for one (supplier, period) pair.
312
+ * Pulls all events in window, runs the pure calculator, persists the
313
+ * snapshot. Idempotent — calling twice with the same period upserts in
314
+ * place.
315
+ */
316
+ computeScore(input: ComputeScoreInput, ctx: SupplierPerformanceContext): Promise<SupplierScoreDocument>;
317
+ /**
318
+ * Read-or-compute. Returns the latest cached scorecard for the supplier;
319
+ * if `period` is supplied, recomputes for that exact window before
320
+ * returning. Pure read otherwise — won't refresh stale snapshots
321
+ * implicitly (callers know when their data has changed).
322
+ */
323
+ getScorecard(supplierId: string, ctx: SupplierPerformanceContext, period?: ScorePeriod): Promise<SupplierScoreDocument | null>;
324
+ private publish;
325
+ }
326
+ declare class RecordEventValidationError extends Error {
327
+ readonly name = "RecordEventValidationError";
328
+ readonly code: "SUPPLIER_PERFORMANCE_VALIDATION";
329
+ constructor(message: string);
330
+ }
331
+ //#endregion
332
+ //#region src/engine/engine-types.d.ts
333
+ interface SupplierPerformanceLogger {
334
+ error(message: string, ...args: unknown[]): void;
335
+ }
336
+ interface SupplierPerformanceConfig {
337
+ /** Shared mongoose connection. */
338
+ connection: Connection;
339
+ /**
340
+ * Optional event transport. Any object matching `@classytic/primitives`
341
+ * `EventTransport` — Arc's MemoryEventTransport, a Redis transport, or
342
+ * the bundled `InProcessSupplierPerformanceBus`. Omit to skip event
343
+ * emission entirely.
344
+ */
345
+ eventTransport?: EventTransport | undefined;
346
+ /**
347
+ * Tenant scoping config. Defaults to `{ fieldType: 'string' }`.
348
+ */
349
+ tenant?: TenantConfig | boolean | undefined;
350
+ /** Optional collection name prefix (PACKAGE_RULES §20.1). */
351
+ collectionPrefix?: string | undefined;
352
+ /** Hot-reload / test fixtures only. Default `false`. */
353
+ forceRecreate?: boolean | undefined;
354
+ /** Optional per-repo plugins. Stacked AFTER the built-in plugins. */
355
+ repositoryPlugins?: {
356
+ performanceEvent?: PluginType[] | undefined;
357
+ supplierScore?: PluginType[] | undefined;
358
+ } | undefined;
359
+ logger?: SupplierPerformanceLogger | undefined;
360
+ }
361
+ interface SupplierPerformanceRepositories {
362
+ performanceEvent: PerformanceEventRepository;
363
+ supplierScore: SupplierScoreRepository;
364
+ }
365
+ interface SupplierPerformanceEngine {
366
+ models: SupplierPerformanceModelBundle;
367
+ repositories: SupplierPerformanceRepositories;
368
+ services: {
369
+ score: ScoreService;
370
+ };
371
+ events?: EventTransport;
372
+ syncIndexes(): Promise<void>;
373
+ destroy(): Promise<void>;
374
+ }
375
+ //#endregion
376
+ //#region src/engine/create-supplier-performance.d.ts
377
+ declare function createSupplierPerformance(config: SupplierPerformanceConfig): Promise<SupplierPerformanceEngine>;
378
+ //#endregion
379
+ //#region src/calc/score-calculator.d.ts
380
+ /**
381
+ * Aggregate raw performance events into a scorecard. Events outside the
382
+ * `period` window are filtered out (defensive — callers should already
383
+ * have queried within the window).
384
+ */
385
+ declare function scoreFromEvents(events: ReadonlyArray<PerformanceEvent>, period: ScorePeriod): ScoreMetrics;
386
+ //#endregion
387
+ //#region src/repositories/repo-options.d.ts
388
+ interface RepoOptions {
389
+ organizationId: string;
390
+ actorRef: string;
391
+ actorKind: SupplierPerformanceContext['actorKind'];
392
+ correlationId: string;
393
+ session?: ClientSession;
394
+ idempotencyKey?: string;
395
+ [key: string]: unknown;
396
+ }
397
+ declare function repoOptionsFromCtx(ctx: SupplierPerformanceContext): RepoOptions;
398
+ //#endregion
399
+ //#region src/events/event-constants.d.ts
400
+ /**
401
+ * Canonical event names emitted by `@classytic/supplier-performance`.
402
+ *
403
+ * Prefix `supplier_performance:` matches the sibling-package convention
404
+ * (`order:...`, `commission:...`). Hosts wiring an Arc transport can
405
+ * pattern-match on `supplier_performance:*`.
406
+ */
407
+ declare const SupplierPerformanceEvents: {
408
+ readonly EVENT_RECORDED: "supplier_performance:event.recorded";
409
+ readonly SCORE_COMPUTED: "supplier_performance:score.computed";
410
+ };
411
+ type SupplierPerformanceEventName = (typeof SupplierPerformanceEvents)[keyof typeof SupplierPerformanceEvents];
412
+ //#endregion
413
+ //#region src/events/in-process-bus.d.ts
414
+ interface InProcessBusOptions {
415
+ logger?: {
416
+ error(message: string, ...args: unknown[]): void;
417
+ };
418
+ }
419
+ /**
420
+ * Zero-dep in-process event bus. Subscribers can use glob patterns
421
+ * (`supplier_performance:*`, `*`, exact type). Subscriber errors are
422
+ * caught and logged — they never break the emitter or sibling
423
+ * subscribers.
424
+ *
425
+ * Drop-in compatible with any `EventTransport` — hosts replace it by
426
+ * passing their own at `createSupplierPerformance({ eventTransport })`.
427
+ */
428
+ declare class InProcessSupplierPerformanceBus implements EventTransport {
429
+ readonly name = "in-process-supplier-performance";
430
+ private patterns;
431
+ private logger;
432
+ constructor(options?: InProcessBusOptions);
433
+ publish(event: DomainEvent): Promise<void>;
434
+ subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
435
+ }
436
+ //#endregion
437
+ 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 };
438
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
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,MAAA;UAGE,CAAA,EAAA,MAAA,CAAA,MAAA,EAAA,OAAA,CAAA;WACA,EAAA,IAAA;WACA,EAAA,IAAA;;AAV6C,UA0BzC,2BAAA,CA1ByC;EA0BzC,gBAAA,CAAA,EAAA,MAAA,GAAA,SAA2B;EAiC/B,aAAA,CAAA,EAAA,OAAA;AAUb;AAA2C,cAV9B,mCAAA,SAA4C,KAAA,CAUd;aAC7B,CAAA,IAAA,EAAA,MAAA;;AAEJ,iBAHM,2BAAA,CAGN,UAAA,EAFI,UAEJ,EAAA,MAAA,EADA,oBACA,EAAA,MAAA,CAAA,EAAA,2BAAA,CAAA,EACP,KADO,CACD,wBADC,CAAA;;;UCzEO,qBAAA,SAA8B;;;;IDC9B,KAAA,ECEE,IDFF;IAAyB,GAAA,ECEZ,IDFY;IAI5B,KAAA,CAAA,EAAA,MAAA;;SAID,ECLF,MDKE,CAAA,MAAA,EAAA,OAAA,CAAA;YACA,ECLC,IDKD;YACA,EAAA,MAAA;WAVqC,ECMrC,IDNqC;EAAQ,SAAA,ECO7C,IDP6C;AA0B1D;AAiCa,UCxBI,wBAAA,CDwBgC;EAUjC,gBAAA,CAAA,EAAA,MAAA,GAAA,SAA2B;EAAA,aAAA,CAAA,EAAA,OAAA;;AAEjC,cCPG,gCAAA,SAAyC,KAAA,CDO5C;aACA,CAAA,IAAA,EAAA,MAAA;;AACP,iBCCa,wBAAA,CDDb,UAAA,ECEW,UDFX,EAAA,MAAA,ECGO,oBDHP,EAAA,MAAA,CAAA,ECIO,wBDJP,CAAA,ECKA,KDLA,CCKM,qBD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