@classytic/supplier-performance 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -10
- package/LICENSE +75 -21
- package/dist/event-catalog.js +16 -38
- package/dist/in-process-bus.d.ts +4 -24
- package/dist/index.d.ts +131 -54
- package/dist/index.js +232 -112
- package/package.json +10 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,15 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
3
|
+
|
|
4
|
+
## 0.4.0 — 2026-08-17
|
|
5
|
+
|
|
6
|
+
### Changed
|
|
7
|
+
- Supplier-score model and score service updated; engine types and repositories aligned (10 src files)
|
|
8
|
+
|
|
9
|
+
## 1.0.0 - 2026-07-29
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
- **License:** relicensed from MIT to the **Classytic Source-Available License** (Community & Commercial). Evaluation/development use remains free; production use now requires a commercial license from Classytic LLC. See `LICENSE`.
|
|
13
|
+
- Major bump marks the license change; versions published before 1.0.0 remain under their original MIT terms.
|
|
14
|
+
|
|
15
|
+
## 0.3.2 - 2026-07-22 (unpublished)
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
- Internal: `InProcess*Bus` is now a thin subclass of `@classytic/primitives/event-infra`'s shared `InProcessEventBus` (dedup / error-isolation / close semantics unchanged); `MemoryOutboxStore` re-exported from the shared runtime where applicable. No public API, event-name, or wire-envelope change. Requires `@classytic/primitives >=0.13.0`.
|
|
19
|
+
|
|
20
|
+
## [0.3.1] — 2026-07-16
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
|
|
24
|
+
- injectTenantField no longer force-indexes the tenant field: the compound
|
|
25
|
+
prepend makes the tenant the leading key of every index, so the bare single
|
|
26
|
+
was a redundant prefix paid on every insert (PACKAGE_RULES P11.1, fleet
|
|
27
|
+
index audit). A dedicated tenant index is still created when a schema
|
|
28
|
+
declares no compounds to prepend. Index-declaration change only.
|
|
29
|
+
|
|
13
30
|
## [0.3.0] — unpublished (2026-07-15)
|
|
14
31
|
|
|
15
32
|
### Changed — kit refresh (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
|
package/LICENSE
CHANGED
|
@@ -1,21 +1,75 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 Classytic
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
Classytic Source-Available License (Community & Commercial), Version 1.0
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Classytic LLC. All rights reserved.
|
|
4
|
+
|
|
5
|
+
This software is source-available, not open source. Please read this License
|
|
6
|
+
before using it.
|
|
7
|
+
|
|
8
|
+
1. DEFINITIONS
|
|
9
|
+
"Software" means the contents of this package and any accompanying source
|
|
10
|
+
code, object code, or documentation, in any form.
|
|
11
|
+
"Licensor" means Classytic LLC, a limited liability company organized in the
|
|
12
|
+
United States.
|
|
13
|
+
"You" means the individual or legal entity exercising rights under this
|
|
14
|
+
License.
|
|
15
|
+
"Evaluation Use" means use for evaluation, development, testing,
|
|
16
|
+
experimentation, or internal non-commercial purposes only.
|
|
17
|
+
"Production Use" means any use of the Software that is live, commercial,
|
|
18
|
+
revenue-generating, or customer-facing, or any use other than Evaluation Use.
|
|
19
|
+
"Commercial License" means a separate written agreement executed with
|
|
20
|
+
Licensor that grants Production Use rights.
|
|
21
|
+
|
|
22
|
+
2. OWNERSHIP
|
|
23
|
+
The Software is licensed, not sold. Licensor retains all right, title, and
|
|
24
|
+
interest in and to the Software, including all intellectual property rights.
|
|
25
|
+
All rights not expressly granted in this License are reserved by Licensor.
|
|
26
|
+
|
|
27
|
+
3. EVALUATION GRANT
|
|
28
|
+
Subject to Your compliance with this License, Licensor grants You a
|
|
29
|
+
worldwide, royalty-free, non-exclusive, non-transferable, revocable license
|
|
30
|
+
to download, install, run, and modify the Software solely for Evaluation Use.
|
|
31
|
+
|
|
32
|
+
4. PRODUCTION USE REQUIRES A COMMERCIAL LICENSE
|
|
33
|
+
Production Use of the Software is NOT permitted under this License and
|
|
34
|
+
requires a Commercial License from Licensor. A Commercial License may be
|
|
35
|
+
granted at Licensor's discretion, with or without a fee, and may confer
|
|
36
|
+
perpetual, irrevocable, and transferable Production Use rights as set out in
|
|
37
|
+
that agreement. Contact licensing@classytic.com to obtain one.
|
|
38
|
+
|
|
39
|
+
5. RESTRICTIONS
|
|
40
|
+
You may not:
|
|
41
|
+
(a) make any Production Use of the Software without a Commercial License;
|
|
42
|
+
(b) redistribute, resell, rent, sublicense, or otherwise make the Software
|
|
43
|
+
(in whole or in part, original or modified) available to third parties as
|
|
44
|
+
a stand-alone product, framework, library, or hosted/managed service that
|
|
45
|
+
competes with the Software or with Licensor;
|
|
46
|
+
(c) remove, obscure, or alter any copyright, license, or attribution notice.
|
|
47
|
+
|
|
48
|
+
6. FEEDBACK AND CONTRIBUTIONS
|
|
49
|
+
Any feedback, suggestions, or contributions You provide relating to the
|
|
50
|
+
Software may be used by Licensor for any purpose without obligation to You.
|
|
51
|
+
|
|
52
|
+
7. TERMINATION
|
|
53
|
+
This License and the Evaluation Grant terminate automatically if You breach
|
|
54
|
+
any term. Upon termination You must cease all use of the Software and destroy
|
|
55
|
+
all copies in Your possession. Rights under a Commercial License are governed
|
|
56
|
+
by that agreement's own terms and survive termination of this License to the
|
|
57
|
+
extent stated there.
|
|
58
|
+
|
|
59
|
+
8. DISCLAIMER OF WARRANTY
|
|
60
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
61
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
62
|
+
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
|
|
63
|
+
|
|
64
|
+
9. LIMITATION OF LIABILITY
|
|
65
|
+
TO THE MAXIMUM EXTENT PERMITTED BY LAW, IN NO EVENT SHALL LICENSOR BE LIABLE
|
|
66
|
+
FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
67
|
+
TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE
|
|
68
|
+
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
69
|
+
|
|
70
|
+
10. GOVERNING LAW
|
|
71
|
+
This License is governed by the laws of the State of Delaware, United States,
|
|
72
|
+
without regard to its conflict-of-laws principles. (Adjust to Your LLC's state
|
|
73
|
+
of formation.)
|
|
74
|
+
|
|
75
|
+
For commercial licensing, contact: licensing@classytic.com
|
package/dist/event-catalog.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { createEvent
|
|
1
|
+
import { createEvent } from "@classytic/primitives/events";
|
|
2
|
+
import { InProcessEventBus } from "@classytic/primitives/event-infra";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
//#region src/domain/enums/event-type.enum.ts
|
|
4
5
|
/**
|
|
@@ -60,46 +61,23 @@ function createEvent$1(type, payload, ctx, meta) {
|
|
|
60
61
|
//#endregion
|
|
61
62
|
//#region src/events/in-process-bus.ts
|
|
62
63
|
/**
|
|
63
|
-
*
|
|
64
|
-
* (`supplier_performance:*`, `*`, exact type). Subscriber errors are
|
|
65
|
-
* caught and logged — they never break the emitter or sibling
|
|
66
|
-
* subscribers.
|
|
64
|
+
* In-process fan-out transport — the default when the host injects none.
|
|
67
65
|
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
66
|
+
* A thin subclass of `@classytic/primitives/event-infra`'s shared
|
|
67
|
+
* `InProcessEventBus` (the single implementation every kernel now defaults
|
|
68
|
+
* to). Prior semantics preserved exactly: glob matching via
|
|
69
|
+
* `matchEventPattern` (exact / `*` / `prefix.*` / `prefix:*`), Set-dedup so a
|
|
70
|
+
* handler matched by multiple patterns fires once, per-handler error
|
|
71
|
+
* isolation (errors logged; default `console`), idempotent `close()`.
|
|
72
|
+
* Structurally identical to arc's `MemoryEventTransport`.
|
|
70
73
|
*/
|
|
71
|
-
var InProcessSupplierPerformanceBus = class {
|
|
72
|
-
name = "in-process-supplier-performance";
|
|
73
|
-
patterns = /* @__PURE__ */ new Map();
|
|
74
|
-
logger;
|
|
74
|
+
var InProcessSupplierPerformanceBus = class extends InProcessEventBus {
|
|
75
75
|
constructor(options = {}) {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
for (const fn of handlers) try {
|
|
82
|
-
await fn(event);
|
|
83
|
-
} catch (err) {
|
|
84
|
-
this.logger.error(`[supplier-performance] subscriber threw on ${event.type}: ${err.message}`, err);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
async subscribe(pattern, handler) {
|
|
89
|
-
let set = this.patterns.get(pattern);
|
|
90
|
-
if (!set) {
|
|
91
|
-
set = /* @__PURE__ */ new Set();
|
|
92
|
-
this.patterns.set(pattern, set);
|
|
93
|
-
}
|
|
94
|
-
set.add(handler);
|
|
95
|
-
return () => {
|
|
96
|
-
const s = this.patterns.get(pattern);
|
|
97
|
-
s?.delete(handler);
|
|
98
|
-
if (s && s.size === 0) this.patterns.delete(pattern);
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
async close() {
|
|
102
|
-
this.patterns.clear();
|
|
76
|
+
super({
|
|
77
|
+
name: "in-process-supplier-performance",
|
|
78
|
+
logLabel: "supplier-performance",
|
|
79
|
+
...options
|
|
80
|
+
});
|
|
103
81
|
}
|
|
104
82
|
};
|
|
105
83
|
//#endregion
|
package/dist/in-process-bus.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { DomainEvent,
|
|
1
|
+
import { DomainEvent, EventMeta } from "@classytic/primitives/events";
|
|
2
|
+
import { InProcessEventBus, InProcessEventBusOptions } from "@classytic/primitives/event-infra";
|
|
2
3
|
import { z } from "zod";
|
|
3
|
-
|
|
4
4
|
//#region src/events/event-constants.d.ts
|
|
5
|
-
|
|
6
5
|
/**
|
|
7
6
|
* Canonical event names emitted by `@classytic/supplier-performance`.
|
|
8
7
|
*
|
|
@@ -136,28 +135,9 @@ interface SupplierPerformanceContext {
|
|
|
136
135
|
declare function createEvent$1<T>(type: SupplierPerformanceEventName, payload: T, ctx?: SupplierPerformanceContext, meta?: Partial<EventMeta>): DomainEvent<T>;
|
|
137
136
|
//#endregion
|
|
138
137
|
//#region src/events/in-process-bus.d.ts
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
error(message: string, ...args: unknown[]): void;
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* Zero-dep in-process event bus. Subscribers can use glob patterns
|
|
146
|
-
* (`supplier_performance:*`, `*`, exact type). Subscriber errors are
|
|
147
|
-
* caught and logged — they never break the emitter or sibling
|
|
148
|
-
* subscribers.
|
|
149
|
-
*
|
|
150
|
-
* Drop-in compatible with any `EventTransport` — hosts replace it by
|
|
151
|
-
* passing their own at `createSupplierPerformance({ eventTransport })`.
|
|
152
|
-
*/
|
|
153
|
-
declare class InProcessSupplierPerformanceBus implements EventTransport {
|
|
154
|
-
readonly name = "in-process-supplier-performance";
|
|
155
|
-
private patterns;
|
|
156
|
-
private logger;
|
|
138
|
+
type InProcessBusOptions = InProcessEventBusOptions;
|
|
139
|
+
declare class InProcessSupplierPerformanceBus extends InProcessEventBus {
|
|
157
140
|
constructor(options?: InProcessBusOptions);
|
|
158
|
-
publish(event: DomainEvent): Promise<void>;
|
|
159
|
-
subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
|
|
160
|
-
close(): Promise<void>;
|
|
161
141
|
}
|
|
162
142
|
//#endregion
|
|
163
143
|
export { ScoreComputed as a, supplierPerformanceEventDefinitions as c, PerformanceEventType as d, PerformanceEventTypeValue as f, EventRecorded as i, SupplierPerformanceEventPayloads as l, SupplierPerformanceEvents as m, createEvent$1 as n, SupplierPerformanceEventDefinition as o, SupplierPerformanceEventName as p, SupplierPerformanceContext as r, SupplierPerformanceEventSchema as s, InProcessSupplierPerformanceBus as t, PERFORMANCE_EVENT_TYPE_VALUES as u };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { a as ScoreComputed, c as supplierPerformanceEventDefinitions, d as PerformanceEventType, f as PerformanceEventTypeValue, i as EventRecorded, l as SupplierPerformanceEventPayloads, m as SupplierPerformanceEvents, n as createEvent, o as SupplierPerformanceEventDefinition, p as SupplierPerformanceEventName, r as SupplierPerformanceContext, s as SupplierPerformanceEventSchema, t as InProcessSupplierPerformanceBus, u as PERFORMANCE_EVENT_TYPE_VALUES } from "./in-process-bus.js";
|
|
2
|
-
import { PluginType, Repository, RepositoryContext } from "@classytic/mongokit";
|
|
2
|
+
import { ModelBlueprint, PluginType, Repository, RepositoryContext } from "@classytic/mongokit";
|
|
3
3
|
import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
|
|
4
4
|
import { ClientSession, Connection, Document, Model, Schema, Types } from "mongoose";
|
|
5
5
|
import { EventTransport } from "@classytic/primitives/events";
|
|
6
6
|
import { OutboxStore } from "@classytic/primitives/outbox";
|
|
7
7
|
import { HttpError } from "@classytic/repo-core/errors";
|
|
8
|
-
|
|
9
8
|
//#region src/models/performance-event.model.d.ts
|
|
10
9
|
interface PerformanceEventDocument extends Document {
|
|
11
10
|
organizationId: unknown;
|
|
@@ -19,14 +18,15 @@ interface PerformanceEventDocument extends Document {
|
|
|
19
18
|
createdAt: Date;
|
|
20
19
|
updatedAt: Date;
|
|
21
20
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
21
|
+
/** Base collection name (before any host-supplied prefix). */
|
|
22
|
+
declare const PERFORMANCE_EVENT_COLLECTION = "supplier_performance_events";
|
|
23
|
+
/**
|
|
24
|
+
* Build the PerformanceEvent schema for a resolved tenant config. Pure — the
|
|
25
|
+
* `defineSupplierPerformanceModels` blueprint invokes this factory once, only
|
|
26
|
+
* when the model is actually registered (§5.2). The collection name (incl. any
|
|
27
|
+
* host prefix) is supplied to `connection.model()` by the blueprint, not here.
|
|
28
|
+
*/
|
|
29
|
+
declare function buildPerformanceEventSchema(tenant: ResolvedTenantConfig): Schema<PerformanceEventDocument>;
|
|
30
30
|
//#endregion
|
|
31
31
|
//#region src/models/supplier-score.model.d.ts
|
|
32
32
|
interface SupplierScoreDocument extends Document {
|
|
@@ -43,27 +43,36 @@ interface SupplierScoreDocument extends Document {
|
|
|
43
43
|
createdAt: Date;
|
|
44
44
|
updatedAt: Date;
|
|
45
45
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
46
|
+
/** Base collection name (before any host-supplied prefix). */
|
|
47
|
+
declare const SUPPLIER_SCORE_COLLECTION = "supplier_scores";
|
|
48
|
+
/**
|
|
49
|
+
* Build the SupplierScore schema for a resolved tenant config. Pure — the
|
|
50
|
+
* `defineSupplierPerformanceModels` blueprint invokes this factory once, only
|
|
51
|
+
* when the model is actually registered (§5.2). The collection name (incl. any
|
|
52
|
+
* host prefix) is supplied to `connection.model()` by the blueprint, not here.
|
|
53
|
+
*/
|
|
54
|
+
declare function buildSupplierScoreSchema(tenant: ResolvedTenantConfig): Schema<SupplierScoreDocument>;
|
|
54
55
|
//#endregion
|
|
55
56
|
//#region src/models/create-models.d.ts
|
|
56
|
-
interface
|
|
57
|
-
PerformanceEvent:
|
|
58
|
-
SupplierScore:
|
|
57
|
+
interface SupplierPerformanceModels {
|
|
58
|
+
PerformanceEvent: Model<PerformanceEventDocument>;
|
|
59
|
+
SupplierScore: Model<SupplierScoreDocument>;
|
|
59
60
|
}
|
|
60
|
-
interface
|
|
61
|
-
/** Resolved tenant config
|
|
62
|
-
tenant
|
|
61
|
+
interface DefineSupplierPerformanceModelsConfig {
|
|
62
|
+
/** Resolved tenant config — drives schema field type + compound-index prefix. */
|
|
63
|
+
tenant: ResolvedTenantConfig;
|
|
64
|
+
/** Optional collection name prefix (PACKAGE_RULES §20.1). */
|
|
63
65
|
collectionPrefix?: string | undefined;
|
|
64
|
-
|
|
66
|
+
/** Mongoose auto-index builds. Default `true` (dev); `false` in prod (§35). */
|
|
67
|
+
autoIndex?: boolean;
|
|
68
|
+
/** On a name collision: `false` (default) throws; `true` re-registers (test/dev fixtures). */
|
|
69
|
+
forceRecreate?: boolean;
|
|
65
70
|
}
|
|
66
|
-
|
|
71
|
+
/**
|
|
72
|
+
* Describe the supplier-performance model set as a connection-free blueprint.
|
|
73
|
+
* Pure — builds no schema and registers nothing until `.bind(connection)`.
|
|
74
|
+
*/
|
|
75
|
+
declare function defineSupplierPerformanceModels(config: DefineSupplierPerformanceModelsConfig): ModelBlueprint<SupplierPerformanceModels>;
|
|
67
76
|
//#endregion
|
|
68
77
|
//#region src/repositories/performance-event.repository.d.ts
|
|
69
78
|
interface PerformanceEventRepositoryConfig {
|
|
@@ -116,8 +125,19 @@ interface ScoreMetrics {
|
|
|
116
125
|
unitsReceived: number;
|
|
117
126
|
/** Total defective units (sum of `metrics.quantity` on defect events). */
|
|
118
127
|
defectiveUnits: number;
|
|
119
|
-
/**
|
|
128
|
+
/**
|
|
129
|
+
* Fraction CLAMPED to [0, 1]. `min(defectiveUnits / unitsReceived, 1)`.
|
|
130
|
+
* Clamped so the persisted value satisfies the model's `max: 1` schema —
|
|
131
|
+
* see `rawDefectRate` for the un-capped signal.
|
|
132
|
+
*/
|
|
120
133
|
defectRate: number;
|
|
134
|
+
/**
|
|
135
|
+
* Un-clamped `defectiveUnits / unitsReceived`. Can exceed 1 when defects
|
|
136
|
+
* are reported against goods received in a prior period (or a mis-wired
|
|
137
|
+
* supplierId). Diagnostic only — a value > 1 is a data-integrity signal
|
|
138
|
+
* worth alerting on; the composite uses the clamped `defectRate`.
|
|
139
|
+
*/
|
|
140
|
+
rawDefectRate: number;
|
|
121
141
|
/** Number of price-variance events in window. */
|
|
122
142
|
priceVarianceCount: number;
|
|
123
143
|
/** Average variance fraction (e.g. 0.04 = 4% over expected). */
|
|
@@ -128,6 +148,14 @@ interface ScoreMetrics {
|
|
|
128
148
|
* Pure roll-up; hosts with custom weights re-score from the rates.
|
|
129
149
|
*/
|
|
130
150
|
compositeScore: number;
|
|
151
|
+
/**
|
|
152
|
+
* `true` when the period carries no evidence (no deliveries, no received
|
|
153
|
+
* units, no price-variance events). The `compositeScore` still resolves to
|
|
154
|
+
* the documented ~50 "new supplier" baseline for backwards compatibility;
|
|
155
|
+
* this flag lets consumers treat a no-data scorecard as an
|
|
156
|
+
* insufficient-signal sentinel instead of a real middling grade.
|
|
157
|
+
*/
|
|
158
|
+
insufficientSignal: boolean;
|
|
131
159
|
}
|
|
132
160
|
interface ComputeScoreInput {
|
|
133
161
|
supplierId: string;
|
|
@@ -259,10 +287,25 @@ declare class ScoreService {
|
|
|
259
287
|
private logger;
|
|
260
288
|
constructor(config: ScoreServiceConfig);
|
|
261
289
|
/**
|
|
262
|
-
* Append a single performance event to the log.
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
290
|
+
* Append a single performance event to the log.
|
|
291
|
+
*
|
|
292
|
+
* NOT idempotent by construction — a double-fired host bridge writes two
|
|
293
|
+
* rows and double-counts the delivery. This kernel deliberately does NOT
|
|
294
|
+
* ship a default unique dedup index: hosts key idempotency differently
|
|
295
|
+
* (PO-line, PO+SKU, receipt id), and a blanket unique index would be wrong
|
|
296
|
+
* for all of them (and would reject the many events that legitimately carry
|
|
297
|
+
* no key). HOST REQUIREMENT: to make replays safe, dedup upstream (skip if
|
|
298
|
+
* already recorded) OR add an opt-in partial-unique index on your chosen
|
|
299
|
+
* key, e.g. on `metadata.idempotencyKey` / `sourceRef`:
|
|
300
|
+
*
|
|
301
|
+
* schema.index(
|
|
302
|
+
* { organizationId: 1, 'metadata.idempotencyKey': 1 },
|
|
303
|
+
* { unique: true,
|
|
304
|
+
* partialFilterExpression: { 'metadata.idempotencyKey': { $exists: true } } },
|
|
305
|
+
* );
|
|
306
|
+
*
|
|
307
|
+
* `computeScore` remains fully idempotent regardless — it re-aggregates the
|
|
308
|
+
* current event log and upserts one snapshot per (supplier, period).
|
|
266
309
|
*/
|
|
267
310
|
recordEvent(input: RecordEventInput, ctx: SupplierPerformanceContext): Promise<PerformanceEventDocument>;
|
|
268
311
|
/**
|
|
@@ -307,18 +350,12 @@ interface SupplierPerformanceTenantOptions extends TenantConfig {
|
|
|
307
350
|
allowDataInjection?: boolean | undefined;
|
|
308
351
|
onMismatch?: 'throw' | 'overwrite' | undefined;
|
|
309
352
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
* the bundled `InProcessSupplierPerformanceBus`. Omit to skip event
|
|
317
|
-
* emission entirely.
|
|
318
|
-
*/
|
|
319
|
-
/** Optional durable outbox — enables host-session (relay-only) mode. */
|
|
320
|
-
outbox?: OutboxStore | undefined;
|
|
321
|
-
eventTransport?: EventTransport | undefined;
|
|
353
|
+
/**
|
|
354
|
+
* DESCRIBE-time shape — everything that determines the persistence SHAPE and
|
|
355
|
+
* needs no connection or I/O to inspect. Nothing here opens a socket or reads a
|
|
356
|
+
* secret (§6.2).
|
|
357
|
+
*/
|
|
358
|
+
interface SupplierPerformanceShape {
|
|
322
359
|
/**
|
|
323
360
|
* Tenant scoping config — `TenantConfig` from `@classytic/repo-core/tenant`
|
|
324
361
|
* (plus mongokit-runtime knobs) or a boolean shorthand. One resolved value
|
|
@@ -331,8 +368,26 @@ interface SupplierPerformanceConfig {
|
|
|
331
368
|
tenant?: SupplierPerformanceTenantOptions | boolean | undefined;
|
|
332
369
|
/** Optional collection name prefix (PACKAGE_RULES §20.1). */
|
|
333
370
|
collectionPrefix?: string | undefined;
|
|
334
|
-
/**
|
|
371
|
+
/** Mongoose auto-index builds. Default `true` (dev); pass `false` in prod (§35). */
|
|
372
|
+
autoIndex?: boolean | undefined;
|
|
373
|
+
/** Hot-reload / test fixtures only. Default `false`. Maps to mongokit `replace`. */
|
|
335
374
|
forceRecreate?: boolean | undefined;
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* BIND-time runtime collaborators — the live connection is the first `bind`
|
|
378
|
+
* arg; these are the rest. A transport, outbox, logger or per-repo plugin set
|
|
379
|
+
* belongs here, not in the shape (§6.2).
|
|
380
|
+
*/
|
|
381
|
+
interface SupplierPerformanceRuntime {
|
|
382
|
+
/**
|
|
383
|
+
* Optional event transport. Any object matching `@classytic/primitives`
|
|
384
|
+
* `EventTransport` — Arc's MemoryEventTransport, a Redis transport, or the
|
|
385
|
+
* bundled `InProcessSupplierPerformanceBus`. Omit and the engine creates (and
|
|
386
|
+
* owns) an in-process bus; supply one and its lifecycle stays with the host.
|
|
387
|
+
*/
|
|
388
|
+
eventTransport?: EventTransport | undefined;
|
|
389
|
+
/** Optional durable outbox — enables host-session (relay-only) mode. */
|
|
390
|
+
outbox?: OutboxStore | undefined;
|
|
336
391
|
/** Optional per-repo plugins. Stacked AFTER the built-in plugins. */
|
|
337
392
|
repositoryPlugins?: {
|
|
338
393
|
performanceEvent?: PluginType[] | undefined;
|
|
@@ -345,18 +400,34 @@ interface SupplierPerformanceRepositories {
|
|
|
345
400
|
supplierScore: SupplierScoreRepository;
|
|
346
401
|
}
|
|
347
402
|
interface SupplierPerformanceEngine {
|
|
348
|
-
models:
|
|
403
|
+
models: SupplierPerformanceModels;
|
|
349
404
|
repositories: SupplierPerformanceRepositories;
|
|
350
405
|
services: {
|
|
351
406
|
score: ScoreService;
|
|
352
407
|
};
|
|
353
408
|
events: EventTransport;
|
|
354
409
|
syncIndexes(): Promise<void>;
|
|
355
|
-
|
|
410
|
+
/** The ONLY teardown verb (§6.4). Closes only an internally-created transport. */
|
|
411
|
+
close(): Promise<void>;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* The DESCRIBE/BIND blueprint returned by `defineSupplierPerformance`. Pure to
|
|
415
|
+
* construct; `bind` compiles the models on the supplied connection and wires the
|
|
416
|
+
* engine.
|
|
417
|
+
*/
|
|
418
|
+
interface SupplierPerformanceBlueprint {
|
|
419
|
+
readonly id: 'supplier-performance';
|
|
420
|
+
/** The model names this blueprint registers — known without a connection. */
|
|
421
|
+
readonly modelNames: readonly string[];
|
|
422
|
+
bind(connection: Connection, runtime?: SupplierPerformanceRuntime): SupplierPerformanceEngine;
|
|
356
423
|
}
|
|
357
424
|
//#endregion
|
|
358
|
-
//#region src/engine/
|
|
359
|
-
|
|
425
|
+
//#region src/engine/define-supplier-performance.d.ts
|
|
426
|
+
/**
|
|
427
|
+
* Describe the supplier-performance engine. Pure — registers no model, builds no
|
|
428
|
+
* schema, performs no I/O.
|
|
429
|
+
*/
|
|
430
|
+
declare function defineSupplierPerformance(shape?: SupplierPerformanceShape): SupplierPerformanceBlueprint;
|
|
360
431
|
//#endregion
|
|
361
432
|
//#region src/domain/errors/supplier-performance.errors.d.ts
|
|
362
433
|
declare class SupplierPerformanceError extends Error implements HttpError {
|
|
@@ -364,11 +435,6 @@ declare class SupplierPerformanceError extends Error implements HttpError {
|
|
|
364
435
|
readonly status: number;
|
|
365
436
|
constructor(message: string, code: string, status: number);
|
|
366
437
|
}
|
|
367
|
-
/**
|
|
368
|
-
* Thrown when a host passes ctx.session but no OutboxStore is wired —
|
|
369
|
-
* publishing mid-transaction would leak ghost events on rollback (§P8.1).
|
|
370
|
-
*/
|
|
371
|
-
|
|
372
438
|
/** Invalid input to `recordEvent` / `computeScore` (missing supplierId, bad period). */
|
|
373
439
|
declare class SupplierPerformanceValidationError extends SupplierPerformanceError {
|
|
374
440
|
constructor(message: string);
|
|
@@ -379,6 +445,16 @@ declare class SupplierPerformanceValidationError extends SupplierPerformanceErro
|
|
|
379
445
|
* Aggregate raw performance events into a scorecard. Events outside the
|
|
380
446
|
* `period` window are filtered out (defensive — callers should already
|
|
381
447
|
* have queried within the window).
|
|
448
|
+
*
|
|
449
|
+
* ON-TIME SEMANTICS (host-owned): a delivery's on-time/late classification
|
|
450
|
+
* is decided by the event TYPE the host records — `delivery_received` is
|
|
451
|
+
* on-time, `delivery_late` is late. This kernel does NOT re-derive that
|
|
452
|
+
* verdict from `metrics.expectedAt`/`actualAt`; those timestamp fields are
|
|
453
|
+
* ADVISORY (drill-down / audit context), not authoritative. `delayDays` is
|
|
454
|
+
* likewise read as a host-supplied denormalization on `delivery_late` events
|
|
455
|
+
* only. Hosts that want timestamp-derived classification classify upstream
|
|
456
|
+
* and emit the matching type — the kernel never silently overrides the
|
|
457
|
+
* host's own verdict. (Intentional; see fix-3 in the scorecard hardening.)
|
|
382
458
|
*/
|
|
383
459
|
declare function scoreFromEvents(events: ReadonlyArray<PerformanceEvent>, period: ScorePeriod): ScoreMetrics;
|
|
384
460
|
//#endregion
|
|
@@ -394,6 +470,7 @@ declare function resolveSupplierPerformanceTenant(input?: TenantConfig | boolean
|
|
|
394
470
|
* existing compound index (so queries are index-efficient under
|
|
395
471
|
* multi-tenant scoping, rule 36).
|
|
396
472
|
*/
|
|
473
|
+
declare function injectTenantField(schema: Schema, tenant: ResolvedTenantConfig): void;
|
|
397
474
|
//#endregion
|
|
398
475
|
//#region src/repositories/repo-options.d.ts
|
|
399
476
|
interface RepoOptions {
|
|
@@ -409,4 +486,4 @@ interface RepoOptions {
|
|
|
409
486
|
}
|
|
410
487
|
declare function repoOptionsFromCtx(ctx: SupplierPerformanceContext): RepoOptions;
|
|
411
488
|
//#endregion
|
|
412
|
-
export { type ComputeScoreInput, type
|
|
489
|
+
export { type ComputeScoreInput, type DefineSupplierPerformanceModelsConfig, EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_COLLECTION, PERFORMANCE_EVENT_TYPE_VALUES, type PerformanceEvent, type PerformanceEventDocument, PerformanceEventRepository, type PerformanceEventRepositoryConfig, PerformanceEventType, type PerformanceEventTypeValue, type PerformanceMetrics, type RecordEventInput, type RepoOptions, SUPPLIER_SCORE_COLLECTION, ScoreComputed, type ScoreMetrics, type ScorePeriod, ScoreService, type ScoreServiceConfig, type SupplierPerformanceBlueprint, type SupplierPerformanceContext, type SupplierPerformanceEngine, SupplierPerformanceError, type SupplierPerformanceEventDefinition, type SupplierPerformanceEventName, type SupplierPerformanceEventPayloads, type SupplierPerformanceEventSchema, SupplierPerformanceEvents, type SupplierPerformanceLogger, type SupplierPerformanceModels, type SupplierPerformanceRepositories, type SupplierPerformanceRuntime, type SupplierPerformanceShape, type SupplierPerformanceTenantOptions, SupplierPerformanceValidationError, type SupplierScore, type SupplierScoreDocument, SupplierScoreRepository, type SupplierScoreRepositoryConfig, type UpsertScoreInput, buildPerformanceEventSchema, buildSupplierScoreSchema, createEvent, defineSupplierPerformance, defineSupplierPerformanceModels, injectTenantField, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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";
|
|
2
|
+
import { Repository, createOptionsExtractor, defineModels, methodRegistryPlugin, multiTenantPlugin } from "@classytic/mongokit";
|
|
3
|
+
import { assertNoLegacyTenantKeys, resolveTenantConfig } from "@classytic/repo-core/tenant";
|
|
4
4
|
import mongoose, { Schema } from "mongoose";
|
|
5
5
|
//#region src/models/inject-tenant.ts
|
|
6
6
|
/**
|
|
@@ -47,6 +47,8 @@ function injectTenantField(schema, tenant) {
|
|
|
47
47
|
}
|
|
48
48
|
//#endregion
|
|
49
49
|
//#region src/models/performance-event.model.ts
|
|
50
|
+
/** Base collection name (before any host-supplied prefix). */
|
|
51
|
+
const PERFORMANCE_EVENT_COLLECTION = "supplier_performance_events";
|
|
50
52
|
const metricsSchema$1 = new Schema({
|
|
51
53
|
quantity: {
|
|
52
54
|
type: Number,
|
|
@@ -68,6 +70,12 @@ const metricsSchema$1 = new Schema({
|
|
|
68
70
|
_id: false,
|
|
69
71
|
strict: false
|
|
70
72
|
});
|
|
73
|
+
/**
|
|
74
|
+
* Build the PerformanceEvent schema for a resolved tenant config. Pure — the
|
|
75
|
+
* `defineSupplierPerformanceModels` blueprint invokes this factory once, only
|
|
76
|
+
* when the model is actually registered (§5.2). The collection name (incl. any
|
|
77
|
+
* host prefix) is supplied to `connection.model()` by the blueprint, not here.
|
|
78
|
+
*/
|
|
71
79
|
function buildPerformanceEventSchema(tenant) {
|
|
72
80
|
const schema = new Schema({
|
|
73
81
|
supplierId: {
|
|
@@ -91,10 +99,7 @@ function buildPerformanceEventSchema(tenant) {
|
|
|
91
99
|
sourceRef: String,
|
|
92
100
|
sourceType: String,
|
|
93
101
|
metadata: { type: Schema.Types.Mixed }
|
|
94
|
-
}, {
|
|
95
|
-
timestamps: true,
|
|
96
|
-
collection: "supplier_performance_events"
|
|
97
|
-
});
|
|
102
|
+
}, { timestamps: true });
|
|
98
103
|
schema.index({
|
|
99
104
|
supplierId: 1,
|
|
100
105
|
occurredAt: 1
|
|
@@ -106,20 +111,10 @@ function buildPerformanceEventSchema(tenant) {
|
|
|
106
111
|
injectTenantField(schema, tenant);
|
|
107
112
|
return schema;
|
|
108
113
|
}
|
|
109
|
-
var PerformanceEventModelCollisionError = class extends Error {
|
|
110
|
-
constructor(name) {
|
|
111
|
-
super(`[supplier-performance] Mongoose model "${name}" already exists on this connection. Pass \`forceRecreate: true\` for hot-reload, or use two Mongoose connections.`);
|
|
112
|
-
this.name = "PerformanceEventModelCollisionError";
|
|
113
|
-
}
|
|
114
|
-
};
|
|
115
|
-
function createPerformanceEventModel(connection, tenant, config = {}) {
|
|
116
|
-
if (connection.models.PerformanceEvent) if (config.forceRecreate) connection.deleteModel("PerformanceEvent");
|
|
117
|
-
else throw new PerformanceEventModelCollisionError("PerformanceEvent");
|
|
118
|
-
const collection = (config.collectionPrefix ?? "") + "supplier_performance_events";
|
|
119
|
-
return connection.model("PerformanceEvent", buildPerformanceEventSchema(tenant), collection);
|
|
120
|
-
}
|
|
121
114
|
//#endregion
|
|
122
115
|
//#region src/models/supplier-score.model.ts
|
|
116
|
+
/** Base collection name (before any host-supplied prefix). */
|
|
117
|
+
const SUPPLIER_SCORE_COLLECTION = "supplier_scores";
|
|
123
118
|
const periodSchema = new Schema({
|
|
124
119
|
start: {
|
|
125
120
|
type: Date,
|
|
@@ -168,6 +163,11 @@ const metricsSchema = new Schema({
|
|
|
168
163
|
min: 0,
|
|
169
164
|
max: 1
|
|
170
165
|
},
|
|
166
|
+
rawDefectRate: {
|
|
167
|
+
type: Number,
|
|
168
|
+
default: 0,
|
|
169
|
+
min: 0
|
|
170
|
+
},
|
|
171
171
|
priceVarianceCount: {
|
|
172
172
|
type: Number,
|
|
173
173
|
default: 0,
|
|
@@ -182,8 +182,18 @@ const metricsSchema = new Schema({
|
|
|
182
182
|
default: 0,
|
|
183
183
|
min: 0,
|
|
184
184
|
max: 100
|
|
185
|
+
},
|
|
186
|
+
insufficientSignal: {
|
|
187
|
+
type: Boolean,
|
|
188
|
+
default: false
|
|
185
189
|
}
|
|
186
190
|
}, { _id: false });
|
|
191
|
+
/**
|
|
192
|
+
* Build the SupplierScore schema for a resolved tenant config. Pure — the
|
|
193
|
+
* `defineSupplierPerformanceModels` blueprint invokes this factory once, only
|
|
194
|
+
* when the model is actually registered (§5.2). The collection name (incl. any
|
|
195
|
+
* host prefix) is supplied to `connection.model()` by the blueprint, not here.
|
|
196
|
+
*/
|
|
187
197
|
function buildSupplierScoreSchema(tenant) {
|
|
188
198
|
const schema = new Schema({
|
|
189
199
|
supplierId: {
|
|
@@ -209,10 +219,7 @@ function buildSupplierScoreSchema(tenant) {
|
|
|
209
219
|
default: 0,
|
|
210
220
|
min: 0
|
|
211
221
|
}
|
|
212
|
-
}, {
|
|
213
|
-
timestamps: true,
|
|
214
|
-
collection: "supplier_scores"
|
|
215
|
-
});
|
|
222
|
+
}, { timestamps: true });
|
|
216
223
|
schema.index({
|
|
217
224
|
supplierId: 1,
|
|
218
225
|
"period.start": 1,
|
|
@@ -225,35 +232,55 @@ function buildSupplierScoreSchema(tenant) {
|
|
|
225
232
|
injectTenantField(schema, tenant);
|
|
226
233
|
return schema;
|
|
227
234
|
}
|
|
228
|
-
var SupplierScoreModelCollisionError = class extends Error {
|
|
229
|
-
constructor(name) {
|
|
230
|
-
super(`[supplier-performance] Mongoose model "${name}" already exists on this connection. Pass \`forceRecreate: true\` for hot-reload, or use two Mongoose connections.`);
|
|
231
|
-
this.name = "SupplierScoreModelCollisionError";
|
|
232
|
-
}
|
|
233
|
-
};
|
|
234
|
-
function createSupplierScoreModel(connection, tenant, config = {}) {
|
|
235
|
-
if (connection.models.SupplierScore) if (config.forceRecreate) connection.deleteModel("SupplierScore");
|
|
236
|
-
else throw new SupplierScoreModelCollisionError("SupplierScore");
|
|
237
|
-
const collection = (config.collectionPrefix ?? "") + "supplier_scores";
|
|
238
|
-
return connection.model("SupplierScore", buildSupplierScoreSchema(tenant), collection);
|
|
239
|
-
}
|
|
240
235
|
//#endregion
|
|
241
236
|
//#region src/models/create-models.ts
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
237
|
+
/**
|
|
238
|
+
* Supplier-performance model specification — the ONE authoritative place the
|
|
239
|
+
* PerformanceEvent + SupplierScore models are described.
|
|
240
|
+
*
|
|
241
|
+
* `defineSupplierPerformanceModels(config)` returns a connection-free mongokit
|
|
242
|
+
* `ModelBlueprint`; `defineSupplierPerformance` binds it during engine
|
|
243
|
+
* construction. Collision handling, auto-index, tenant field shape and
|
|
244
|
+
* collection prefixing live here once (PACKAGE_RULES §20/§21, §P11). A name
|
|
245
|
+
* collision surfaces as mongokit's typed `ModelCollisionError` — no
|
|
246
|
+
* kernel-specific collision error.
|
|
247
|
+
*/
|
|
248
|
+
/**
|
|
249
|
+
* Describe the supplier-performance model set as a connection-free blueprint.
|
|
250
|
+
* Pure — builds no schema and registers nothing until `.bind(connection)`.
|
|
251
|
+
*/
|
|
252
|
+
function defineSupplierPerformanceModels(config) {
|
|
253
|
+
const autoIndex = config.autoIndex ?? true;
|
|
254
|
+
const prefix = config.collectionPrefix ?? "";
|
|
255
|
+
const existing = config.forceRecreate ? {
|
|
256
|
+
mode: "replace",
|
|
257
|
+
environment: "test"
|
|
258
|
+
} : { mode: "throw" };
|
|
259
|
+
return defineModels({
|
|
260
|
+
models: [{
|
|
261
|
+
name: "PerformanceEvent",
|
|
262
|
+
collection: prefix + PERFORMANCE_EVENT_COLLECTION,
|
|
263
|
+
schema: () => {
|
|
264
|
+
const schema = buildPerformanceEventSchema(config.tenant);
|
|
265
|
+
schema.set("autoIndex", autoIndex);
|
|
266
|
+
return schema;
|
|
267
|
+
},
|
|
268
|
+
existing
|
|
269
|
+
}, {
|
|
270
|
+
name: "SupplierScore",
|
|
271
|
+
collection: prefix + SUPPLIER_SCORE_COLLECTION,
|
|
272
|
+
schema: () => {
|
|
273
|
+
const schema = buildSupplierScoreSchema(config.tenant);
|
|
274
|
+
schema.set("autoIndex", autoIndex);
|
|
275
|
+
return schema;
|
|
276
|
+
},
|
|
277
|
+
existing
|
|
278
|
+
}],
|
|
279
|
+
assemble: (models) => Object.freeze({
|
|
280
|
+
PerformanceEvent: models.get("PerformanceEvent"),
|
|
281
|
+
SupplierScore: models.get("SupplierScore")
|
|
282
|
+
})
|
|
283
|
+
});
|
|
257
284
|
}
|
|
258
285
|
//#endregion
|
|
259
286
|
//#region src/repositories/repo-options.ts
|
|
@@ -397,6 +424,16 @@ const COMPOSITE_WEIGHTS = {
|
|
|
397
424
|
* Aggregate raw performance events into a scorecard. Events outside the
|
|
398
425
|
* `period` window are filtered out (defensive — callers should already
|
|
399
426
|
* have queried within the window).
|
|
427
|
+
*
|
|
428
|
+
* ON-TIME SEMANTICS (host-owned): a delivery's on-time/late classification
|
|
429
|
+
* is decided by the event TYPE the host records — `delivery_received` is
|
|
430
|
+
* on-time, `delivery_late` is late. This kernel does NOT re-derive that
|
|
431
|
+
* verdict from `metrics.expectedAt`/`actualAt`; those timestamp fields are
|
|
432
|
+
* ADVISORY (drill-down / audit context), not authoritative. `delayDays` is
|
|
433
|
+
* likewise read as a host-supplied denormalization on `delivery_late` events
|
|
434
|
+
* only. Hosts that want timestamp-derived classification classify upstream
|
|
435
|
+
* and emit the matching type — the kernel never silently overrides the
|
|
436
|
+
* host's own verdict. (Intentional; see fix-3 in the scorecard hardening.)
|
|
400
437
|
*/
|
|
401
438
|
function scoreFromEvents(events, period) {
|
|
402
439
|
const inWindow = events.filter((e) => e.occurredAt >= period.start && e.occurredAt < period.end);
|
|
@@ -410,7 +447,7 @@ function scoreFromEvents(events, period) {
|
|
|
410
447
|
let totalVariancePct = 0;
|
|
411
448
|
for (const event of inWindow) {
|
|
412
449
|
const metrics = event.metrics ?? {};
|
|
413
|
-
const qty =
|
|
450
|
+
const qty = finiteOr(metrics.quantity, 1);
|
|
414
451
|
switch (event.type) {
|
|
415
452
|
case "delivery_received":
|
|
416
453
|
deliveryCount++;
|
|
@@ -421,7 +458,7 @@ function scoreFromEvents(events, period) {
|
|
|
421
458
|
deliveryCount++;
|
|
422
459
|
lateCount++;
|
|
423
460
|
unitsReceived += qty;
|
|
424
|
-
const delay =
|
|
461
|
+
const delay = finiteOr(metrics.delayDays, 0);
|
|
425
462
|
if (delay > 0) totalDelayDays += delay;
|
|
426
463
|
break;
|
|
427
464
|
}
|
|
@@ -430,14 +467,15 @@ function scoreFromEvents(events, period) {
|
|
|
430
467
|
break;
|
|
431
468
|
case "price_variance":
|
|
432
469
|
priceVarianceCount++;
|
|
433
|
-
totalVariancePct +=
|
|
434
|
-
break;
|
|
470
|
+
totalVariancePct += finiteOr(metrics.variancePct, 0);
|
|
435
471
|
}
|
|
436
472
|
}
|
|
437
473
|
const onTimeRate = deliveryCount > 0 ? onTimeCount / deliveryCount : 0;
|
|
438
474
|
const avgDelayDays = lateCount > 0 ? totalDelayDays / lateCount : 0;
|
|
439
|
-
const
|
|
475
|
+
const rawDefectRate = unitsReceived > 0 ? defectiveUnits / unitsReceived : 0;
|
|
476
|
+
const defectRate = Math.min(rawDefectRate, 1);
|
|
440
477
|
const avgPriceVariance = priceVarianceCount > 0 ? totalVariancePct / priceVarianceCount : 0;
|
|
478
|
+
const insufficientSignal = deliveryCount === 0 && unitsReceived === 0 && priceVarianceCount === 0;
|
|
441
479
|
const composite = onTimeRate * COMPOSITE_WEIGHTS.onTime + (1 - defectRate) * COMPOSITE_WEIGHTS.defectFree + (1 - Math.min(Math.abs(avgPriceVariance), 1)) * COMPOSITE_WEIGHTS.pricedToPlan;
|
|
442
480
|
return {
|
|
443
481
|
deliveryCount,
|
|
@@ -447,11 +485,24 @@ function scoreFromEvents(events, period) {
|
|
|
447
485
|
unitsReceived,
|
|
448
486
|
defectiveUnits,
|
|
449
487
|
defectRate: round(defectRate, 4),
|
|
488
|
+
rawDefectRate: round(rawDefectRate, 4),
|
|
450
489
|
priceVarianceCount,
|
|
451
490
|
avgPriceVariance: round(avgPriceVariance, 4),
|
|
452
|
-
compositeScore: round(Math.max(0, Math.min(100, composite * 100)), 2)
|
|
491
|
+
compositeScore: round(Math.max(0, Math.min(100, composite * 100)), 2),
|
|
492
|
+
insufficientSignal
|
|
453
493
|
};
|
|
454
494
|
}
|
|
495
|
+
/**
|
|
496
|
+
* Coerce a possibly-untrusted metric to a finite number, falling back to
|
|
497
|
+
* `fallback` on `NaN`/`Infinity`/non-numeric input. The event `metrics`
|
|
498
|
+
* subdoc is `strict: false`, so a host can persist `quantity: "abc"`; without
|
|
499
|
+
* this guard `Number("abc")` → `NaN` propagates into the composite and lands a
|
|
500
|
+
* `NaN`/CastError on the score doc, poisoning the whole scorecard.
|
|
501
|
+
*/
|
|
502
|
+
function finiteOr(value, fallback) {
|
|
503
|
+
const n = Number(value ?? fallback);
|
|
504
|
+
return Number.isFinite(n) ? n : fallback;
|
|
505
|
+
}
|
|
455
506
|
function round(value, digits) {
|
|
456
507
|
const factor = 10 ** digits;
|
|
457
508
|
return Math.round(value * factor) / factor;
|
|
@@ -484,10 +535,25 @@ var ScoreService = class {
|
|
|
484
535
|
this.logger = config.logger ?? console;
|
|
485
536
|
}
|
|
486
537
|
/**
|
|
487
|
-
* Append a single performance event to the log.
|
|
488
|
-
*
|
|
489
|
-
*
|
|
490
|
-
*
|
|
538
|
+
* Append a single performance event to the log.
|
|
539
|
+
*
|
|
540
|
+
* NOT idempotent by construction — a double-fired host bridge writes two
|
|
541
|
+
* rows and double-counts the delivery. This kernel deliberately does NOT
|
|
542
|
+
* ship a default unique dedup index: hosts key idempotency differently
|
|
543
|
+
* (PO-line, PO+SKU, receipt id), and a blanket unique index would be wrong
|
|
544
|
+
* for all of them (and would reject the many events that legitimately carry
|
|
545
|
+
* no key). HOST REQUIREMENT: to make replays safe, dedup upstream (skip if
|
|
546
|
+
* already recorded) OR add an opt-in partial-unique index on your chosen
|
|
547
|
+
* key, e.g. on `metadata.idempotencyKey` / `sourceRef`:
|
|
548
|
+
*
|
|
549
|
+
* schema.index(
|
|
550
|
+
* { organizationId: 1, 'metadata.idempotencyKey': 1 },
|
|
551
|
+
* { unique: true,
|
|
552
|
+
* partialFilterExpression: { 'metadata.idempotencyKey': { $exists: true } } },
|
|
553
|
+
* );
|
|
554
|
+
*
|
|
555
|
+
* `computeScore` remains fully idempotent regardless — it re-aggregates the
|
|
556
|
+
* current event log and upserts one snapshot per (supplier, period).
|
|
491
557
|
*/
|
|
492
558
|
async recordEvent(input, ctx) {
|
|
493
559
|
if (!input.supplierId) throw new SupplierPerformanceValidationError("supplierId is required");
|
|
@@ -595,63 +661,117 @@ function normalizePeriod(period) {
|
|
|
595
661
|
return period;
|
|
596
662
|
}
|
|
597
663
|
//#endregion
|
|
598
|
-
//#region src/engine/
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
664
|
+
//#region src/engine/define-supplier-performance.ts
|
|
665
|
+
/**
|
|
666
|
+
* `defineSupplierPerformance` — the DESCRIBE/BIND blueprint for the supplier
|
|
667
|
+
* performance engine (STANDARDIZATION-PLAN §6). Splits construction into two
|
|
668
|
+
* phases:
|
|
669
|
+
*
|
|
670
|
+
* - **describe** (`defineSupplierPerformance(shape)`): pure. Resolves the
|
|
671
|
+
* tenant config and freezes the model names via mongokit's `defineModels()`.
|
|
672
|
+
* No connection, no schema built, no I/O — safe at import / module-composition
|
|
673
|
+
* time.
|
|
674
|
+
* - **bind** (`blueprint.bind(connection, runtime)`): compiles the schemas on
|
|
675
|
+
* the supplied connection, registers the models, wires the tenant plugin /
|
|
676
|
+
* repositories / service / transport, and returns the frozen
|
|
677
|
+
* `SupplierPerformanceEngine`.
|
|
678
|
+
*
|
|
679
|
+
* This is the sole construction API — there is no `createSupplierPerformance`
|
|
680
|
+
* wrapper.
|
|
681
|
+
*/
|
|
682
|
+
/**
|
|
683
|
+
* Describe the supplier-performance engine. Pure — registers no model, builds no
|
|
684
|
+
* schema, performs no I/O.
|
|
685
|
+
*/
|
|
686
|
+
function defineSupplierPerformance(shape = {}) {
|
|
687
|
+
/**
|
|
688
|
+
* The pre-consolidation tenant keys are REFUSED, never absorbed.
|
|
689
|
+
*
|
|
690
|
+
* Tenancy resolves from `shape.tenant`, so a leftover `multiTenant` /
|
|
691
|
+
* `tenantFieldType` is invisible here and scoping silently falls back to the
|
|
692
|
+
* package default instead of what the host configured — no error, and every
|
|
693
|
+
* read afterwards returns plausible rows from the wrong scope.
|
|
694
|
+
*
|
|
695
|
+
* tsc cannot cover it: excess-property checking does not fire for a typed
|
|
696
|
+
* variable, a spread, or a shape handed over from a dependency's dist.
|
|
697
|
+
*/
|
|
698
|
+
assertNoLegacyTenantKeys(shape, "defineSupplierPerformance", [["tenantFieldType", "tenant.fieldType"]]);
|
|
699
|
+
const tenant = resolveTenantConfig(shape.tenant);
|
|
700
|
+
if (tenant.strategy === "custom") throw new Error("[supplier-performance] tenant.strategy 'custom' is unsupported: supplier-performance repositories require one concrete tenant field");
|
|
701
|
+
const tenantExtras = typeof shape.tenant === "object" && shape.tenant !== null ? shape.tenant : void 0;
|
|
702
|
+
const modelBlueprint = defineSupplierPerformanceModels({
|
|
605
703
|
tenant,
|
|
606
|
-
...
|
|
607
|
-
...
|
|
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 ?? {};
|
|
625
|
-
const performanceEvent = new PerformanceEventRepository({
|
|
626
|
-
model: models.PerformanceEvent,
|
|
627
|
-
plugins: [...tenantPlugins, ...repoPlugins.performanceEvent ?? []]
|
|
628
|
-
});
|
|
629
|
-
const supplierScore = new SupplierScoreRepository({
|
|
630
|
-
model: models.SupplierScore,
|
|
631
|
-
plugins: [...tenantPlugins, ...repoPlugins.supplierScore ?? []]
|
|
632
|
-
});
|
|
633
|
-
const score = new ScoreService({
|
|
634
|
-
events: performanceEvent,
|
|
635
|
-
scores: supplierScore,
|
|
636
|
-
eventTransport: events,
|
|
637
|
-
...config.outbox !== void 0 ? { outbox: config.outbox } : {},
|
|
638
|
-
logger
|
|
704
|
+
...shape.collectionPrefix !== void 0 ? { collectionPrefix: shape.collectionPrefix } : {},
|
|
705
|
+
...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {},
|
|
706
|
+
...shape.forceRecreate !== void 0 ? { forceRecreate: shape.forceRecreate } : {}
|
|
639
707
|
});
|
|
640
708
|
return {
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
709
|
+
id: "supplier-performance",
|
|
710
|
+
modelNames: modelBlueprint.modelNames,
|
|
711
|
+
bind(connection, runtime = {}) {
|
|
712
|
+
/**
|
|
713
|
+
* §11 outbox atomicity — checked BEFORE the models bind, so a refused bind
|
|
714
|
+
* leaves the connection's model registry untouched.
|
|
715
|
+
*
|
|
716
|
+
* `OutboxWriteOptions.session` is best-effort BY CONTRACT (see
|
|
717
|
+
* `@classytic/primitives/outbox`), so a hand-rolled store satisfies
|
|
718
|
+
* `OutboxStore` and then keeps the row when the transaction aborts:
|
|
719
|
+
* a delivery/defect signal that survives a rolled-back write scores a supplier on an
|
|
720
|
+
* event that never happened — and scorecards drive sourcing decisions and penalties.
|
|
721
|
+
* Nothing throws on either side — the divergence only ever shows up
|
|
722
|
+
* downstream, as a consumer acting on something that never happened.
|
|
723
|
+
*
|
|
724
|
+
* Discovering that in production is far worse than at boot.
|
|
725
|
+
*/
|
|
726
|
+
if (runtime.outbox && runtime.outbox.transactionalSave !== true) throw new Error("defineSupplierPerformance.bind: the configured OutboxStore does not declare `transactionalSave: true`, so it does not promise that `save()` enlists `ctx.session` (see @classytic/primitives/outbox — the option is best-effort by contract). Supplier-performance writes its event rows inside the transaction of its caller; a store that ignores the session scores suppliers on signals that rolled back, so a scorecard — which drives sourcing decisions and contractual penalties — is computed from deliveries that were never recorded. Arc's `repositoryAsOutboxStore` declares it; the in-memory `MemoryOutboxStore` must not — pass no outbox instead.");
|
|
727
|
+
const models = modelBlueprint.bind(connection);
|
|
728
|
+
const logger = runtime.logger ?? console;
|
|
729
|
+
const ownsTransport = runtime.eventTransport === void 0;
|
|
730
|
+
const transport = runtime.eventTransport ?? new InProcessSupplierPerformanceBus({ logger });
|
|
731
|
+
const tenantPlugins = !tenant.enabled || tenant.strategy !== "field" ? [] : [multiTenantPlugin({
|
|
732
|
+
tenantField: tenant.tenantField,
|
|
733
|
+
fieldType: tenant.fieldType,
|
|
734
|
+
contextKey: tenant.contextKey,
|
|
735
|
+
required: tenant.required,
|
|
736
|
+
...tenantExtras?.skipOperations !== void 0 ? { skipOperations: tenantExtras.skipOperations } : {},
|
|
737
|
+
...tenantExtras?.skipWhen !== void 0 ? { skipWhen: tenantExtras.skipWhen } : {},
|
|
738
|
+
...tenantExtras?.resolveContext !== void 0 ? { resolveContext: tenantExtras.resolveContext } : {},
|
|
739
|
+
...tenantExtras?.allowDataInjection !== void 0 ? { allowDataInjection: tenantExtras.allowDataInjection } : {},
|
|
740
|
+
...tenantExtras?.onMismatch !== void 0 ? { onMismatch: tenantExtras.onMismatch } : {}
|
|
741
|
+
})];
|
|
742
|
+
const repoPlugins = runtime.repositoryPlugins ?? {};
|
|
743
|
+
const performanceEvent = new PerformanceEventRepository({
|
|
744
|
+
model: models.PerformanceEvent,
|
|
745
|
+
plugins: [...tenantPlugins, ...repoPlugins.performanceEvent ?? []]
|
|
746
|
+
});
|
|
747
|
+
const supplierScore = new SupplierScoreRepository({
|
|
748
|
+
model: models.SupplierScore,
|
|
749
|
+
plugins: [...tenantPlugins, ...repoPlugins.supplierScore ?? []]
|
|
750
|
+
});
|
|
751
|
+
const score = new ScoreService({
|
|
752
|
+
events: performanceEvent,
|
|
753
|
+
scores: supplierScore,
|
|
754
|
+
eventTransport: transport,
|
|
755
|
+
...runtime.outbox !== void 0 ? { outbox: runtime.outbox } : {},
|
|
756
|
+
logger
|
|
757
|
+
});
|
|
758
|
+
return Object.freeze({
|
|
759
|
+
models,
|
|
760
|
+
repositories: Object.freeze({
|
|
761
|
+
performanceEvent,
|
|
762
|
+
supplierScore
|
|
763
|
+
}),
|
|
764
|
+
services: Object.freeze({ score }),
|
|
765
|
+
events: transport,
|
|
766
|
+
async syncIndexes() {
|
|
767
|
+
await Promise.all([models.PerformanceEvent.syncIndexes(), models.SupplierScore.syncIndexes()]);
|
|
768
|
+
},
|
|
769
|
+
async close() {
|
|
770
|
+
if (ownsTransport) await transport.close?.();
|
|
771
|
+
}
|
|
772
|
+
});
|
|
653
773
|
}
|
|
654
774
|
};
|
|
655
775
|
}
|
|
656
776
|
//#endregion
|
|
657
|
-
export { EventRecorded, InProcessSupplierPerformanceBus,
|
|
777
|
+
export { EventRecorded, InProcessSupplierPerformanceBus, PERFORMANCE_EVENT_COLLECTION, PERFORMANCE_EVENT_TYPE_VALUES, PerformanceEventRepository, PerformanceEventType, SUPPLIER_SCORE_COLLECTION, ScoreComputed, ScoreService, SupplierPerformanceError, SupplierPerformanceEvents, SupplierPerformanceValidationError, SupplierScoreRepository, buildPerformanceEventSchema, buildSupplierScoreSchema, createEvent, defineSupplierPerformance, defineSupplierPerformanceModels, injectTenantField, repoOptionsFromCtx, resolveSupplierPerformanceTenant, scoreFromEvents, supplierPerformanceEventDefinitions };
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@classytic/supplier-performance",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Framework-agnostic supplier performance engine — on-time-delivery, defect, and price-variance tracking with append-only event log + cached scorecards. Powered by MongoDB via @classytic/mongokit. Zero framework deps — usable from Arc, Express, Nest, Next.js, or raw Node.",
|
|
5
5
|
"author": "Classytic",
|
|
6
|
-
"license": "
|
|
6
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
7
7
|
"homepage": "https://www.npmjs.com/package/@classytic/supplier-performance",
|
|
8
8
|
"bugs": {
|
|
9
9
|
"url": "https://github.com/classytic/supplier-performance/issues"
|
|
@@ -60,21 +60,22 @@
|
|
|
60
60
|
"release": "npm run push -- main && npm run release:tag && npm publish"
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|
|
63
|
-
"@classytic/mongokit": ">=3.
|
|
64
|
-
"@classytic/
|
|
65
|
-
"@classytic/
|
|
63
|
+
"@classytic/mongokit": ">=3.33.0",
|
|
64
|
+
"@classytic/primitives": ">=0.23.0",
|
|
65
|
+
"@classytic/repo-core": ">=0.24.0",
|
|
66
66
|
"mongoose": ">=9.4.1",
|
|
67
67
|
"zod": ">=4.0.0"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
70
|
"@classytic/dev-tools": "^0.2.0",
|
|
71
|
-
"@classytic/mongokit": "^3.
|
|
72
|
-
"@classytic/
|
|
73
|
-
"@classytic/
|
|
71
|
+
"@classytic/mongokit": "^3.33.0",
|
|
72
|
+
"@classytic/primitives": ">=0.23.0",
|
|
73
|
+
"@classytic/repo-core": ">=0.24.0",
|
|
74
74
|
"@types/node": "^25.5.0",
|
|
75
75
|
"mongodb-memory-server": "^10.2.3",
|
|
76
76
|
"mongoose": "^9.4.1",
|
|
77
|
-
"
|
|
77
|
+
"publint": "^0.3.23",
|
|
78
|
+
"tsdown": "^0.22.14",
|
|
78
79
|
"typescript": "^5.8.2",
|
|
79
80
|
"vitest": "^3.2.4",
|
|
80
81
|
"zod": "^4.0.0"
|