@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 +21 -0
- package/README.md +208 -0
- package/dist/index.d.ts +438 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +675 -0
- package/dist/index.js.map +1 -0
- package/package.json +73 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["metricsSchema"],"sources":["../src/domain/enums/event-type.enum.ts","../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","/**\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/primitives/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/primitives/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/primitives/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/primitives/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 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\nexport function repoOptionsFromCtx(ctx: SupplierPerformanceContext): RepoOptions {\n const opts: RepoOptions = {\n organizationId: ctx.organizationId,\n actorRef: ctx.actorRef,\n actorKind: ctx.actorKind,\n correlationId: ctx.correlationId,\n };\n if (ctx.session !== undefined) opts.session = ctx.session as ClientSession;\n if (ctx.idempotencyKey !== undefined) opts.idempotencyKey = ctx.idempotencyKey;\n return opts;\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 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"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,MAAa,uBAAuB;CAClC,mBAAmB;CACnB,eAAe;CACf,iBAAiB;CACjB,gBAAgB;CACjB;AAKD,MAAa,gCAAgC,OAAO,OAClD,qBACD;;;;;;;;;;;ACHD,SAAgB,iCACd,QAAwC,EAAE,EACpB;AACtB,KAAI,OAAO,UAAU,UACnB,QAAO,sBAAsB,oBAAoB,MAAM,CAAC;AAE1D,KAAI,qBAAqB,SAAS,iBAAiB,OAAO;EACxD,MAAM,SAAS;AACf,SAAO,oBAAoB;GACzB,SAAS,OAAO,gBAAgB;GAChC,WAAW,OAAO,mBAAmB;GACtC,CAAC;;CAEJ,MAAM,MAAM;AACZ,KAAI,IAAI,cAAc,KAAA,EACpB,QAAO,oBAAoB;EAAE,GAAG;EAAK,WAAW;EAAU,CAAC;AAE7D,QAAO,oBAAoB,IAAI;;AAGjC,SAAS,sBAAsB,UAAsD;AACnF,QAAO;EAAE,GAAG;EAAU,WAAW;EAAU;;;;;;;AAQ7C,SAAgB,kBAAkB,QAAgB,QAAoC;CACpF,MAAM,kBAAkB,OAAO,aAAa;CAC5C,MAAM,aAAa,OAAO,cAAc;AAExC,QAAO,IAAI,GACR,OAAO,cAAc;EACpB,MAAM,aAAa,SAAS,OAAO,MAAM,WAAW;EACpD,GAAI,OAAO,WAAW,OAAO,WAAW,EAAE,UAAU,MAAM,GAAG,EAAE;EAC/D,OAAO;EACP,GAAI,cAAc,OAAO,MAAM,EAAE,KAAK,OAAO,KAAK,GAAG,EAAE;EACxD,EACF,CAAC;AAEF,KAAI,CAAC,OAAO,WAAW,CAAC,gBAAiB;CAEzC,MAAM,kBACJ,OAGA;AACF,KAAI,mBAAmB,gBAAgB,SAAS,EAC9C,MAAK,MAAM,cAAc,iBAAiB;EACxC,MAAM,SA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QACoC;AACpC,KAAI,CAAC,OAAO,WACV,OAAM,IAAI,MAAM,2DAA2D;CAG7E,MAAM,SAAS,OAAO,UAAU;CAChC,MAAM,SAAS,OAAO,kBAAkB,IAAI,gCAAgC,EAAE,QAAQ,CAAC;CAEvF,MAAM,SAAS,iCAAiC,OAAO,OAAO;CAC9D,MAAM,SAAS,gCAAgC,OAAO,YAAY;EAChE;EACA,GAAI,OAAO,qBAAqB,KAAA,IAAY,EAAE,kBAAkB,OAAO,kBAAkB,GAAG,EAAE;EAC9F,GAAI,OAAO,kBAAkB,KAAA,IAAY,EAAE,eAAe,OAAO,eAAe,GAAG,EAAE;EACtF,CAAC;CAEF,MAAM,mBAAmB,IAAI,2BAA2B;EACtD,OAAO,OAAO;EACd,GAAI,OAAO,mBAAmB,qBAAqB,KAAA,IAC/C,EAAE,SAAS,OAAO,kBAAkB,kBAAkB,GACtD,EAAE;EACP,CAAC;CACF,MAAM,gBAAgB,IAAI,wBAAwB;EAChD,OAAO,OAAO;EACd,GAAI,OAAO,mBAAmB,kBAAkB,KAAA,IAC5C,EAAE,SAAS,OAAO,kBAAkB,eAAe,GACnD,EAAE;EACP,CAAC;CAEF,MAAM,QAAQ,IAAI,aAAa;EAC7B,QAAQ;EACR,QAAQ;EACR,gBAAgB;EAChB;EACD,CAAC;AAEF,QAAO;EACL;EACA,cAAc;GAAE;GAAkB;GAAe;EACjD,UAAU,EAAE,OAAO;EACnB;EACA,MAAM,cAAc;AAClB,SAAM,QAAQ,IAAI,CAChB,OAAO,iBAAiB,aAAa,EACrC,OAAO,cAAc,aAAa,CACnC,CAAC;;EAEJ,MAAM,UAAU;EAGjB"}
|
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@classytic/supplier-performance",
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"author": "Classytic",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://www.npmjs.com/package/@classytic/supplier-performance",
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://github.com/classytic/supplier-performance/issues"
|
|
10
|
+
},
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/classytic/supplier-performance.git"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"supplier",
|
|
17
|
+
"performance",
|
|
18
|
+
"scorecard",
|
|
19
|
+
"vendor",
|
|
20
|
+
"procurement",
|
|
21
|
+
"on-time-delivery",
|
|
22
|
+
"defect-rate",
|
|
23
|
+
"price-variance",
|
|
24
|
+
"mongodb",
|
|
25
|
+
"classytic"
|
|
26
|
+
],
|
|
27
|
+
"type": "module",
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"default": "./dist/index.js"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"main": "./dist/index.js",
|
|
42
|
+
"types": "./dist/index.d.ts",
|
|
43
|
+
"files": [
|
|
44
|
+
"dist",
|
|
45
|
+
"README.md",
|
|
46
|
+
"LICENSE"
|
|
47
|
+
],
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsdown",
|
|
50
|
+
"typecheck": "tsc --noEmit",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"prepublishOnly": "npm run typecheck && npm run test && npm run build",
|
|
53
|
+
"push": "classytic-push",
|
|
54
|
+
"release:tag": "node -e \"require('child_process').execSync('npm run push -- v'+require('./package.json').version,{stdio:'inherit'})\"",
|
|
55
|
+
"release": "npm run push -- main && npm run release:tag && npm publish"
|
|
56
|
+
},
|
|
57
|
+
"peerDependencies": {
|
|
58
|
+
"@classytic/mongokit": ">=3.11.0",
|
|
59
|
+
"@classytic/primitives": ">=0.1.0",
|
|
60
|
+
"mongoose": ">=9.4.1"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@classytic/dev-tools": "^0.2.0",
|
|
64
|
+
"@classytic/mongokit": "^3.11.0",
|
|
65
|
+
"@classytic/primitives": "^0.1.1",
|
|
66
|
+
"@types/node": "^25.5.0",
|
|
67
|
+
"mongodb-memory-server": "^10.2.3",
|
|
68
|
+
"mongoose": "^9.4.1",
|
|
69
|
+
"tsdown": "^0.14.2",
|
|
70
|
+
"typescript": "^5.8.2",
|
|
71
|
+
"vitest": "^3.2.4"
|
|
72
|
+
}
|
|
73
|
+
}
|