@rytass/wms-module-core 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/docs/api-reference.md +4 -0
  2. package/index.cjs.js +1705 -203
  3. package/index.js +11 -1
  4. package/lib/constants/consumption-change-kind.d.ts +17 -0
  5. package/lib/constants/consumption-change-kind.js +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 +9 -0
  9. package/lib/constants/order-type.d.ts +30 -0
  10. package/lib/constants/order-type.js +33 -0
  11. package/lib/constants/stock-status.d.ts +4 -1
  12. package/lib/constants/stock-status.js +6 -0
  13. package/lib/core.module.js +87 -3
  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 +98 -15
  17. package/lib/events/wms-event.tokens.d.ts +2 -0
  18. package/lib/events/wms-event.tokens.js +3 -1
  19. package/lib/events/wms-event.types.d.ts +38 -6
  20. package/lib/events/wms-operation-runner.d.ts +57 -0
  21. package/lib/events/wms-operation-runner.js +101 -0
  22. package/lib/models/extensions/consumption-order/consumption-order-change.entity.d.ts +19 -0
  23. package/lib/models/extensions/consumption-order/consumption-order-change.entity.js +59 -0
  24. package/lib/models/extensions/consumption-order/consumption-order-item.entity.d.ts +26 -0
  25. package/lib/models/extensions/consumption-order/consumption-order-item.entity.js +114 -0
  26. package/lib/models/extensions/consumption-order/consumption-order.entity.d.ts +32 -0
  27. package/lib/models/extensions/consumption-order/consumption-order.entity.js +69 -0
  28. package/lib/models/extensions/consumption-order/index.d.ts +3 -0
  29. package/lib/models/extensions/index.d.ts +4 -0
  30. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.d.ts +13 -1
  31. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.js +17 -1
  32. package/lib/models/extensions/order-reference/index.d.ts +1 -0
  33. package/lib/models/extensions/order-reference/order-reference.entity.d.ts +49 -0
  34. package/lib/models/extensions/order-reference/order-reference.entity.js +95 -0
  35. package/lib/models/metadata/batch.entity.d.ts +46 -0
  36. package/lib/models/metadata/batch.entity.js +58 -0
  37. package/lib/models/models.module.js +8 -0
  38. package/lib/services/allocate-inventory-order.service.js +4 -0
  39. package/lib/services/base-order.service.d.ts +18 -3
  40. package/lib/services/base-order.service.js +76 -0
  41. package/lib/services/batch.service.d.ts +17 -0
  42. package/lib/services/batch.service.js +41 -1
  43. package/lib/services/consumption-order.service.d.ts +75 -0
  44. package/lib/services/consumption-order.service.js +504 -0
  45. package/lib/services/hold-inventory-order.service.js +4 -0
  46. package/lib/services/index.d.ts +3 -0
  47. package/lib/services/inventory-count-order.service.js +7 -0
  48. package/lib/services/loader.service.js +4 -0
  49. package/lib/services/location.service.js +4 -0
  50. package/lib/services/material.service.js +4 -0
  51. package/lib/services/merge-batch-order.service.js +4 -0
  52. package/lib/services/order-reference.service.d.ts +50 -0
  53. package/lib/services/order-reference.service.js +136 -0
  54. package/lib/services/quality-inspection-order.service.js +4 -0
  55. package/lib/services/receive-inventory-order.service.js +132 -78
  56. package/lib/services/reclassify-inventory-order.service.js +4 -0
  57. package/lib/services/scrape.service.js +4 -0
  58. package/lib/services/ship-inventory-order.service.js +4 -0
  59. package/lib/services/split-batch-order.service.js +69 -46
  60. package/lib/services/stock.service.js +48 -4
  61. package/lib/services/transfer-customer-order.service.js +4 -0
  62. package/lib/services/transfer-order.service.js +4 -2
  63. package/lib/services/transfer-vendor-order.service.js +4 -0
  64. package/lib/services/unit.service.js +4 -0
  65. package/lib/typings/aggregated-stock.d.ts +6 -0
  66. package/lib/typings/consumption-order.input.d.ts +72 -0
  67. package/lib/typings/core-module-options.d.ts +34 -1
  68. package/lib/typings/custom-change-table.d.ts +70 -0
  69. package/lib/typings/find-stock.input.d.ts +23 -0
  70. package/lib/typings/get-batch.input.d.ts +16 -0
  71. package/lib/typings/index.d.ts +3 -0
  72. package/lib/typings/order-reference.input.d.ts +28 -0
  73. package/lib/typings/split-batch.input.d.ts +11 -0
  74. package/package.json +1 -1
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([
@@ -3194,7 +3731,14 @@ exports.StockService = class StockService {
3194
3731
  }
3195
3732
  async findAggregatedStocks(options) {
3196
3733
  // Create the aggregated subquery without pagination
3197
- const aggregateSubquery = this.pipeSelectOptionsToQueryBuilder({ ...options, offset: undefined, limit: undefined }, this.selectQueryBuilder('stock'), options.aggregated ? true : false);
3734
+ const aggregateSubquery = this.pipeSelectOptionsToQueryBuilder({ ...options, offset: undefined, limit: undefined }, this.selectQueryBuilder('stock'),
3735
+ // Always aggregated. The outer projection below is hard-wired to the
3736
+ // aggregated shape (it selects agg."saleSerialId" and friends), so letting
3737
+ // the caller switch the inner subquery off asked the outer query for a
3738
+ // column the inner one never produced — a hard `column agg."saleSerialId"
3739
+ // does not exist`. There was never a working `false` here: this method
3740
+ // returns AggregatedStock[], so aggregating is its only meaning.
3741
+ true);
3198
3742
  // Wrap the aggregated subquery and apply pagination on top
3199
3743
  const paginatedQueryBuilder = this.dataSource
3200
3744
  .createQueryBuilder()
@@ -3211,6 +3755,9 @@ exports.StockService = class StockService {
3211
3755
  paginatedQueryBuilder.addSelect('agg."customerId"', 'customerId');
3212
3756
  paginatedQueryBuilder.addSelect('agg."vendorId"', 'vendorId');
3213
3757
  paginatedQueryBuilder.addSelect('agg."inspectionResult"', 'inspectionResult');
3758
+ paginatedQueryBuilder.addSelect('agg."requiresInspection"', 'requiresInspection');
3759
+ paginatedQueryBuilder.addSelect('agg."parentBatchId"', 'parentBatchId');
3760
+ paginatedQueryBuilder.addSelect('agg."attributes"', 'attributes');
3214
3761
  // Apply pagination to the outer query
3215
3762
  if (options.offset !== undefined && options.offset >= 0) {
3216
3763
  paginatedQueryBuilder.skip(options.offset);
@@ -3219,7 +3766,14 @@ exports.StockService = class StockService {
3219
3766
  paginatedQueryBuilder.take(options.limit);
3220
3767
  }
3221
3768
  // Get total count from the aggregated subquery
3222
- const countBuilder = this.pipeSelectOptionsToQueryBuilder({ ...options, offset: undefined, limit: undefined }, this.selectQueryBuilder('stock'), options.aggregated ? true : false);
3769
+ const countBuilder = this.pipeSelectOptionsToQueryBuilder({ ...options, offset: undefined, limit: undefined }, this.selectQueryBuilder('stock'),
3770
+ // Always aggregated. The outer projection below is hard-wired to the
3771
+ // aggregated shape (it selects agg."saleSerialId" and friends), so letting
3772
+ // the caller switch the inner subquery off asked the outer query for a
3773
+ // column the inner one never produced — a hard `column agg."saleSerialId"
3774
+ // does not exist`. There was never a working `false` here: this method
3775
+ // returns AggregatedStock[], so aggregating is its only meaning.
3776
+ true);
3223
3777
  const countResult = await this.dataSource
3224
3778
  .createQueryBuilder()
3225
3779
  .select('COUNT(*)', 'count')
@@ -3743,6 +4297,23 @@ exports.BatchService = class BatchService {
3743
4297
  throw new Error('Inspection result already set, cannot modify');
3744
4298
  }
3745
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
+ */
3746
4317
  async getBatch({ manager = this.dataSource.manager, ...options }) {
3747
4318
  const batchRepository = manager.getRepository(this.batchEntity);
3748
4319
  const batchGroupRepository = manager.getRepository(this.batchGroupEntity);
@@ -3807,6 +4378,21 @@ exports.BatchService = class BatchService {
3807
4378
  transferId: orNull(mergedBatch.transferId),
3808
4379
  held: mergedBatch.held ?? false,
3809
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
+ }),
3810
4396
  };
3811
4397
  // Check if a batch with these exact metrics already exists in the same group
3812
4398
  const existingBatch = await batchRepository.findOne({
@@ -3819,6 +4405,10 @@ exports.BatchService = class BatchService {
3819
4405
  return batchRepository.save(batchRepository.create({
3820
4406
  ...mergedBatch,
3821
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,
3822
4412
  id: undefined,
3823
4413
  }));
3824
4414
  }
@@ -4122,89 +4712,139 @@ exports.ReceiveInventoryOrderService = class ReceiveInventoryOrderService {
4122
4712
  const locationRepository = manager.getRepository(this.entities.location);
4123
4713
  const loaderRepository = manager.getRepository(exports.LoadersEntityClass);
4124
4714
  const stockRepository = manager.getRepository(this.entities.stock);
4715
+ const batchRepository = manager.getRepository(this.entities.batch);
4125
4716
  const items = await itemRepository.find({
4126
4717
  where: { id: typeorm.In(options.map((o) => o.itemId)) },
4127
4718
  relations: { changes: true },
4128
4719
  });
4129
4720
  const itemMap = new Map(items.map((i) => [i.id, i]));
4130
- await Promise.all(options.map(async (option) => {
4131
- const item = itemMap.get(option.itemId);
4132
- if (!item)
4133
- return;
4134
- if (!item.batchId && option.batchKey) {
4135
- // if batchKey is provided but item doesn't have batchId, attempt to find or create batch and update item with batchId
4136
- item.batchId = await this.batchService
4137
- .getBatch({
4138
- manager,
4139
- key: option.batchKey,
4140
- materialId: item.materialId,
4141
- })
4142
- .then(async (b) => {
4143
- await itemRepository.update({ id: item.id }, { batchId: b.id });
4144
- return b.id;
4145
- });
4146
- }
4147
- const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId || undefined);
4148
- const totalChanged = item.changes.reduce((sum, change) => sum + Number(change.quantityChanged), 0);
4149
- const remainingQuantity = conversionFactor * item.targetReceivedQuantity - totalChanged;
4150
- if (remainingQuantity - option.quantity * conversionFactor < 0) {
4151
- throw new Error(`Receiving quantity exceeds target for item ${option.itemId}`);
4152
- }
4153
- const newOrder = await orderRepository.save(orderRepository.create());
4154
- let batchId = item.batchId;
4155
- if (option.batchKey)
4156
- batchId = await this.batchService
4157
- .getBatch({
4158
- manager,
4159
- key: option.batchKey,
4160
- materialId: item.materialId,
4161
- })
4162
- .then(({ id }) => id);
4163
- if (!batchId)
4164
- batchId = await this.batchService
4165
- .getBatch({
4166
- manager,
4167
- key: await this.helperService.getSeq('BATCH'),
4168
- materialId: item.materialId,
4169
- })
4170
- .then(({ id }) => id);
4171
- const inspectionResult = item.requireInspection === false
4172
- ? true
4173
- : (option.inspectionResult ?? null);
4174
- if (inspectionResult != null)
4175
- batchId = await this.batchService
4176
- .splitBatch({
4177
- manager,
4178
- id: batchId,
4179
- inspectionResult,
4180
- })
4181
- .then(({ id }) => id);
4182
- let locationId = item.locationId;
4183
- if (option.locationKey && !locationId)
4184
- locationId = await locationRepository
4185
- .findOneByOrFail({ key: option.locationKey })
4186
- .then(({ id }) => id);
4187
- let loaderId = item.loaderId;
4188
- if (option.loaderKey && !loaderId)
4189
- loaderId = await loaderRepository
4190
- .findOneByOrFail({ serialId: option.loaderKey })
4191
- .then(({ id }) => id);
4192
- await Promise.all([
4193
- changeRepository.save(changeRepository.create({
4194
- itemId: option.itemId,
4195
- quantityChanged: option.quantity * conversionFactor,
4196
- id: newOrder.id,
4197
- })),
4198
- stockRepository.save(stockRepository.create({
4199
- batchId: batchId || undefined,
4200
- locationId: this.stockService.resolveLocationId(locationId),
4201
- loaderId: this.stockService.resolveLoaderId(loaderId),
4202
- materialId: item.materialId,
4203
- quantity: option.quantity * conversionFactor,
4204
- orderId: newOrder.id,
4205
- })),
4206
- ]);
4207
- }));
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
+ }
4208
4848
  return true;
4209
4849
  });
4210
4850
  }
@@ -5100,7 +5740,6 @@ exports.TransferOrderService = class TransferOrderService {
5100
5740
  for (const srcLoaderId of wholeLoaderSourceIds) {
5101
5741
  const [aggRows] = await this.stockService.findAggregatedStocks({
5102
5742
  loaderId: srcLoaderId,
5103
- aggregated: true,
5104
5743
  });
5105
5744
  // Gate 1
5106
5745
  const nonFree = aggRows.filter((r) => r.status !== exports.StockStatus.FREE);
@@ -5331,7 +5970,6 @@ exports.TransferOrderService = class TransferOrderService {
5331
5970
  for (const [srcLoaderId, subTotalQty] of wholeLoaderGroupSums) {
5332
5971
  const [aggRows] = await this.stockService.findAggregatedStocks({
5333
5972
  loaderId: srcLoaderId,
5334
- aggregated: true,
5335
5973
  });
5336
5974
  const loaderTotalQty = aggRows.reduce((s, r) => s + Number(r.quantity), 0);
5337
5975
  if (subTotalQty !== loaderTotalQty) {
@@ -5938,64 +6576,83 @@ exports.SplitBatchOrderService = class SplitBatchOrderService {
5938
6576
  const originalBatch = await batchRepository.findOneOrFail({
5939
6577
  where: { id: options.batchId },
5940
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
+ }
5941
6591
  const key = await this.helperService.getSeq(this.seqPrefix, manager);
5942
6592
  const order = await splitBatchOrderRepository.save(splitBatchOrderRepository.create({
5943
6593
  key,
5944
6594
  }));
5945
6595
  // Get conversion factor for unit conversion
5946
6596
  const conversionFactor = await this.materialService.getConversionFactor(originalBatch.materialId, options.unitId || undefined);
5947
- // Process each item split
5948
- await Promise.all(options.items.map(async (item) => {
5949
- // Get or create target batch
5950
- const targetBatch = await this.batchService.getBatch({
5951
- key: item.batchKey,
5952
- materialId: originalBatch.materialId,
5953
- manager,
5954
- });
5955
- // Create base order record
5956
- const baseOrder = await orderRepository.save({});
5957
- // Create split batch order item
5958
- const splitItem = await splitBatchOrderItemRepository.save(splitBatchOrderItemRepository.create({
5959
- targetSplitQuantity: item.quantity,
5960
- locationId: this.stockService.resolveLocationId(item.locationId),
5961
- loaderId: item.loaderId,
5962
- orderId: order.id,
5963
- }));
5964
- // Record the change
5965
- await splitBatchOrderChangeRepository.save(splitBatchOrderChangeRepository.create({
5966
- itemId: splitItem.id,
5967
- id: baseOrder.id,
5968
- quantityChanged: item.quantity * conversionFactor,
5969
- }));
5970
- // Update stock: deduct from original batch and add to target batch
5971
- await this.stockService.validateStockAvailability({
5972
- materialId: originalBatch.materialId,
5973
- batchId: options.batchId,
5974
- locationId: this.stockService.resolveLocationId(item.locationId),
5975
- loaderId: this.stockService.resolveLoaderId(item.loaderId),
5976
- quantity: item.quantity * conversionFactor,
5977
- }, manager);
5978
- await stockRepository.save(stockRepository.create([
5979
- // Deduct from original batch
5980
- {
5981
- 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,
5982
6606
  materialId: originalBatch.materialId,
5983
- 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,
5984
6616
  locationId: this.stockService.resolveLocationId(item.locationId),
5985
- loaderId: this.stockService.resolveLoaderId(item.loaderId),
5986
- quantity: -1 * item.quantity * conversionFactor,
5987
- },
5988
- // Add to target batch
5989
- {
5990
- 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({
5991
6628
  materialId: originalBatch.materialId,
5992
- batchId: targetBatch.id,
6629
+ batchId: options.batchId,
5993
6630
  locationId: this.stockService.resolveLocationId(item.locationId),
5994
6631
  loaderId: this.stockService.resolveLoaderId(item.loaderId),
5995
6632
  quantity: item.quantity * conversionFactor,
5996
- },
5997
- ]));
5998
- }));
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
+ }
5999
6656
  return order;
6000
6657
  });
6001
6658
  }
@@ -6152,6 +6809,574 @@ exports.MergeBatchOrderService = tslib.__decorate([
6152
6809
  exports.StockService, Object, Object])
6153
6810
  ], exports.MergeBatchOrderService);
6154
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
+
6155
7380
  exports.ReclassifyInventoryOrderService = class ReclassifyInventoryOrderService {
6156
7381
  dataSource;
6157
7382
  entities;
@@ -6920,6 +8145,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6920
8145
  .addSelect('batch.held', 'held')
6921
8146
  .addSelect('batch."inShipment"', 'inShipment')
6922
8147
  .addSelect('batch."inspectionResult"', 'inspectionResult')
8148
+ .addSelect('batch."requiresInspection"', 'requiresInspection')
6923
8149
  .addSelect('batch."transferId"', 'transferId')
6924
8150
  .addSelect('batch."vendorId"', 'vendorId')
6925
8151
  .addSelect('batch."customerId"', 'customerId')
@@ -6937,6 +8163,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6937
8163
  .addGroupBy('batch.held')
6938
8164
  .addGroupBy('batch."inShipment"')
6939
8165
  .addGroupBy('batch."inspectionResult"')
8166
+ .addGroupBy('batch."requiresInspection"')
6940
8167
  .addGroupBy('batch."transferId"')
6941
8168
  .addGroupBy('batch."vendorId"')
6942
8169
  .addGroupBy('batch."customerId"')
@@ -6954,6 +8181,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6954
8181
  held: row.held ?? null,
6955
8182
  inShipment: row.inShipment ?? null,
6956
8183
  inspectionResult: row.inspectionResult ?? null,
8184
+ requiresInspection: row.requiresInspection ?? null,
6957
8185
  transferId: row.transferId ?? null,
6958
8186
  vendorId: row.vendorId ?? null,
6959
8187
  customerId: row.customerId ?? null,
@@ -7536,37 +8764,52 @@ const WMS_EVENT_EMITTER_BRIDGE = Symbol('WMS_EVENT_EMITTER_BRIDGE');
7536
8764
  const WMS_ACTOR_EXTRACTOR = Symbol('WMS_ACTOR_EXTRACTOR');
7537
8765
  /** DI token holding the boolean "enrich stock events" flag (default false). */
7538
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');
7539
8769
 
7540
8770
  /**
7541
- * Resolve the `ChangeType` for a change table. Tables whose semantics depend on
7542
- * the sign of `quantityChanged` (ship / transfer / vendor / customer / hold /
7543
- * 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`.
7544
8785
  */
7545
8786
  const TABLE_TO_CHANGE_TYPE = new Map([
7546
8787
  ['receive_inventory_order_changes', () => exports.ChangeType.RECEIVED],
7547
8788
  [
7548
8789
  'ship_inventory_order_changes',
7549
- (q) => (q > 0 ? exports.ChangeType.IN_SHIPMENT : exports.ChangeType.SHIPPED),
8790
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.IN_SHIPMENT : exports.ChangeType.SHIPPED,
7550
8791
  ],
7551
8792
  [
7552
8793
  'transfer_order_changes',
7553
- (q) => (q > 0 ? exports.ChangeType.IN_TRANSFER : exports.ChangeType.TRANSFERRED),
8794
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.IN_TRANSFER : exports.ChangeType.TRANSFERRED,
7554
8795
  ],
7555
8796
  [
7556
8797
  'transfer_vendor_order_changes',
7557
- (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,
7558
8801
  ],
7559
8802
  [
7560
8803
  'transfer_customer_order_changes',
7561
- (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,
7562
8805
  ],
7563
8806
  [
7564
8807
  'hold_inventory_order_changes',
7565
- (q) => (q > 0 ? exports.ChangeType.HELD : exports.ChangeType.RELEASED),
8808
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.HELD : exports.ChangeType.RELEASED,
7566
8809
  ],
7567
8810
  [
7568
8811
  'allocate_inventory_order_changes',
7569
- (q) => (q > 0 ? exports.ChangeType.ALLOCATED : exports.ChangeType.DEALLOCATED),
8812
+ ({ quantityChanged: q }) => Number(q) > 0 ? exports.ChangeType.ALLOCATED : exports.ChangeType.DEALLOCATED,
7570
8813
  ],
7571
8814
  ['split_batch_order_changes', () => exports.ChangeType.SPLITTED],
7572
8815
  ['merge_batch_order_changes', () => exports.ChangeType.MERGED],
@@ -7574,7 +8817,11 @@ const TABLE_TO_CHANGE_TYPE = new Map([
7574
8817
  ['scrape_order_changes', () => exports.ChangeType.SCRAPED],
7575
8818
  [
7576
8819
  'inventory_count_order_changes',
7577
- (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),
7578
8825
  ],
7579
8826
  ]);
7580
8827
  const CHANGE_TYPE_TO_EVENT = {
@@ -7597,8 +8844,28 @@ const CHANGE_TYPE_TO_EVENT = {
7597
8844
  [exports.ChangeType.SCRAPED]: 'stock.scraped',
7598
8845
  [exports.ChangeType.COUNT_GAINED]: 'stock.count-gained',
7599
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',
7600
8850
  };
7601
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));
7602
8869
  /**
7603
8870
  * Centralized collection of stock domain events. Listens to every
7604
8871
  * `*_order_change` insert and, using the change table name plus the sign of
@@ -7613,9 +8880,12 @@ const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
7613
8880
  let StockChangeSubscriber = class StockChangeSubscriber {
7614
8881
  collector;
7615
8882
  enrich;
7616
- 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) {
7617
8886
  this.collector = collector;
7618
8887
  this.enrich = enrich;
8888
+ this.customTables = new Map((customTables ?? []).map((entry) => [entry.table, entry]));
7619
8889
  dataSource.subscribers.push(this);
7620
8890
  }
7621
8891
  async afterInsert(event) {
@@ -7639,12 +8909,22 @@ let StockChangeSubscriber = class StockChangeSubscriber {
7639
8909
  });
7640
8910
  return;
7641
8911
  }
8912
+ const custom = this.customTables.get(tableName);
8913
+ if (custom) {
8914
+ await this.collectCustom(event, entity, quantityDelta, custom);
8915
+ return;
8916
+ }
7642
8917
  const resolveChangeType = TABLE_TO_CHANGE_TYPE.get(tableName);
7643
8918
  if (!resolveChangeType) {
7644
8919
  // Not a stock change table — enrich nothing, emit nothing.
7645
8920
  return;
7646
8921
  }
7647
- 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
+ }
7648
8928
  const enrichment = this.enrich
7649
8929
  ? await this.loadItemFields(event, entity.itemId)
7650
8930
  : undefined;
@@ -7656,6 +8936,36 @@ let StockChangeSubscriber = class StockChangeSubscriber {
7656
8936
  ...enrichment,
7657
8937
  });
7658
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
+ }
7659
8969
  /**
7660
8970
  * Load `materialId / batchId / locationId / loaderId` from the change's order
7661
8971
  * item (one PK lookup, same transaction). Generic across all 12 change tables
@@ -7693,8 +9003,10 @@ StockChangeSubscriber = tslib.__decorate([
7693
9003
  tslib.__param(0, typeorm$1.InjectDataSource()),
7694
9004
  tslib.__param(2, common.Optional()),
7695
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)),
7696
9008
  tslib.__metadata("design:paramtypes", [typeorm.DataSource,
7697
- exports.WmsEventCollector, Object])
9009
+ exports.WmsEventCollector, Object, Object])
7698
9010
  ], StockChangeSubscriber);
7699
9011
 
7700
9012
  /** The count's own settlement writes here; it must never lock itself out. */
@@ -7789,6 +9101,159 @@ exports.InventoryCountLockSubscriber = tslib.__decorate([
7789
9101
  tslib.__metadata("design:paramtypes", [typeorm.DataSource])
7790
9102
  ], exports.InventoryCountLockSubscriber);
7791
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
+
7792
9257
  var WmsModuleCoreModule_1;
7793
9258
  /**
7794
9259
  * The entity Symbols a consumer can rebind, each paired with the base module's
@@ -7884,12 +9349,75 @@ const exportDependencies = [
7884
9349
  exports.SaleOrderService,
7885
9350
  exports.SplitBatchOrderService,
7886
9351
  exports.MergeBatchOrderService,
9352
+ exports.OrderReferenceService,
9353
+ exports.ConsumptionOrderService,
7887
9354
  exports.ReclassifyInventoryOrderService,
7888
9355
  exports.ScrapeService,
7889
9356
  exports.InventoryCountOrderService,
7890
9357
  exports.QualityInspectionOrderService,
7891
9358
  exports.WarehouseMapDataService,
7892
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
+ };
7893
9421
  exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule {
7894
9422
  static forRoot(options, coreOptions) {
7895
9423
  const coreModule = wmsBaseNestjsModule.WMSBaseModule.forRoot(options);
@@ -7901,6 +9429,11 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
7901
9429
  StockChangeSubscriber,
7902
9430
  exports.InventoryCountLockSubscriber,
7903
9431
  ...resolvedEntityProviders,
9432
+ ...eventProviders(coreOptions),
9433
+ {
9434
+ provide: WMS_CUSTOM_CHANGE_TABLES,
9435
+ useValue: assertCustomChangeTables(coreOptions.customChangeTables),
9436
+ },
7904
9437
  { provide: WMS_CORE_MODULE_OPTIONS, useValue: coreOptions },
7905
9438
  {
7906
9439
  provide: WMS_STOCK_ENRICH,
@@ -7912,12 +9445,13 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
7912
9445
  coreModule,
7913
9446
  ModelsModule,
7914
9447
  ...exportedEntityTokens,
9448
+ ...eventExports,
7915
9449
  WMS_CORE_MODULE_OPTIONS,
7916
9450
  ],
7917
9451
  };
7918
9452
  }
7919
9453
  static forRootAsync(options) {
7920
- const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, enrichStockEvents, ...baseOptions } = options;
9454
+ const { defaultLoaderSerialId, defaultLoaderTypeKey, defaultLocationKey, enrichStockEvents, beforeHooks, afterListeners, actorExtractor, eventEmitterBridge, customChangeTables, ...baseOptions } = options;
7921
9455
  const coreModule = wmsBaseNestjsModule.WMSBaseModule.forRootAsync(baseOptions);
7922
9456
  return {
7923
9457
  module: WmsModuleCoreModule_1,
@@ -7927,6 +9461,16 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
7927
9461
  StockChangeSubscriber,
7928
9462
  exports.InventoryCountLockSubscriber,
7929
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
+ },
7930
9474
  {
7931
9475
  provide: WMS_CORE_MODULE_OPTIONS,
7932
9476
  useValue: {
@@ -7942,6 +9486,7 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
7942
9486
  coreModule,
7943
9487
  ModelsModule,
7944
9488
  ...exportedEntityTokens,
9489
+ ...eventExports,
7945
9490
  WMS_CORE_MODULE_OPTIONS,
7946
9491
  ],
7947
9492
  };
@@ -7965,6 +9510,12 @@ const WMS_OPERATION_NAMES = [
7965
9510
  'batch:merge',
7966
9511
  'batch:read',
7967
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',
7968
9519
  'hold-inventory-order:create',
7969
9520
  'hold-inventory-order:read',
7970
9521
  'hold-inventory-order:release',
@@ -7989,6 +9540,9 @@ const WMS_OPERATION_NAMES = [
7989
9540
  'material:create',
7990
9541
  'material:read',
7991
9542
  'material:update',
9543
+ 'order-reference:attach',
9544
+ 'order-reference:detach',
9545
+ 'order-reference:read',
7992
9546
  'quality-inspection-order:inspect',
7993
9547
  'receive-inventory-order:create',
7994
9548
  'receive-inventory-order:read',
@@ -8019,64 +9573,6 @@ const WMS_OPERATION_NAMES = [
8019
9573
  'warehouse-map:update',
8020
9574
  ];
8021
9575
 
8022
- var WmsEventDispatcher_1;
8023
- /**
8024
- * Central event dispatcher. Runs consumer before-hooks (which may veto) and,
8025
- * post-commit, flushes collected events to consumer after-listeners and the
8026
- * optional emitter bridge. Listener errors are isolated so one failing listener
8027
- * never blocks the others or the already-committed mutation.
8028
- */
8029
- exports.WmsEventDispatcher = WmsEventDispatcher_1 = class WmsEventDispatcher {
8030
- options;
8031
- bridge;
8032
- logger = new common.Logger(WmsEventDispatcher_1.name);
8033
- constructor(options, bridge = null) {
8034
- this.options = options;
8035
- this.bridge = bridge;
8036
- }
8037
- /** Whether any hook, listener or bridge is wired (lets the interceptor skip overhead entirely). */
8038
- isActive() {
8039
- const { beforeHooks, afterListeners } = this.options;
8040
- return (!!this.bridge ||
8041
- (!!beforeHooks && Object.keys(beforeHooks).length > 0) ||
8042
- (!!afterListeners && Object.keys(afterListeners).length > 0));
8043
- }
8044
- /** Invoke the before-hook for an event. A thrown error vetoes the mutation. */
8045
- async runBeforeHook(context) {
8046
- const hook = this.options.beforeHooks?.[context.event];
8047
- if (hook) {
8048
- await hook(context);
8049
- }
8050
- }
8051
- /** Flush collected events to after-listeners and the emitter bridge (post-commit). */
8052
- async flush(events) {
8053
- for (const event of events) {
8054
- const listener = this.options.afterListeners?.[event.name];
8055
- if (listener) {
8056
- try {
8057
- await listener({ event: event.name, payload: event.payload });
8058
- }
8059
- catch (error) {
8060
- this.logger.error(`WMS after-listener for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
8061
- }
8062
- }
8063
- try {
8064
- this.bridge?.forward(event);
8065
- }
8066
- catch (error) {
8067
- this.logger.error(`WMS emitter bridge for "${event.name}" threw: ${error instanceof Error ? error.message : String(error)}`);
8068
- }
8069
- }
8070
- }
8071
- };
8072
- exports.WmsEventDispatcher = WmsEventDispatcher_1 = tslib.__decorate([
8073
- common.Injectable(),
8074
- tslib.__param(0, common.Inject(WMS_EVENT_OPTIONS)),
8075
- tslib.__param(1, common.Optional()),
8076
- tslib.__param(1, common.Inject(WMS_EVENT_EMITTER_BRIDGE)),
8077
- tslib.__metadata("design:paramtypes", [Object, Object])
8078
- ], exports.WmsEventDispatcher);
8079
-
8080
9576
  Object.defineProperty(exports, "OrderEntityClass", {
8081
9577
  enumerable: true,
8082
9578
  get: function () { return wmsBaseNestjsModule.OrderEntity; }
@@ -8084,8 +9580,12 @@ Object.defineProperty(exports, "OrderEntityClass", {
8084
9580
  exports.AllocateInventoryOrderChangeEntity = AllocateInventoryOrderChangeEntity;
8085
9581
  exports.AllocateInventoryOrderEntity = AllocateInventoryOrderEntity;
8086
9582
  exports.AllocateInventoryOrderItemEntity = AllocateInventoryOrderItemEntity;
9583
+ exports.BaseOrderService = BaseOrderService;
8087
9584
  exports.BatchEntity = BatchEntity;
8088
9585
  exports.BatchGroupEntity = BatchGroupEntity;
9586
+ exports.ConsumptionOrderChangeEntity = ConsumptionOrderChangeEntity;
9587
+ exports.ConsumptionOrderEntity = ConsumptionOrderEntity;
9588
+ exports.ConsumptionOrderItemEntity = ConsumptionOrderItemEntity;
8089
9589
  exports.HoldInventoryOrderChangeEntity = HoldInventoryOrderChangeEntity;
8090
9590
  exports.HoldInventoryOrderEntity = HoldInventoryOrderEntity;
8091
9591
  exports.HoldInventoryOrderItemEntity = HoldInventoryOrderItemEntity;
@@ -8103,6 +9603,7 @@ exports.MergeBatchOrderChangeEntity = MergeBatchOrderChangeEntity;
8103
9603
  exports.MergeBatchOrderEntity = MergeBatchOrderEntity;
8104
9604
  exports.MergeBatchOrderItemEntity = MergeBatchOrderItemEntity;
8105
9605
  exports.OrderEntity = OrderEntity;
9606
+ exports.OrderReferenceEntity = OrderReferenceEntity;
8106
9607
  exports.QualityInspectionOrderChangeEntity = QualityInspectionOrderChangeEntity;
8107
9608
  exports.QualityInspectionOrderEntity = QualityInspectionOrderEntity;
8108
9609
  exports.QualityInspectionOrderItemEntity = QualityInspectionOrderItemEntity;
@@ -8136,6 +9637,7 @@ exports.TransferVendorOrderItemEntity = TransferVendorOrderItemEntity;
8136
9637
  exports.UnitEntity = UnitEntity;
8137
9638
  exports.WMS_ACTOR_EXTRACTOR = WMS_ACTOR_EXTRACTOR;
8138
9639
  exports.WMS_CORE_MODULE_OPTIONS = WMS_CORE_MODULE_OPTIONS;
9640
+ exports.WMS_CUSTOM_CHANGE_TABLES = WMS_CUSTOM_CHANGE_TABLES;
8139
9641
  exports.WMS_EVENT_EMITTER_BRIDGE = WMS_EVENT_EMITTER_BRIDGE;
8140
9642
  exports.WMS_EVENT_OPTIONS = WMS_EVENT_OPTIONS;
8141
9643
  exports.WMS_OPERATION_NAMES = WMS_OPERATION_NAMES;