@rytass/wms-module-core 0.1.6 → 0.3.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/README.md CHANGED
@@ -86,8 +86,8 @@ Full documentation is shipped inside this package under the `docs/` directory (a
86
86
 
87
87
  GitHub hosted links (always up-to-date):
88
88
 
89
- - [Integration Guide — §4 Backend setup](https://github.com/Rytass/WMS-Module/blob/main/docs/integration-guide.md#4-backend-setup-nestjs--graphql--typeorm)
90
- - [API Reference — @rytass/wms-module-core](https://github.com/Rytass/WMS-Module/blob/main/docs/api-reference.md#rytasswms-module-core)
89
+ - [Integration Guide — §4 Backend setup](https://github.com/Rytass/WMS-Module/blob/main/libs/graphql/docs/integration-guide.md#4-backend-setup-nestjs--graphql--typeorm)
90
+ - [API Reference — @rytass/wms-module-core](https://github.com/Rytass/WMS-Module/blob/main/libs/graphql/docs/api-reference.md#rytasswms-module-core)
91
91
 
92
92
  ## License
93
93
 
package/index.cjs.js CHANGED
@@ -4,10 +4,54 @@ var tslib = require('tslib');
4
4
  var common = require('@nestjs/common');
5
5
  var wmsBaseNestjsModule = require('@rytass/wms-base-nestjs-module');
6
6
  var typeorm$1 = require('@nestjs/typeorm');
7
+ var node_async_hooks = require('node:async_hooks');
7
8
  var warehouseMap_entity = require('@rytass/wms-base-nestjs-module/models/warehouse-map.entity');
8
9
  var typeorm = require('typeorm');
9
10
  var luxon = require('luxon');
10
11
 
12
+ /**
13
+ * Process-wide async-context store that buffers domain events for the lifetime
14
+ * of a single mutation. Propagates automatically across `await` boundaries
15
+ * (resolver -> service -> cross-service) via the V8 async context, so services
16
+ * collect into the same buffer without threading any context argument.
17
+ */
18
+ const dispatchAls = new node_async_hooks.AsyncLocalStorage();
19
+ /** Push an event into the active scope. No-op when called outside a scope. */
20
+ function collectToScope(event) {
21
+ dispatchAls.getStore()?.buffer.push(event);
22
+ }
23
+ /**
24
+ * Run `fn` inside a dispatch scope. If a scope already exists (nested mutation),
25
+ * joins it and returns `events: null` so only the outermost owner flushes — this
26
+ * guarantees a single post-commit flush after the outermost transaction.
27
+ */
28
+ async function runInDispatchScope(fn) {
29
+ if (dispatchAls.getStore()) {
30
+ const result = await fn();
31
+ return { result, events: null };
32
+ }
33
+ const scope = { buffer: [] };
34
+ const result = await dispatchAls.run(scope, fn);
35
+ return { result, events: scope.buffer };
36
+ }
37
+
38
+ /**
39
+ * Injected into core services so they can record stock domain events at the
40
+ * point a `*_order_change` / state transition is written. Events are buffered
41
+ * in the current dispatch scope and flushed post-commit by the graphql
42
+ * interceptor. Outside a scope (the service called directly as a plain library)
43
+ * this is a silent no-op.
44
+ */
45
+ exports.WmsEventCollector = class WmsEventCollector {
46
+ collect(name, payload) {
47
+ const event = { name, payload };
48
+ collectToScope(event);
49
+ }
50
+ };
51
+ exports.WmsEventCollector = tslib.__decorate([
52
+ common.Injectable()
53
+ ], exports.WmsEventCollector);
54
+
11
55
  const BatchEntity = Symbol('BatchEntity');
12
56
  exports.BatchEntityClass = class BatchEntityClass extends wmsBaseNestjsModule.BatchEntity {
13
57
  groupId;
@@ -2360,8 +2404,8 @@ let ModelsModule = class ModelsModule {
2360
2404
  ModelsModule = tslib.__decorate([
2361
2405
  common.Module({
2362
2406
  imports: [typeorm$1.TypeOrmModule.forFeature(entities.map(([_, entity]) => entity))],
2363
- providers: ResolvedEntitiesProviders,
2364
- exports: [typeorm$1.TypeOrmModule, ...ResolvedEntitiesProviders],
2407
+ providers: [...ResolvedEntitiesProviders, exports.WmsEventCollector],
2408
+ exports: [typeorm$1.TypeOrmModule, ...ResolvedEntitiesProviders, exports.WmsEventCollector],
2365
2409
  })
2366
2410
  ], ModelsModule);
2367
2411
 
@@ -6353,6 +6397,169 @@ exports.WarehouseMapDataService = tslib.__decorate([
6353
6397
  tslib.__metadata("design:paramtypes", [typeorm.DataSource])
6354
6398
  ], exports.WarehouseMapDataService);
6355
6399
 
6400
+ /** DI token holding the resolved {@link WmsEventModuleOptions}. */
6401
+ const WMS_EVENT_OPTIONS = Symbol('WMS_EVENT_OPTIONS');
6402
+ /** DI token for an optional external emitter bridge (e.g. @nestjs/event-emitter). */
6403
+ const WMS_EVENT_EMITTER_BRIDGE = Symbol('WMS_EVENT_EMITTER_BRIDGE');
6404
+ /** DI token for the optional host-neutral actor extractor. */
6405
+ const WMS_ACTOR_EXTRACTOR = Symbol('WMS_ACTOR_EXTRACTOR');
6406
+ /** DI token holding the boolean "enrich stock events" flag (default false). */
6407
+ const WMS_STOCK_ENRICH = Symbol('WMS_STOCK_ENRICH');
6408
+
6409
+ /**
6410
+ * Resolve the `ChangeType` for a change table. Tables whose semantics depend on
6411
+ * the sign of `quantityChanged` (ship / transfer / vendor / customer / hold /
6412
+ * allocate) branch on it; the rest are fixed.
6413
+ */
6414
+ const TABLE_TO_CHANGE_TYPE = new Map([
6415
+ ['receive_inventory_order_changes', () => exports.ChangeType.RECEIVED],
6416
+ [
6417
+ 'ship_inventory_order_changes',
6418
+ (q) => (q > 0 ? exports.ChangeType.IN_SHIPMENT : exports.ChangeType.SHIPPED),
6419
+ ],
6420
+ [
6421
+ 'transfer_order_changes',
6422
+ (q) => (q > 0 ? exports.ChangeType.IN_TRANSFER : exports.ChangeType.TRANSFERRED),
6423
+ ],
6424
+ [
6425
+ 'transfer_vendor_order_changes',
6426
+ (q) => q > 0 ? exports.ChangeType.VENDOR_TRANSFERRED : exports.ChangeType.VENDOR_RETURNED,
6427
+ ],
6428
+ [
6429
+ 'transfer_customer_order_changes',
6430
+ (q) => q > 0 ? exports.ChangeType.CUSTOMER_HELD : exports.ChangeType.CUSTOMER_RETURNED,
6431
+ ],
6432
+ [
6433
+ 'hold_inventory_order_changes',
6434
+ (q) => (q > 0 ? exports.ChangeType.HELD : exports.ChangeType.RELEASED),
6435
+ ],
6436
+ [
6437
+ 'allocate_inventory_order_changes',
6438
+ (q) => (q > 0 ? exports.ChangeType.ALLOCATED : exports.ChangeType.DEALLOCATED),
6439
+ ],
6440
+ ['split_batch_order_changes', () => exports.ChangeType.SPLITTED],
6441
+ ['merge_batch_order_changes', () => exports.ChangeType.MERGED],
6442
+ ['reclassify_inventory_order_changes', () => exports.ChangeType.RECLASSIFIED],
6443
+ ['scrape_order_changes', () => exports.ChangeType.SCRAPED],
6444
+ ]);
6445
+ const CHANGE_TYPE_TO_EVENT = {
6446
+ [exports.ChangeType.RECEIVED]: 'stock.received',
6447
+ [exports.ChangeType.IN_SHIPMENT]: 'stock.in-shipment',
6448
+ [exports.ChangeType.SHIPPED]: 'stock.shipped',
6449
+ [exports.ChangeType.IN_TRANSFER]: 'stock.in-transfer',
6450
+ [exports.ChangeType.TRANSFERRED]: 'stock.transferred',
6451
+ [exports.ChangeType.VENDOR_TRANSFERRED]: 'stock.vendor-transferred',
6452
+ [exports.ChangeType.VENDOR_RETURNED]: 'stock.vendor-returned',
6453
+ [exports.ChangeType.HELD]: 'stock.held',
6454
+ [exports.ChangeType.RELEASED]: 'stock.released',
6455
+ [exports.ChangeType.CUSTOMER_HELD]: 'stock.customer-held',
6456
+ [exports.ChangeType.CUSTOMER_RETURNED]: 'stock.customer-returned',
6457
+ [exports.ChangeType.SPLITTED]: 'stock.splitted',
6458
+ [exports.ChangeType.MERGED]: 'stock.merged',
6459
+ [exports.ChangeType.ALLOCATED]: 'stock.allocated',
6460
+ [exports.ChangeType.DEALLOCATED]: 'stock.deallocated',
6461
+ [exports.ChangeType.RECLASSIFIED]: 'stock.reclassified',
6462
+ [exports.ChangeType.SCRAPED]: 'stock.scraped',
6463
+ };
6464
+ const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
6465
+ /**
6466
+ * Centralized collection of stock domain events. Listens to every
6467
+ * `*_order_change` insert and, using the change table name plus the sign of
6468
+ * `quantityChanged`, derives the `ChangeType` and buffers a `stock.*` event
6469
+ * into the active dispatch scope (flushed post-commit by the graphql
6470
+ * interceptor). This keeps the 12 domain services untouched and automatically
6471
+ * covers any future code path that writes a change row.
6472
+ *
6473
+ * It self-registers on the data source so no global TypeORM `subscribers`
6474
+ * config is required.
6475
+ */
6476
+ let StockChangeSubscriber = class StockChangeSubscriber {
6477
+ collector;
6478
+ enrich;
6479
+ constructor(dataSource, collector, enrich = false) {
6480
+ this.collector = collector;
6481
+ this.enrich = enrich;
6482
+ dataSource.subscribers.push(this);
6483
+ }
6484
+ async afterInsert(event) {
6485
+ const tableName = event.metadata.tableName;
6486
+ const entity = event.entity;
6487
+ if (!entity || typeof entity.id !== 'string') {
6488
+ return;
6489
+ }
6490
+ const quantityDelta = Number(entity.quantityChanged);
6491
+ if (tableName === QUALITY_INSPECTION_TABLE) {
6492
+ const enrichment = this.enrich
6493
+ ? await this.loadItemFields(event, entity.itemId)
6494
+ : undefined;
6495
+ this.collector.collect('stock.inspection-resolved', {
6496
+ orderId: entity.id,
6497
+ itemId: entity.itemId,
6498
+ quantityDelta,
6499
+ changeType: null,
6500
+ inspectionResult: entity.result ?? null,
6501
+ ...enrichment,
6502
+ });
6503
+ return;
6504
+ }
6505
+ const resolveChangeType = TABLE_TO_CHANGE_TYPE.get(tableName);
6506
+ if (!resolveChangeType) {
6507
+ // Not a stock change table — enrich nothing, emit nothing.
6508
+ return;
6509
+ }
6510
+ const changeType = resolveChangeType(quantityDelta);
6511
+ const enrichment = this.enrich
6512
+ ? await this.loadItemFields(event, entity.itemId)
6513
+ : undefined;
6514
+ this.collector.collect(CHANGE_TYPE_TO_EVENT[changeType], {
6515
+ orderId: entity.id,
6516
+ itemId: entity.itemId,
6517
+ quantityDelta,
6518
+ changeType,
6519
+ ...enrichment,
6520
+ });
6521
+ }
6522
+ /**
6523
+ * Load `materialId / batchId / locationId / loaderId` from the change's order
6524
+ * item (one PK lookup, same transaction). Generic across all 12 change tables
6525
+ * via the `item` relation metadata. Returns `undefined` on any miss so the
6526
+ * event still fires with the lazy payload. split/merge/reclassify items carry
6527
+ * no material/batch — those stay null.
6528
+ */
6529
+ async loadItemFields(event, itemId) {
6530
+ try {
6531
+ const itemRelation = event.metadata.relations.find((relation) => relation.propertyName === 'item');
6532
+ if (!itemRelation) {
6533
+ return undefined;
6534
+ }
6535
+ const item = await event.manager
6536
+ .getRepository(itemRelation.inverseEntityMetadata.target)
6537
+ .findOne({ where: { id: itemId } });
6538
+ if (!item) {
6539
+ return undefined;
6540
+ }
6541
+ return {
6542
+ materialId: item.materialId ?? null,
6543
+ batchId: item.batchId ?? null,
6544
+ locationId: item.locationId ?? null,
6545
+ loaderId: item.loaderId ?? null,
6546
+ };
6547
+ }
6548
+ catch {
6549
+ // Enrichment is best-effort; never break the mutation over it.
6550
+ return undefined;
6551
+ }
6552
+ }
6553
+ };
6554
+ StockChangeSubscriber = tslib.__decorate([
6555
+ common.Injectable(),
6556
+ tslib.__param(0, typeorm$1.InjectDataSource()),
6557
+ tslib.__param(2, common.Optional()),
6558
+ tslib.__param(2, common.Inject(WMS_STOCK_ENRICH)),
6559
+ tslib.__metadata("design:paramtypes", [typeorm.DataSource,
6560
+ exports.WmsEventCollector, Object])
6561
+ ], StockChangeSubscriber);
6562
+
6356
6563
  var WmsModuleCoreModule_1;
6357
6564
  const exportDependencies = [
6358
6565
  exports.LoaderService,
@@ -6385,7 +6592,9 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
6385
6592
  imports: [coreModule, ModelsModule],
6386
6593
  providers: [
6387
6594
  ...exportDependencies,
6595
+ StockChangeSubscriber,
6388
6596
  { provide: WMS_CORE_MODULE_OPTIONS, useValue: coreOptions },
6597
+ { provide: WMS_STOCK_ENRICH, useValue: !!coreOptions.enrichStockEvents },
6389
6598
  ],
6390
6599
  exports: [
6391
6600
  ...exportDependencies,
@@ -6396,13 +6605,14 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
6396
6605
  };
6397
6606
  }
6398
6607
  static forRootAsync(options) {
6399
- const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, ...baseOptions } = options;
6608
+ const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, enrichStockEvents, ...baseOptions } = options;
6400
6609
  const coreModule = wmsBaseNestjsModule.WMSBaseModule.forRootAsync(baseOptions);
6401
6610
  return {
6402
6611
  module: WmsModuleCoreModule_1,
6403
6612
  imports: [coreModule, ModelsModule],
6404
6613
  providers: [
6405
6614
  ...exportDependencies,
6615
+ StockChangeSubscriber,
6406
6616
  {
6407
6617
  provide: WMS_CORE_MODULE_OPTIONS,
6408
6618
  useValue: {
@@ -6411,6 +6621,7 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
6411
6621
  defaultLocationKey,
6412
6622
  },
6413
6623
  },
6624
+ { provide: WMS_STOCK_ENRICH, useValue: !!enrichStockEvents },
6414
6625
  ],
6415
6626
  exports: [
6416
6627
  ...exportDependencies,
@@ -6427,6 +6638,64 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = tslib.__decorate([
6427
6638
  })
6428
6639
  ], exports.WmsModuleCoreModule);
6429
6640
 
6641
+ var WmsEventDispatcher_1;
6642
+ /**
6643
+ * Central event dispatcher. Runs consumer before-hooks (which may veto) and,
6644
+ * post-commit, flushes collected events to consumer after-listeners and the
6645
+ * optional emitter bridge. Listener errors are isolated so one failing listener
6646
+ * never blocks the others or the already-committed mutation.
6647
+ */
6648
+ exports.WmsEventDispatcher = WmsEventDispatcher_1 = class WmsEventDispatcher {
6649
+ options;
6650
+ bridge;
6651
+ logger = new common.Logger(WmsEventDispatcher_1.name);
6652
+ constructor(options, bridge = null) {
6653
+ this.options = options;
6654
+ this.bridge = bridge;
6655
+ }
6656
+ /** Whether any hook, listener or bridge is wired (lets the interceptor skip overhead entirely). */
6657
+ isActive() {
6658
+ const { beforeHooks, afterListeners } = this.options;
6659
+ return (!!this.bridge ||
6660
+ (!!beforeHooks && Object.keys(beforeHooks).length > 0) ||
6661
+ (!!afterListeners && Object.keys(afterListeners).length > 0));
6662
+ }
6663
+ /** Invoke the before-hook for an event. A thrown error vetoes the mutation. */
6664
+ async runBeforeHook(context) {
6665
+ const hook = this.options.beforeHooks?.[context.event];
6666
+ if (hook) {
6667
+ await hook(context);
6668
+ }
6669
+ }
6670
+ /** Flush collected events to after-listeners and the emitter bridge (post-commit). */
6671
+ async flush(events) {
6672
+ for (const event of events) {
6673
+ const listener = this.options.afterListeners?.[event.name];
6674
+ if (listener) {
6675
+ try {
6676
+ await listener({ event: event.name, payload: event.payload });
6677
+ }
6678
+ catch (error) {
6679
+ this.logger.error(`WMS after-listener for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
6680
+ }
6681
+ }
6682
+ try {
6683
+ this.bridge?.forward(event);
6684
+ }
6685
+ catch (error) {
6686
+ this.logger.error(`WMS emitter bridge for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
6687
+ }
6688
+ }
6689
+ }
6690
+ };
6691
+ exports.WmsEventDispatcher = WmsEventDispatcher_1 = tslib.__decorate([
6692
+ common.Injectable(),
6693
+ tslib.__param(0, common.Inject(WMS_EVENT_OPTIONS)),
6694
+ tslib.__param(1, common.Optional()),
6695
+ tslib.__param(1, common.Inject(WMS_EVENT_EMITTER_BRIDGE)),
6696
+ tslib.__metadata("design:paramtypes", [Object, Object])
6697
+ ], exports.WmsEventDispatcher);
6698
+
6430
6699
  exports.AllocateInventoryOrderChangeEntity = AllocateInventoryOrderChangeEntity;
6431
6700
  exports.AllocateInventoryOrderEntity = AllocateInventoryOrderEntity;
6432
6701
  exports.AllocateInventoryOrderItemEntity = AllocateInventoryOrderItemEntity;
@@ -6475,5 +6744,11 @@ exports.TransferVendorOrderChangeEntity = TransferVendorOrderChangeEntity;
6475
6744
  exports.TransferVendorOrderEntity = TransferVendorOrderEntity;
6476
6745
  exports.TransferVendorOrderItemEntity = TransferVendorOrderItemEntity;
6477
6746
  exports.UnitEntity = UnitEntity;
6747
+ exports.WMS_ACTOR_EXTRACTOR = WMS_ACTOR_EXTRACTOR;
6478
6748
  exports.WMS_CORE_MODULE_OPTIONS = WMS_CORE_MODULE_OPTIONS;
6749
+ exports.WMS_EVENT_EMITTER_BRIDGE = WMS_EVENT_EMITTER_BRIDGE;
6750
+ exports.WMS_EVENT_OPTIONS = WMS_EVENT_OPTIONS;
6751
+ exports.WMS_STOCK_ENRICH = WMS_STOCK_ENRICH;
6479
6752
  exports.WarehouseMapEntity = WarehouseMapEntity;
6753
+ exports.collectToScope = collectToScope;
6754
+ exports.runInDispatchScope = runInDispatchScope;
package/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export * from './lib/models';
3
3
  export * from './lib/services';
4
4
  export * from './lib/typings';
5
5
  export * from './lib/constants';
6
+ export * from './lib/events';
package/index.js CHANGED
@@ -72,3 +72,7 @@ export { WMS_CORE_MODULE_OPTIONS } from './lib/typings/core-module-options.js';
72
72
  export { ReceiveInventoryOrderStatus } from './lib/typings/find-receive-inventory-order.input.js';
73
73
  export { ShipInventoryOrderStatus } from './lib/typings/find-ship-inventory-order.input.js';
74
74
  export { ChangeType, StockStatus } from './lib/constants/stock-status.js';
75
+ export { WMS_ACTOR_EXTRACTOR, WMS_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS, WMS_STOCK_ENRICH } from './lib/events/wms-event.tokens.js';
76
+ export { WmsEventCollector } from './lib/events/wms-event.collector.js';
77
+ export { WmsEventDispatcher } from './lib/events/wms-event.dispatcher.js';
78
+ export { collectToScope, runInDispatchScope } from './lib/events/dispatch-scope.js';
@@ -23,6 +23,8 @@ import { SaleOrderService } from './services/sale-order.service.js';
23
23
  import { ScrapeService } from './services/scrape.service.js';
24
24
  import { WarehouseMapDataService } from './services/warehouse-map.service.js';
25
25
  import { HelperService } from './services/helper.service.js';
26
+ import { StockChangeSubscriber } from './events/stock-change.subscriber.js';
27
+ import { WMS_STOCK_ENRICH } from './events/wms-event.tokens.js';
26
28
  import { WMS_CORE_MODULE_OPTIONS } from './typings/core-module-options.js';
27
29
 
28
30
  var WmsModuleCoreModule_1;
@@ -57,7 +59,9 @@ let WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule {
57
59
  imports: [coreModule, ModelsModule],
58
60
  providers: [
59
61
  ...exportDependencies,
62
+ StockChangeSubscriber,
60
63
  { provide: WMS_CORE_MODULE_OPTIONS, useValue: coreOptions },
64
+ { provide: WMS_STOCK_ENRICH, useValue: !!coreOptions.enrichStockEvents },
61
65
  ],
62
66
  exports: [
63
67
  ...exportDependencies,
@@ -68,13 +72,14 @@ let WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule {
68
72
  };
69
73
  }
70
74
  static forRootAsync(options) {
71
- const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, ...baseOptions } = options;
75
+ const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, enrichStockEvents, ...baseOptions } = options;
72
76
  const coreModule = WMSBaseModule.forRootAsync(baseOptions);
73
77
  return {
74
78
  module: WmsModuleCoreModule_1,
75
79
  imports: [coreModule, ModelsModule],
76
80
  providers: [
77
81
  ...exportDependencies,
82
+ StockChangeSubscriber,
78
83
  {
79
84
  provide: WMS_CORE_MODULE_OPTIONS,
80
85
  useValue: {
@@ -83,6 +88,7 @@ let WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule {
83
88
  defaultLocationKey,
84
89
  },
85
90
  },
91
+ { provide: WMS_STOCK_ENRICH, useValue: !!enrichStockEvents },
86
92
  ],
87
93
  exports: [
88
94
  ...exportDependencies,
@@ -0,0 +1,18 @@
1
+ import type { WmsDomainEvent } from './wms-event.types';
2
+ /** Push an event into the active scope. No-op when called outside a scope. */
3
+ export declare function collectToScope(event: WmsDomainEvent): void;
4
+ export interface DispatchScopeResult<T> {
5
+ readonly result: T;
6
+ /**
7
+ * The collected events when this call **owns** the outermost scope (caller
8
+ * must flush them), or `null` when joining an existing outer scope (the outer
9
+ * owner flushes).
10
+ */
11
+ readonly events: readonly WmsDomainEvent[] | null;
12
+ }
13
+ /**
14
+ * Run `fn` inside a dispatch scope. If a scope already exists (nested mutation),
15
+ * joins it and returns `events: null` so only the outermost owner flushes — this
16
+ * guarantees a single post-commit flush after the outermost transaction.
17
+ */
18
+ export declare function runInDispatchScope<T>(fn: () => Promise<T>): Promise<DispatchScopeResult<T>>;
@@ -0,0 +1,29 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+
3
+ /**
4
+ * Process-wide async-context store that buffers domain events for the lifetime
5
+ * of a single mutation. Propagates automatically across `await` boundaries
6
+ * (resolver -> service -> cross-service) via the V8 async context, so services
7
+ * collect into the same buffer without threading any context argument.
8
+ */
9
+ const dispatchAls = new AsyncLocalStorage();
10
+ /** Push an event into the active scope. No-op when called outside a scope. */
11
+ function collectToScope(event) {
12
+ dispatchAls.getStore()?.buffer.push(event);
13
+ }
14
+ /**
15
+ * Run `fn` inside a dispatch scope. If a scope already exists (nested mutation),
16
+ * joins it and returns `events: null` so only the outermost owner flushes — this
17
+ * guarantees a single post-commit flush after the outermost transaction.
18
+ */
19
+ async function runInDispatchScope(fn) {
20
+ if (dispatchAls.getStore()) {
21
+ const result = await fn();
22
+ return { result, events: null };
23
+ }
24
+ const scope = { buffer: [] };
25
+ const result = await dispatchAls.run(scope, fn);
26
+ return { result, events: scope.buffer };
27
+ }
28
+
29
+ export { collectToScope, runInDispatchScope };
@@ -0,0 +1,5 @@
1
+ export { WMS_ACTOR_EXTRACTOR, WMS_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS, WMS_STOCK_ENRICH, } from './wms-event.tokens';
2
+ export { WmsEventCollector } from './wms-event.collector';
3
+ export { WmsEventDispatcher } from './wms-event.dispatcher';
4
+ export { collectToScope, runInDispatchScope, type DispatchScopeResult, } from './dispatch-scope';
5
+ export type { WmsActor, WmsActorExtractor, WmsAfterEventContext, WmsAfterListener, WmsAfterListenerMap, WmsBeforeHook, WmsBeforeHookContext, WmsBeforeHookMap, WmsDomainEvent, WmsEventEmitterBridge, WmsEventModuleOptions, WmsEventName, WmsEventPayloadMap, WmsOperationEventName, WmsOperationEventPayload, WmsStockEventName, WmsStockEventPayload, } from './wms-event.types';
@@ -0,0 +1,27 @@
1
+ import { DataSource, type EntitySubscriberInterface, type InsertEvent } from 'typeorm';
2
+ import { WmsEventCollector } from './wms-event.collector';
3
+ /**
4
+ * Centralized collection of stock domain events. Listens to every
5
+ * `*_order_change` insert and, using the change table name plus the sign of
6
+ * `quantityChanged`, derives the `ChangeType` and buffers a `stock.*` event
7
+ * into the active dispatch scope (flushed post-commit by the graphql
8
+ * interceptor). This keeps the 12 domain services untouched and automatically
9
+ * covers any future code path that writes a change row.
10
+ *
11
+ * It self-registers on the data source so no global TypeORM `subscribers`
12
+ * config is required.
13
+ */
14
+ export declare class StockChangeSubscriber implements EntitySubscriberInterface {
15
+ private readonly collector;
16
+ private readonly enrich;
17
+ constructor(dataSource: DataSource, collector: WmsEventCollector, enrich?: boolean);
18
+ afterInsert(event: InsertEvent<unknown>): Promise<void>;
19
+ /**
20
+ * Load `materialId / batchId / locationId / loaderId` from the change's order
21
+ * item (one PK lookup, same transaction). Generic across all 12 change tables
22
+ * via the `item` relation metadata. Returns `undefined` on any miss so the
23
+ * event still fires with the lazy payload. split/merge/reclassify items carry
24
+ * no material/batch — those stay null.
25
+ */
26
+ private loadItemFields;
27
+ }
@@ -0,0 +1,163 @@
1
+ import { __decorate, __param, __metadata } from 'tslib';
2
+ import { Injectable, Optional, Inject } from '@nestjs/common';
3
+ import { InjectDataSource } from '@nestjs/typeorm';
4
+ import { DataSource } from 'typeorm';
5
+ import { ChangeType } from '../constants/stock-status.js';
6
+ import { WmsEventCollector } from './wms-event.collector.js';
7
+ import { WMS_STOCK_ENRICH } from './wms-event.tokens.js';
8
+
9
+ /**
10
+ * Resolve the `ChangeType` for a change table. Tables whose semantics depend on
11
+ * the sign of `quantityChanged` (ship / transfer / vendor / customer / hold /
12
+ * allocate) branch on it; the rest are fixed.
13
+ */
14
+ const TABLE_TO_CHANGE_TYPE = new Map([
15
+ ['receive_inventory_order_changes', () => ChangeType.RECEIVED],
16
+ [
17
+ 'ship_inventory_order_changes',
18
+ (q) => (q > 0 ? ChangeType.IN_SHIPMENT : ChangeType.SHIPPED),
19
+ ],
20
+ [
21
+ 'transfer_order_changes',
22
+ (q) => (q > 0 ? ChangeType.IN_TRANSFER : ChangeType.TRANSFERRED),
23
+ ],
24
+ [
25
+ 'transfer_vendor_order_changes',
26
+ (q) => q > 0 ? ChangeType.VENDOR_TRANSFERRED : ChangeType.VENDOR_RETURNED,
27
+ ],
28
+ [
29
+ 'transfer_customer_order_changes',
30
+ (q) => q > 0 ? ChangeType.CUSTOMER_HELD : ChangeType.CUSTOMER_RETURNED,
31
+ ],
32
+ [
33
+ 'hold_inventory_order_changes',
34
+ (q) => (q > 0 ? ChangeType.HELD : ChangeType.RELEASED),
35
+ ],
36
+ [
37
+ 'allocate_inventory_order_changes',
38
+ (q) => (q > 0 ? ChangeType.ALLOCATED : ChangeType.DEALLOCATED),
39
+ ],
40
+ ['split_batch_order_changes', () => ChangeType.SPLITTED],
41
+ ['merge_batch_order_changes', () => ChangeType.MERGED],
42
+ ['reclassify_inventory_order_changes', () => ChangeType.RECLASSIFIED],
43
+ ['scrape_order_changes', () => ChangeType.SCRAPED],
44
+ ]);
45
+ const CHANGE_TYPE_TO_EVENT = {
46
+ [ChangeType.RECEIVED]: 'stock.received',
47
+ [ChangeType.IN_SHIPMENT]: 'stock.in-shipment',
48
+ [ChangeType.SHIPPED]: 'stock.shipped',
49
+ [ChangeType.IN_TRANSFER]: 'stock.in-transfer',
50
+ [ChangeType.TRANSFERRED]: 'stock.transferred',
51
+ [ChangeType.VENDOR_TRANSFERRED]: 'stock.vendor-transferred',
52
+ [ChangeType.VENDOR_RETURNED]: 'stock.vendor-returned',
53
+ [ChangeType.HELD]: 'stock.held',
54
+ [ChangeType.RELEASED]: 'stock.released',
55
+ [ChangeType.CUSTOMER_HELD]: 'stock.customer-held',
56
+ [ChangeType.CUSTOMER_RETURNED]: 'stock.customer-returned',
57
+ [ChangeType.SPLITTED]: 'stock.splitted',
58
+ [ChangeType.MERGED]: 'stock.merged',
59
+ [ChangeType.ALLOCATED]: 'stock.allocated',
60
+ [ChangeType.DEALLOCATED]: 'stock.deallocated',
61
+ [ChangeType.RECLASSIFIED]: 'stock.reclassified',
62
+ [ChangeType.SCRAPED]: 'stock.scraped',
63
+ };
64
+ const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
65
+ /**
66
+ * Centralized collection of stock domain events. Listens to every
67
+ * `*_order_change` insert and, using the change table name plus the sign of
68
+ * `quantityChanged`, derives the `ChangeType` and buffers a `stock.*` event
69
+ * into the active dispatch scope (flushed post-commit by the graphql
70
+ * interceptor). This keeps the 12 domain services untouched and automatically
71
+ * covers any future code path that writes a change row.
72
+ *
73
+ * It self-registers on the data source so no global TypeORM `subscribers`
74
+ * config is required.
75
+ */
76
+ let StockChangeSubscriber = class StockChangeSubscriber {
77
+ collector;
78
+ enrich;
79
+ constructor(dataSource, collector, enrich = false) {
80
+ this.collector = collector;
81
+ this.enrich = enrich;
82
+ dataSource.subscribers.push(this);
83
+ }
84
+ async afterInsert(event) {
85
+ const tableName = event.metadata.tableName;
86
+ const entity = event.entity;
87
+ if (!entity || typeof entity.id !== 'string') {
88
+ return;
89
+ }
90
+ const quantityDelta = Number(entity.quantityChanged);
91
+ if (tableName === QUALITY_INSPECTION_TABLE) {
92
+ const enrichment = this.enrich
93
+ ? await this.loadItemFields(event, entity.itemId)
94
+ : undefined;
95
+ this.collector.collect('stock.inspection-resolved', {
96
+ orderId: entity.id,
97
+ itemId: entity.itemId,
98
+ quantityDelta,
99
+ changeType: null,
100
+ inspectionResult: entity.result ?? null,
101
+ ...enrichment,
102
+ });
103
+ return;
104
+ }
105
+ const resolveChangeType = TABLE_TO_CHANGE_TYPE.get(tableName);
106
+ if (!resolveChangeType) {
107
+ // Not a stock change table — enrich nothing, emit nothing.
108
+ return;
109
+ }
110
+ const changeType = resolveChangeType(quantityDelta);
111
+ const enrichment = this.enrich
112
+ ? await this.loadItemFields(event, entity.itemId)
113
+ : undefined;
114
+ this.collector.collect(CHANGE_TYPE_TO_EVENT[changeType], {
115
+ orderId: entity.id,
116
+ itemId: entity.itemId,
117
+ quantityDelta,
118
+ changeType,
119
+ ...enrichment,
120
+ });
121
+ }
122
+ /**
123
+ * Load `materialId / batchId / locationId / loaderId` from the change's order
124
+ * item (one PK lookup, same transaction). Generic across all 12 change tables
125
+ * via the `item` relation metadata. Returns `undefined` on any miss so the
126
+ * event still fires with the lazy payload. split/merge/reclassify items carry
127
+ * no material/batch — those stay null.
128
+ */
129
+ async loadItemFields(event, itemId) {
130
+ try {
131
+ const itemRelation = event.metadata.relations.find((relation) => relation.propertyName === 'item');
132
+ if (!itemRelation) {
133
+ return undefined;
134
+ }
135
+ const item = await event.manager
136
+ .getRepository(itemRelation.inverseEntityMetadata.target)
137
+ .findOne({ where: { id: itemId } });
138
+ if (!item) {
139
+ return undefined;
140
+ }
141
+ return {
142
+ materialId: item.materialId ?? null,
143
+ batchId: item.batchId ?? null,
144
+ locationId: item.locationId ?? null,
145
+ loaderId: item.loaderId ?? null,
146
+ };
147
+ }
148
+ catch {
149
+ // Enrichment is best-effort; never break the mutation over it.
150
+ return undefined;
151
+ }
152
+ }
153
+ };
154
+ StockChangeSubscriber = __decorate([
155
+ Injectable(),
156
+ __param(0, InjectDataSource()),
157
+ __param(2, Optional()),
158
+ __param(2, Inject(WMS_STOCK_ENRICH)),
159
+ __metadata("design:paramtypes", [DataSource,
160
+ WmsEventCollector, Object])
161
+ ], StockChangeSubscriber);
162
+
163
+ export { StockChangeSubscriber };
@@ -0,0 +1,11 @@
1
+ import type { WmsEventName, WmsEventPayloadMap } from './wms-event.types';
2
+ /**
3
+ * Injected into core services so they can record stock domain events at the
4
+ * point a `*_order_change` / state transition is written. Events are buffered
5
+ * in the current dispatch scope and flushed post-commit by the graphql
6
+ * interceptor. Outside a scope (the service called directly as a plain library)
7
+ * this is a silent no-op.
8
+ */
9
+ export declare class WmsEventCollector {
10
+ collect<N extends WmsEventName>(name: N, payload: WmsEventPayloadMap[N]): void;
11
+ }
@@ -0,0 +1,22 @@
1
+ import { __decorate } from 'tslib';
2
+ import { Injectable } from '@nestjs/common';
3
+ import { collectToScope } from './dispatch-scope.js';
4
+
5
+ /**
6
+ * Injected into core services so they can record stock domain events at the
7
+ * point a `*_order_change` / state transition is written. Events are buffered
8
+ * in the current dispatch scope and flushed post-commit by the graphql
9
+ * interceptor. Outside a scope (the service called directly as a plain library)
10
+ * this is a silent no-op.
11
+ */
12
+ let WmsEventCollector = class WmsEventCollector {
13
+ collect(name, payload) {
14
+ const event = { name, payload };
15
+ collectToScope(event);
16
+ }
17
+ };
18
+ WmsEventCollector = __decorate([
19
+ Injectable()
20
+ ], WmsEventCollector);
21
+
22
+ export { WmsEventCollector };
@@ -0,0 +1,19 @@
1
+ import type { WmsBeforeHookContext, WmsDomainEvent, WmsEventEmitterBridge, WmsEventModuleOptions } from './wms-event.types';
2
+ /**
3
+ * Central event dispatcher. Runs consumer before-hooks (which may veto) and,
4
+ * post-commit, flushes collected events to consumer after-listeners and the
5
+ * optional emitter bridge. Listener errors are isolated so one failing listener
6
+ * never blocks the others or the already-committed mutation.
7
+ */
8
+ export declare class WmsEventDispatcher {
9
+ private readonly options;
10
+ private readonly bridge;
11
+ private readonly logger;
12
+ constructor(options: WmsEventModuleOptions, bridge?: WmsEventEmitterBridge | null);
13
+ /** Whether any hook, listener or bridge is wired (lets the interceptor skip overhead entirely). */
14
+ isActive(): boolean;
15
+ /** Invoke the before-hook for an event. A thrown error vetoes the mutation. */
16
+ runBeforeHook(context: WmsBeforeHookContext): Promise<void>;
17
+ /** Flush collected events to after-listeners and the emitter bridge (post-commit). */
18
+ flush(events: readonly WmsDomainEvent[]): Promise<void>;
19
+ }
@@ -0,0 +1,63 @@
1
+ import { __decorate, __param, __metadata } from 'tslib';
2
+ import { Injectable, Inject, Optional, Logger } from '@nestjs/common';
3
+ import { WMS_EVENT_OPTIONS, WMS_EVENT_EMITTER_BRIDGE } from './wms-event.tokens.js';
4
+
5
+ var WmsEventDispatcher_1;
6
+ /**
7
+ * Central event dispatcher. Runs consumer before-hooks (which may veto) and,
8
+ * post-commit, flushes collected events to consumer after-listeners and the
9
+ * optional emitter bridge. Listener errors are isolated so one failing listener
10
+ * never blocks the others or the already-committed mutation.
11
+ */
12
+ let WmsEventDispatcher = WmsEventDispatcher_1 = class WmsEventDispatcher {
13
+ options;
14
+ bridge;
15
+ logger = new Logger(WmsEventDispatcher_1.name);
16
+ constructor(options, bridge = null) {
17
+ this.options = options;
18
+ this.bridge = bridge;
19
+ }
20
+ /** Whether any hook, listener or bridge is wired (lets the interceptor skip overhead entirely). */
21
+ isActive() {
22
+ const { beforeHooks, afterListeners } = this.options;
23
+ return (!!this.bridge ||
24
+ (!!beforeHooks && Object.keys(beforeHooks).length > 0) ||
25
+ (!!afterListeners && Object.keys(afterListeners).length > 0));
26
+ }
27
+ /** Invoke the before-hook for an event. A thrown error vetoes the mutation. */
28
+ async runBeforeHook(context) {
29
+ const hook = this.options.beforeHooks?.[context.event];
30
+ if (hook) {
31
+ await hook(context);
32
+ }
33
+ }
34
+ /** Flush collected events to after-listeners and the emitter bridge (post-commit). */
35
+ async flush(events) {
36
+ for (const event of events) {
37
+ const listener = this.options.afterListeners?.[event.name];
38
+ if (listener) {
39
+ try {
40
+ await listener({ event: event.name, payload: event.payload });
41
+ }
42
+ catch (error) {
43
+ this.logger.error(`WMS after-listener for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
44
+ }
45
+ }
46
+ try {
47
+ this.bridge?.forward(event);
48
+ }
49
+ catch (error) {
50
+ this.logger.error(`WMS emitter bridge for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
51
+ }
52
+ }
53
+ }
54
+ };
55
+ WmsEventDispatcher = WmsEventDispatcher_1 = __decorate([
56
+ Injectable(),
57
+ __param(0, Inject(WMS_EVENT_OPTIONS)),
58
+ __param(1, Optional()),
59
+ __param(1, Inject(WMS_EVENT_EMITTER_BRIDGE)),
60
+ __metadata("design:paramtypes", [Object, Object])
61
+ ], WmsEventDispatcher);
62
+
63
+ export { WmsEventDispatcher };
@@ -0,0 +1,8 @@
1
+ /** DI token holding the resolved {@link WmsEventModuleOptions}. */
2
+ export declare const WMS_EVENT_OPTIONS: unique symbol;
3
+ /** DI token for an optional external emitter bridge (e.g. @nestjs/event-emitter). */
4
+ export declare const WMS_EVENT_EMITTER_BRIDGE: unique symbol;
5
+ /** DI token for the optional host-neutral actor extractor. */
6
+ export declare const WMS_ACTOR_EXTRACTOR: unique symbol;
7
+ /** DI token holding the boolean "enrich stock events" flag (default false). */
8
+ export declare const WMS_STOCK_ENRICH: unique symbol;
@@ -0,0 +1,10 @@
1
+ /** DI token holding the resolved {@link WmsEventModuleOptions}. */
2
+ const WMS_EVENT_OPTIONS = Symbol('WMS_EVENT_OPTIONS');
3
+ /** DI token for an optional external emitter bridge (e.g. @nestjs/event-emitter). */
4
+ const WMS_EVENT_EMITTER_BRIDGE = Symbol('WMS_EVENT_EMITTER_BRIDGE');
5
+ /** DI token for the optional host-neutral actor extractor. */
6
+ const WMS_ACTOR_EXTRACTOR = Symbol('WMS_ACTOR_EXTRACTOR');
7
+ /** DI token holding the boolean "enrich stock events" flag (default false). */
8
+ const WMS_STOCK_ENRICH = Symbol('WMS_STOCK_ENRICH');
9
+
10
+ export { WMS_ACTOR_EXTRACTOR, WMS_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS, WMS_STOCK_ENRICH };
@@ -0,0 +1,130 @@
1
+ import type { ExecutionContext } from '@nestjs/common';
2
+ import type { ChangeType } from '../constants/stock-status';
3
+ /**
4
+ * Host-neutral event/hook contracts for WMS mutations.
5
+ *
6
+ * Two tiers of events:
7
+ * - **Operation events** (`<domain>.<past-tense-action>`): exactly one per root
8
+ * mutation, emitted by the GraphQL interceptor after the handler resolves
9
+ * (post-commit) carrying the operation result.
10
+ * - **Stock domain events** (`stock.<change-type>`): driven by the `ChangeType`
11
+ * state machine, collected inside core services (possibly many per operation)
12
+ * and flushed post-commit.
13
+ *
14
+ * The library never knows what a consumer does with these — it only declares the
15
+ * names and payloads. Wiring is opt-in via `forRootAsync({ beforeHooks,
16
+ * afterListeners })`; when nothing is configured the whole chain is inert.
17
+ */
18
+ export type WmsOperationEventName = 'receive-inventory-order.created' | 'receive-inventory-order.updated' | 'receive-inventory-order.received' | 'ship-inventory-order.created' | 'ship-inventory-order.updated' | 'ship-inventory-order.shipped' | 'ship-inventory-order.ship-cancelled' | 'transfer-order.created' | 'transfer-order.updated' | 'transfer-order.transferred' | 'transfer-order.transfer-cancelled' | 'hold-inventory-order.created' | 'hold-inventory-order.updated' | 'hold-inventory-order.released' | 'allocate-inventory-order.created' | 'allocate-inventory-order.updated' | 'allocate-inventory-order.deallocated' | 'transfer-vendor-order.created' | 'transfer-vendor-order.updated' | 'transfer-vendor-order.returned' | 'transfer-customer-order.created' | 'transfer-customer-order.updated' | 'transfer-customer-order.returned' | 'quality-inspection-order.inspected' | 'scrape-order.scraped' | 'reclassify-inventory-order.reclassified' | 'batch.merged' | 'batch.splitted' | 'material.created' | 'material.updated' | 'loader.created' | 'loader.batch-created' | 'loader.updated' | 'loader.type-created' | 'loader.type-updated' | 'location.created' | 'location.updated' | 'warehouse-map.updated';
19
+ export type WmsStockEventName = 'stock.received' | 'stock.in-shipment' | 'stock.shipped' | 'stock.in-transfer' | 'stock.transferred' | 'stock.vendor-transferred' | 'stock.vendor-returned' | 'stock.held' | 'stock.released' | 'stock.customer-held' | 'stock.customer-returned' | 'stock.splitted' | 'stock.merged' | 'stock.allocated' | 'stock.deallocated' | 'stock.reclassified' | 'stock.scraped' | 'stock.inspection-resolved';
20
+ export type WmsEventName = WmsOperationEventName | WmsStockEventName;
21
+ /**
22
+ * The authenticated identity that performed a mutation, in a host-neutral shape.
23
+ * Populated by a consumer-supplied {@link WmsActorExtractor}; `null` when no
24
+ * extractor is configured or the request is unauthenticated.
25
+ */
26
+ export interface WmsActor {
27
+ readonly id: string;
28
+ readonly domain?: string;
29
+ /** Host-specific extras (e.g. the raw token payload), if the extractor adds them. */
30
+ readonly raw?: unknown;
31
+ }
32
+ /**
33
+ * Host-neutral function that derives the current {@link WmsActor} from the
34
+ * NestJS execution context. Wired via `forRootAsync({ actorExtractor })`; the
35
+ * `@rytass/wms-module-graphql/adapters/member-base` entrypoint ships a default.
36
+ */
37
+ export type WmsActorExtractor = (context: ExecutionContext) => WmsActor | null;
38
+ /**
39
+ * Payload for an operation event. `id` is the primary key of the operation's
40
+ * main entity/order (correlation id shared with the stock events it fans out
41
+ * to); `result` is the mutation's return value (a DTO, or `boolean` for action
42
+ * mutations); `args` is the raw GraphQL input (the intent — useful for action
43
+ * mutations whose `result` is just `boolean`); `actor` is who performed it.
44
+ */
45
+ export interface WmsOperationEventPayload<TResult = unknown> {
46
+ readonly id: string | null;
47
+ readonly result: TResult;
48
+ readonly args: Readonly<Record<string, unknown>>;
49
+ readonly actor: WmsActor | null;
50
+ }
51
+ /**
52
+ * Payload for a stock domain event, built from the inserted `*_order_change`
53
+ * row. These four fields are reliably available the moment the change is
54
+ * written (no extra query). For richer batch/material/location details a
55
+ * listener can look them up by `orderId` / `itemId` after commit.
56
+ */
57
+ export interface WmsStockEventPayload {
58
+ /** Base order id (`change.id`) — correlation id shared with the operation event. */
59
+ readonly orderId: string;
60
+ /** The order item this change applies to (`change.itemId`). */
61
+ readonly itemId: string;
62
+ /** `change.quantityChanged` — sign carries direction (in: +, out: -). */
63
+ readonly quantityDelta: number;
64
+ /** The resolved `ChangeType` for this stock movement (null for inspection). */
65
+ readonly changeType: ChangeType | null;
66
+ /** Quality-inspection result, present only on `stock.inspection-resolved`. */
67
+ readonly inspectionResult?: boolean | null;
68
+ readonly materialId?: string | null;
69
+ readonly batchId?: string | null;
70
+ readonly locationId?: string | null;
71
+ readonly loaderId?: string | null;
72
+ }
73
+ /** Maps every event name to its payload type. */
74
+ export type WmsEventPayloadMap = {
75
+ readonly [N in WmsOperationEventName]: WmsOperationEventPayload;
76
+ } & {
77
+ readonly [N in WmsStockEventName]: WmsStockEventPayload;
78
+ };
79
+ /** A collected domain event: a name plus its typed payload. */
80
+ export interface WmsDomainEvent<N extends WmsEventName = WmsEventName> {
81
+ readonly name: N;
82
+ readonly payload: WmsEventPayloadMap[N];
83
+ }
84
+ /**
85
+ * Context handed to a before-hook. Runs *before* any DB work, so it sees the
86
+ * mutation **intent** (raw GraphQL arguments) rather than a result. Throwing
87
+ * vetoes the whole mutation with zero side effects.
88
+ */
89
+ export interface WmsBeforeHookContext<N extends WmsEventName = WmsEventName> {
90
+ readonly event: N;
91
+ readonly args: Readonly<Record<string, unknown>>;
92
+ readonly executionContext: ExecutionContext;
93
+ readonly actor: WmsActor | null;
94
+ }
95
+ /** Context handed to an after-listener. Runs post-commit with the event payload. */
96
+ export interface WmsAfterEventContext<N extends WmsEventName = WmsEventName> {
97
+ readonly event: N;
98
+ readonly payload: WmsEventPayloadMap[N];
99
+ }
100
+ export type WmsBeforeHook<N extends WmsEventName = WmsEventName> = (context: WmsBeforeHookContext<N>) => void | Promise<void>;
101
+ export type WmsAfterListener<N extends WmsEventName = WmsEventName> = (context: WmsAfterEventContext<N>) => void | Promise<void>;
102
+ export type WmsBeforeHookMap = {
103
+ readonly [N in WmsEventName]?: WmsBeforeHook<N>;
104
+ };
105
+ export type WmsAfterListenerMap = {
106
+ readonly [N in WmsEventName]?: WmsAfterListener<N>;
107
+ };
108
+ /**
109
+ * Event options merged into the module options. All optional — omit everything
110
+ * to keep the module inert (pre-event behaviour).
111
+ */
112
+ export interface WmsEventModuleOptions {
113
+ readonly beforeHooks?: WmsBeforeHookMap;
114
+ readonly afterListeners?: WmsAfterListenerMap;
115
+ /**
116
+ * When `true`, stock events are enriched (in the same transaction, one PK
117
+ * lookup per event) with `materialId / batchId / locationId / loaderId` from
118
+ * the change's order item. Off by default (lazy: ids only). See
119
+ * {@link WmsActorExtractor} for the separately-wired actor.
120
+ */
121
+ readonly enrichStockEvents?: boolean;
122
+ }
123
+ /**
124
+ * Runtime bridge to an external emitter (e.g. `@nestjs/event-emitter`). The
125
+ * graphql package provides an implementation; when absent, dispatch simply
126
+ * skips it.
127
+ */
128
+ export interface WmsEventEmitterBridge {
129
+ forward(event: WmsDomainEvent): void;
130
+ }
@@ -1,6 +1,7 @@
1
1
  import { __decorate } from 'tslib';
2
2
  import { Module } from '@nestjs/common';
3
3
  import { TypeOrmModule } from '@nestjs/typeorm';
4
+ import { WmsEventCollector } from '../events/wms-event.collector.js';
4
5
  import { WarehouseMapEntity as WarehouseMapEntity$1 } from '@rytass/wms-base-nestjs-module/models/warehouse-map.entity';
5
6
  import { BatchEntity, BatchEntityClass } from './metadata/batch.entity.js';
6
7
  import { BatchGroupEntity, BatchGroupEntityClass } from './metadata/batch-group.entity.js';
@@ -114,8 +115,8 @@ let ModelsModule = class ModelsModule {
114
115
  ModelsModule = __decorate([
115
116
  Module({
116
117
  imports: [TypeOrmModule.forFeature(entities.map(([_, entity]) => entity))],
117
- providers: ResolvedEntitiesProviders,
118
- exports: [TypeOrmModule, ...ResolvedEntitiesProviders],
118
+ providers: [...ResolvedEntitiesProviders, WmsEventCollector],
119
+ exports: [TypeOrmModule, ...ResolvedEntitiesProviders, WmsEventCollector],
119
120
  })
120
121
  ], ModelsModule);
121
122
 
@@ -4,5 +4,12 @@ export interface WmsModuleCoreModuleOptions {
4
4
  defaultLoaderSerialId: string;
5
5
  defaultLoaderTypeKey: string;
6
6
  defaultLocationKey: string;
7
+ /**
8
+ * When `true`, stock domain events are enriched (one PK lookup per event, same
9
+ * transaction) with `materialId / batchId / locationId / loaderId` from the
10
+ * change's order item. Off by default. Usually set via the graphql module's
11
+ * `forRootAsync({ enrichStockEvents })`, which forwards it here.
12
+ */
13
+ enrichStockEvents?: boolean;
7
14
  }
8
15
  export type WmsModuleCoreModuleAsyncOptions = WMSBaseModuleAsyncOptions & WmsModuleCoreModuleOptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rytass/wms-module-core",
3
- "version": "0.1.6",
3
+ "version": "0.3.0",
4
4
  "description": "Rytass WMS Module — NestJS services and TypeORM entities for warehouse management",
5
5
  "keywords": [
6
6
  "rytass",