@rytass/wms-module-core 0.9.0 → 0.10.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.
Files changed (143) hide show
  1. package/README.md +15 -2
  2. package/docs/README.md +2 -2
  3. package/docs/api-reference.md +129 -10
  4. package/docs/host-integration.md +172 -0
  5. package/docs/integration-guide.md +84 -43
  6. package/index.cjs.js +2454 -1658
  7. package/index.d.ts +2 -0
  8. package/lib/events/inventory-count-lock.subscriber.d.ts +17 -5
  9. package/lib/models/metadata/index.d.ts +1 -0
  10. package/lib/models/metadata/sequence.entity.d.ts +9 -0
  11. package/lib/models/models.module.d.ts +7 -0
  12. package/lib/services/allocate-inventory-order.service.d.ts +3 -3
  13. package/lib/services/batch.service.d.ts +13 -1
  14. package/lib/services/consumption-order.service.d.ts +6 -6
  15. package/lib/services/helper.service.d.ts +10 -4
  16. package/lib/services/hold-inventory-order.service.d.ts +3 -3
  17. package/lib/services/index.d.ts +1 -0
  18. package/lib/services/inventory-count-order.service.d.ts +28 -9
  19. package/lib/services/loader.service.d.ts +11 -3
  20. package/lib/services/material.service.d.ts +1 -1
  21. package/lib/services/merge-batch-order.service.d.ts +2 -2
  22. package/lib/services/quality-inspection-order.service.d.ts +1 -1
  23. package/lib/services/receive-inventory-order.service.d.ts +4 -4
  24. package/lib/services/reclassify-inventory-order.service.d.ts +2 -2
  25. package/lib/services/scrape.service.d.ts +1 -1
  26. package/lib/services/sequence.service.d.ts +58 -0
  27. package/lib/services/ship-inventory-order.service.d.ts +6 -6
  28. package/lib/services/split-batch-order.service.d.ts +2 -2
  29. package/lib/services/stock.service.d.ts +48 -2
  30. package/lib/services/transfer-customer-order.service.d.ts +3 -3
  31. package/lib/services/transfer-order.service.d.ts +7 -5
  32. package/lib/services/transfer-vendor-order.service.d.ts +3 -3
  33. package/lib/table-prefix/logical-table-name.d.ts +21 -0
  34. package/lib/table-prefix/table-prefix.d.ts +30 -0
  35. package/lib/typings/core-module-options.d.ts +31 -0
  36. package/lib/typings/create-transfer-order.input.d.ts +2 -0
  37. package/lib/typings/index.d.ts +20 -0
  38. package/lib/utils/run-in-transaction.d.ts +23 -0
  39. package/lib/utils/table-path.d.ts +13 -0
  40. package/package.json +9 -6
  41. package/index.js +0 -98
  42. package/lib/constants/consumption-change-kind.js +0 -20
  43. package/lib/constants/inventory-count-status.js +0 -22
  44. package/lib/constants/operations.js +0 -76
  45. package/lib/constants/order-type.js +0 -33
  46. package/lib/constants/stock-status.js +0 -61
  47. package/lib/core.module.js +0 -287
  48. package/lib/events/dispatch-scope.js +0 -29
  49. package/lib/events/inventory-count-lock.subscriber.js +0 -98
  50. package/lib/events/stock-change.subscriber.js +0 -252
  51. package/lib/events/wms-event.collector.js +0 -22
  52. package/lib/events/wms-event.dispatcher.js +0 -63
  53. package/lib/events/wms-event.tokens.js +0 -12
  54. package/lib/events/wms-operation-runner.js +0 -101
  55. package/lib/models/extensions/allocate-inventory-order/allocate-inventory-order-change.entity.js +0 -40
  56. package/lib/models/extensions/allocate-inventory-order/allocate-inventory-order-item.entity.js +0 -104
  57. package/lib/models/extensions/allocate-inventory-order/allocate-inventory-order.entity.js +0 -33
  58. package/lib/models/extensions/consumption-order/consumption-order-change.entity.js +0 -59
  59. package/lib/models/extensions/consumption-order/consumption-order-item.entity.js +0 -114
  60. package/lib/models/extensions/consumption-order/consumption-order.entity.js +0 -69
  61. package/lib/models/extensions/hold-inventory-order/hold-inventory-order-change.entity.js +0 -40
  62. package/lib/models/extensions/hold-inventory-order/hold-inventory-order-item.entity.js +0 -98
  63. package/lib/models/extensions/hold-inventory-order/hold-inventory-order.entity.js +0 -43
  64. package/lib/models/extensions/inventory-count-order/inventory-count-order-change.entity.js +0 -50
  65. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.js +0 -191
  66. package/lib/models/extensions/inventory-count-order/inventory-count-order.entity.js +0 -155
  67. package/lib/models/extensions/merge-batch-order/merge-batch-order-change.entity.js +0 -40
  68. package/lib/models/extensions/merge-batch-order/merge-batch-order-item.entity.js +0 -75
  69. package/lib/models/extensions/merge-batch-order/merge-batch-order.entity.js +0 -33
  70. package/lib/models/extensions/order-reference/order-reference.entity.js +0 -95
  71. package/lib/models/extensions/quality-inspection-order/quality-inspection-order-change.entity.js +0 -45
  72. package/lib/models/extensions/quality-inspection-order/quality-inspection-order-item.entity.js +0 -94
  73. package/lib/models/extensions/quality-inspection-order/quality-inspection-order.entity.js +0 -38
  74. package/lib/models/extensions/receive-inventory-order/receive-inventory-order-change.entity.js +0 -46
  75. package/lib/models/extensions/receive-inventory-order/receive-inventory-order-item.entity.js +0 -89
  76. package/lib/models/extensions/receive-inventory-order/receive-inventory-order.entity.js +0 -57
  77. package/lib/models/extensions/reclassify-inventory-order/reclassify-inventory-order-change.entity.js +0 -40
  78. package/lib/models/extensions/reclassify-inventory-order/reclassify-inventory-order-item.entity.js +0 -75
  79. package/lib/models/extensions/reclassify-inventory-order/reclassify-inventory-order.entity.js +0 -33
  80. package/lib/models/extensions/scrape-order/scrape-order-change.entity.js +0 -40
  81. package/lib/models/extensions/scrape-order/scrape-order-item.entity.js +0 -94
  82. package/lib/models/extensions/scrape-order/scrape-order.entity.js +0 -33
  83. package/lib/models/extensions/ship-inventory-order/ship-inventory-order-change.entity.js +0 -46
  84. package/lib/models/extensions/ship-inventory-order/ship-inventory-order-item.entity.js +0 -90
  85. package/lib/models/extensions/ship-inventory-order/ship-inventory-order-reference.entity.js +0 -65
  86. package/lib/models/extensions/ship-inventory-order/ship-inventory-order.entity.js +0 -56
  87. package/lib/models/extensions/split-batch-order/split-batch-order-change.entity.js +0 -40
  88. package/lib/models/extensions/split-batch-order/split-batch-order-item.entity.js +0 -75
  89. package/lib/models/extensions/split-batch-order/split-batch-order.entity.js +0 -33
  90. package/lib/models/extensions/transfer-customer-order/transfer-customer-order-change.entity.js +0 -40
  91. package/lib/models/extensions/transfer-customer-order/transfer-customer-order-item.entity.js +0 -99
  92. package/lib/models/extensions/transfer-customer-order/transfer-customer-order.entity.js +0 -33
  93. package/lib/models/extensions/transfer-order/transfer-order-change.entity.js +0 -40
  94. package/lib/models/extensions/transfer-order/transfer-order-item.entity.js +0 -109
  95. package/lib/models/extensions/transfer-order/transfer-order.entity.js +0 -53
  96. package/lib/models/extensions/transfer-vendor-order/transfer-vendor-order-change.entity.js +0 -40
  97. package/lib/models/extensions/transfer-vendor-order/transfer-vendor-order-item.entity.js +0 -99
  98. package/lib/models/extensions/transfer-vendor-order/transfer-vendor-order.entity.js +0 -33
  99. package/lib/models/metadata/batch-group.entity.js +0 -31
  100. package/lib/models/metadata/batch.entity.js +0 -131
  101. package/lib/models/metadata/loader-type.entity.js +0 -43
  102. package/lib/models/metadata/loader-unit.entity.js +0 -21
  103. package/lib/models/metadata/loader.entity.js +0 -98
  104. package/lib/models/metadata/location.entity.js +0 -28
  105. package/lib/models/metadata/material-unit.entity.js +0 -51
  106. package/lib/models/metadata/material.entity.js +0 -28
  107. package/lib/models/metadata/order.entity.js +0 -5
  108. package/lib/models/metadata/sale-order.entity.js +0 -21
  109. package/lib/models/metadata/stock.entity.js +0 -29
  110. package/lib/models/metadata/unit.entity.js +0 -21
  111. package/lib/models/models.module.js +0 -158
  112. package/lib/models/wms-entities.js +0 -82
  113. package/lib/services/allocate-inventory-order.service.js +0 -310
  114. package/lib/services/base-order.service.js +0 -76
  115. package/lib/services/batch.service.js +0 -272
  116. package/lib/services/consumption-order.service.js +0 -504
  117. package/lib/services/helper.service.js +0 -28
  118. package/lib/services/hold-inventory-order.service.js +0 -296
  119. package/lib/services/inventory-count-order.service.js +0 -648
  120. package/lib/services/loader.service.js +0 -291
  121. package/lib/services/location.service.js +0 -139
  122. package/lib/services/material.service.js +0 -181
  123. package/lib/services/merge-batch-order.service.js +0 -206
  124. package/lib/services/order-reference.service.js +0 -136
  125. package/lib/services/quality-inspection-order.service.js +0 -146
  126. package/lib/services/receive-inventory-order.service.js +0 -468
  127. package/lib/services/reclassify-inventory-order.service.js +0 -192
  128. package/lib/services/sale-order.service.js +0 -20
  129. package/lib/services/scrape.service.js +0 -150
  130. package/lib/services/ship-inventory-order.service.js +0 -610
  131. package/lib/services/split-batch-order.service.js +0 -191
  132. package/lib/services/stock.service.js +0 -559
  133. package/lib/services/transfer-customer-order.service.js +0 -290
  134. package/lib/services/transfer-order.service.js +0 -641
  135. package/lib/services/transfer-vendor-order.service.js +0 -290
  136. package/lib/services/unit.service.js +0 -76
  137. package/lib/services/warehouse-map.service.js +0 -50
  138. package/lib/typings/core-module-options.js +0 -3
  139. package/lib/typings/entity-overrides.d.ts +0 -34
  140. package/lib/typings/entity-overrides.js +0 -7
  141. package/lib/typings/find-receive-inventory-order.input.js +0 -9
  142. package/lib/typings/find-ship-inventory-order.input.js +0 -9
  143. package/src/lib/models/extensions/README.md +0 -219
@@ -1,287 +0,0 @@
1
- import { __decorate } from 'tslib';
2
- import { Module } from '@nestjs/common';
3
- import { PROVIDE_MATERIAL_ENTITY, PROVIDE_BATCH_ENTITY, PROVIDE_LOCATION_ENTITY, PROVIDE_STOCK_ENTITY, OrderEntity, PROVIDE_ORDER_ENTITY, PROVIDE_WAREHOUSE_MAP_ENTITY, WMSBaseModule } from '@rytass/wms-base-nestjs-module';
4
- import { WarehouseMapEntity } from '@rytass/wms-base-nestjs-module/models/warehouse-map.entity';
5
- import { ModelsModule } from './models/models.module.js';
6
- import { WmsEntities } from './models/wms-entities.js';
7
- import { BatchEntityClass, BatchEntity } from './models/metadata/batch.entity.js';
8
- import { LocationEntityClass, LocationEntity, WarehouseMapEntity as WarehouseMapEntity$1 } from './models/metadata/location.entity.js';
9
- import { MaterialEntityClass, MaterialEntity } from './models/metadata/material.entity.js';
10
- import { OrderEntity as OrderEntity$1 } from './models/metadata/order.entity.js';
11
- import { StockEntityClass, StockEntity } from './models/metadata/stock.entity.js';
12
- import { StockService } from './services/stock.service.js';
13
- import { LoaderService } from './services/loader.service.js';
14
- import { MaterialService } from './services/material.service.js';
15
- import { BatchService } from './services/batch.service.js';
16
- import { ReceiveInventoryOrderService } from './services/receive-inventory-order.service.js';
17
- import { ShipInventoryOrderService } from './services/ship-inventory-order.service.js';
18
- import { LocationService } from './services/location.service.js';
19
- import { UnitService } from './services/unit.service.js';
20
- import { TransferOrderService } from './services/transfer-order.service.js';
21
- import { HoldInventoryOrderService } from './services/hold-inventory-order.service.js';
22
- import { AllocateInventoryOrderService } from './services/allocate-inventory-order.service.js';
23
- import { SplitBatchOrderService } from './services/split-batch-order.service.js';
24
- import { MergeBatchOrderService } from './services/merge-batch-order.service.js';
25
- import { ConsumptionOrderService } from './services/consumption-order.service.js';
26
- import { OrderReferenceService } from './services/order-reference.service.js';
27
- import { ReclassifyInventoryOrderService } from './services/reclassify-inventory-order.service.js';
28
- import { TransferVendorOrderService } from './services/transfer-vendor-order.service.js';
29
- import { QualityInspectionOrderService } from './services/quality-inspection-order.service.js';
30
- import { TransferCustomerOrderService } from './services/transfer-customer-order.service.js';
31
- import { SaleOrderService } from './services/sale-order.service.js';
32
- import { InventoryCountOrderService } from './services/inventory-count-order.service.js';
33
- import { ScrapeService } from './services/scrape.service.js';
34
- import { WarehouseMapDataService } from './services/warehouse-map.service.js';
35
- import { HelperService } from './services/helper.service.js';
36
- import { StockChangeSubscriber, OWNED_CHANGE_TABLES } from './events/stock-change.subscriber.js';
37
- import { InventoryCountLockSubscriber } from './events/inventory-count-lock.subscriber.js';
38
- import { WMS_EVENT_OPTIONS, WMS_ACTOR_EXTRACTOR, WMS_CUSTOM_CHANGE_TABLES, WMS_STOCK_ENRICH } from './events/wms-event.tokens.js';
39
- import { WmsEventDispatcher } from './events/wms-event.dispatcher.js';
40
- import { WmsOperationRunner } from './events/wms-operation-runner.js';
41
- import { WMS_CORE_MODULE_OPTIONS } from './typings/core-module-options.js';
42
-
43
- var WmsModuleCoreModule_1;
44
- /**
45
- * The entity Symbols a consumer can rebind, each paired with the base module's
46
- * token carrying their replacement and the class it falls back to.
47
- *
48
- * These Symbols are how the whole package reaches an entity — no service,
49
- * DataLoader or query imports the class directly — so rebinding one here swaps
50
- * that entity everywhere at once. Resolution happens at injection time, from
51
- * tokens `WMSBaseModule` derives from its own options, which means an override
52
- * may arrive from `forRoot` or from an async options factory alike and cannot
53
- * drift from the repository the base module resolved: both come from one option.
54
- */
55
- const OVERRIDABLE_ENTITIES = [
56
- {
57
- option: 'materialEntity',
58
- token: MaterialEntity,
59
- provide: PROVIDE_MATERIAL_ENTITY,
60
- fallback: MaterialEntityClass,
61
- requires: 'description / baseUnit / isActive',
62
- },
63
- {
64
- option: 'batchEntity',
65
- token: BatchEntity,
66
- provide: PROVIDE_BATCH_ENTITY,
67
- fallback: BatchEntityClass,
68
- },
69
- {
70
- option: 'locationEntity',
71
- token: LocationEntity,
72
- provide: PROVIDE_LOCATION_ENTITY,
73
- fallback: LocationEntityClass,
74
- requires: 'description / isActive',
75
- },
76
- {
77
- option: 'stockEntity',
78
- token: StockEntity,
79
- provide: PROVIDE_STOCK_ENTITY,
80
- fallback: StockEntityClass,
81
- requires: 'loaderId / rollbackedAt',
82
- },
83
- {
84
- option: 'orderEntity',
85
- token: OrderEntity$1,
86
- provide: PROVIDE_ORDER_ENTITY,
87
- fallback: OrderEntity,
88
- },
89
- {
90
- option: 'warehouseMapEntity',
91
- token: WarehouseMapEntity$1,
92
- provide: PROVIDE_WAREHOUSE_MAP_ENTITY,
93
- fallback: WarehouseMapEntity,
94
- },
95
- ];
96
- const entityProviders = OVERRIDABLE_ENTITIES.map(({ option, token, provide, fallback, requires }) => ({
97
- provide: token,
98
- useFactory: (configured) => {
99
- if (!configured || configured === fallback)
100
- return fallback;
101
- // `WMSBaseModuleOptions` only asks for a child of the *base* entity, but
102
- // this package reads the columns its own subclass adds. TypeScript's
103
- // structural typing happily accepts a sibling that never declares them,
104
- // which then surfaces as a missing column mid-query — a much worse error
105
- // to work backwards from than this one.
106
- if (!(configured.prototype instanceof fallback))
107
- throw new Error(`WmsModuleCoreModule: ${option} "${configured.name}" must extend ${fallback.name} (a @ChildEntity() of it)${requires
108
- ? `. @rytass/wms-module-core reads ${requires} from it, which the base entity does not declare`
109
- : ''}.`);
110
- return configured;
111
- },
112
- inject: [provide],
113
- }));
114
- /** Bound after {@link entityProviders}, since it reads every one of them. */
115
- const resolvedEntityProviders = [...entityProviders, WmsEntities];
116
- const exportedEntityTokens = [
117
- ...OVERRIDABLE_ENTITIES.map(({ token }) => token),
118
- WmsEntities,
119
- ];
120
- const exportDependencies = [
121
- LoaderService,
122
- MaterialService,
123
- BatchService,
124
- ReceiveInventoryOrderService,
125
- ShipInventoryOrderService,
126
- TransferOrderService,
127
- TransferCustomerOrderService,
128
- TransferVendorOrderService,
129
- HoldInventoryOrderService,
130
- AllocateInventoryOrderService,
131
- StockService,
132
- LocationService,
133
- UnitService,
134
- HelperService,
135
- SaleOrderService,
136
- SplitBatchOrderService,
137
- MergeBatchOrderService,
138
- OrderReferenceService,
139
- ConsumptionOrderService,
140
- ReclassifyInventoryOrderService,
141
- ScrapeService,
142
- InventoryCountOrderService,
143
- QualityInspectionOrderService,
144
- WarehouseMapDataService,
145
- ];
146
- /**
147
- * The event machinery, bound here rather than in the graphql module so a
148
- * consumer that only installs `@rytass/wms-module-core` still gets hooks,
149
- * listeners and `WmsOperationRunner`. `WmsModuleGraphqlModule` forwards its own
150
- * event options down to `forRootAsync`, which keeps exactly one binding per
151
- * token — two live bindings would resolve to whichever module the injector
152
- * reached first, the same hazard the overridable entity Symbols avoid.
153
- */
154
- const eventProviders = (wiring) => [
155
- {
156
- provide: WMS_EVENT_OPTIONS,
157
- useValue: {
158
- beforeHooks: wiring.beforeHooks,
159
- afterListeners: wiring.afterListeners,
160
- },
161
- },
162
- { provide: WMS_ACTOR_EXTRACTOR, useValue: wiring.actorExtractor ?? null },
163
- WmsEventDispatcher,
164
- WmsOperationRunner,
165
- ...(wiring.eventEmitterBridge ? [wiring.eventEmitterBridge] : []),
166
- ];
167
- const eventExports = [
168
- WmsEventDispatcher,
169
- WmsOperationRunner,
170
- WMS_EVENT_OPTIONS,
171
- WMS_ACTOR_EXTRACTOR,
172
- ];
173
- /**
174
- * Reject a registration that would shadow one of this package's own change
175
- * tables.
176
- *
177
- * Silently letting a host redefine `receive_inventory_order_changes` would
178
- * reclassify every receipt in the warehouse from somewhere the reader of that
179
- * report would never think to look. Refusing at module-definition time costs a
180
- * startup crash and buys an obvious one.
181
- *
182
- * The list is derived from `StockChangeSubscriber`'s own table map rather than
183
- * restated here: two hand-maintained copies would drift, and the drift would
184
- * open exactly the hole this guard exists to close.
185
- */
186
- const assertCustomChangeTables = (tables) => {
187
- if (!tables?.length)
188
- return [];
189
- const seen = new Set();
190
- for (const { table } of tables) {
191
- if (OWNED_CHANGE_TABLES.has(table)) {
192
- throw new Error(`WmsModuleCoreModule: customChangeTables cannot register "${table}" — this package owns it.`);
193
- }
194
- if (seen.has(table)) {
195
- throw new Error(`WmsModuleCoreModule: customChangeTables registers "${table}" twice.`);
196
- }
197
- if (!table.endsWith('_order_changes')) {
198
- // The inventory count lock keys off this suffix, so a table without it
199
- // gets events but silently escapes the lock — the worse half of the
200
- // bargain, and not one a host would knowingly take.
201
- throw new Error(`WmsModuleCoreModule: customChangeTables entry "${table}" must end in "_order_changes" so the inventory count lock covers it too.`);
202
- }
203
- seen.add(table);
204
- }
205
- return tables;
206
- };
207
- let WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule {
208
- static forRoot(options, coreOptions) {
209
- const coreModule = WMSBaseModule.forRoot(options);
210
- return {
211
- module: WmsModuleCoreModule_1,
212
- imports: [coreModule, ModelsModule],
213
- providers: [
214
- ...exportDependencies,
215
- StockChangeSubscriber,
216
- InventoryCountLockSubscriber,
217
- ...resolvedEntityProviders,
218
- ...eventProviders(coreOptions),
219
- {
220
- provide: WMS_CUSTOM_CHANGE_TABLES,
221
- useValue: assertCustomChangeTables(coreOptions.customChangeTables),
222
- },
223
- { provide: WMS_CORE_MODULE_OPTIONS, useValue: coreOptions },
224
- {
225
- provide: WMS_STOCK_ENRICH,
226
- useValue: !!coreOptions.enrichStockEvents,
227
- },
228
- ],
229
- exports: [
230
- ...exportDependencies,
231
- coreModule,
232
- ModelsModule,
233
- ...exportedEntityTokens,
234
- ...eventExports,
235
- WMS_CORE_MODULE_OPTIONS,
236
- ],
237
- };
238
- }
239
- static forRootAsync(options) {
240
- const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, enrichStockEvents, beforeHooks, afterListeners, actorExtractor, eventEmitterBridge, customChangeTables, ...baseOptions } = options;
241
- const coreModule = WMSBaseModule.forRootAsync(baseOptions);
242
- return {
243
- module: WmsModuleCoreModule_1,
244
- imports: [coreModule, ModelsModule],
245
- providers: [
246
- ...exportDependencies,
247
- StockChangeSubscriber,
248
- InventoryCountLockSubscriber,
249
- ...resolvedEntityProviders,
250
- ...eventProviders({
251
- beforeHooks,
252
- afterListeners,
253
- actorExtractor,
254
- eventEmitterBridge,
255
- }),
256
- {
257
- provide: WMS_CUSTOM_CHANGE_TABLES,
258
- useValue: assertCustomChangeTables(customChangeTables),
259
- },
260
- {
261
- provide: WMS_CORE_MODULE_OPTIONS,
262
- useValue: {
263
- defaultLoaderSerialId,
264
- defaultLoaderTypeKey,
265
- defaultLocationKey,
266
- },
267
- },
268
- { provide: WMS_STOCK_ENRICH, useValue: !!enrichStockEvents },
269
- ],
270
- exports: [
271
- ...exportDependencies,
272
- coreModule,
273
- ModelsModule,
274
- ...exportedEntityTokens,
275
- ...eventExports,
276
- WMS_CORE_MODULE_OPTIONS,
277
- ],
278
- };
279
- }
280
- };
281
- WmsModuleCoreModule = WmsModuleCoreModule_1 = __decorate([
282
- Module({
283
- providers: exportDependencies,
284
- })
285
- ], WmsModuleCoreModule);
286
-
287
- export { WmsModuleCoreModule };
@@ -1,29 +0,0 @@
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 };
@@ -1,98 +0,0 @@
1
- import { __decorate, __param, __metadata } from 'tslib';
2
- import { Injectable, ConflictException } from '@nestjs/common';
3
- import { InjectDataSource } from '@nestjs/typeorm';
4
- import { DataSource } from 'typeorm';
5
-
6
- /** The count's own settlement writes here; it must never lock itself out. */
7
- const INVENTORY_COUNT_CHANGE_TABLE = 'inventory_count_order_changes';
8
- /**
9
- * Refuse stock movements in locations a running inventory count has locked.
10
- *
11
- * Starting a count snapshots the ledger for its scope. That snapshot is what the
12
- * variance is measured against, so it has to stay true: if a transfer or a
13
- * shipment moved stock in the meantime, settlement would post the difference
14
- * between "what we counted" and "what the books said an hour ago" — silently
15
- * writing off someone else's legitimate movement.
16
- *
17
- * Why a subscriber rather than a check in each service
18
- * ---------------------------------------------------
19
- * Every stock movement in this package, without exception, ends in a row on some
20
- * `*_order_change` table — that is the same property `StockChangeSubscriber`
21
- * relies on to collect `stock.*` events without touching a single service. Doing
22
- * the lock check at the same choke point means:
23
- *
24
- * - the twelve domain services stay untouched;
25
- * - any future path that writes a change row is covered automatically;
26
- * - a consumer calling a service **directly**, bypassing the resolvers, is
27
- * covered too — which is exactly the case that matters, because a host with
28
- * its own inbound flow does precisely that.
29
- *
30
- * The check costs one indexed lookup per change row. That is deliberate: caching
31
- * the locked set would open a window right after `start()` in which a movement
32
- * slips through, and a lock with a window is not a lock.
33
- */
34
- let InventoryCountLockSubscriber = class InventoryCountLockSubscriber {
35
- constructor(dataSource) {
36
- dataSource.subscribers.push(this);
37
- }
38
- async beforeInsert(event) {
39
- const tableName = event.metadata.tableName;
40
- if (tableName === INVENTORY_COUNT_CHANGE_TABLE ||
41
- !tableName.endsWith('_order_changes')) {
42
- return;
43
- }
44
- const locationId = await this.resolveLocationId(event);
45
- if (!locationId) {
46
- // split / merge / reclassify items carry no location. They still move
47
- // stock, but only within a position the caller already named elsewhere;
48
- // there is nothing to match against the scope here.
49
- return;
50
- }
51
- const locks = await event.manager.query(`SELECT o."key"
52
- FROM inventory_count_order_locations l
53
- JOIN inventory_count_orders o ON o.id = l."orderId"
54
- WHERE l."locationId" = $1
55
- AND o.status = 'COUNTING'
56
- LIMIT 1`, [locationId]);
57
- if (!locks.length) {
58
- return;
59
- }
60
- // Naming the order is the difference between an operator who can go and
61
- // settle the count and one who just sees "denied".
62
- throw new ConflictException(`Location ${locationId} is locked by inventory count order ${locks[0].key}; finish or cancel that count before moving this stock.`);
63
- }
64
- /**
65
- * The location the change ultimately touches, taken from the change's order
66
- * item. `beforeInsert` may see the relation either already flattened to
67
- * `itemId` or still as the item object, depending on how the caller built the
68
- * row, so both are accepted.
69
- */
70
- async resolveLocationId(event) {
71
- const entity = event.entity;
72
- if (!entity) {
73
- return null;
74
- }
75
- if (entity.item && entity.item.locationId !== undefined) {
76
- return entity.item.locationId;
77
- }
78
- const itemId = entity.itemId ?? entity.item?.id;
79
- if (!itemId) {
80
- return null;
81
- }
82
- const itemRelation = event.metadata.relations.find((relation) => relation.propertyName === 'item');
83
- if (!itemRelation) {
84
- return null;
85
- }
86
- const item = await event.manager
87
- .getRepository(itemRelation.inverseEntityMetadata.target)
88
- .findOne({ where: { id: itemId } });
89
- return item?.locationId ?? null;
90
- }
91
- };
92
- InventoryCountLockSubscriber = __decorate([
93
- Injectable(),
94
- __param(0, InjectDataSource()),
95
- __metadata("design:paramtypes", [DataSource])
96
- ], InventoryCountLockSubscriber);
97
-
98
- export { InventoryCountLockSubscriber };
@@ -1,252 +0,0 @@
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 { ConsumptionChangeKind } from '../constants/consumption-change-kind.js';
6
- import { ChangeType } from '../constants/stock-status.js';
7
- import { WmsEventCollector } from './wms-event.collector.js';
8
- import { WMS_STOCK_ENRICH, WMS_CUSTOM_CHANGE_TABLES } from './wms-event.tokens.js';
9
-
10
- /**
11
- * The consumption order's three actions, which the sign cannot separate: a
12
- * return and a settlement are both negative.
13
- */
14
- const CONSUMPTION_KIND_TO_CHANGE_TYPE = {
15
- [ConsumptionChangeKind.ISSUE]: ChangeType.ISSUED,
16
- [ConsumptionChangeKind.RETURN]: ChangeType.RETURNED,
17
- [ConsumptionChangeKind.SETTLE]: ChangeType.CONSUMED,
18
- };
19
- /**
20
- * Resolve the `ChangeType` for a change table. Most tables whose semantics
21
- * depend on direction (ship / transfer / vendor / customer / hold / allocate)
22
- * branch on the sign of `quantityChanged`; the rest are fixed. The resolver is
23
- * handed the whole row rather than just the quantity because the sign is not
24
- * always enough — see `consumption_order_changes`.
25
- */
26
- const TABLE_TO_CHANGE_TYPE = new Map([
27
- ['receive_inventory_order_changes', () => ChangeType.RECEIVED],
28
- [
29
- 'ship_inventory_order_changes',
30
- ({ quantityChanged: q }) => Number(q) > 0 ? ChangeType.IN_SHIPMENT : ChangeType.SHIPPED,
31
- ],
32
- [
33
- 'transfer_order_changes',
34
- ({ quantityChanged: q }) => Number(q) > 0 ? ChangeType.IN_TRANSFER : ChangeType.TRANSFERRED,
35
- ],
36
- [
37
- 'transfer_vendor_order_changes',
38
- ({ quantityChanged: q }) => Number(q) > 0
39
- ? ChangeType.VENDOR_TRANSFERRED
40
- : ChangeType.VENDOR_RETURNED,
41
- ],
42
- [
43
- 'transfer_customer_order_changes',
44
- ({ quantityChanged: q }) => Number(q) > 0 ? ChangeType.CUSTOMER_HELD : ChangeType.CUSTOMER_RETURNED,
45
- ],
46
- [
47
- 'hold_inventory_order_changes',
48
- ({ quantityChanged: q }) => Number(q) > 0 ? ChangeType.HELD : ChangeType.RELEASED,
49
- ],
50
- [
51
- 'allocate_inventory_order_changes',
52
- ({ quantityChanged: q }) => Number(q) > 0 ? ChangeType.ALLOCATED : ChangeType.DEALLOCATED,
53
- ],
54
- ['split_batch_order_changes', () => ChangeType.SPLITTED],
55
- ['merge_batch_order_changes', () => ChangeType.MERGED],
56
- ['reclassify_inventory_order_changes', () => ChangeType.RECLASSIFIED],
57
- ['scrape_order_changes', () => ChangeType.SCRAPED],
58
- [
59
- 'inventory_count_order_changes',
60
- ({ quantityChanged: q }) => Number(q) > 0 ? ChangeType.COUNT_GAINED : ChangeType.COUNT_LOST,
61
- ],
62
- [
63
- 'consumption_order_changes',
64
- ({ kind }) => (kind ? CONSUMPTION_KIND_TO_CHANGE_TYPE[kind] : null),
65
- ],
66
- ]);
67
- const CHANGE_TYPE_TO_EVENT = {
68
- [ChangeType.RECEIVED]: 'stock.received',
69
- [ChangeType.IN_SHIPMENT]: 'stock.in-shipment',
70
- [ChangeType.SHIPPED]: 'stock.shipped',
71
- [ChangeType.IN_TRANSFER]: 'stock.in-transfer',
72
- [ChangeType.TRANSFERRED]: 'stock.transferred',
73
- [ChangeType.VENDOR_TRANSFERRED]: 'stock.vendor-transferred',
74
- [ChangeType.VENDOR_RETURNED]: 'stock.vendor-returned',
75
- [ChangeType.HELD]: 'stock.held',
76
- [ChangeType.RELEASED]: 'stock.released',
77
- [ChangeType.CUSTOMER_HELD]: 'stock.customer-held',
78
- [ChangeType.CUSTOMER_RETURNED]: 'stock.customer-returned',
79
- [ChangeType.SPLITTED]: 'stock.splitted',
80
- [ChangeType.MERGED]: 'stock.merged',
81
- [ChangeType.ALLOCATED]: 'stock.allocated',
82
- [ChangeType.DEALLOCATED]: 'stock.deallocated',
83
- [ChangeType.RECLASSIFIED]: 'stock.reclassified',
84
- [ChangeType.SCRAPED]: 'stock.scraped',
85
- [ChangeType.COUNT_GAINED]: 'stock.count-gained',
86
- [ChangeType.COUNT_LOST]: 'stock.count-lost',
87
- [ChangeType.ISSUED]: 'stock.issued',
88
- [ChangeType.RETURNED]: 'stock.returned',
89
- [ChangeType.CONSUMED]: 'stock.consumed',
90
- };
91
- const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
92
- /**
93
- * Every change table this package owns, derived from the map above rather than
94
- * restated.
95
- *
96
- * `WmsModuleCoreModule` refuses to let a host register one of these, and the
97
- * subscriber consults host registrations *before* the built-in map — so a table
98
- * added to the map but forgotten in a hand-maintained copy of this list would
99
- * become host-registrable, letting a host's resolver silently reclassify every
100
- * row on it. Deriving it is the difference between a rule and a rule someone has
101
- * to remember.
102
- */
103
- const OWNED_CHANGE_TABLES = new Set([
104
- ...TABLE_TO_CHANGE_TYPE.keys(),
105
- QUALITY_INSPECTION_TABLE,
106
- ]);
107
- /** Every `ChangeType` value, for deciding whether a host reused our vocabulary. */
108
- const CHANGE_TYPE_VALUES = new Set(Object.values(ChangeType));
109
- /**
110
- * Centralized collection of stock domain events. Listens to every
111
- * `*_order_change` insert and, using the change table name plus the sign of
112
- * `quantityChanged`, derives the `ChangeType` and buffers a `stock.*` event
113
- * into the active dispatch scope (flushed post-commit by the graphql
114
- * interceptor). This keeps the 12 domain services untouched and automatically
115
- * covers any future code path that writes a change row.
116
- *
117
- * It self-registers on the data source so no global TypeORM `subscribers`
118
- * config is required.
119
- */
120
- let StockChangeSubscriber = class StockChangeSubscriber {
121
- collector;
122
- enrich;
123
- /** Host-registered tables, keyed by table name. Empty unless configured. */
124
- customTables;
125
- constructor(dataSource, collector, enrich = false, customTables = null) {
126
- this.collector = collector;
127
- this.enrich = enrich;
128
- this.customTables = new Map((customTables ?? []).map((entry) => [entry.table, entry]));
129
- dataSource.subscribers.push(this);
130
- }
131
- async afterInsert(event) {
132
- const tableName = event.metadata.tableName;
133
- const entity = event.entity;
134
- if (!entity || typeof entity.id !== 'string') {
135
- return;
136
- }
137
- const quantityDelta = Number(entity.quantityChanged);
138
- if (tableName === QUALITY_INSPECTION_TABLE) {
139
- const enrichment = this.enrich
140
- ? await this.loadItemFields(event, entity.itemId)
141
- : undefined;
142
- this.collector.collect('stock.inspection-resolved', {
143
- orderId: entity.id,
144
- itemId: entity.itemId,
145
- quantityDelta,
146
- changeType: null,
147
- inspectionResult: entity.result ?? null,
148
- ...enrichment,
149
- });
150
- return;
151
- }
152
- const custom = this.customTables.get(tableName);
153
- if (custom) {
154
- await this.collectCustom(event, entity, quantityDelta, custom);
155
- return;
156
- }
157
- const resolveChangeType = TABLE_TO_CHANGE_TYPE.get(tableName);
158
- if (!resolveChangeType) {
159
- // Not a stock change table — enrich nothing, emit nothing.
160
- return;
161
- }
162
- const changeType = resolveChangeType(entity);
163
- if (!changeType) {
164
- // A row the table's resolver could not classify. Emitting a wrong event
165
- // would be worse than emitting none.
166
- return;
167
- }
168
- const enrichment = this.enrich
169
- ? await this.loadItemFields(event, entity.itemId)
170
- : undefined;
171
- this.collector.collect(CHANGE_TYPE_TO_EVENT[changeType], {
172
- orderId: entity.id,
173
- itemId: entity.itemId,
174
- quantityDelta,
175
- changeType,
176
- ...enrichment,
177
- });
178
- }
179
- /**
180
- * Emit for a table the host registered.
181
- *
182
- * A resolver that names one of our own `ChangeType`s gets that type's event,
183
- * so a movement the host models itself but which really is a receipt or a
184
- * scrap still counts in reports as one. Anything else becomes `stock.custom`
185
- * carrying the host's string, because inventing an event name per host would
186
- * break every exhaustive listener in the package.
187
- */
188
- async collectCustom(event, entity, quantityDelta, custom) {
189
- const resolved = custom.changeType(entity);
190
- if (!resolved) {
191
- // The host says this row does not move stock. Nothing to say about it.
192
- return;
193
- }
194
- const enrichment = this.enrich
195
- ? await this.loadItemFields(event, entity.itemId)
196
- : undefined;
197
- const known = CHANGE_TYPE_VALUES.has(resolved)
198
- ? resolved
199
- : null;
200
- this.collector.collect(known ? CHANGE_TYPE_TO_EVENT[known] : 'stock.custom', {
201
- orderId: entity.id,
202
- itemId: entity.itemId,
203
- quantityDelta,
204
- changeType: known,
205
- ...(known ? {} : { customChangeType: resolved }),
206
- ...enrichment,
207
- });
208
- }
209
- /**
210
- * Load `materialId / batchId / locationId / loaderId` from the change's order
211
- * item (one PK lookup, same transaction). Generic across all 12 change tables
212
- * via the `item` relation metadata. Returns `undefined` on any miss so the
213
- * event still fires with the lazy payload. split/merge/reclassify items carry
214
- * no material/batch — those stay null.
215
- */
216
- async loadItemFields(event, itemId) {
217
- try {
218
- const itemRelation = event.metadata.relations.find((relation) => relation.propertyName === 'item');
219
- if (!itemRelation) {
220
- return undefined;
221
- }
222
- const item = await event.manager
223
- .getRepository(itemRelation.inverseEntityMetadata.target)
224
- .findOne({ where: { id: itemId } });
225
- if (!item) {
226
- return undefined;
227
- }
228
- return {
229
- materialId: item.materialId ?? null,
230
- batchId: item.batchId ?? null,
231
- locationId: item.locationId ?? null,
232
- loaderId: item.loaderId ?? null,
233
- };
234
- }
235
- catch {
236
- // Enrichment is best-effort; never break the mutation over it.
237
- return undefined;
238
- }
239
- }
240
- };
241
- StockChangeSubscriber = __decorate([
242
- Injectable(),
243
- __param(0, InjectDataSource()),
244
- __param(2, Optional()),
245
- __param(2, Inject(WMS_STOCK_ENRICH)),
246
- __param(3, Optional()),
247
- __param(3, Inject(WMS_CUSTOM_CHANGE_TABLES)),
248
- __metadata("design:paramtypes", [DataSource,
249
- WmsEventCollector, Object, Object])
250
- ], StockChangeSubscriber);
251
-
252
- export { OWNED_CHANGE_TABLES, StockChangeSubscriber };