@rytass/wms-module-core 0.8.1 → 0.9.1

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 (141) hide show
  1. package/index.cjs.js +1689 -199
  2. package/index.d.mts +6 -0
  3. package/{index.js → index.mjs} +97 -87
  4. package/lib/constants/consumption-change-kind.d.ts +17 -0
  5. package/lib/constants/consumption-change-kind.mjs +20 -0
  6. package/lib/constants/index.d.ts +2 -0
  7. package/lib/constants/operations.d.ts +1 -1
  8. package/lib/constants/{operations.js → operations.mjs} +9 -0
  9. package/lib/constants/order-type.d.ts +30 -0
  10. package/lib/constants/order-type.mjs +33 -0
  11. package/lib/constants/stock-status.d.ts +4 -1
  12. package/lib/constants/{stock-status.js → stock-status.mjs} +6 -0
  13. package/lib/{core.module.js → core.module.mjs} +118 -34
  14. package/lib/events/index.d.ts +2 -1
  15. package/lib/events/stock-change.subscriber.d.ts +26 -1
  16. package/lib/events/{stock-change.subscriber.js → stock-change.subscriber.mjs} +100 -17
  17. package/lib/events/{wms-event.collector.js → wms-event.collector.mjs} +1 -1
  18. package/lib/events/{wms-event.dispatcher.js → wms-event.dispatcher.mjs} +1 -1
  19. package/lib/events/wms-event.tokens.d.ts +2 -0
  20. package/lib/events/{wms-event.tokens.js → wms-event.tokens.mjs} +3 -1
  21. package/lib/events/wms-event.types.d.ts +38 -6
  22. package/lib/events/wms-operation-runner.d.ts +57 -0
  23. package/lib/events/wms-operation-runner.mjs +101 -0
  24. package/lib/models/extensions/allocate-inventory-order/{allocate-inventory-order-change.entity.js → allocate-inventory-order-change.entity.mjs} +1 -1
  25. package/lib/models/extensions/allocate-inventory-order/{allocate-inventory-order-item.entity.js → allocate-inventory-order-item.entity.mjs} +12 -12
  26. package/lib/models/extensions/consumption-order/consumption-order-change.entity.d.ts +19 -0
  27. package/lib/models/extensions/consumption-order/consumption-order-change.entity.mjs +59 -0
  28. package/lib/models/extensions/consumption-order/consumption-order-item.entity.d.ts +26 -0
  29. package/lib/models/extensions/consumption-order/consumption-order-item.entity.mjs +114 -0
  30. package/lib/models/extensions/consumption-order/consumption-order.entity.d.ts +32 -0
  31. package/lib/models/extensions/consumption-order/consumption-order.entity.mjs +69 -0
  32. package/lib/models/extensions/consumption-order/index.d.ts +3 -0
  33. package/lib/models/extensions/hold-inventory-order/{hold-inventory-order-change.entity.js → hold-inventory-order-change.entity.mjs} +1 -1
  34. package/lib/models/extensions/hold-inventory-order/{hold-inventory-order-item.entity.js → hold-inventory-order-item.entity.mjs} +12 -12
  35. package/lib/models/extensions/index.d.ts +4 -0
  36. package/lib/models/extensions/inventory-count-order/{inventory-count-order-change.entity.js → inventory-count-order-change.entity.mjs} +1 -1
  37. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.d.ts +13 -1
  38. package/lib/models/extensions/inventory-count-order/{inventory-count-order-item.entity.js → inventory-count-order-item.entity.mjs} +29 -13
  39. package/lib/models/extensions/inventory-count-order/{inventory-count-order.entity.js → inventory-count-order.entity.mjs} +12 -12
  40. package/lib/models/extensions/merge-batch-order/{merge-batch-order-change.entity.js → merge-batch-order-change.entity.mjs} +1 -1
  41. package/lib/models/extensions/merge-batch-order/{merge-batch-order-item.entity.js → merge-batch-order-item.entity.mjs} +12 -12
  42. package/lib/models/extensions/order-reference/index.d.ts +1 -0
  43. package/lib/models/extensions/order-reference/order-reference.entity.d.ts +49 -0
  44. package/lib/models/extensions/order-reference/order-reference.entity.mjs +95 -0
  45. package/lib/models/extensions/quality-inspection-order/{quality-inspection-order-change.entity.js → quality-inspection-order-change.entity.mjs} +1 -1
  46. package/lib/models/extensions/quality-inspection-order/{quality-inspection-order-item.entity.js → quality-inspection-order-item.entity.mjs} +12 -12
  47. package/lib/models/extensions/receive-inventory-order/{receive-inventory-order-change.entity.js → receive-inventory-order-change.entity.mjs} +2 -2
  48. package/lib/models/extensions/receive-inventory-order/{receive-inventory-order-item.entity.js → receive-inventory-order-item.entity.mjs} +2 -2
  49. package/lib/models/extensions/receive-inventory-order/{receive-inventory-order.entity.js → receive-inventory-order.entity.mjs} +2 -2
  50. package/lib/models/extensions/reclassify-inventory-order/{reclassify-inventory-order-change.entity.js → reclassify-inventory-order-change.entity.mjs} +1 -1
  51. package/lib/models/extensions/reclassify-inventory-order/{reclassify-inventory-order-item.entity.js → reclassify-inventory-order-item.entity.mjs} +12 -12
  52. package/lib/models/extensions/scrape-order/{scrape-order-change.entity.js → scrape-order-change.entity.mjs} +1 -1
  53. package/lib/models/extensions/scrape-order/{scrape-order-item.entity.js → scrape-order-item.entity.mjs} +12 -12
  54. package/lib/models/extensions/ship-inventory-order/{ship-inventory-order-change.entity.js → ship-inventory-order-change.entity.mjs} +2 -2
  55. package/lib/models/extensions/ship-inventory-order/{ship-inventory-order-item.entity.js → ship-inventory-order-item.entity.mjs} +2 -2
  56. package/lib/models/extensions/ship-inventory-order/{ship-inventory-order.entity.js → ship-inventory-order.entity.mjs} +2 -2
  57. package/lib/models/extensions/split-batch-order/{split-batch-order-change.entity.js → split-batch-order-change.entity.mjs} +1 -1
  58. package/lib/models/extensions/split-batch-order/{split-batch-order-item.entity.js → split-batch-order-item.entity.mjs} +12 -12
  59. package/lib/models/extensions/transfer-customer-order/{transfer-customer-order-change.entity.js → transfer-customer-order-change.entity.mjs} +1 -1
  60. package/lib/models/extensions/transfer-customer-order/{transfer-customer-order-item.entity.js → transfer-customer-order-item.entity.mjs} +12 -12
  61. package/lib/models/extensions/transfer-order/{transfer-order-change.entity.js → transfer-order-change.entity.mjs} +1 -1
  62. package/lib/models/extensions/transfer-order/{transfer-order-item.entity.js → transfer-order-item.entity.mjs} +12 -12
  63. package/lib/models/extensions/transfer-vendor-order/{transfer-vendor-order-change.entity.js → transfer-vendor-order-change.entity.mjs} +1 -1
  64. package/lib/models/extensions/transfer-vendor-order/{transfer-vendor-order-item.entity.js → transfer-vendor-order-item.entity.mjs} +12 -12
  65. package/lib/models/metadata/batch.entity.d.ts +46 -0
  66. package/lib/models/metadata/batch.entity.mjs +131 -0
  67. package/lib/models/metadata/{loader.entity.js → loader.entity.mjs} +1 -1
  68. package/lib/models/metadata/{material-unit.entity.js → material-unit.entity.mjs} +1 -1
  69. package/lib/models/metadata/{stock.entity.js → stock.entity.mjs} +1 -1
  70. package/lib/models/{models.module.js → models.module.mjs} +60 -52
  71. package/lib/models/{wms-entities.js → wms-entities.mjs} +5 -5
  72. package/lib/services/{allocate-inventory-order.service.js → allocate-inventory-order.service.mjs} +60 -56
  73. package/lib/services/base-order.service.d.ts +18 -3
  74. package/lib/services/base-order.service.mjs +76 -0
  75. package/lib/services/batch.service.d.ts +17 -0
  76. package/lib/services/{batch.service.js → batch.service.mjs} +93 -53
  77. package/lib/services/consumption-order.service.d.ts +75 -0
  78. package/lib/services/consumption-order.service.mjs +504 -0
  79. package/lib/services/{hold-inventory-order.service.js → hold-inventory-order.service.mjs} +60 -56
  80. package/lib/services/index.d.ts +3 -0
  81. package/lib/services/{inventory-count-order.service.js → inventory-count-order.service.mjs} +64 -57
  82. package/lib/services/{loader.service.js → loader.service.mjs} +56 -52
  83. package/lib/services/{location.service.js → location.service.mjs} +56 -52
  84. package/lib/services/{material.service.js → material.service.mjs} +56 -52
  85. package/lib/services/{merge-batch-order.service.js → merge-batch-order.service.mjs} +60 -56
  86. package/lib/services/order-reference.service.d.ts +50 -0
  87. package/lib/services/order-reference.service.mjs +136 -0
  88. package/lib/services/{quality-inspection-order.service.js → quality-inspection-order.service.mjs} +59 -55
  89. package/lib/services/{receive-inventory-order.service.js → receive-inventory-order.service.mjs} +189 -135
  90. package/lib/services/{reclassify-inventory-order.service.js → reclassify-inventory-order.service.mjs} +60 -56
  91. package/lib/services/{sale-order.service.js → sale-order.service.mjs} +1 -1
  92. package/lib/services/{scrape.service.js → scrape.service.mjs} +59 -55
  93. package/lib/services/{ship-inventory-order.service.js → ship-inventory-order.service.mjs} +60 -56
  94. package/lib/services/split-batch-order.service.mjs +191 -0
  95. package/lib/services/{stock.service.js → stock.service.mjs} +86 -56
  96. package/lib/services/{transfer-customer-order.service.js → transfer-customer-order.service.mjs} +60 -56
  97. package/lib/services/{transfer-order.service.js → transfer-order.service.mjs} +61 -57
  98. package/lib/services/{transfer-vendor-order.service.js → transfer-vendor-order.service.mjs} +60 -56
  99. package/lib/services/{unit.service.js → unit.service.mjs} +56 -52
  100. package/lib/services/{warehouse-map.service.js → warehouse-map.service.mjs} +1 -1
  101. package/lib/typings/aggregated-stock.d.ts +6 -0
  102. package/lib/typings/consumption-order.input.d.ts +72 -0
  103. package/lib/typings/core-module-options.d.ts +34 -1
  104. package/lib/typings/custom-change-table.d.ts +70 -0
  105. package/lib/typings/find-stock.input.d.ts +14 -0
  106. package/lib/typings/get-batch.input.d.ts +16 -0
  107. package/lib/typings/index.d.ts +3 -0
  108. package/lib/typings/order-reference.input.d.ts +28 -0
  109. package/lib/typings/split-batch.input.d.ts +11 -0
  110. package/package.json +19 -7
  111. package/lib/models/metadata/batch.entity.js +0 -73
  112. package/lib/services/split-batch-order.service.js +0 -168
  113. package/lib/typings/entity-overrides.d.ts +0 -34
  114. package/lib/typings/entity-overrides.js +0 -7
  115. package/src/lib/models/extensions/README.md +0 -219
  116. /package/lib/constants/{inventory-count-status.js → inventory-count-status.mjs} +0 -0
  117. /package/lib/events/{dispatch-scope.js → dispatch-scope.mjs} +0 -0
  118. /package/lib/events/{inventory-count-lock.subscriber.js → inventory-count-lock.subscriber.mjs} +0 -0
  119. /package/lib/models/extensions/allocate-inventory-order/{allocate-inventory-order.entity.js → allocate-inventory-order.entity.mjs} +0 -0
  120. /package/lib/models/extensions/hold-inventory-order/{hold-inventory-order.entity.js → hold-inventory-order.entity.mjs} +0 -0
  121. /package/lib/models/extensions/merge-batch-order/{merge-batch-order.entity.js → merge-batch-order.entity.mjs} +0 -0
  122. /package/lib/models/extensions/quality-inspection-order/{quality-inspection-order.entity.js → quality-inspection-order.entity.mjs} +0 -0
  123. /package/lib/models/extensions/reclassify-inventory-order/{reclassify-inventory-order.entity.js → reclassify-inventory-order.entity.mjs} +0 -0
  124. /package/lib/models/extensions/scrape-order/{scrape-order.entity.js → scrape-order.entity.mjs} +0 -0
  125. /package/lib/models/extensions/ship-inventory-order/{ship-inventory-order-reference.entity.js → ship-inventory-order-reference.entity.mjs} +0 -0
  126. /package/lib/models/extensions/split-batch-order/{split-batch-order.entity.js → split-batch-order.entity.mjs} +0 -0
  127. /package/lib/models/extensions/transfer-customer-order/{transfer-customer-order.entity.js → transfer-customer-order.entity.mjs} +0 -0
  128. /package/lib/models/extensions/transfer-order/{transfer-order.entity.js → transfer-order.entity.mjs} +0 -0
  129. /package/lib/models/extensions/transfer-vendor-order/{transfer-vendor-order.entity.js → transfer-vendor-order.entity.mjs} +0 -0
  130. /package/lib/models/metadata/{batch-group.entity.js → batch-group.entity.mjs} +0 -0
  131. /package/lib/models/metadata/{loader-type.entity.js → loader-type.entity.mjs} +0 -0
  132. /package/lib/models/metadata/{loader-unit.entity.js → loader-unit.entity.mjs} +0 -0
  133. /package/lib/models/metadata/{location.entity.js → location.entity.mjs} +0 -0
  134. /package/lib/models/metadata/{material.entity.js → material.entity.mjs} +0 -0
  135. /package/lib/models/metadata/{order.entity.js → order.entity.mjs} +0 -0
  136. /package/lib/models/metadata/{sale-order.entity.js → sale-order.entity.mjs} +0 -0
  137. /package/lib/models/metadata/{unit.entity.js → unit.entity.mjs} +0 -0
  138. /package/lib/services/{helper.service.js → helper.service.mjs} +0 -0
  139. /package/lib/typings/{core-module-options.js → core-module-options.mjs} +0 -0
  140. /package/lib/typings/{find-receive-inventory-order.input.js → find-receive-inventory-order.input.mjs} +0 -0
  141. /package/lib/typings/{find-ship-inventory-order.input.js → find-ship-inventory-order.input.mjs} +0 -0
package/index.cjs.js CHANGED
@@ -64,12 +64,58 @@ exports.BatchEntityClass = class BatchEntityClass extends wmsBaseNestjsModule.Ba
64
64
  vendorId;
65
65
  // added when quality inspection, used to link to quality inspection order
66
66
  inspectionResult;
67
+ /**
68
+ * Whether anyone ever asked for this batch to be inspected.
69
+ *
70
+ * `inspectionResult IS NULL` on its own cannot answer that: null is also the
71
+ * state of every batch nobody ever intended to inspect, which is most of
72
+ * them. Reading it as "awaiting inspection" made `StockStatus`
73
+ * `PENDING_INSPECTION` return the whole warehouse.
74
+ *
75
+ * Set when a receive order item carrying `requireInspection` lands without a
76
+ * result yet; cleared by nothing, because the pending filter also requires
77
+ * `inspectionResult IS NULL` and an inspection fills that in.
78
+ */
79
+ requiresInspection;
67
80
  // added when transfer inventory, used to link to transfer order
68
81
  transferId;
69
82
  // added when hold inventory, used to link to hold inventory order
70
83
  held;
71
84
  // added when shipment inventory, used to link to shipment order
72
85
  inShipment;
86
+ /**
87
+ * The batch this one was first split out of, or `null` for a batch that was
88
+ * created outright.
89
+ *
90
+ * Written once, at creation, and never updated — it is a genealogy line, not
91
+ * a current-parent pointer. Every status in this model is a flag on the batch
92
+ * rather than a column on the stock row, so holding, transferring or shipping
93
+ * *part* of a batch splits a child off first (see
94
+ * `HoldInventoryOrderService`); before this column those children were
95
+ * orphans, and the only way back to the original batch was to read the stock
96
+ * ledger. Following `parentBatchId` upwards now yields the root batch, which
97
+ * is what a label or a shipping document should print.
98
+ *
99
+ * `BatchService.splitBatch` reuses an existing sibling when one already
100
+ * carries the requested attributes, so a reused batch keeps the parent it was
101
+ * first created from. The quantity ledger in `stocks` remains the authority
102
+ * on what actually moved.
103
+ */
104
+ parentBatchId;
105
+ /**
106
+ * Host-defined attributes describing this batch, stored verbatim.
107
+ *
108
+ * The module reads nothing out of this and validates nothing in it: what a
109
+ * grade, a bin code or a die count means belongs to the host, and a schema
110
+ * enforced here would be a second, weaker copy of the host's own. It exists
111
+ * because `batchEntity` overrides solve the storage half of the problem but
112
+ * not the display half — a column the module does not know about cannot be
113
+ * carried through a split or shown on a batch row, and this can.
114
+ *
115
+ * Set at creation; two splits asking for different attributes produce two
116
+ * batches rather than one merged one.
117
+ */
118
+ attributes;
73
119
  batchGroup;
74
120
  };
75
121
  tslib.__decorate([
@@ -96,6 +142,10 @@ tslib.__decorate([
96
142
  typeorm.Column({ type: 'bool', nullable: true }),
97
143
  tslib.__metadata("design:type", Object)
98
144
  ], exports.BatchEntityClass.prototype, "inspectionResult", void 0);
145
+ tslib.__decorate([
146
+ typeorm.Column({ type: 'bool', default: false }),
147
+ tslib.__metadata("design:type", Boolean)
148
+ ], exports.BatchEntityClass.prototype, "requiresInspection", void 0);
99
149
  tslib.__decorate([
100
150
  typeorm.Column({ type: 'varchar', nullable: true }),
101
151
  tslib.__metadata("design:type", Object)
@@ -108,6 +158,14 @@ tslib.__decorate([
108
158
  typeorm.Column({ type: 'bool', default: false }),
109
159
  tslib.__metadata("design:type", Boolean)
110
160
  ], exports.BatchEntityClass.prototype, "inShipment", void 0);
161
+ tslib.__decorate([
162
+ typeorm.Column({ type: 'uuid', nullable: true }),
163
+ tslib.__metadata("design:type", Object)
164
+ ], exports.BatchEntityClass.prototype, "parentBatchId", void 0);
165
+ tslib.__decorate([
166
+ typeorm.Column({ type: 'jsonb', nullable: true }),
167
+ tslib.__metadata("design:type", Object)
168
+ ], exports.BatchEntityClass.prototype, "attributes", void 0);
111
169
  tslib.__decorate([
112
170
  typeorm.ManyToOne('batch_groups', (batchGroup) => batchGroup.batches, {
113
171
  onDelete: 'CASCADE',
@@ -458,6 +516,12 @@ exports.ChangeType = void 0;
458
516
  ChangeType["COUNT_LOST"] = "COUNT_LOST";
459
517
  // scrape-order-change.entity.ts
460
518
  ChangeType["SCRAPED"] = "SCRAPED";
519
+ // consumption-order-change.entity.ts, kind = ISSUE
520
+ ChangeType["ISSUED"] = "ISSUED";
521
+ // consumption-order-change.entity.ts, kind = RETURN
522
+ ChangeType["RETURNED"] = "RETURNED";
523
+ // consumption-order-change.entity.ts, kind = SETTLE
524
+ ChangeType["CONSUMED"] = "CONSUMED";
461
525
  })(exports.ChangeType || (exports.ChangeType = {}));
462
526
 
463
527
  const StockEntity = Symbol('StockEntity');
@@ -2550,8 +2614,20 @@ exports.InventoryCountOrderItemEntityClass = class InventoryCountOrderItemEntity
2550
2614
  // `null` before counting has started.
2551
2615
  held;
2552
2616
  inShipment;
2553
- /** `null` = 待檢驗, `false` = 檢驗失敗, `true` = passed. */
2617
+ /**
2618
+ * `false` = 檢驗失敗, `true` = passed, `null` = not inspected.
2619
+ *
2620
+ * `null` on its own does **not** mean 待檢驗: it is the resting state of
2621
+ * almost every batch in the warehouse. Pair it with
2622
+ * {@link InventoryCountOrderItemEntityClass.requiresInspection}.
2623
+ */
2554
2624
  inspectionResult;
2625
+ /**
2626
+ * Whether anybody had asked for this position to be inspected when the count
2627
+ * started. Snapshotted for the same reason as the flags around it, and needed
2628
+ * because `inspectionResult IS NULL` alone would mark the whole sheet 待檢驗.
2629
+ */
2630
+ requiresInspection;
2555
2631
  transferId;
2556
2632
  vendorId;
2557
2633
  customerId;
@@ -2620,6 +2696,10 @@ tslib.__decorate([
2620
2696
  typeorm.Column({ type: 'boolean', nullable: true }),
2621
2697
  tslib.__metadata("design:type", Object)
2622
2698
  ], exports.InventoryCountOrderItemEntityClass.prototype, "inspectionResult", void 0);
2699
+ tslib.__decorate([
2700
+ typeorm.Column({ type: 'boolean', nullable: true }),
2701
+ tslib.__metadata("design:type", Object)
2702
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "requiresInspection", void 0);
2623
2703
  tslib.__decorate([
2624
2704
  typeorm.Column({ type: 'uuid', nullable: true }),
2625
2705
  tslib.__metadata("design:type", Object)
@@ -2708,6 +2788,361 @@ exports.InventoryCountOrderChangeEntityClass = tslib.__decorate([
2708
2788
  typeorm.Entity('inventory_count_order_changes')
2709
2789
  ], exports.InventoryCountOrderChangeEntityClass);
2710
2790
 
2791
+ const ConsumptionOrderEntity = Symbol('ConsumptionOrderEntity');
2792
+ /**
2793
+ * Material handed to a process that consumes it.
2794
+ *
2795
+ * One order covers the whole life of that handover: issue material out to a
2796
+ * consuming location, take back what was not used, and settle what was. Three
2797
+ * actions on one document rather than three documents, which is the grammar
2798
+ * every other stateful order here already uses -- hold/release, allocate/
2799
+ * deallocate and transfer/cancel are each a single order too.
2800
+ *
2801
+ * Nothing about it is specific to manufacturing. "Give stock to a process that
2802
+ * eats some of it, possibly returns the rest, and may produce something else"
2803
+ * is equally a subcontract, a repair job, a teardown, or a kitchen prep list.
2804
+ * What the process *is* belongs in `order_references`.
2805
+ *
2806
+ * The consuming location is an ordinary location, and material sitting there is
2807
+ * ordinary `FREE` stock. There is no work-in-progress status: status in this
2808
+ * model is a flag on the batch, so a status would force every partial issue to
2809
+ * split a child batch off, and a batch key per issue is a worse answer than a
2810
+ * location. `excludeLocationIds` is how a stock report leaves that location
2811
+ * out.
2812
+ */
2813
+ exports.ConsumptionOrderEntityClass = class ConsumptionOrderEntityClass {
2814
+ id;
2815
+ key;
2816
+ description;
2817
+ createdBy;
2818
+ removedAt;
2819
+ createdAt;
2820
+ items;
2821
+ };
2822
+ tslib.__decorate([
2823
+ typeorm.PrimaryGeneratedColumn('uuid'),
2824
+ tslib.__metadata("design:type", String)
2825
+ ], exports.ConsumptionOrderEntityClass.prototype, "id", void 0);
2826
+ tslib.__decorate([
2827
+ typeorm.Column({ type: 'varchar', unique: true }),
2828
+ typeorm.Index(),
2829
+ tslib.__metadata("design:type", String)
2830
+ ], exports.ConsumptionOrderEntityClass.prototype, "key", void 0);
2831
+ tslib.__decorate([
2832
+ typeorm.Column({ type: 'text', nullable: true }),
2833
+ tslib.__metadata("design:type", Object)
2834
+ ], exports.ConsumptionOrderEntityClass.prototype, "description", void 0);
2835
+ tslib.__decorate([
2836
+ typeorm.Column({ type: 'varchar', nullable: true }),
2837
+ tslib.__metadata("design:type", Object)
2838
+ ], exports.ConsumptionOrderEntityClass.prototype, "createdBy", void 0);
2839
+ tslib.__decorate([
2840
+ typeorm.Column({ type: 'timestamptz', nullable: true }),
2841
+ tslib.__metadata("design:type", Object)
2842
+ ], exports.ConsumptionOrderEntityClass.prototype, "removedAt", void 0);
2843
+ tslib.__decorate([
2844
+ typeorm.CreateDateColumn({ type: 'timestamptz' }),
2845
+ tslib.__metadata("design:type", Date)
2846
+ ], exports.ConsumptionOrderEntityClass.prototype, "createdAt", void 0);
2847
+ tslib.__decorate([
2848
+ typeorm.OneToMany('consumption_order_items', (entity) => entity.order),
2849
+ tslib.__metadata("design:type", Array)
2850
+ ], exports.ConsumptionOrderEntityClass.prototype, "items", void 0);
2851
+ exports.ConsumptionOrderEntityClass = tslib.__decorate([
2852
+ typeorm.Entity('consumption_orders'),
2853
+ typeorm.TableInheritance({ column: { type: 'varchar', name: 'entityName' } })
2854
+ ], exports.ConsumptionOrderEntityClass);
2855
+
2856
+ const ConsumptionOrderItemEntity = Symbol('ConsumptionOrderItemEntity');
2857
+ exports.ConsumptionOrderItemEntityClass = class ConsumptionOrderItemEntityClass {
2858
+ id;
2859
+ materialId;
2860
+ batchId;
2861
+ /** Where the material is issued from. */
2862
+ locationId;
2863
+ loaderId;
2864
+ unitId;
2865
+ targetConsumedQuantity;
2866
+ /**
2867
+ * Where the material sits while the process holds it. An ordinary location;
2868
+ * the host decides which of its own means "in the hands of a process".
2869
+ */
2870
+ targetLocationId;
2871
+ targetLoaderId;
2872
+ orderId;
2873
+ removedAt;
2874
+ location;
2875
+ loader;
2876
+ order;
2877
+ changes;
2878
+ };
2879
+ tslib.__decorate([
2880
+ typeorm.PrimaryGeneratedColumn('uuid'),
2881
+ tslib.__metadata("design:type", String)
2882
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "id", void 0);
2883
+ tslib.__decorate([
2884
+ typeorm.Column({ type: 'uuid' }),
2885
+ typeorm.Index(),
2886
+ tslib.__metadata("design:type", String)
2887
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "materialId", void 0);
2888
+ tslib.__decorate([
2889
+ typeorm.Column({ type: 'uuid' }),
2890
+ typeorm.Index(),
2891
+ tslib.__metadata("design:type", String)
2892
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "batchId", void 0);
2893
+ tslib.__decorate([
2894
+ typeorm.Column({ type: 'uuid' }),
2895
+ typeorm.Index(),
2896
+ tslib.__metadata("design:type", String)
2897
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "locationId", void 0);
2898
+ tslib.__decorate([
2899
+ typeorm.Column({ type: 'uuid', nullable: true }),
2900
+ tslib.__metadata("design:type", Object)
2901
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "loaderId", void 0);
2902
+ tslib.__decorate([
2903
+ typeorm.Column({ type: 'uuid', nullable: true }),
2904
+ tslib.__metadata("design:type", Object)
2905
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "unitId", void 0);
2906
+ tslib.__decorate([
2907
+ typeorm.Column({ type: 'numeric' }),
2908
+ tslib.__metadata("design:type", Number)
2909
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "targetConsumedQuantity", void 0);
2910
+ tslib.__decorate([
2911
+ typeorm.Column({ type: 'uuid', nullable: true }),
2912
+ typeorm.Index(),
2913
+ tslib.__metadata("design:type", Object)
2914
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "targetLocationId", void 0);
2915
+ tslib.__decorate([
2916
+ typeorm.Column({ type: 'uuid', nullable: true }),
2917
+ typeorm.Index(),
2918
+ tslib.__metadata("design:type", Object)
2919
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "targetLoaderId", void 0);
2920
+ tslib.__decorate([
2921
+ typeorm.Column({ type: 'uuid' }),
2922
+ typeorm.Index(),
2923
+ tslib.__metadata("design:type", String)
2924
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "orderId", void 0);
2925
+ tslib.__decorate([
2926
+ typeorm.Column({ type: 'timestamptz', nullable: true }),
2927
+ tslib.__metadata("design:type", Object)
2928
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "removedAt", void 0);
2929
+ tslib.__decorate([
2930
+ typeorm.ManyToOne('locations'),
2931
+ typeorm.JoinColumn({ name: 'locationId', referencedColumnName: 'id' }),
2932
+ tslib.__metadata("design:type", exports.LocationEntityClass)
2933
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "location", void 0);
2934
+ tslib.__decorate([
2935
+ typeorm.ManyToOne('loaders'),
2936
+ typeorm.JoinColumn({ name: 'loaderId', referencedColumnName: 'id' }),
2937
+ tslib.__metadata("design:type", exports.LoadersEntityClass)
2938
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "loader", void 0);
2939
+ tslib.__decorate([
2940
+ typeorm.ManyToOne('consumption_orders', (entity) => entity.items),
2941
+ typeorm.JoinColumn({ name: 'orderId', referencedColumnName: 'id' }),
2942
+ tslib.__metadata("design:type", exports.ConsumptionOrderEntityClass)
2943
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "order", void 0);
2944
+ tslib.__decorate([
2945
+ typeorm.OneToMany('consumption_order_changes', (change) => change.item),
2946
+ tslib.__metadata("design:type", Array)
2947
+ ], exports.ConsumptionOrderItemEntityClass.prototype, "changes", void 0);
2948
+ exports.ConsumptionOrderItemEntityClass = tslib.__decorate([
2949
+ typeorm.Entity('consumption_order_items'),
2950
+ typeorm.TableInheritance({ column: { type: 'varchar', name: 'entityName' } })
2951
+ ], exports.ConsumptionOrderItemEntityClass);
2952
+
2953
+ /**
2954
+ * What a `consumption_order_changes` row records.
2955
+ *
2956
+ * The three actions cannot be told apart by the sign of `quantityChanged`
2957
+ * alone, which is how every other change table in this package encodes
2958
+ * direction: a return and a settlement are both negative, and the difference
2959
+ * between "it came back to the shelf" and "it is gone" is the entire point of
2960
+ * the order. So the intent is stored rather than inferred.
2961
+ */
2962
+ exports.ConsumptionChangeKind = void 0;
2963
+ (function (ConsumptionChangeKind) {
2964
+ /** Material left the shelf for the consuming location. */
2965
+ ConsumptionChangeKind["ISSUE"] = "ISSUE";
2966
+ /** Material came back from the consuming location, unused. */
2967
+ ConsumptionChangeKind["RETURN"] = "RETURN";
2968
+ /** Material at the consuming location was used up and left inventory. */
2969
+ ConsumptionChangeKind["SETTLE"] = "SETTLE";
2970
+ })(exports.ConsumptionChangeKind || (exports.ConsumptionChangeKind = {}));
2971
+
2972
+ const ConsumptionOrderChangeEntity = Symbol('ConsumptionOrderChangeEntity');
2973
+ exports.ConsumptionOrderChangeEntityClass = class ConsumptionOrderChangeEntityClass {
2974
+ id;
2975
+ itemId;
2976
+ /** Positive for an issue, negative for a return or a settlement. */
2977
+ quantityChanged;
2978
+ /**
2979
+ * Which of the three actions wrote this row. A return and a settlement are
2980
+ * both negative, so the sign cannot carry it -- see
2981
+ * {@link ConsumptionChangeKind}.
2982
+ */
2983
+ kind;
2984
+ createdAt;
2985
+ order;
2986
+ item;
2987
+ };
2988
+ tslib.__decorate([
2989
+ typeorm.PrimaryGeneratedColumn('uuid'),
2990
+ tslib.__metadata("design:type", String)
2991
+ ], exports.ConsumptionOrderChangeEntityClass.prototype, "id", void 0);
2992
+ tslib.__decorate([
2993
+ typeorm.Column({ type: 'uuid' }),
2994
+ typeorm.Index(),
2995
+ tslib.__metadata("design:type", String)
2996
+ ], exports.ConsumptionOrderChangeEntityClass.prototype, "itemId", void 0);
2997
+ tslib.__decorate([
2998
+ typeorm.Column({ type: 'numeric' }),
2999
+ tslib.__metadata("design:type", Number)
3000
+ ], exports.ConsumptionOrderChangeEntityClass.prototype, "quantityChanged", void 0);
3001
+ tslib.__decorate([
3002
+ typeorm.Column({ type: 'varchar' }),
3003
+ typeorm.Index(),
3004
+ tslib.__metadata("design:type", String)
3005
+ ], exports.ConsumptionOrderChangeEntityClass.prototype, "kind", void 0);
3006
+ tslib.__decorate([
3007
+ typeorm.CreateDateColumn({ type: 'timestamptz' }),
3008
+ tslib.__metadata("design:type", Date)
3009
+ ], exports.ConsumptionOrderChangeEntityClass.prototype, "createdAt", void 0);
3010
+ tslib.__decorate([
3011
+ typeorm.OneToOne('orders'),
3012
+ typeorm.JoinColumn({ name: 'id', referencedColumnName: 'id' }),
3013
+ tslib.__metadata("design:type", wmsBaseNestjsModule.OrderEntity)
3014
+ ], exports.ConsumptionOrderChangeEntityClass.prototype, "order", void 0);
3015
+ tslib.__decorate([
3016
+ typeorm.ManyToOne('consumption_order_items', (item) => item.changes),
3017
+ typeorm.JoinColumn({ name: 'itemId', referencedColumnName: 'id' }),
3018
+ tslib.__metadata("design:type", exports.ConsumptionOrderItemEntityClass)
3019
+ ], exports.ConsumptionOrderChangeEntityClass.prototype, "item", void 0);
3020
+ exports.ConsumptionOrderChangeEntityClass = tslib.__decorate([
3021
+ typeorm.Entity('consumption_order_changes')
3022
+ ], exports.ConsumptionOrderChangeEntityClass);
3023
+
3024
+ /**
3025
+ * @file order-type.ts
3026
+ * The order families this package owns, named exactly as the `resource` half of
3027
+ * the matching {@link WmsOperationName}s.
3028
+ *
3029
+ * One vocabulary, two uses: it is what `@WmsOperation` already calls each
3030
+ * family, and it is what `order_references.orderType` stores. Reusing the
3031
+ * strings rather than inventing a parallel set means a host that has switched
3032
+ * `hold-inventory-order:create` off already knows the name to look for when it
3033
+ * queries that family's references.
3034
+ *
3035
+ * Adding a family here is additive for consumers; renaming one is a breaking
3036
+ * change, because the value is persisted in `order_references`.
3037
+ */
3038
+ exports.WmsOrderType = void 0;
3039
+ (function (WmsOrderType) {
3040
+ WmsOrderType["ALLOCATE_INVENTORY_ORDER"] = "allocate-inventory-order";
3041
+ WmsOrderType["CONSUMPTION_ORDER"] = "consumption-order";
3042
+ WmsOrderType["HOLD_INVENTORY_ORDER"] = "hold-inventory-order";
3043
+ WmsOrderType["INVENTORY_COUNT_ORDER"] = "inventory-count-order";
3044
+ WmsOrderType["MERGE_BATCH_ORDER"] = "merge-batch-order";
3045
+ WmsOrderType["QUALITY_INSPECTION_ORDER"] = "quality-inspection-order";
3046
+ WmsOrderType["RECEIVE_INVENTORY_ORDER"] = "receive-inventory-order";
3047
+ WmsOrderType["RECLASSIFY_INVENTORY_ORDER"] = "reclassify-inventory-order";
3048
+ WmsOrderType["SCRAPE_ORDER"] = "scrape-order";
3049
+ WmsOrderType["SHIP_INVENTORY_ORDER"] = "ship-inventory-order";
3050
+ WmsOrderType["SPLIT_BATCH_ORDER"] = "split-batch-order";
3051
+ WmsOrderType["TRANSFER_CUSTOMER_ORDER"] = "transfer-customer-order";
3052
+ WmsOrderType["TRANSFER_ORDER"] = "transfer-order";
3053
+ WmsOrderType["TRANSFER_VENDOR_ORDER"] = "transfer-vendor-order";
3054
+ })(exports.WmsOrderType || (exports.WmsOrderType = {}));
3055
+
3056
+ const OrderReferenceEntity = Symbol('OrderReferenceEntity');
3057
+ /**
3058
+ * Why an order was opened, in the host's own vocabulary.
3059
+ *
3060
+ * Every order family in this package records *what* moved and *when*, and none
3061
+ * of them records *what for*. A host that drives the warehouse from somewhere
3062
+ * else — a work order, a purchase order, a repair job, a subcontract — has no
3063
+ * way to ask "which stock movements happened because of this", and no way to
3064
+ * show an operator which upstream document a transfer belongs to.
3065
+ *
3066
+ * One polymorphic table rather than three columns on each of the thirteen order
3067
+ * entities: the reference is the same idea everywhere, a new order family picks
3068
+ * it up for free, and a per-item reference (`itemId`) has somewhere to live
3069
+ * without widening every item table too.
3070
+ *
3071
+ * `referenceType` / `referenceId` are opaque strings. This module never parses
3072
+ * them and never resolves them to anything — what a `work-order` is belongs to
3073
+ * the host, and `@rytass/wms-module-react`'s `referenceLinkResolver` is how a
3074
+ * host turns one into a link.
3075
+ *
3076
+ * Not to be confused with `ShipInventoryOrderReferenceEntityClass`, which
3077
+ * despite the name is a line-level shipment plan (it carries quantities and a
3078
+ * removal timestamp), not a pointer at an upstream document. The two coexist.
3079
+ */
3080
+ exports.OrderReferenceEntityClass = class OrderReferenceEntityClass {
3081
+ id;
3082
+ /** Which order family `orderId` belongs to. */
3083
+ orderType;
3084
+ orderId;
3085
+ /**
3086
+ * The order item this reference is about, when the reference is line-level —
3087
+ * one order covering several upstream lines. `null` means it applies to the
3088
+ * order as a whole.
3089
+ */
3090
+ itemId;
3091
+ /** Host-defined kind of document, e.g. `work-order`, `purchase-order`. */
3092
+ referenceType;
3093
+ /** The upstream document's identifier, as the host knows it. */
3094
+ referenceId;
3095
+ /** The line within that document, when it has lines. */
3096
+ referenceLine;
3097
+ /**
3098
+ * Anything else the host wants to carry along — an operation sequence, a
3099
+ * component line, a reason code. Stored verbatim and never interpreted.
3100
+ */
3101
+ metadata;
3102
+ createdAt;
3103
+ };
3104
+ tslib.__decorate([
3105
+ typeorm.PrimaryGeneratedColumn('uuid'),
3106
+ tslib.__metadata("design:type", String)
3107
+ ], exports.OrderReferenceEntityClass.prototype, "id", void 0);
3108
+ tslib.__decorate([
3109
+ typeorm.Column({ type: 'varchar' }),
3110
+ tslib.__metadata("design:type", String)
3111
+ ], exports.OrderReferenceEntityClass.prototype, "orderType", void 0);
3112
+ tslib.__decorate([
3113
+ typeorm.Column({ type: 'uuid' }),
3114
+ tslib.__metadata("design:type", String)
3115
+ ], exports.OrderReferenceEntityClass.prototype, "orderId", void 0);
3116
+ tslib.__decorate([
3117
+ typeorm.Column({ type: 'uuid', nullable: true }),
3118
+ tslib.__metadata("design:type", Object)
3119
+ ], exports.OrderReferenceEntityClass.prototype, "itemId", void 0);
3120
+ tslib.__decorate([
3121
+ typeorm.Column({ type: 'varchar' }),
3122
+ tslib.__metadata("design:type", String)
3123
+ ], exports.OrderReferenceEntityClass.prototype, "referenceType", void 0);
3124
+ tslib.__decorate([
3125
+ typeorm.Column({ type: 'varchar' }),
3126
+ tslib.__metadata("design:type", String)
3127
+ ], exports.OrderReferenceEntityClass.prototype, "referenceId", void 0);
3128
+ tslib.__decorate([
3129
+ typeorm.Column({ type: 'varchar', nullable: true }),
3130
+ tslib.__metadata("design:type", Object)
3131
+ ], exports.OrderReferenceEntityClass.prototype, "referenceLine", void 0);
3132
+ tslib.__decorate([
3133
+ typeorm.Column({ type: 'jsonb', nullable: true }),
3134
+ tslib.__metadata("design:type", Object)
3135
+ ], exports.OrderReferenceEntityClass.prototype, "metadata", void 0);
3136
+ tslib.__decorate([
3137
+ typeorm.CreateDateColumn({ type: 'timestamptz' }),
3138
+ tslib.__metadata("design:type", Date)
3139
+ ], exports.OrderReferenceEntityClass.prototype, "createdAt", void 0);
3140
+ exports.OrderReferenceEntityClass = tslib.__decorate([
3141
+ typeorm.Entity('order_references'),
3142
+ typeorm.Index(['orderType', 'orderId']),
3143
+ typeorm.Index(['referenceType', 'referenceId'])
3144
+ ], exports.OrderReferenceEntityClass);
3145
+
2711
3146
  const entities = [
2712
3147
  [UnitEntity, exports.UnitEntityClass],
2713
3148
  [MaterialEntity, exports.MaterialEntityClass],
@@ -2765,6 +3200,10 @@ const entities = [
2765
3200
  [InventoryCountOrderLocationEntity, exports.InventoryCountOrderLocationEntityClass],
2766
3201
  [InventoryCountOrderItemEntity, exports.InventoryCountOrderItemEntityClass],
2767
3202
  [InventoryCountOrderChangeEntity, exports.InventoryCountOrderChangeEntityClass],
3203
+ [OrderReferenceEntity, exports.OrderReferenceEntityClass],
3204
+ [ConsumptionOrderEntity, exports.ConsumptionOrderEntityClass],
3205
+ [ConsumptionOrderItemEntity, exports.ConsumptionOrderItemEntityClass],
3206
+ [ConsumptionOrderChangeEntity, exports.ConsumptionOrderChangeEntityClass],
2768
3207
  ];
2769
3208
  /**
2770
3209
  * The overridable entities are deliberately absent: `WmsModuleCoreModule` binds
@@ -2871,6 +3310,81 @@ exports.WmsEntities = tslib.__decorate([
2871
3310
  tslib.__metadata("design:paramtypes", [typeorm.DataSource, Object, Object, Object, Object, Object, Object])
2872
3311
  ], exports.WmsEntities);
2873
3312
 
3313
+ /**
3314
+ * Base service for order operations that create/deduct stock entries.
3315
+ * Provides common methods for adding and deducting inventory across different
3316
+ * order types.
3317
+ *
3318
+ * Public API, with one precondition that is easy to miss.
3319
+ *
3320
+ * `add` and `deduct` write an `orders` row and `stocks` rows — and nothing else.
3321
+ * They do **not** write a `*_order_changes` row, and both `StockChangeSubscriber`
3322
+ * and `InventoryCountLockSubscriber` hook the insert of that row. So a host that
3323
+ * extends this and registers `customChangeTables`, but leaves its own change row
3324
+ * unwritten, gets neither the `stock.*` event nor the inventory count lock: its
3325
+ * movements pass a running count in silence. Writing the change row is the
3326
+ * host's job, exactly as it is for every service in this package.
3327
+ *
3328
+ * What extending it does buy is unit conversion and
3329
+ * `StockService.validateStockAvailability` around the stock write. See
3330
+ * {@link WmsCustomChangeTable} for the rest of what a custom family inherits.
3331
+ */
3332
+ class BaseOrderService {
3333
+ /**
3334
+ * Creates a new order and saves a positive quantity stock entry
3335
+ * @param repos Repository map containing order and stock repositories
3336
+ * @param params Stock entry parameters (materialId, batchId, quantity, locationId?, loaderId?, unitId?)
3337
+ * @returns Created order ID
3338
+ */
3339
+ async add(repos, params) {
3340
+ const { materialId, batchId, quantity, locationId, loaderId, unitId } = params;
3341
+ // Create new order
3342
+ const order = await repos.order.save({});
3343
+ // Get conversion factor if unitId is provided
3344
+ const conversionFactor = await this.materialService.getConversionFactor(materialId, unitId);
3345
+ // Create positive stock entry linked to this order
3346
+ await repos.stock.save(repos.stock.create({
3347
+ orderId: order.id,
3348
+ materialId,
3349
+ batchId,
3350
+ locationId: this.stockService.resolveLocationId(locationId),
3351
+ loaderId: this.stockService.resolveLoaderId(loaderId),
3352
+ quantity: quantity * conversionFactor,
3353
+ }));
3354
+ return order.id;
3355
+ }
3356
+ /**
3357
+ * Creates a negative quantity stock entry linked to a source order
3358
+ * Used to deduct stock from an existing status (FREE, ALLOCATED, IN_TRANSFER, etc.)
3359
+ * @param repos Repository map containing order and stock repositories
3360
+ * @param sourceOrderId The order ID to link the deduction to (typically an existing allocated/transferred order)
3361
+ * @param params Stock entry parameters (materialId, batchId, quantity, locationId?, loaderId?, unitId?)
3362
+ */
3363
+ async deduct(repos, params) {
3364
+ const { materialId, batchId, quantity, locationId, loaderId, unitId } = params;
3365
+ const order = await repos.order.save({});
3366
+ // Get conversion factor if unitId is provided
3367
+ const conversionFactor = await this.materialService.getConversionFactor(materialId, unitId);
3368
+ // Create negative stock entry linked to source order
3369
+ // This allows the status calculation to determine what status is being deducted from
3370
+ await this.stockService.validateStockAvailability({
3371
+ materialId,
3372
+ batchId,
3373
+ locationId: this.stockService.resolveLocationId(locationId),
3374
+ loaderId: this.stockService.resolveLoaderId(loaderId),
3375
+ quantity: quantity * conversionFactor,
3376
+ }, repos.stock.manager);
3377
+ await repos.stock.save(repos.stock.create({
3378
+ orderId: order.id,
3379
+ materialId,
3380
+ batchId,
3381
+ locationId: this.stockService.resolveLocationId(locationId),
3382
+ loaderId: this.stockService.resolveLoaderId(loaderId),
3383
+ quantity: -1 * quantity * conversionFactor,
3384
+ }));
3385
+ }
3386
+ }
3387
+
2874
3388
  exports.StockService = class StockService {
2875
3389
  dataSource;
2876
3390
  entities;
@@ -2920,6 +3434,7 @@ exports.StockService = class StockService {
2920
3434
  .addSelect('b."held"', 'held')
2921
3435
  .addSelect('b."inShipment"', 'inShipment')
2922
3436
  .addSelect('b."inspectionResult"', 'inspectionResult')
3437
+ .addSelect('b."requiresInspection"', 'requiresInspection')
2923
3438
  .addSelect('b."saleId"', 'saleId')
2924
3439
  .addSelect('b."vendorId"', 'vendorId')
2925
3440
  .addSelect('b."customerId"', 'customerId')
@@ -2930,6 +3445,7 @@ exports.StockService = class StockService {
2930
3445
  .addSelect('stock_status.held', 'held')
2931
3446
  .addSelect('stock_status."inShipment"', 'inShipment')
2932
3447
  .addSelect('stock_status."inspectionResult"', 'inspectionResult')
3448
+ .addSelect('stock_status."requiresInspection"', 'requiresInspection')
2933
3449
  .addSelect('stock_status."saleId"', 'saleId')
2934
3450
  .addSelect('stock_status."vendorId"', 'vendorId')
2935
3451
  .addSelect('stock_status."customerId"', 'customerId')
@@ -2992,6 +3508,8 @@ exports.StockService = class StockService {
2992
3508
  queryBuilder.andWhere('stock."locationId" = :locationId', {
2993
3509
  locationId: options.locationId,
2994
3510
  });
3511
+ if (options.excludeLocationIds?.length)
3512
+ queryBuilder.andWhere('stock."locationId" NOT IN (:...excludeLocationIds)', { excludeLocationIds: options.excludeLocationIds });
2995
3513
  if (options.loaderId)
2996
3514
  queryBuilder.andWhere('stock."loaderId" = :loaderId', {
2997
3515
  loaderId: options.loaderId,
@@ -3009,7 +3527,13 @@ exports.StockService = class StockService {
3009
3527
  if (options.status) {
3010
3528
  switch (options.status) {
3011
3529
  case exports.StockStatus.PENDING_INSPECTION:
3012
- queryBuilder.andWhere('stock_status."inspectionResult" IS NULL');
3530
+ /*
3531
+ * Both halves are required. `inspectionResult IS NULL` alone is the
3532
+ * resting state of every batch nobody ever asked to inspect, so on
3533
+ * its own it reported the whole warehouse as awaiting inspection --
3534
+ * a wrong answer that looked plausible because it was never zero.
3535
+ */
3536
+ queryBuilder.andWhere('stock_status."requiresInspection" = true AND stock_status."inspectionResult" IS NULL');
3013
3537
  break;
3014
3538
  case exports.StockStatus.INSPECTION_FAILED:
3015
3539
  queryBuilder.andWhere('stock_status."inspectionResult" = false');
@@ -3033,7 +3557,7 @@ exports.StockService = class StockService {
3033
3557
  if (options.negateStatus) {
3034
3558
  switch (options.negateStatus) {
3035
3559
  case exports.StockStatus.PENDING_INSPECTION:
3036
- queryBuilder.andWhere('stock_status."inspectionResult" IS NOT NULL');
3560
+ queryBuilder.andWhere('NOT (stock_status."requiresInspection" = true AND stock_status."inspectionResult" IS NULL)');
3037
3561
  break;
3038
3562
  case exports.StockStatus.INSPECTION_FAILED:
3039
3563
  queryBuilder.andWhere('(stock_status."inspectionResult" IS NULL OR stock_status."inspectionResult" != false)');
@@ -3120,6 +3644,16 @@ exports.StockService = class StockService {
3120
3644
  queryBuilder.addSelect('b."customerId"', 'customerId');
3121
3645
  queryBuilder.addSelect('b."vendorId"', 'vendorId');
3122
3646
  queryBuilder.addSelect('b."inspectionResult"', 'inspectionResult');
3647
+ queryBuilder.addSelect('b."requiresInspection"', 'requiresInspection');
3648
+ /*
3649
+ * Lineage and the host's own attributes, carried along the same way the
3650
+ * commercial attributes above are. Both are functionally dependent on
3651
+ * `batchId`, which is already a grouping key, but SQL still wants them
3652
+ * named in GROUP BY. `attributes` is jsonb, which groups fine — jsonb has
3653
+ * equality and a btree opclass.
3654
+ */
3655
+ queryBuilder.addSelect('b."parentBatchId"', 'parentBatchId');
3656
+ queryBuilder.addSelect('b."attributes"', 'attributes');
3123
3657
  queryBuilder.addSelect('SUM(stock.quantity)', 'quantity');
3124
3658
  queryBuilder.groupBy('stock."materialId"');
3125
3659
  queryBuilder.addGroupBy('stock."batchId"');
@@ -3134,6 +3668,9 @@ exports.StockService = class StockService {
3134
3668
  queryBuilder.addGroupBy('b."customerId"');
3135
3669
  queryBuilder.addGroupBy('b."vendorId"');
3136
3670
  queryBuilder.addGroupBy('b."inspectionResult"');
3671
+ queryBuilder.addGroupBy('b."requiresInspection"');
3672
+ queryBuilder.addGroupBy('b."parentBatchId"');
3673
+ queryBuilder.addGroupBy('b."attributes"');
3137
3674
  queryBuilder.having('SUM(stock.quantity) <> 0');
3138
3675
  if (options.aggregatedKeys?.length)
3139
3676
  queryBuilder.andHaving([
@@ -3218,6 +3755,9 @@ exports.StockService = class StockService {
3218
3755
  paginatedQueryBuilder.addSelect('agg."customerId"', 'customerId');
3219
3756
  paginatedQueryBuilder.addSelect('agg."vendorId"', 'vendorId');
3220
3757
  paginatedQueryBuilder.addSelect('agg."inspectionResult"', 'inspectionResult');
3758
+ paginatedQueryBuilder.addSelect('agg."requiresInspection"', 'requiresInspection');
3759
+ paginatedQueryBuilder.addSelect('agg."parentBatchId"', 'parentBatchId');
3760
+ paginatedQueryBuilder.addSelect('agg."attributes"', 'attributes');
3221
3761
  // Apply pagination to the outer query
3222
3762
  if (options.offset !== undefined && options.offset >= 0) {
3223
3763
  paginatedQueryBuilder.skip(options.offset);
@@ -3757,6 +4297,23 @@ exports.BatchService = class BatchService {
3757
4297
  throw new Error('Inspection result already set, cannot modify');
3758
4298
  }
3759
4299
  }
4300
+ /**
4301
+ * Find the unsplit batch carrying `key` for this material, or create it.
4302
+ *
4303
+ * `parentBatchId` and `attributes` are write-on-create only: the lookup still
4304
+ * matches on key, material and the unsplit condition alone, so a caller that
4305
+ * passes them for a key that already exists gets the existing batch back
4306
+ * untouched. `key` is the batch's identity in this model — `batches` carries
4307
+ * `UNIQUE (key, materialId)`, so there is exactly one row per key — and
4308
+ * attributes describe a batch rather than distinguish one. A host that needs
4309
+ * two distinct batches gives them two keys; asking for two here fails on the
4310
+ * constraint.
4311
+ *
4312
+ * Deliberately **not** filtered on `requiresInspection`: a receipt awaiting
4313
+ * inspection may flag the batch in place, and the flag must not then hide the
4314
+ * key from the next lookup — which, given the unique constraint, would leave
4315
+ * it trying to create a duplicate.
4316
+ */
3760
4317
  async getBatch({ manager = this.dataSource.manager, ...options }) {
3761
4318
  const batchRepository = manager.getRepository(this.batchEntity);
3762
4319
  const batchGroupRepository = manager.getRepository(this.batchGroupEntity);
@@ -3821,6 +4378,21 @@ exports.BatchService = class BatchService {
3821
4378
  transferId: orNull(mergedBatch.transferId),
3822
4379
  held: mergedBatch.held ?? false,
3823
4380
  inShipment: mergedBatch.inShipment ?? false,
4381
+ // Part of the batch's identity: material waiting on an inspection must
4382
+ // not be merged back into the free stock it was split away from.
4383
+ requiresInspection: mergedBatch.requiresInspection ?? false,
4384
+ /*
4385
+ * Attributes take part in the identity check, so a split that asks for
4386
+ * `{ bin: 'B1' }` never lands on the sibling holding `{ bin: 'B2' }`.
4387
+ * Compared as `jsonb`, whose equality is by content rather than by the
4388
+ * text of the document, so key order and whitespace do not matter — which
4389
+ * a plain string comparison on the serialized column would get wrong.
4390
+ */
4391
+ attributes: mergedBatch.attributes === null || mergedBatch.attributes === undefined
4392
+ ? typeorm.IsNull()
4393
+ : typeorm.Raw((alias) => `${alias} = cast(:batchAttributes as jsonb)`, {
4394
+ batchAttributes: JSON.stringify(mergedBatch.attributes),
4395
+ }),
3824
4396
  };
3825
4397
  // Check if a batch with these exact metrics already exists in the same group
3826
4398
  const existingBatch = await batchRepository.findOne({
@@ -3833,6 +4405,10 @@ exports.BatchService = class BatchService {
3833
4405
  return batchRepository.save(batchRepository.create({
3834
4406
  ...mergedBatch,
3835
4407
  key: `${batch.batchGroup.key}_${Date.now().toString()}`,
4408
+ // Not inherited from `mergedBatch`: spreading the source batch would
4409
+ // copy *its* parent and flatten the chain by one link. The parent of
4410
+ // the batch being created is the batch it was split out of.
4411
+ parentBatchId: batch.id,
3836
4412
  id: undefined,
3837
4413
  }));
3838
4414
  }
@@ -4136,89 +4712,139 @@ exports.ReceiveInventoryOrderService = class ReceiveInventoryOrderService {
4136
4712
  const locationRepository = manager.getRepository(this.entities.location);
4137
4713
  const loaderRepository = manager.getRepository(exports.LoadersEntityClass);
4138
4714
  const stockRepository = manager.getRepository(this.entities.stock);
4715
+ const batchRepository = manager.getRepository(this.entities.batch);
4139
4716
  const items = await itemRepository.find({
4140
4717
  where: { id: typeorm.In(options.map((o) => o.itemId)) },
4141
4718
  relations: { changes: true },
4142
4719
  });
4143
4720
  const itemMap = new Map(items.map((i) => [i.id, i]));
4144
- await Promise.all(options.map(async (option) => {
4145
- const item = itemMap.get(option.itemId);
4146
- if (!item)
4147
- return;
4148
- if (!item.batchId && option.batchKey) {
4149
- // if batchKey is provided but item doesn't have batchId, attempt to find or create batch and update item with batchId
4150
- item.batchId = await this.batchService
4151
- .getBatch({
4152
- manager,
4153
- key: option.batchKey,
4154
- materialId: item.materialId,
4155
- })
4156
- .then(async (b) => {
4157
- await itemRepository.update({ id: item.id }, { batchId: b.id });
4158
- return b.id;
4159
- });
4160
- }
4161
- const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId || undefined);
4162
- const totalChanged = item.changes.reduce((sum, change) => sum + Number(change.quantityChanged), 0);
4163
- const remainingQuantity = conversionFactor * item.targetReceivedQuantity - totalChanged;
4164
- if (remainingQuantity - option.quantity * conversionFactor < 0) {
4165
- throw new Error(`Receiving quantity exceeds target for item ${option.itemId}`);
4166
- }
4167
- const newOrder = await orderRepository.save(orderRepository.create());
4168
- let batchId = item.batchId;
4169
- if (option.batchKey)
4170
- batchId = await this.batchService
4171
- .getBatch({
4172
- manager,
4173
- key: option.batchKey,
4174
- materialId: item.materialId,
4175
- })
4176
- .then(({ id }) => id);
4177
- if (!batchId)
4178
- batchId = await this.batchService
4179
- .getBatch({
4180
- manager,
4181
- key: await this.helperService.getSeq('BATCH'),
4182
- materialId: item.materialId,
4183
- })
4184
- .then(({ id }) => id);
4185
- const inspectionResult = item.requireInspection === false
4186
- ? true
4187
- : (option.inspectionResult ?? null);
4188
- if (inspectionResult != null)
4189
- batchId = await this.batchService
4190
- .splitBatch({
4191
- manager,
4192
- id: batchId,
4193
- inspectionResult,
4194
- })
4195
- .then(({ id }) => id);
4196
- let locationId = item.locationId;
4197
- if (option.locationKey && !locationId)
4198
- locationId = await locationRepository
4199
- .findOneByOrFail({ key: option.locationKey })
4200
- .then(({ id }) => id);
4201
- let loaderId = item.loaderId;
4202
- if (option.loaderKey && !loaderId)
4203
- loaderId = await loaderRepository
4204
- .findOneByOrFail({ serialId: option.loaderKey })
4205
- .then(({ id }) => id);
4206
- await Promise.all([
4207
- changeRepository.save(changeRepository.create({
4208
- itemId: option.itemId,
4209
- quantityChanged: option.quantity * conversionFactor,
4210
- id: newOrder.id,
4211
- })),
4212
- stockRepository.save(stockRepository.create({
4213
- batchId: batchId || undefined,
4214
- locationId: this.stockService.resolveLocationId(locationId),
4215
- loaderId: this.stockService.resolveLoaderId(loaderId),
4216
- materialId: item.materialId,
4217
- quantity: option.quantity * conversionFactor,
4218
- orderId: newOrder.id,
4219
- })),
4220
- ]);
4221
- }));
4721
+ /*
4722
+ * Sequential, not `Promise.all`. Two options for one item both reach the
4723
+ * batch lookups below before either has written, so `splitBatch`'s
4724
+ * read-then-create misses twice and one receipt ends up fragmented across
4725
+ * two batch identities. A receive order has a handful of lines; ordering
4726
+ * them costs nothing worth measuring.
4727
+ */
4728
+ for (const option of options) {
4729
+ await (async () => {
4730
+ const item = itemMap.get(option.itemId);
4731
+ if (!item)
4732
+ return;
4733
+ if (!item.batchId && option.batchKey) {
4734
+ // if batchKey is provided but item doesn't have batchId, attempt to find or create batch and update item with batchId
4735
+ item.batchId = await this.batchService
4736
+ .getBatch({
4737
+ manager,
4738
+ key: option.batchKey,
4739
+ materialId: item.materialId,
4740
+ })
4741
+ .then(async (b) => {
4742
+ await itemRepository.update({ id: item.id }, { batchId: b.id });
4743
+ return b.id;
4744
+ });
4745
+ }
4746
+ const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId || undefined);
4747
+ const totalChanged = item.changes.reduce((sum, change) => sum + Number(change.quantityChanged), 0);
4748
+ const remainingQuantity = conversionFactor * item.targetReceivedQuantity - totalChanged;
4749
+ if (remainingQuantity - option.quantity * conversionFactor < 0) {
4750
+ throw new Error(`Receiving quantity exceeds target for item ${option.itemId}`);
4751
+ }
4752
+ const newOrder = await orderRepository.save(orderRepository.create());
4753
+ let batchId = item.batchId;
4754
+ if (option.batchKey)
4755
+ batchId = await this.batchService
4756
+ .getBatch({
4757
+ manager,
4758
+ key: option.batchKey,
4759
+ materialId: item.materialId,
4760
+ })
4761
+ .then(({ id }) => id);
4762
+ if (!batchId)
4763
+ batchId = await this.batchService
4764
+ .getBatch({
4765
+ manager,
4766
+ key: await this.helperService.getSeq('BATCH'),
4767
+ materialId: item.materialId,
4768
+ })
4769
+ .then(({ id }) => id);
4770
+ const inspectionResult = item.requireInspection === false
4771
+ ? true
4772
+ : (option.inspectionResult ?? null);
4773
+ if (inspectionResult != null) {
4774
+ batchId = await this.batchService
4775
+ .splitBatch({
4776
+ manager,
4777
+ id: batchId,
4778
+ inspectionResult,
4779
+ })
4780
+ .then(({ id }) => id);
4781
+ }
4782
+ else if (item.requireInspection) {
4783
+ /*
4784
+ * Somebody asked for this to be inspected and it has not been yet.
4785
+ * Recording that on the batch is what lets `PENDING_INSPECTION`
4786
+ * mean "awaiting inspection" rather than "never inspected" -- the
4787
+ * latter being true of almost every batch in the warehouse.
4788
+ *
4789
+ * Split only when the batch already holds something. `require-
4790
+ * Inspection` defaults to **true**, so this is the ordinary receive
4791
+ * path, not an edge case: splitting unconditionally moved every
4792
+ * default receipt off the batch key the caller asked for and onto a
4793
+ * synthetic child, which an exact-id lookup then could not find.
4794
+ *
4795
+ * A batch with nothing on it yet has nothing to commingle with, so
4796
+ * flagging it in place is both sufficient and invisible. Only a
4797
+ * receipt joining stock that is already there needs its own batch,
4798
+ * which is the same thing holding or shipping part of a batch does.
4799
+ */
4800
+ const onHand = await stockRepository
4801
+ .createQueryBuilder('stock')
4802
+ .select('COALESCE(SUM(stock.quantity), 0)', 'total')
4803
+ .where('stock."batchId" = :batchId', { batchId })
4804
+ .getRawOne()
4805
+ .then((row) => parseFloat(row?.total ?? '0'));
4806
+ if (onHand > 0) {
4807
+ batchId = await this.batchService
4808
+ .splitBatch({
4809
+ manager,
4810
+ id: batchId,
4811
+ requiresInspection: true,
4812
+ })
4813
+ .then(({ id }) => id);
4814
+ }
4815
+ else {
4816
+ await batchRepository.update({ id: batchId }, {
4817
+ requiresInspection: true,
4818
+ });
4819
+ }
4820
+ }
4821
+ let locationId = item.locationId;
4822
+ if (option.locationKey && !locationId)
4823
+ locationId = await locationRepository
4824
+ .findOneByOrFail({ key: option.locationKey })
4825
+ .then(({ id }) => id);
4826
+ let loaderId = item.loaderId;
4827
+ if (option.loaderKey && !loaderId)
4828
+ loaderId = await loaderRepository
4829
+ .findOneByOrFail({ serialId: option.loaderKey })
4830
+ .then(({ id }) => id);
4831
+ await Promise.all([
4832
+ changeRepository.save(changeRepository.create({
4833
+ itemId: option.itemId,
4834
+ quantityChanged: option.quantity * conversionFactor,
4835
+ id: newOrder.id,
4836
+ })),
4837
+ stockRepository.save(stockRepository.create({
4838
+ batchId: batchId || undefined,
4839
+ locationId: this.stockService.resolveLocationId(locationId),
4840
+ loaderId: this.stockService.resolveLoaderId(loaderId),
4841
+ materialId: item.materialId,
4842
+ quantity: option.quantity * conversionFactor,
4843
+ orderId: newOrder.id,
4844
+ })),
4845
+ ]);
4846
+ })();
4847
+ }
4222
4848
  return true;
4223
4849
  });
4224
4850
  }
@@ -5950,64 +6576,83 @@ exports.SplitBatchOrderService = class SplitBatchOrderService {
5950
6576
  const originalBatch = await batchRepository.findOneOrFail({
5951
6577
  where: { id: options.batchId },
5952
6578
  });
6579
+ /*
6580
+ * `batches` carries `UNIQUE (key, materialId)`, so two items aiming at the
6581
+ * same target key cannot both create one. Left alone they race
6582
+ * `getBatch`'s read-then-create and the second insert aborts the whole
6583
+ * split with a constraint violation that names neither item.
6584
+ */
6585
+ const duplicateKey = options.items
6586
+ .map(({ batchKey }) => batchKey)
6587
+ .find((batchKey, index, keys) => keys.indexOf(batchKey) !== index);
6588
+ if (duplicateKey) {
6589
+ throw new Error(`Split order names batch key "${duplicateKey}" more than once; each child needs its own key.`);
6590
+ }
5953
6591
  const key = await this.helperService.getSeq(this.seqPrefix, manager);
5954
6592
  const order = await splitBatchOrderRepository.save(splitBatchOrderRepository.create({
5955
6593
  key,
5956
6594
  }));
5957
6595
  // Get conversion factor for unit conversion
5958
6596
  const conversionFactor = await this.materialService.getConversionFactor(originalBatch.materialId, options.unitId || undefined);
5959
- // Process each item split
5960
- await Promise.all(options.items.map(async (item) => {
5961
- // Get or create target batch
5962
- const targetBatch = await this.batchService.getBatch({
5963
- key: item.batchKey,
5964
- materialId: originalBatch.materialId,
5965
- manager,
5966
- });
5967
- // Create base order record
5968
- const baseOrder = await orderRepository.save({});
5969
- // Create split batch order item
5970
- const splitItem = await splitBatchOrderItemRepository.save(splitBatchOrderItemRepository.create({
5971
- targetSplitQuantity: item.quantity,
5972
- locationId: this.stockService.resolveLocationId(item.locationId),
5973
- loaderId: item.loaderId,
5974
- orderId: order.id,
5975
- }));
5976
- // Record the change
5977
- await splitBatchOrderChangeRepository.save(splitBatchOrderChangeRepository.create({
5978
- itemId: splitItem.id,
5979
- id: baseOrder.id,
5980
- quantityChanged: item.quantity * conversionFactor,
5981
- }));
5982
- // Update stock: deduct from original batch and add to target batch
5983
- await this.stockService.validateStockAvailability({
5984
- materialId: originalBatch.materialId,
5985
- batchId: options.batchId,
5986
- locationId: this.stockService.resolveLocationId(item.locationId),
5987
- loaderId: this.stockService.resolveLoaderId(item.loaderId),
5988
- quantity: item.quantity * conversionFactor,
5989
- }, manager);
5990
- await stockRepository.save(stockRepository.create([
5991
- // Deduct from original batch
5992
- {
5993
- orderId: baseOrder.id,
6597
+ // Sequential: two items can reference the same *source* batch, and the
6598
+ // availability check below reads the ledger the earlier item just wrote.
6599
+ for (const item of options.items) {
6600
+ await (async () => {
6601
+ // Get or create target batch. The genealogy link and the host's
6602
+ // attributes only land when this call creates the batch — reusing an
6603
+ // existing key keeps whatever it already carries.
6604
+ const targetBatch = await this.batchService.getBatch({
6605
+ key: item.batchKey,
5994
6606
  materialId: originalBatch.materialId,
5995
- batchId: options.batchId,
6607
+ parentBatchId: options.batchId,
6608
+ attributes: item.attributes ?? null,
6609
+ manager,
6610
+ });
6611
+ // Create base order record
6612
+ const baseOrder = await orderRepository.save({});
6613
+ // Create split batch order item
6614
+ const splitItem = await splitBatchOrderItemRepository.save(splitBatchOrderItemRepository.create({
6615
+ targetSplitQuantity: item.quantity,
5996
6616
  locationId: this.stockService.resolveLocationId(item.locationId),
5997
- loaderId: this.stockService.resolveLoaderId(item.loaderId),
5998
- quantity: -1 * item.quantity * conversionFactor,
5999
- },
6000
- // Add to target batch
6001
- {
6002
- orderId: baseOrder.id,
6617
+ loaderId: item.loaderId,
6618
+ orderId: order.id,
6619
+ }));
6620
+ // Record the change
6621
+ await splitBatchOrderChangeRepository.save(splitBatchOrderChangeRepository.create({
6622
+ itemId: splitItem.id,
6623
+ id: baseOrder.id,
6624
+ quantityChanged: item.quantity * conversionFactor,
6625
+ }));
6626
+ // Update stock: deduct from original batch and add to target batch
6627
+ await this.stockService.validateStockAvailability({
6003
6628
  materialId: originalBatch.materialId,
6004
- batchId: targetBatch.id,
6629
+ batchId: options.batchId,
6005
6630
  locationId: this.stockService.resolveLocationId(item.locationId),
6006
6631
  loaderId: this.stockService.resolveLoaderId(item.loaderId),
6007
6632
  quantity: item.quantity * conversionFactor,
6008
- },
6009
- ]));
6010
- }));
6633
+ }, manager);
6634
+ await stockRepository.save(stockRepository.create([
6635
+ // Deduct from original batch
6636
+ {
6637
+ orderId: baseOrder.id,
6638
+ materialId: originalBatch.materialId,
6639
+ batchId: options.batchId,
6640
+ locationId: this.stockService.resolveLocationId(item.locationId),
6641
+ loaderId: this.stockService.resolveLoaderId(item.loaderId),
6642
+ quantity: -1 * item.quantity * conversionFactor,
6643
+ },
6644
+ // Add to target batch
6645
+ {
6646
+ orderId: baseOrder.id,
6647
+ materialId: originalBatch.materialId,
6648
+ batchId: targetBatch.id,
6649
+ locationId: this.stockService.resolveLocationId(item.locationId),
6650
+ loaderId: this.stockService.resolveLoaderId(item.loaderId),
6651
+ quantity: item.quantity * conversionFactor,
6652
+ },
6653
+ ]));
6654
+ })();
6655
+ }
6011
6656
  return order;
6012
6657
  });
6013
6658
  }
@@ -6164,6 +6809,574 @@ exports.MergeBatchOrderService = tslib.__decorate([
6164
6809
  exports.StockService, Object, Object])
6165
6810
  ], exports.MergeBatchOrderService);
6166
6811
 
6812
+ /**
6813
+ * Material handed to a process that consumes it: issue it out, take back what
6814
+ * came home, settle what was used.
6815
+ *
6816
+ * The three actions share one order because they are one story, and because
6817
+ * that is the grammar the rest of this package already speaks — hold/release,
6818
+ * allocate/deallocate and transfer/cancel are each a single order too.
6819
+ *
6820
+ * No new stock status. An issue is a location move and nothing else: status
6821
+ * here is a flag on the *batch*, so a "being consumed" status would force every
6822
+ * partial issue to split a child batch off it, and one batch key per issue is a
6823
+ * worse answer than one location. What the process actually is — a work order,
6824
+ * a repair job, a subcontract — belongs in `order_references`, which can say
6825
+ * *which* one; a status could only ever say "some".
6826
+ */
6827
+ exports.ConsumptionOrderService = class ConsumptionOrderService {
6828
+ dataSource;
6829
+ entities;
6830
+ helperService;
6831
+ materialService;
6832
+ stockService;
6833
+ consumptionOrderEntity;
6834
+ consumptionOrderItemEntity;
6835
+ stockEntity;
6836
+ seqPrefix = 'CSO';
6837
+ consumptionOrderRepository;
6838
+ constructor(dataSource, entities, helperService, materialService, stockService, consumptionOrderEntity, consumptionOrderItemEntity, stockEntity) {
6839
+ this.dataSource = dataSource;
6840
+ this.entities = entities;
6841
+ this.helperService = helperService;
6842
+ this.materialService = materialService;
6843
+ this.stockService = stockService;
6844
+ this.consumptionOrderEntity = consumptionOrderEntity;
6845
+ this.consumptionOrderItemEntity = consumptionOrderItemEntity;
6846
+ this.stockEntity = stockEntity;
6847
+ this.consumptionOrderRepository = this.dataSource.getRepository(this.consumptionOrderEntity);
6848
+ }
6849
+ getRepositories(manager) {
6850
+ return {
6851
+ consumptionOrder: manager.getRepository(this.consumptionOrderEntity),
6852
+ consumptionOrderItem: manager.getRepository(this.consumptionOrderItemEntity),
6853
+ consumptionOrderChange: manager.getRepository(exports.ConsumptionOrderChangeEntityClass),
6854
+ order: manager.getRepository(this.entities.order),
6855
+ stock: manager.getRepository(this.stockEntity),
6856
+ };
6857
+ }
6858
+ itemRow(input, orderId) {
6859
+ const locationId = this.stockService.resolveLocationId(input.locationId);
6860
+ return {
6861
+ orderId,
6862
+ materialId: input.materialId,
6863
+ batchId: input.batchId,
6864
+ locationId,
6865
+ loaderId: this.stockService.resolveLoaderId(input.loaderId),
6866
+ unitId: input.unitId ?? null,
6867
+ targetConsumedQuantity: input.quantity,
6868
+ // Defaulting the destination to the source keeps a host that does not
6869
+ // separate a consuming location from the shelf working: the stock rows
6870
+ // net out and only the change rows record what happened.
6871
+ targetLocationId: this.stockService.resolveLocationId(input.targetLocationId ?? locationId),
6872
+ targetLoaderId: this.stockService.resolveLoaderId(input.targetLoaderId ?? input.loaderId),
6873
+ };
6874
+ }
6875
+ async createConsumptionOrder(options) {
6876
+ if (!options.items.length) {
6877
+ throw new Error('A consumption order needs at least one item');
6878
+ }
6879
+ return this.dataSource.transaction(async (manager) => {
6880
+ const repos = this.getRepositories(manager);
6881
+ const key = await this.helperService.getSeq(this.seqPrefix, manager);
6882
+ const order = await repos.consumptionOrder.save(repos.consumptionOrder.create({
6883
+ key,
6884
+ description: options.description ?? null,
6885
+ createdBy: options.createdBy ?? null,
6886
+ }));
6887
+ await repos.consumptionOrderItem.save(options.items.map((item) => repos.consumptionOrderItem.create(this.itemRow(item, order.id))));
6888
+ return order;
6889
+ });
6890
+ }
6891
+ /**
6892
+ * Replace the order's lines. Refused once anything has moved: the changes
6893
+ * point at items, so swapping the items out from under them would leave the
6894
+ * ledger describing lines that no longer exist.
6895
+ */
6896
+ async updateConsumptionOrder(options) {
6897
+ return this.dataSource.transaction(async (manager) => {
6898
+ const repos = this.getRepositories(manager);
6899
+ const order = await repos.consumptionOrder.findOneOrFail({
6900
+ where: { id: options.id },
6901
+ });
6902
+ if (order.removedAt) {
6903
+ // The "has anything moved" check below only looks at live items, and a
6904
+ // removed order has none — so without this it would happily attach a
6905
+ // fresh set of lines to an order that is supposed to be gone.
6906
+ throw new Error(`Consumption order ${order.key} has been removed and cannot be updated`);
6907
+ }
6908
+ if (options.description !== undefined) {
6909
+ await repos.consumptionOrder.update(order.id, {
6910
+ description: options.description,
6911
+ });
6912
+ }
6913
+ if (options.items) {
6914
+ const existing = await repos.consumptionOrderItem.find({
6915
+ where: { orderId: order.id, removedAt: typeorm.IsNull() },
6916
+ });
6917
+ const moved = existing.length
6918
+ ? await repos.consumptionOrderChange.count({
6919
+ where: { itemId: typeorm.In(existing.map(({ id }) => id)) },
6920
+ })
6921
+ : 0;
6922
+ if (moved > 0) {
6923
+ throw new Error(`Consumption order ${order.key} has already moved stock; its items can no longer be replaced`);
6924
+ }
6925
+ await repos.consumptionOrderItem.remove(existing);
6926
+ await repos.consumptionOrderItem.save(options.items.map((item) => repos.consumptionOrderItem.create(this.itemRow(item, order.id))));
6927
+ }
6928
+ return repos.consumptionOrder.findOneOrFail({
6929
+ where: { id: order.id },
6930
+ });
6931
+ });
6932
+ }
6933
+ async removeConsumptionOrder(id) {
6934
+ return this.dataSource.transaction(async (manager) => {
6935
+ const repos = this.getRepositories(manager);
6936
+ const items = await repos.consumptionOrderItem.find({
6937
+ where: { orderId: id, removedAt: typeorm.IsNull() },
6938
+ });
6939
+ const moved = items.length
6940
+ ? await repos.consumptionOrderChange.count({
6941
+ where: { itemId: typeorm.In(items.map(({ id: itemId }) => itemId)) },
6942
+ })
6943
+ : 0;
6944
+ if (moved > 0) {
6945
+ throw new Error(`Consumption order ${id} has already moved stock and cannot be removed`);
6946
+ }
6947
+ const removedAt = new Date();
6948
+ await repos.consumptionOrderItem.update({ orderId: id }, {
6949
+ removedAt,
6950
+ });
6951
+ await repos.consumptionOrder.update(id, { removedAt });
6952
+ return true;
6953
+ });
6954
+ }
6955
+ /**
6956
+ * How much of each line has moved, **in base units**.
6957
+ *
6958
+ * The changes are the only record of that — nothing is denormalised onto the
6959
+ * item — so `issue`, `return` and `settle` all read it back before they write.
6960
+ *
6961
+ * Base units on both sides is the point. `quantityChanged` is written in base
6962
+ * units (the stock ledger's own unit), while `targetConsumedQuantity` is
6963
+ * stored in whatever unit the line was written in. Reporting the two side by
6964
+ * side without converting made every comparison in `act` wrong by the
6965
+ * conversion factor. `ReceiveInventoryOrderService` resolves the same tension
6966
+ * the same way.
6967
+ */
6968
+ async getProgress(orderId, manager = this.dataSource.manager) {
6969
+ const repos = this.getRepositories(manager);
6970
+ const items = await repos.consumptionOrderItem.find({
6971
+ where: { orderId, removedAt: typeorm.IsNull() },
6972
+ });
6973
+ if (!items.length)
6974
+ return [];
6975
+ const changes = await repos.consumptionOrderChange.find({
6976
+ where: { itemId: typeorm.In(items.map(({ id }) => id)) },
6977
+ });
6978
+ return Promise.all(items.map(async (item) => {
6979
+ const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId || undefined);
6980
+ const own = changes.filter((change) => change.itemId === item.id);
6981
+ const sum = (kind) => own
6982
+ .filter((change) => change.kind === kind)
6983
+ .reduce((total, change) => total + Math.abs(Number(change.quantityChanged)), 0);
6984
+ const issued = sum(exports.ConsumptionChangeKind.ISSUE);
6985
+ const returned = sum(exports.ConsumptionChangeKind.RETURN);
6986
+ const settled = sum(exports.ConsumptionChangeKind.SETTLE);
6987
+ return {
6988
+ itemId: item.id,
6989
+ target: Number(item.targetConsumedQuantity) * conversionFactor,
6990
+ issued,
6991
+ returned,
6992
+ settled,
6993
+ outstanding: issued - returned - settled,
6994
+ };
6995
+ }));
6996
+ }
6997
+ /**
6998
+ * Hand material to the process: it leaves the source location and appears at
6999
+ * the consuming one. Nothing about the batch changes.
7000
+ */
7001
+ issue(options) {
7002
+ return this.act(options, exports.ConsumptionChangeKind.ISSUE);
7003
+ }
7004
+ /** Take back material the process did not use. */
7005
+ return(options) {
7006
+ return this.act(options, exports.ConsumptionChangeKind.RETURN);
7007
+ }
7008
+ /** Close out material the process used up: it leaves inventory. */
7009
+ settle(options) {
7010
+ return this.act(options, exports.ConsumptionChangeKind.SETTLE);
7011
+ }
7012
+ async act(options, kind) {
7013
+ return this.dataSource.transaction(async (manager) => {
7014
+ const repos = this.getRepositories(manager);
7015
+ /*
7016
+ * Serialise concurrent actions on one order before reading anything.
7017
+ *
7018
+ * The whole guard rests on a progress snapshot, and two transactions that
7019
+ * both read it before either writes both believe the line is untouched --
7020
+ * so a ten-unit line goes out twice. `validateStockAvailability` does not
7021
+ * save us: it checks that the shelf has the stock, not that the order
7022
+ * asked for it, so the over-draw only surfaces when the shelf happens to
7023
+ * be short.
7024
+ */
7025
+ const order = await repos.consumptionOrder.findOne({
7026
+ where: { id: options.orderId },
7027
+ lock: { mode: 'pessimistic_write' },
7028
+ });
7029
+ if (!order) {
7030
+ throw new Error(`Consumption order ${options.orderId} does not exist`);
7031
+ }
7032
+ if (order.removedAt) {
7033
+ // Nothing else reads the order's own `removedAt`, so without this a
7034
+ // removed order still moves stock while staying out of every listing.
7035
+ throw new Error(`Consumption order ${order.key} has been removed and cannot move stock`);
7036
+ }
7037
+ const items = await repos.consumptionOrderItem.find({
7038
+ where: { orderId: options.orderId, removedAt: typeorm.IsNull() },
7039
+ });
7040
+ if (!items.length) {
7041
+ throw new Error(`Consumption order ${options.orderId} has no items`);
7042
+ }
7043
+ const progress = await this.getProgress(options.orderId, manager);
7044
+ const progressById = new Map(progress.map((entry) => [entry.itemId, entry]));
7045
+ if (options.items?.length === 0) {
7046
+ // Omitting `items` already means "every line". An empty array is
7047
+ // therefore a caller that meant to name lines and computed none —
7048
+ // succeeding silently would hide that.
7049
+ throw new Error(`Consumption order ${order.key} was asked to ${kind.toLowerCase()} an empty line list; omit "items" to act on every line`);
7050
+ }
7051
+ const lines = options.items ??
7052
+ items.map((item) => ({ itemId: item.id, quantity: undefined }));
7053
+ /*
7054
+ * What this call has already moved, per line. The snapshot above is read
7055
+ * once, so without this two lines naming the same item would each see
7056
+ * "nothing moved yet" and both go through.
7057
+ */
7058
+ const movedInThisCall = new Map();
7059
+ for (const line of lines) {
7060
+ const item = items.find(({ id }) => id === line.itemId);
7061
+ if (!item) {
7062
+ throw new Error(`Item ${line.itemId} does not belong to consumption order ${options.orderId}`);
7063
+ }
7064
+ const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId || undefined);
7065
+ const state = progressById.get(item.id);
7066
+ const alreadyMoved = movedInThisCall.get(item.id) ?? 0;
7067
+ // Everything here is in base units: `getProgress` reports base units and
7068
+ // converts the target, and a caller's `quantity` -- which is in the
7069
+ // line's own unit -- is converted on the way in. Mixing the two is what
7070
+ // made a whole-order settle ask for twelve times what was there.
7071
+ //
7072
+ // `??` rather than `||`: a line with nothing left must stay 0 and be
7073
+ // rejected below, not fall through to the whole target.
7074
+ const remaining = (kind === exports.ConsumptionChangeKind.ISSUE
7075
+ ? (state?.target ?? 0) - (state?.issued ?? 0)
7076
+ : (state?.outstanding ?? 0)) - alreadyMoved;
7077
+ const amount = line.quantity === undefined
7078
+ ? remaining
7079
+ : line.quantity * conversionFactor;
7080
+ if (amount <= 0) {
7081
+ // Acting on the whole order is the common call, and an order where
7082
+ // some lines are already done is the common state; skipping them
7083
+ // beats making the caller compute the list.
7084
+ if (line.quantity === undefined)
7085
+ continue;
7086
+ throw new Error(`Consumption order line ${item.id} cannot move ${amount} (base units)`);
7087
+ }
7088
+ if (amount > remaining) {
7089
+ throw new Error(kind === exports.ConsumptionChangeKind.ISSUE
7090
+ ? `Consumption order line ${item.id} has only ${remaining} left to issue, asked for ${amount} (base units)`
7091
+ : `Consumption order line ${item.id} has only ${remaining} outstanding, asked to ${kind.toLowerCase()} ${amount} (base units)`);
7092
+ }
7093
+ await this.writeMovement(repos, manager, item, kind, amount);
7094
+ movedInThisCall.set(item.id, alreadyMoved + amount);
7095
+ }
7096
+ return true;
7097
+ });
7098
+ }
7099
+ /** `amount` is in base units; `act` has already converted. */
7100
+ async writeMovement(repos, manager, item, kind, amount) {
7101
+ const source = {
7102
+ locationId: this.stockService.resolveLocationId(item.locationId),
7103
+ loaderId: this.stockService.resolveLoaderId(item.loaderId),
7104
+ };
7105
+ const target = {
7106
+ locationId: this.stockService.resolveLocationId(item.targetLocationId),
7107
+ loaderId: this.stockService.resolveLoaderId(item.targetLoaderId),
7108
+ };
7109
+ const movement = kind === exports.ConsumptionChangeKind.ISSUE
7110
+ ? { from: source, to: target }
7111
+ : kind === exports.ConsumptionChangeKind.RETURN
7112
+ ? { from: target, to: source }
7113
+ : { from: target, to: null };
7114
+ await this.stockService.validateStockAvailability({
7115
+ materialId: item.materialId,
7116
+ batchId: item.batchId,
7117
+ locationId: movement.from.locationId,
7118
+ loaderId: movement.from.loaderId,
7119
+ quantity: amount,
7120
+ }, manager);
7121
+ const base = await repos.order.save({});
7122
+ await repos.consumptionOrderChange.save(repos.consumptionOrderChange.create({
7123
+ id: base.id,
7124
+ itemId: item.id,
7125
+ // The sign follows the stock the order controls: an issue puts material
7126
+ // into the process's hands, a return and a settlement take it back out.
7127
+ quantityChanged: kind === exports.ConsumptionChangeKind.ISSUE ? amount : -1 * amount,
7128
+ kind,
7129
+ }));
7130
+ const rows = [
7131
+ {
7132
+ orderId: base.id,
7133
+ materialId: item.materialId,
7134
+ batchId: item.batchId,
7135
+ locationId: movement.from.locationId,
7136
+ loaderId: movement.from.loaderId,
7137
+ quantity: -1 * amount,
7138
+ },
7139
+ ];
7140
+ if (movement.to) {
7141
+ rows.push({
7142
+ orderId: base.id,
7143
+ materialId: item.materialId,
7144
+ batchId: item.batchId,
7145
+ locationId: movement.to.locationId,
7146
+ loaderId: movement.to.loaderId,
7147
+ quantity: amount,
7148
+ });
7149
+ }
7150
+ await repos.stock.save(repos.stock.create(rows));
7151
+ }
7152
+ async findMany(options) {
7153
+ const queryBuilder = this.consumptionOrderRepository
7154
+ .createQueryBuilder('consumption')
7155
+ .leftJoinAndSelect('consumption.items', 'item');
7156
+ if (!options.includeRemoved) {
7157
+ queryBuilder.andWhere('consumption."removedAt" IS NULL');
7158
+ }
7159
+ if (options.ids?.length) {
7160
+ queryBuilder.andWhere('consumption.id IN (:...ids)', {
7161
+ ids: options.ids,
7162
+ });
7163
+ }
7164
+ if (options.key) {
7165
+ queryBuilder.andWhere('consumption.key ILIKE :key', {
7166
+ key: `%${options.key}%`,
7167
+ });
7168
+ }
7169
+ if (options.description) {
7170
+ queryBuilder.andWhere('consumption.description ILIKE :description', {
7171
+ description: `%${options.description}%`,
7172
+ });
7173
+ }
7174
+ if (options.createdBy) {
7175
+ queryBuilder.andWhere('consumption."createdBy" = :createdBy', {
7176
+ createdBy: options.createdBy,
7177
+ });
7178
+ }
7179
+ if (options.materialId) {
7180
+ queryBuilder.andWhere('item."materialId" = :materialId', {
7181
+ materialId: options.materialId,
7182
+ });
7183
+ }
7184
+ if (options.batchId) {
7185
+ queryBuilder.andWhere('item."batchId" = :batchId', {
7186
+ batchId: options.batchId,
7187
+ });
7188
+ }
7189
+ if (options.locationId) {
7190
+ queryBuilder.andWhere('(item."locationId" = :locationId OR item."targetLocationId" = :locationId)', { locationId: options.locationId });
7191
+ }
7192
+ if (options.createdAtFrom) {
7193
+ queryBuilder.andWhere('consumption."createdAt" >= :createdAtFrom', {
7194
+ createdAtFrom: options.createdAtFrom,
7195
+ });
7196
+ }
7197
+ if (options.createdAtTo) {
7198
+ queryBuilder.andWhere('consumption."createdAt" <= :createdAtTo', {
7199
+ createdAtTo: options.createdAtTo,
7200
+ });
7201
+ }
7202
+ /*
7203
+ * The property path, not a quoted column. `getManyAndCount` with a joined
7204
+ * relation and a limit wraps the query in a `SELECT DISTINCT` over the root
7205
+ * ids, and it can only carry an ordering across that wrapper if it
7206
+ * recognises the expression as a column of the aliased entity. Given raw
7207
+ * SQL it copies the string through verbatim and Postgres rejects
7208
+ * `distinctAlias.consumption_"createdAt"`. Unpaginated calls never hit it,
7209
+ * which is why it took a page-sized query to surface.
7210
+ */
7211
+ queryBuilder.orderBy('consumption.createdAt', 'DESC');
7212
+ if (options.offset !== undefined && options.offset >= 0) {
7213
+ queryBuilder.skip(options.offset);
7214
+ }
7215
+ if (options.limit !== undefined && options.limit > 0) {
7216
+ queryBuilder.take(options.limit);
7217
+ }
7218
+ return queryBuilder.getManyAndCount();
7219
+ }
7220
+ findOne(id) {
7221
+ return this.consumptionOrderRepository.findOneOrFail({
7222
+ where: { id },
7223
+ relations: { items: true },
7224
+ });
7225
+ }
7226
+ /** Every line of the given orders, for a DataLoader batching one round trip. */
7227
+ async findItemsByOrders(orderIds) {
7228
+ if (!orderIds.length)
7229
+ return [];
7230
+ return this.dataSource
7231
+ .getRepository(this.consumptionOrderItemEntity)
7232
+ .find({
7233
+ where: { orderId: typeorm.In([...orderIds]), removedAt: typeorm.IsNull() },
7234
+ order: { id: 'ASC' },
7235
+ });
7236
+ }
7237
+ };
7238
+ exports.ConsumptionOrderService = tslib.__decorate([
7239
+ common.Injectable(),
7240
+ tslib.__param(5, common.Inject(ConsumptionOrderEntity)),
7241
+ tslib.__param(6, common.Inject(ConsumptionOrderItemEntity)),
7242
+ tslib.__param(7, common.Inject(StockEntity)),
7243
+ tslib.__metadata("design:paramtypes", [typeorm.DataSource,
7244
+ exports.WmsEntities,
7245
+ exports.HelperService,
7246
+ exports.MaterialService,
7247
+ exports.StockService, Object, Object, Object])
7248
+ ], exports.ConsumptionOrderService);
7249
+
7250
+ /**
7251
+ * Reads and writes the link between an order in this package and the host
7252
+ * document it was opened for.
7253
+ *
7254
+ * Deliberately a service of its own rather than an argument threaded through
7255
+ * thirteen `create*` signatures: the link is the same shape for every family,
7256
+ * including families added later, and a host driving the warehouse from its own
7257
+ * transaction can attach references in that transaction by passing `manager`.
7258
+ */
7259
+ exports.OrderReferenceService = class OrderReferenceService {
7260
+ dataSource;
7261
+ orderReferenceEntity;
7262
+ orderReferenceRepository;
7263
+ constructor(dataSource, orderReferenceEntity) {
7264
+ this.dataSource = dataSource;
7265
+ this.orderReferenceEntity = orderReferenceEntity;
7266
+ this.orderReferenceRepository =
7267
+ this.dataSource.getRepository(this.orderReferenceEntity);
7268
+ }
7269
+ repository(manager) {
7270
+ return manager
7271
+ ? manager.getRepository(this.orderReferenceEntity)
7272
+ : this.orderReferenceRepository;
7273
+ }
7274
+ /**
7275
+ * Record why an order was opened.
7276
+ *
7277
+ * Additive: calling it twice adds two sets of references rather than
7278
+ * replacing the first. Pass `manager` to join the caller's transaction, so a
7279
+ * host that creates an order and attaches its references sees both rows land
7280
+ * together or neither.
7281
+ */
7282
+ async attach({ manager, ...options }) {
7283
+ if (!options.references.length)
7284
+ return [];
7285
+ const repository = this.repository(manager);
7286
+ return repository.save(options.references.map((reference) => repository.create({
7287
+ orderType: options.orderType,
7288
+ orderId: options.orderId,
7289
+ itemId: reference.itemId ?? null,
7290
+ referenceType: reference.referenceType,
7291
+ referenceId: reference.referenceId,
7292
+ referenceLine: reference.referenceLine ?? null,
7293
+ metadata: reference.metadata ?? null,
7294
+ })));
7295
+ }
7296
+ /**
7297
+ * Replace every reference on an order with the given set. An empty
7298
+ * `references` clears them.
7299
+ */
7300
+ async replace({ manager, ...options }) {
7301
+ const repository = this.repository(manager);
7302
+ await repository.delete({
7303
+ orderType: options.orderType,
7304
+ orderId: options.orderId,
7305
+ });
7306
+ return this.attach({ ...options, manager });
7307
+ }
7308
+ async detach(id, manager) {
7309
+ await this.repository(manager).delete({ id });
7310
+ }
7311
+ /**
7312
+ * Both directions of the link in one query: give it an order to list what
7313
+ * that order was for, or a `referenceType` / `referenceId` to list every
7314
+ * order opened for that document.
7315
+ */
7316
+ async findMany(options) {
7317
+ /*
7318
+ * A lowercase alias on purpose: the conditions below are raw SQL fragments,
7319
+ * and Postgres folds an unquoted identifier to lowercase — a camelCase
7320
+ * alias would compile to `orderreference."orderType"` and fail with
7321
+ * `missing FROM-clause entry`.
7322
+ */
7323
+ const queryBuilder = this.orderReferenceRepository.createQueryBuilder('reference');
7324
+ if (options.orderType)
7325
+ queryBuilder.andWhere('reference."orderType" = :orderType', {
7326
+ orderType: options.orderType,
7327
+ });
7328
+ if (options.orderId)
7329
+ queryBuilder.andWhere('reference."orderId" = :orderId', {
7330
+ orderId: options.orderId,
7331
+ });
7332
+ if (options.itemId)
7333
+ queryBuilder.andWhere('reference."itemId" = :itemId', {
7334
+ itemId: options.itemId,
7335
+ });
7336
+ /*
7337
+ * Matched exactly, never with ILIKE. These are identifiers the host system
7338
+ * owns, and a substring match on 「WO-1」 would quietly return 「WO-10」 as
7339
+ * well — the same reasoning that governs the batch commercial attributes on
7340
+ * the stock queries.
7341
+ */
7342
+ if (options.referenceType)
7343
+ queryBuilder.andWhere('reference."referenceType" = :referenceType', {
7344
+ referenceType: options.referenceType,
7345
+ });
7346
+ if (options.referenceId)
7347
+ queryBuilder.andWhere('reference."referenceId" = :referenceId', {
7348
+ referenceId: options.referenceId,
7349
+ });
7350
+ if (options.referenceLine)
7351
+ queryBuilder.andWhere('reference."referenceLine" = :referenceLine', {
7352
+ referenceLine: options.referenceLine,
7353
+ });
7354
+ queryBuilder.orderBy('reference."createdAt"', 'ASC');
7355
+ if (options.offset !== undefined && options.offset >= 0)
7356
+ queryBuilder.skip(options.offset);
7357
+ if (options.limit !== undefined && options.limit > 0)
7358
+ queryBuilder.take(options.limit);
7359
+ return queryBuilder.getManyAndCount();
7360
+ }
7361
+ /**
7362
+ * Every reference on each of the given orders, for a DataLoader batching one
7363
+ * round trip across a page of orders.
7364
+ */
7365
+ async findByOrders(orderType, orderIds) {
7366
+ if (!orderIds.length)
7367
+ return [];
7368
+ return this.orderReferenceRepository.find({
7369
+ where: { orderType, orderId: typeorm.In([...orderIds]) },
7370
+ order: { createdAt: 'ASC' },
7371
+ });
7372
+ }
7373
+ };
7374
+ exports.OrderReferenceService = tslib.__decorate([
7375
+ common.Injectable(),
7376
+ tslib.__param(1, common.Inject(OrderReferenceEntity)),
7377
+ tslib.__metadata("design:paramtypes", [typeorm.DataSource, Object])
7378
+ ], exports.OrderReferenceService);
7379
+
6167
7380
  exports.ReclassifyInventoryOrderService = class ReclassifyInventoryOrderService {
6168
7381
  dataSource;
6169
7382
  entities;
@@ -6932,6 +8145,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6932
8145
  .addSelect('batch.held', 'held')
6933
8146
  .addSelect('batch."inShipment"', 'inShipment')
6934
8147
  .addSelect('batch."inspectionResult"', 'inspectionResult')
8148
+ .addSelect('batch."requiresInspection"', 'requiresInspection')
6935
8149
  .addSelect('batch."transferId"', 'transferId')
6936
8150
  .addSelect('batch."vendorId"', 'vendorId')
6937
8151
  .addSelect('batch."customerId"', 'customerId')
@@ -6949,6 +8163,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6949
8163
  .addGroupBy('batch.held')
6950
8164
  .addGroupBy('batch."inShipment"')
6951
8165
  .addGroupBy('batch."inspectionResult"')
8166
+ .addGroupBy('batch."requiresInspection"')
6952
8167
  .addGroupBy('batch."transferId"')
6953
8168
  .addGroupBy('batch."vendorId"')
6954
8169
  .addGroupBy('batch."customerId"')
@@ -6966,6 +8181,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6966
8181
  held: row.held ?? null,
6967
8182
  inShipment: row.inShipment ?? null,
6968
8183
  inspectionResult: row.inspectionResult ?? null,
8184
+ requiresInspection: row.requiresInspection ?? null,
6969
8185
  transferId: row.transferId ?? null,
6970
8186
  vendorId: row.vendorId ?? null,
6971
8187
  customerId: row.customerId ?? null,
@@ -7548,37 +8764,52 @@ const WMS_EVENT_EMITTER_BRIDGE = Symbol('WMS_EVENT_EMITTER_BRIDGE');
7548
8764
  const WMS_ACTOR_EXTRACTOR = Symbol('WMS_ACTOR_EXTRACTOR');
7549
8765
  /** DI token holding the boolean "enrich stock events" flag (default false). */
7550
8766
  const WMS_STOCK_ENRICH = Symbol('WMS_STOCK_ENRICH');
8767
+ /** DI token holding the host's registered custom change tables (default none). */
8768
+ const WMS_CUSTOM_CHANGE_TABLES = Symbol('WMS_CUSTOM_CHANGE_TABLES');
7551
8769
 
7552
8770
  /**
7553
- * Resolve the `ChangeType` for a change table. Tables whose semantics depend on
7554
- * the sign of `quantityChanged` (ship / transfer / vendor / customer / hold /
7555
- * allocate) branch on it; the rest are fixed.
8771
+ * The consumption order's three actions, which the sign cannot separate: a
8772
+ * return and a settlement are both negative.
8773
+ */
8774
+ const CONSUMPTION_KIND_TO_CHANGE_TYPE = {
8775
+ [exports.ConsumptionChangeKind.ISSUE]: exports.ChangeType.ISSUED,
8776
+ [exports.ConsumptionChangeKind.RETURN]: exports.ChangeType.RETURNED,
8777
+ [exports.ConsumptionChangeKind.SETTLE]: exports.ChangeType.CONSUMED,
8778
+ };
8779
+ /**
8780
+ * Resolve the `ChangeType` for a change table. Most tables whose semantics
8781
+ * depend on direction (ship / transfer / vendor / customer / hold / allocate)
8782
+ * branch on the sign of `quantityChanged`; the rest are fixed. The resolver is
8783
+ * handed the whole row rather than just the quantity because the sign is not
8784
+ * always enough — see `consumption_order_changes`.
7556
8785
  */
7557
8786
  const TABLE_TO_CHANGE_TYPE = new Map([
7558
8787
  ['receive_inventory_order_changes', () => exports.ChangeType.RECEIVED],
7559
8788
  [
7560
8789
  'ship_inventory_order_changes',
7561
- (q) => (q > 0 ? exports.ChangeType.IN_SHIPMENT : exports.ChangeType.SHIPPED),
8790
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.IN_SHIPMENT : exports.ChangeType.SHIPPED,
7562
8791
  ],
7563
8792
  [
7564
8793
  'transfer_order_changes',
7565
- (q) => (q > 0 ? exports.ChangeType.IN_TRANSFER : exports.ChangeType.TRANSFERRED),
8794
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.IN_TRANSFER : exports.ChangeType.TRANSFERRED,
7566
8795
  ],
7567
8796
  [
7568
8797
  'transfer_vendor_order_changes',
7569
- (q) => q > 0 ? exports.ChangeType.VENDOR_TRANSFERRED : exports.ChangeType.VENDOR_RETURNED,
8798
+ ({ quantityChanged: q }) => Number(q) > 0
8799
+ ? exports.ChangeType.VENDOR_TRANSFERRED
8800
+ : exports.ChangeType.VENDOR_RETURNED,
7570
8801
  ],
7571
8802
  [
7572
8803
  'transfer_customer_order_changes',
7573
- (q) => q > 0 ? exports.ChangeType.CUSTOMER_HELD : exports.ChangeType.CUSTOMER_RETURNED,
8804
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.CUSTOMER_HELD : exports.ChangeType.CUSTOMER_RETURNED,
7574
8805
  ],
7575
8806
  [
7576
8807
  'hold_inventory_order_changes',
7577
- (q) => (q > 0 ? exports.ChangeType.HELD : exports.ChangeType.RELEASED),
8808
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.HELD : exports.ChangeType.RELEASED,
7578
8809
  ],
7579
8810
  [
7580
8811
  'allocate_inventory_order_changes',
7581
- (q) => (q > 0 ? exports.ChangeType.ALLOCATED : exports.ChangeType.DEALLOCATED),
8812
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.ALLOCATED : exports.ChangeType.DEALLOCATED,
7582
8813
  ],
7583
8814
  ['split_batch_order_changes', () => exports.ChangeType.SPLITTED],
7584
8815
  ['merge_batch_order_changes', () => exports.ChangeType.MERGED],
@@ -7586,7 +8817,11 @@ const TABLE_TO_CHANGE_TYPE = new Map([
7586
8817
  ['scrape_order_changes', () => exports.ChangeType.SCRAPED],
7587
8818
  [
7588
8819
  'inventory_count_order_changes',
7589
- (q) => (q > 0 ? exports.ChangeType.COUNT_GAINED : exports.ChangeType.COUNT_LOST),
8820
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.COUNT_GAINED : exports.ChangeType.COUNT_LOST,
8821
+ ],
8822
+ [
8823
+ 'consumption_order_changes',
8824
+ ({ kind }) => (kind ? CONSUMPTION_KIND_TO_CHANGE_TYPE[kind] : null),
7590
8825
  ],
7591
8826
  ]);
7592
8827
  const CHANGE_TYPE_TO_EVENT = {
@@ -7609,8 +8844,28 @@ const CHANGE_TYPE_TO_EVENT = {
7609
8844
  [exports.ChangeType.SCRAPED]: 'stock.scraped',
7610
8845
  [exports.ChangeType.COUNT_GAINED]: 'stock.count-gained',
7611
8846
  [exports.ChangeType.COUNT_LOST]: 'stock.count-lost',
8847
+ [exports.ChangeType.ISSUED]: 'stock.issued',
8848
+ [exports.ChangeType.RETURNED]: 'stock.returned',
8849
+ [exports.ChangeType.CONSUMED]: 'stock.consumed',
7612
8850
  };
7613
8851
  const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
8852
+ /**
8853
+ * Every change table this package owns, derived from the map above rather than
8854
+ * restated.
8855
+ *
8856
+ * `WmsModuleCoreModule` refuses to let a host register one of these, and the
8857
+ * subscriber consults host registrations *before* the built-in map — so a table
8858
+ * added to the map but forgotten in a hand-maintained copy of this list would
8859
+ * become host-registrable, letting a host's resolver silently reclassify every
8860
+ * row on it. Deriving it is the difference between a rule and a rule someone has
8861
+ * to remember.
8862
+ */
8863
+ const OWNED_CHANGE_TABLES = new Set([
8864
+ ...TABLE_TO_CHANGE_TYPE.keys(),
8865
+ QUALITY_INSPECTION_TABLE,
8866
+ ]);
8867
+ /** Every `ChangeType` value, for deciding whether a host reused our vocabulary. */
8868
+ const CHANGE_TYPE_VALUES = new Set(Object.values(exports.ChangeType));
7614
8869
  /**
7615
8870
  * Centralized collection of stock domain events. Listens to every
7616
8871
  * `*_order_change` insert and, using the change table name plus the sign of
@@ -7625,9 +8880,12 @@ const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
7625
8880
  let StockChangeSubscriber = class StockChangeSubscriber {
7626
8881
  collector;
7627
8882
  enrich;
7628
- constructor(dataSource, collector, enrich = false) {
8883
+ /** Host-registered tables, keyed by table name. Empty unless configured. */
8884
+ customTables;
8885
+ constructor(dataSource, collector, enrich = false, customTables = null) {
7629
8886
  this.collector = collector;
7630
8887
  this.enrich = enrich;
8888
+ this.customTables = new Map((customTables ?? []).map((entry) => [entry.table, entry]));
7631
8889
  dataSource.subscribers.push(this);
7632
8890
  }
7633
8891
  async afterInsert(event) {
@@ -7651,12 +8909,22 @@ let StockChangeSubscriber = class StockChangeSubscriber {
7651
8909
  });
7652
8910
  return;
7653
8911
  }
8912
+ const custom = this.customTables.get(tableName);
8913
+ if (custom) {
8914
+ await this.collectCustom(event, entity, quantityDelta, custom);
8915
+ return;
8916
+ }
7654
8917
  const resolveChangeType = TABLE_TO_CHANGE_TYPE.get(tableName);
7655
8918
  if (!resolveChangeType) {
7656
8919
  // Not a stock change table — enrich nothing, emit nothing.
7657
8920
  return;
7658
8921
  }
7659
- const changeType = resolveChangeType(quantityDelta);
8922
+ const changeType = resolveChangeType(entity);
8923
+ if (!changeType) {
8924
+ // A row the table's resolver could not classify. Emitting a wrong event
8925
+ // would be worse than emitting none.
8926
+ return;
8927
+ }
7660
8928
  const enrichment = this.enrich
7661
8929
  ? await this.loadItemFields(event, entity.itemId)
7662
8930
  : undefined;
@@ -7668,6 +8936,36 @@ let StockChangeSubscriber = class StockChangeSubscriber {
7668
8936
  ...enrichment,
7669
8937
  });
7670
8938
  }
8939
+ /**
8940
+ * Emit for a table the host registered.
8941
+ *
8942
+ * A resolver that names one of our own `ChangeType`s gets that type's event,
8943
+ * so a movement the host models itself but which really is a receipt or a
8944
+ * scrap still counts in reports as one. Anything else becomes `stock.custom`
8945
+ * carrying the host's string, because inventing an event name per host would
8946
+ * break every exhaustive listener in the package.
8947
+ */
8948
+ async collectCustom(event, entity, quantityDelta, custom) {
8949
+ const resolved = custom.changeType(entity);
8950
+ if (!resolved) {
8951
+ // The host says this row does not move stock. Nothing to say about it.
8952
+ return;
8953
+ }
8954
+ const enrichment = this.enrich
8955
+ ? await this.loadItemFields(event, entity.itemId)
8956
+ : undefined;
8957
+ const known = CHANGE_TYPE_VALUES.has(resolved)
8958
+ ? resolved
8959
+ : null;
8960
+ this.collector.collect(known ? CHANGE_TYPE_TO_EVENT[known] : 'stock.custom', {
8961
+ orderId: entity.id,
8962
+ itemId: entity.itemId,
8963
+ quantityDelta,
8964
+ changeType: known,
8965
+ ...(known ? {} : { customChangeType: resolved }),
8966
+ ...enrichment,
8967
+ });
8968
+ }
7671
8969
  /**
7672
8970
  * Load `materialId / batchId / locationId / loaderId` from the change's order
7673
8971
  * item (one PK lookup, same transaction). Generic across all 12 change tables
@@ -7705,8 +9003,10 @@ StockChangeSubscriber = tslib.__decorate([
7705
9003
  tslib.__param(0, typeorm$1.InjectDataSource()),
7706
9004
  tslib.__param(2, common.Optional()),
7707
9005
  tslib.__param(2, common.Inject(WMS_STOCK_ENRICH)),
9006
+ tslib.__param(3, common.Optional()),
9007
+ tslib.__param(3, common.Inject(WMS_CUSTOM_CHANGE_TABLES)),
7708
9008
  tslib.__metadata("design:paramtypes", [typeorm.DataSource,
7709
- exports.WmsEventCollector, Object])
9009
+ exports.WmsEventCollector, Object, Object])
7710
9010
  ], StockChangeSubscriber);
7711
9011
 
7712
9012
  /** The count's own settlement writes here; it must never lock itself out. */
@@ -7801,6 +9101,159 @@ exports.InventoryCountLockSubscriber = tslib.__decorate([
7801
9101
  tslib.__metadata("design:paramtypes", [typeorm.DataSource])
7802
9102
  ], exports.InventoryCountLockSubscriber);
7803
9103
 
9104
+ var WmsEventDispatcher_1;
9105
+ /**
9106
+ * Central event dispatcher. Runs consumer before-hooks (which may veto) and,
9107
+ * post-commit, flushes collected events to consumer after-listeners and the
9108
+ * optional emitter bridge. Listener errors are isolated so one failing listener
9109
+ * never blocks the others or the already-committed mutation.
9110
+ */
9111
+ exports.WmsEventDispatcher = WmsEventDispatcher_1 = class WmsEventDispatcher {
9112
+ options;
9113
+ bridge;
9114
+ logger = new common.Logger(WmsEventDispatcher_1.name);
9115
+ constructor(options, bridge = null) {
9116
+ this.options = options;
9117
+ this.bridge = bridge;
9118
+ }
9119
+ /** Whether any hook, listener or bridge is wired (lets the interceptor skip overhead entirely). */
9120
+ isActive() {
9121
+ const { beforeHooks, afterListeners } = this.options;
9122
+ return (!!this.bridge ||
9123
+ (!!beforeHooks && Object.keys(beforeHooks).length > 0) ||
9124
+ (!!afterListeners && Object.keys(afterListeners).length > 0));
9125
+ }
9126
+ /** Invoke the before-hook for an event. A thrown error vetoes the mutation. */
9127
+ async runBeforeHook(context) {
9128
+ const hook = this.options.beforeHooks?.[context.event];
9129
+ if (hook) {
9130
+ await hook(context);
9131
+ }
9132
+ }
9133
+ /** Flush collected events to after-listeners and the emitter bridge (post-commit). */
9134
+ async flush(events) {
9135
+ for (const event of events) {
9136
+ const listener = this.options.afterListeners?.[event.name];
9137
+ if (listener) {
9138
+ try {
9139
+ await listener({ event: event.name, payload: event.payload });
9140
+ }
9141
+ catch (error) {
9142
+ this.logger.error(`WMS after-listener for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
9143
+ }
9144
+ }
9145
+ try {
9146
+ this.bridge?.forward(event);
9147
+ }
9148
+ catch (error) {
9149
+ this.logger.error(`WMS emitter bridge for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
9150
+ }
9151
+ }
9152
+ }
9153
+ };
9154
+ exports.WmsEventDispatcher = WmsEventDispatcher_1 = tslib.__decorate([
9155
+ common.Injectable(),
9156
+ tslib.__param(0, common.Inject(WMS_EVENT_OPTIONS)),
9157
+ tslib.__param(1, common.Optional()),
9158
+ tslib.__param(1, common.Inject(WMS_EVENT_EMITTER_BRIDGE)),
9159
+ tslib.__metadata("design:paramtypes", [Object, Object])
9160
+ ], exports.WmsEventDispatcher);
9161
+
9162
+ /**
9163
+ * Derive the operation event's correlation id from whatever the operation
9164
+ * returned, falling back to an `id` argument. Action operations that return a
9165
+ * bare `boolean` land on the argument.
9166
+ */
9167
+ const defaultResolveId = (result, args) => {
9168
+ if (result &&
9169
+ typeof result === 'object' &&
9170
+ 'id' in result &&
9171
+ typeof result.id === 'string') {
9172
+ return result.id;
9173
+ }
9174
+ const argId = args['id'];
9175
+ return typeof argId === 'string' ? argId : null;
9176
+ };
9177
+ /**
9178
+ * Runs one WMS operation with the full event guarantee, from any caller.
9179
+ *
9180
+ * The four steps — before-hook (a throw vetoes, before any DB work), the
9181
+ * operation itself, the operation event, and a single post-commit flush of
9182
+ * everything the services collected on the way — used to live inside
9183
+ * `WmsMutationInterceptor`, which meant they only happened for callers coming
9184
+ * in through GraphQL. A host driving the warehouse from its own code path got
9185
+ * no hooks, no actor and no events: `StockChangeSubscriber` still collected
9186
+ * them, but with no scope open there was nothing to collect into and nobody to
9187
+ * flush.
9188
+ *
9189
+ * That is the case that matters. A host with its own inbound flow calls the
9190
+ * domain services directly, and `InventoryCountLockSubscriber` already goes out
9191
+ * of its way to cover exactly that caller.
9192
+ *
9193
+ * The interceptor now delegates here, so the two paths cannot drift.
9194
+ *
9195
+ * ```ts
9196
+ * await runner.run(
9197
+ * { event: 'transfer-order.transferred', args: { orderId }, actor },
9198
+ * () => transferOrderService.transfer(orderId),
9199
+ * );
9200
+ * ```
9201
+ *
9202
+ * Nesting is safe: an inner call joins the outer scope and only the outermost
9203
+ * one flushes, so a host may wrap a service that itself runs operations.
9204
+ */
9205
+ exports.WmsOperationRunner = class WmsOperationRunner {
9206
+ dispatcher;
9207
+ constructor(dispatcher) {
9208
+ this.dispatcher = dispatcher;
9209
+ }
9210
+ async run(options, operation) {
9211
+ // Nothing wired: run the operation and skip the machinery entirely, the way
9212
+ // the interceptor always has. `collectToScope` is already a no-op outside a
9213
+ // scope, so the services behave identically.
9214
+ if (!this.dispatcher.isActive()) {
9215
+ return operation();
9216
+ }
9217
+ const args = options.args ?? {};
9218
+ const actor = options.actor ?? null;
9219
+ if (options.event) {
9220
+ // Before any DB work, so a throw vetoes with zero side effects.
9221
+ await this.dispatcher.runBeforeHook({
9222
+ event: options.event,
9223
+ args,
9224
+ executionContext: options.executionContext ?? null,
9225
+ source: options.executionContext ? 'graphql' : 'host',
9226
+ actor,
9227
+ });
9228
+ }
9229
+ const { result, events } = await runInDispatchScope(async () => {
9230
+ const operationResult = await operation();
9231
+ if (options.event) {
9232
+ const resolveId = options.resolveId ?? defaultResolveId;
9233
+ const operationEvent = {
9234
+ name: options.event,
9235
+ payload: {
9236
+ id: resolveId(operationResult, args),
9237
+ result: operationResult,
9238
+ args,
9239
+ actor,
9240
+ },
9241
+ };
9242
+ collectToScope(operationEvent);
9243
+ }
9244
+ return operationResult;
9245
+ });
9246
+ if (events) {
9247
+ await this.dispatcher.flush(events);
9248
+ }
9249
+ return result;
9250
+ }
9251
+ };
9252
+ exports.WmsOperationRunner = tslib.__decorate([
9253
+ common.Injectable(),
9254
+ tslib.__metadata("design:paramtypes", [exports.WmsEventDispatcher])
9255
+ ], exports.WmsOperationRunner);
9256
+
7804
9257
  var WmsModuleCoreModule_1;
7805
9258
  /**
7806
9259
  * The entity Symbols a consumer can rebind, each paired with the base module's
@@ -7896,12 +9349,75 @@ const exportDependencies = [
7896
9349
  exports.SaleOrderService,
7897
9350
  exports.SplitBatchOrderService,
7898
9351
  exports.MergeBatchOrderService,
9352
+ exports.OrderReferenceService,
9353
+ exports.ConsumptionOrderService,
7899
9354
  exports.ReclassifyInventoryOrderService,
7900
9355
  exports.ScrapeService,
7901
9356
  exports.InventoryCountOrderService,
7902
9357
  exports.QualityInspectionOrderService,
7903
9358
  exports.WarehouseMapDataService,
7904
9359
  ];
9360
+ /**
9361
+ * The event machinery, bound here rather than in the graphql module so a
9362
+ * consumer that only installs `@rytass/wms-module-core` still gets hooks,
9363
+ * listeners and `WmsOperationRunner`. `WmsModuleGraphqlModule` forwards its own
9364
+ * event options down to `forRootAsync`, which keeps exactly one binding per
9365
+ * token — two live bindings would resolve to whichever module the injector
9366
+ * reached first, the same hazard the overridable entity Symbols avoid.
9367
+ */
9368
+ const eventProviders = (wiring) => [
9369
+ {
9370
+ provide: WMS_EVENT_OPTIONS,
9371
+ useValue: {
9372
+ beforeHooks: wiring.beforeHooks,
9373
+ afterListeners: wiring.afterListeners,
9374
+ },
9375
+ },
9376
+ { provide: WMS_ACTOR_EXTRACTOR, useValue: wiring.actorExtractor ?? null },
9377
+ exports.WmsEventDispatcher,
9378
+ exports.WmsOperationRunner,
9379
+ ...(wiring.eventEmitterBridge ? [wiring.eventEmitterBridge] : []),
9380
+ ];
9381
+ const eventExports = [
9382
+ exports.WmsEventDispatcher,
9383
+ exports.WmsOperationRunner,
9384
+ WMS_EVENT_OPTIONS,
9385
+ WMS_ACTOR_EXTRACTOR,
9386
+ ];
9387
+ /**
9388
+ * Reject a registration that would shadow one of this package's own change
9389
+ * tables.
9390
+ *
9391
+ * Silently letting a host redefine `receive_inventory_order_changes` would
9392
+ * reclassify every receipt in the warehouse from somewhere the reader of that
9393
+ * report would never think to look. Refusing at module-definition time costs a
9394
+ * startup crash and buys an obvious one.
9395
+ *
9396
+ * The list is derived from `StockChangeSubscriber`'s own table map rather than
9397
+ * restated here: two hand-maintained copies would drift, and the drift would
9398
+ * open exactly the hole this guard exists to close.
9399
+ */
9400
+ const assertCustomChangeTables = (tables) => {
9401
+ if (!tables?.length)
9402
+ return [];
9403
+ const seen = new Set();
9404
+ for (const { table } of tables) {
9405
+ if (OWNED_CHANGE_TABLES.has(table)) {
9406
+ throw new Error(`WmsModuleCoreModule: customChangeTables cannot register "${table}" — this package owns it.`);
9407
+ }
9408
+ if (seen.has(table)) {
9409
+ throw new Error(`WmsModuleCoreModule: customChangeTables registers "${table}" twice.`);
9410
+ }
9411
+ if (!table.endsWith('_order_changes')) {
9412
+ // The inventory count lock keys off this suffix, so a table without it
9413
+ // gets events but silently escapes the lock — the worse half of the
9414
+ // bargain, and not one a host would knowingly take.
9415
+ throw new Error(`WmsModuleCoreModule: customChangeTables entry "${table}" must end in "_order_changes" so the inventory count lock covers it too.`);
9416
+ }
9417
+ seen.add(table);
9418
+ }
9419
+ return tables;
9420
+ };
7905
9421
  exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule {
7906
9422
  static forRoot(options, coreOptions) {
7907
9423
  const coreModule = wmsBaseNestjsModule.WMSBaseModule.forRoot(options);
@@ -7913,6 +9429,11 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
7913
9429
  StockChangeSubscriber,
7914
9430
  exports.InventoryCountLockSubscriber,
7915
9431
  ...resolvedEntityProviders,
9432
+ ...eventProviders(coreOptions),
9433
+ {
9434
+ provide: WMS_CUSTOM_CHANGE_TABLES,
9435
+ useValue: assertCustomChangeTables(coreOptions.customChangeTables),
9436
+ },
7916
9437
  { provide: WMS_CORE_MODULE_OPTIONS, useValue: coreOptions },
7917
9438
  {
7918
9439
  provide: WMS_STOCK_ENRICH,
@@ -7924,12 +9445,13 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
7924
9445
  coreModule,
7925
9446
  ModelsModule,
7926
9447
  ...exportedEntityTokens,
9448
+ ...eventExports,
7927
9449
  WMS_CORE_MODULE_OPTIONS,
7928
9450
  ],
7929
9451
  };
7930
9452
  }
7931
9453
  static forRootAsync(options) {
7932
- const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, enrichStockEvents, ...baseOptions } = options;
9454
+ const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, enrichStockEvents, beforeHooks, afterListeners, actorExtractor, eventEmitterBridge, customChangeTables, ...baseOptions } = options;
7933
9455
  const coreModule = wmsBaseNestjsModule.WMSBaseModule.forRootAsync(baseOptions);
7934
9456
  return {
7935
9457
  module: WmsModuleCoreModule_1,
@@ -7939,6 +9461,16 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
7939
9461
  StockChangeSubscriber,
7940
9462
  exports.InventoryCountLockSubscriber,
7941
9463
  ...resolvedEntityProviders,
9464
+ ...eventProviders({
9465
+ beforeHooks,
9466
+ afterListeners,
9467
+ actorExtractor,
9468
+ eventEmitterBridge,
9469
+ }),
9470
+ {
9471
+ provide: WMS_CUSTOM_CHANGE_TABLES,
9472
+ useValue: assertCustomChangeTables(customChangeTables),
9473
+ },
7942
9474
  {
7943
9475
  provide: WMS_CORE_MODULE_OPTIONS,
7944
9476
  useValue: {
@@ -7954,6 +9486,7 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
7954
9486
  coreModule,
7955
9487
  ModelsModule,
7956
9488
  ...exportedEntityTokens,
9489
+ ...eventExports,
7957
9490
  WMS_CORE_MODULE_OPTIONS,
7958
9491
  ],
7959
9492
  };
@@ -7977,6 +9510,12 @@ const WMS_OPERATION_NAMES = [
7977
9510
  'batch:merge',
7978
9511
  'batch:read',
7979
9512
  'batch:split',
9513
+ 'consumption-order:create',
9514
+ 'consumption-order:issue',
9515
+ 'consumption-order:read',
9516
+ 'consumption-order:return',
9517
+ 'consumption-order:settle',
9518
+ 'consumption-order:update',
7980
9519
  'hold-inventory-order:create',
7981
9520
  'hold-inventory-order:read',
7982
9521
  'hold-inventory-order:release',
@@ -8001,6 +9540,9 @@ const WMS_OPERATION_NAMES = [
8001
9540
  'material:create',
8002
9541
  'material:read',
8003
9542
  'material:update',
9543
+ 'order-reference:attach',
9544
+ 'order-reference:detach',
9545
+ 'order-reference:read',
8004
9546
  'quality-inspection-order:inspect',
8005
9547
  'receive-inventory-order:create',
8006
9548
  'receive-inventory-order:read',
@@ -8031,64 +9573,6 @@ const WMS_OPERATION_NAMES = [
8031
9573
  'warehouse-map:update',
8032
9574
  ];
8033
9575
 
8034
- var WmsEventDispatcher_1;
8035
- /**
8036
- * Central event dispatcher. Runs consumer before-hooks (which may veto) and,
8037
- * post-commit, flushes collected events to consumer after-listeners and the
8038
- * optional emitter bridge. Listener errors are isolated so one failing listener
8039
- * never blocks the others or the already-committed mutation.
8040
- */
8041
- exports.WmsEventDispatcher = WmsEventDispatcher_1 = class WmsEventDispatcher {
8042
- options;
8043
- bridge;
8044
- logger = new common.Logger(WmsEventDispatcher_1.name);
8045
- constructor(options, bridge = null) {
8046
- this.options = options;
8047
- this.bridge = bridge;
8048
- }
8049
- /** Whether any hook, listener or bridge is wired (lets the interceptor skip overhead entirely). */
8050
- isActive() {
8051
- const { beforeHooks, afterListeners } = this.options;
8052
- return (!!this.bridge ||
8053
- (!!beforeHooks && Object.keys(beforeHooks).length > 0) ||
8054
- (!!afterListeners && Object.keys(afterListeners).length > 0));
8055
- }
8056
- /** Invoke the before-hook for an event. A thrown error vetoes the mutation. */
8057
- async runBeforeHook(context) {
8058
- const hook = this.options.beforeHooks?.[context.event];
8059
- if (hook) {
8060
- await hook(context);
8061
- }
8062
- }
8063
- /** Flush collected events to after-listeners and the emitter bridge (post-commit). */
8064
- async flush(events) {
8065
- for (const event of events) {
8066
- const listener = this.options.afterListeners?.[event.name];
8067
- if (listener) {
8068
- try {
8069
- await listener({ event: event.name, payload: event.payload });
8070
- }
8071
- catch (error) {
8072
- this.logger.error(`WMS after-listener for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
8073
- }
8074
- }
8075
- try {
8076
- this.bridge?.forward(event);
8077
- }
8078
- catch (error) {
8079
- this.logger.error(`WMS emitter bridge for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
8080
- }
8081
- }
8082
- }
8083
- };
8084
- exports.WmsEventDispatcher = WmsEventDispatcher_1 = tslib.__decorate([
8085
- common.Injectable(),
8086
- tslib.__param(0, common.Inject(WMS_EVENT_OPTIONS)),
8087
- tslib.__param(1, common.Optional()),
8088
- tslib.__param(1, common.Inject(WMS_EVENT_EMITTER_BRIDGE)),
8089
- tslib.__metadata("design:paramtypes", [Object, Object])
8090
- ], exports.WmsEventDispatcher);
8091
-
8092
9576
  Object.defineProperty(exports, "OrderEntityClass", {
8093
9577
  enumerable: true,
8094
9578
  get: function () { return wmsBaseNestjsModule.OrderEntity; }
@@ -8096,8 +9580,12 @@ Object.defineProperty(exports, "OrderEntityClass", {
8096
9580
  exports.AllocateInventoryOrderChangeEntity = AllocateInventoryOrderChangeEntity;
8097
9581
  exports.AllocateInventoryOrderEntity = AllocateInventoryOrderEntity;
8098
9582
  exports.AllocateInventoryOrderItemEntity = AllocateInventoryOrderItemEntity;
9583
+ exports.BaseOrderService = BaseOrderService;
8099
9584
  exports.BatchEntity = BatchEntity;
8100
9585
  exports.BatchGroupEntity = BatchGroupEntity;
9586
+ exports.ConsumptionOrderChangeEntity = ConsumptionOrderChangeEntity;
9587
+ exports.ConsumptionOrderEntity = ConsumptionOrderEntity;
9588
+ exports.ConsumptionOrderItemEntity = ConsumptionOrderItemEntity;
8101
9589
  exports.HoldInventoryOrderChangeEntity = HoldInventoryOrderChangeEntity;
8102
9590
  exports.HoldInventoryOrderEntity = HoldInventoryOrderEntity;
8103
9591
  exports.HoldInventoryOrderItemEntity = HoldInventoryOrderItemEntity;
@@ -8115,6 +9603,7 @@ exports.MergeBatchOrderChangeEntity = MergeBatchOrderChangeEntity;
8115
9603
  exports.MergeBatchOrderEntity = MergeBatchOrderEntity;
8116
9604
  exports.MergeBatchOrderItemEntity = MergeBatchOrderItemEntity;
8117
9605
  exports.OrderEntity = OrderEntity;
9606
+ exports.OrderReferenceEntity = OrderReferenceEntity;
8118
9607
  exports.QualityInspectionOrderChangeEntity = QualityInspectionOrderChangeEntity;
8119
9608
  exports.QualityInspectionOrderEntity = QualityInspectionOrderEntity;
8120
9609
  exports.QualityInspectionOrderItemEntity = QualityInspectionOrderItemEntity;
@@ -8148,6 +9637,7 @@ exports.TransferVendorOrderItemEntity = TransferVendorOrderItemEntity;
8148
9637
  exports.UnitEntity = UnitEntity;
8149
9638
  exports.WMS_ACTOR_EXTRACTOR = WMS_ACTOR_EXTRACTOR;
8150
9639
  exports.WMS_CORE_MODULE_OPTIONS = WMS_CORE_MODULE_OPTIONS;
9640
+ exports.WMS_CUSTOM_CHANGE_TABLES = WMS_CUSTOM_CHANGE_TABLES;
8151
9641
  exports.WMS_EVENT_EMITTER_BRIDGE = WMS_EVENT_EMITTER_BRIDGE;
8152
9642
  exports.WMS_EVENT_OPTIONS = WMS_EVENT_OPTIONS;
8153
9643
  exports.WMS_OPERATION_NAMES = WMS_OPERATION_NAMES;