@rytass/wms-module-core 0.2.0 → 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/index.js CHANGED
@@ -72,7 +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_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS } from './lib/events/wms-event.tokens.js';
75
+ export { WMS_ACTOR_EXTRACTOR, WMS_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS, WMS_STOCK_ENRICH } from './lib/events/wms-event.tokens.js';
76
76
  export { WmsEventCollector } from './lib/events/wms-event.collector.js';
77
77
  export { WmsEventDispatcher } from './lib/events/wms-event.dispatcher.js';
78
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,
@@ -1,5 +1,5 @@
1
- export { WMS_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS, } from './wms-event.tokens';
1
+ export { WMS_ACTOR_EXTRACTOR, WMS_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS, WMS_STOCK_ENRICH, } from './wms-event.tokens';
2
2
  export { WmsEventCollector } from './wms-event.collector';
3
3
  export { WmsEventDispatcher } from './wms-event.dispatcher';
4
4
  export { collectToScope, runInDispatchScope, type DispatchScopeResult, } from './dispatch-scope';
5
- export type { WmsAfterEventContext, WmsAfterListener, WmsAfterListenerMap, WmsBeforeHook, WmsBeforeHookContext, WmsBeforeHookMap, WmsDomainEvent, WmsEventEmitterBridge, WmsEventModuleOptions, WmsEventName, WmsEventPayloadMap, WmsOperationEventName, WmsOperationEventPayload, WmsStockEventName, WmsStockEventPayload, } from './wms-event.types';
5
+ export type { WmsActor, WmsActorExtractor, WmsAfterEventContext, WmsAfterListener, WmsAfterListenerMap, WmsBeforeHook, WmsBeforeHookContext, WmsBeforeHookMap, WmsDomainEvent, WmsEventEmitterBridge, WmsEventModuleOptions, WmsEventName, WmsEventPayloadMap, WmsOperationEventName, WmsOperationEventPayload, WmsStockEventName, WmsStockEventPayload, } from './wms-event.types';
@@ -13,6 +13,15 @@ import { WmsEventCollector } from './wms-event.collector';
13
13
  */
14
14
  export declare class StockChangeSubscriber implements EntitySubscriberInterface {
15
15
  private readonly collector;
16
- constructor(dataSource: DataSource, collector: WmsEventCollector);
17
- afterInsert(event: InsertEvent<unknown>): void;
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;
18
27
  }
@@ -1,9 +1,10 @@
1
1
  import { __decorate, __param, __metadata } from 'tslib';
2
- import { Injectable } from '@nestjs/common';
2
+ import { Injectable, Optional, Inject } from '@nestjs/common';
3
3
  import { InjectDataSource } from '@nestjs/typeorm';
4
4
  import { DataSource } from 'typeorm';
5
5
  import { ChangeType } from '../constants/stock-status.js';
6
6
  import { WmsEventCollector } from './wms-event.collector.js';
7
+ import { WMS_STOCK_ENRICH } from './wms-event.tokens.js';
7
8
 
8
9
  /**
9
10
  * Resolve the `ChangeType` for a change table. Tables whose semantics depend on
@@ -74,11 +75,13 @@ const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
74
75
  */
75
76
  let StockChangeSubscriber = class StockChangeSubscriber {
76
77
  collector;
77
- constructor(dataSource, collector) {
78
+ enrich;
79
+ constructor(dataSource, collector, enrich = false) {
78
80
  this.collector = collector;
81
+ this.enrich = enrich;
79
82
  dataSource.subscribers.push(this);
80
83
  }
81
- afterInsert(event) {
84
+ async afterInsert(event) {
82
85
  const tableName = event.metadata.tableName;
83
86
  const entity = event.entity;
84
87
  if (!entity || typeof entity.id !== 'string') {
@@ -86,33 +89,75 @@ let StockChangeSubscriber = class StockChangeSubscriber {
86
89
  }
87
90
  const quantityDelta = Number(entity.quantityChanged);
88
91
  if (tableName === QUALITY_INSPECTION_TABLE) {
92
+ const enrichment = this.enrich
93
+ ? await this.loadItemFields(event, entity.itemId)
94
+ : undefined;
89
95
  this.collector.collect('stock.inspection-resolved', {
90
96
  orderId: entity.id,
91
97
  itemId: entity.itemId,
92
98
  quantityDelta,
93
99
  changeType: null,
94
100
  inspectionResult: entity.result ?? null,
101
+ ...enrichment,
95
102
  });
96
103
  return;
97
104
  }
98
105
  const resolveChangeType = TABLE_TO_CHANGE_TYPE.get(tableName);
99
106
  if (!resolveChangeType) {
107
+ // Not a stock change table — enrich nothing, emit nothing.
100
108
  return;
101
109
  }
102
110
  const changeType = resolveChangeType(quantityDelta);
111
+ const enrichment = this.enrich
112
+ ? await this.loadItemFields(event, entity.itemId)
113
+ : undefined;
103
114
  this.collector.collect(CHANGE_TYPE_TO_EVENT[changeType], {
104
115
  orderId: entity.id,
105
116
  itemId: entity.itemId,
106
117
  quantityDelta,
107
118
  changeType,
119
+ ...enrichment,
108
120
  });
109
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
+ }
110
153
  };
111
154
  StockChangeSubscriber = __decorate([
112
155
  Injectable(),
113
156
  __param(0, InjectDataSource()),
157
+ __param(2, Optional()),
158
+ __param(2, Inject(WMS_STOCK_ENRICH)),
114
159
  __metadata("design:paramtypes", [DataSource,
115
- WmsEventCollector])
160
+ WmsEventCollector, Object])
116
161
  ], StockChangeSubscriber);
117
162
 
118
163
  export { StockChangeSubscriber };
@@ -2,3 +2,7 @@
2
2
  export declare const WMS_EVENT_OPTIONS: unique symbol;
3
3
  /** DI token for an optional external emitter bridge (e.g. @nestjs/event-emitter). */
4
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;
@@ -2,5 +2,9 @@
2
2
  const WMS_EVENT_OPTIONS = Symbol('WMS_EVENT_OPTIONS');
3
3
  /** DI token for an optional external emitter bridge (e.g. @nestjs/event-emitter). */
4
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');
5
9
 
6
- export { WMS_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS };
10
+ export { WMS_ACTOR_EXTRACTOR, WMS_EVENT_EMITTER_BRIDGE, WMS_EVENT_OPTIONS, WMS_STOCK_ENRICH };
@@ -18,15 +18,35 @@ import type { ChangeType } from '../constants/stock-status';
18
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
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
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;
21
38
  /**
22
39
  * Payload for an operation event. `id` is the primary key of the operation's
23
40
  * main entity/order (correlation id shared with the stock events it fans out
24
41
  * to); `result` is the mutation's return value (a DTO, or `boolean` for action
25
- * mutations).
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.
26
44
  */
27
45
  export interface WmsOperationEventPayload<TResult = unknown> {
28
46
  readonly id: string | null;
29
47
  readonly result: TResult;
48
+ readonly args: Readonly<Record<string, unknown>>;
49
+ readonly actor: WmsActor | null;
30
50
  }
31
51
  /**
32
52
  * Payload for a stock domain event, built from the inserted `*_order_change`
@@ -45,6 +65,10 @@ export interface WmsStockEventPayload {
45
65
  readonly changeType: ChangeType | null;
46
66
  /** Quality-inspection result, present only on `stock.inspection-resolved`. */
47
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;
48
72
  }
49
73
  /** Maps every event name to its payload type. */
50
74
  export type WmsEventPayloadMap = {
@@ -66,6 +90,7 @@ export interface WmsBeforeHookContext<N extends WmsEventName = WmsEventName> {
66
90
  readonly event: N;
67
91
  readonly args: Readonly<Record<string, unknown>>;
68
92
  readonly executionContext: ExecutionContext;
93
+ readonly actor: WmsActor | null;
69
94
  }
70
95
  /** Context handed to an after-listener. Runs post-commit with the event payload. */
71
96
  export interface WmsAfterEventContext<N extends WmsEventName = WmsEventName> {
@@ -87,6 +112,13 @@ export type WmsAfterListenerMap = {
87
112
  export interface WmsEventModuleOptions {
88
113
  readonly beforeHooks?: WmsBeforeHookMap;
89
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;
90
122
  }
91
123
  /**
92
124
  * Runtime bridge to an external emitter (e.g. `@nestjs/event-emitter`). The
@@ -2,7 +2,6 @@ import { __decorate } from 'tslib';
2
2
  import { Module } from '@nestjs/common';
3
3
  import { TypeOrmModule } from '@nestjs/typeorm';
4
4
  import { WmsEventCollector } from '../events/wms-event.collector.js';
5
- import { StockChangeSubscriber } from '../events/stock-change.subscriber.js';
6
5
  import { WarehouseMapEntity as WarehouseMapEntity$1 } from '@rytass/wms-base-nestjs-module/models/warehouse-map.entity';
7
6
  import { BatchEntity, BatchEntityClass } from './metadata/batch.entity.js';
8
7
  import { BatchGroupEntity, BatchGroupEntityClass } from './metadata/batch-group.entity.js';
@@ -116,11 +115,7 @@ let ModelsModule = class ModelsModule {
116
115
  ModelsModule = __decorate([
117
116
  Module({
118
117
  imports: [TypeOrmModule.forFeature(entities.map(([_, entity]) => entity))],
119
- providers: [
120
- ...ResolvedEntitiesProviders,
121
- WmsEventCollector,
122
- StockChangeSubscriber,
123
- ],
118
+ providers: [...ResolvedEntitiesProviders, WmsEventCollector],
124
119
  exports: [TypeOrmModule, ...ResolvedEntitiesProviders, WmsEventCollector],
125
120
  })
126
121
  ], ModelsModule);
@@ -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.2.0",
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",