@rytass/wms-module-core 0.8.1 → 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 (73) hide show
  1. package/index.cjs.js +1689 -199
  2. package/index.js +11 -1
  3. package/lib/constants/consumption-change-kind.d.ts +17 -0
  4. package/lib/constants/consumption-change-kind.js +20 -0
  5. package/lib/constants/index.d.ts +2 -0
  6. package/lib/constants/operations.d.ts +1 -1
  7. package/lib/constants/operations.js +9 -0
  8. package/lib/constants/order-type.d.ts +30 -0
  9. package/lib/constants/order-type.js +33 -0
  10. package/lib/constants/stock-status.d.ts +4 -1
  11. package/lib/constants/stock-status.js +6 -0
  12. package/lib/core.module.js +87 -3
  13. package/lib/events/index.d.ts +2 -1
  14. package/lib/events/stock-change.subscriber.d.ts +26 -1
  15. package/lib/events/stock-change.subscriber.js +98 -15
  16. package/lib/events/wms-event.tokens.d.ts +2 -0
  17. package/lib/events/wms-event.tokens.js +3 -1
  18. package/lib/events/wms-event.types.d.ts +38 -6
  19. package/lib/events/wms-operation-runner.d.ts +57 -0
  20. package/lib/events/wms-operation-runner.js +101 -0
  21. package/lib/models/extensions/consumption-order/consumption-order-change.entity.d.ts +19 -0
  22. package/lib/models/extensions/consumption-order/consumption-order-change.entity.js +59 -0
  23. package/lib/models/extensions/consumption-order/consumption-order-item.entity.d.ts +26 -0
  24. package/lib/models/extensions/consumption-order/consumption-order-item.entity.js +114 -0
  25. package/lib/models/extensions/consumption-order/consumption-order.entity.d.ts +32 -0
  26. package/lib/models/extensions/consumption-order/consumption-order.entity.js +69 -0
  27. package/lib/models/extensions/consumption-order/index.d.ts +3 -0
  28. package/lib/models/extensions/index.d.ts +4 -0
  29. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.d.ts +13 -1
  30. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.js +17 -1
  31. package/lib/models/extensions/order-reference/index.d.ts +1 -0
  32. package/lib/models/extensions/order-reference/order-reference.entity.d.ts +49 -0
  33. package/lib/models/extensions/order-reference/order-reference.entity.js +95 -0
  34. package/lib/models/metadata/batch.entity.d.ts +46 -0
  35. package/lib/models/metadata/batch.entity.js +58 -0
  36. package/lib/models/models.module.js +8 -0
  37. package/lib/services/allocate-inventory-order.service.js +4 -0
  38. package/lib/services/base-order.service.d.ts +18 -3
  39. package/lib/services/base-order.service.js +76 -0
  40. package/lib/services/batch.service.d.ts +17 -0
  41. package/lib/services/batch.service.js +41 -1
  42. package/lib/services/consumption-order.service.d.ts +75 -0
  43. package/lib/services/consumption-order.service.js +504 -0
  44. package/lib/services/hold-inventory-order.service.js +4 -0
  45. package/lib/services/index.d.ts +3 -0
  46. package/lib/services/inventory-count-order.service.js +7 -0
  47. package/lib/services/loader.service.js +4 -0
  48. package/lib/services/location.service.js +4 -0
  49. package/lib/services/material.service.js +4 -0
  50. package/lib/services/merge-batch-order.service.js +4 -0
  51. package/lib/services/order-reference.service.d.ts +50 -0
  52. package/lib/services/order-reference.service.js +136 -0
  53. package/lib/services/quality-inspection-order.service.js +4 -0
  54. package/lib/services/receive-inventory-order.service.js +132 -78
  55. package/lib/services/reclassify-inventory-order.service.js +4 -0
  56. package/lib/services/scrape.service.js +4 -0
  57. package/lib/services/ship-inventory-order.service.js +4 -0
  58. package/lib/services/split-batch-order.service.js +69 -46
  59. package/lib/services/stock.service.js +32 -2
  60. package/lib/services/transfer-customer-order.service.js +4 -0
  61. package/lib/services/transfer-order.service.js +4 -0
  62. package/lib/services/transfer-vendor-order.service.js +4 -0
  63. package/lib/services/unit.service.js +4 -0
  64. package/lib/typings/aggregated-stock.d.ts +6 -0
  65. package/lib/typings/consumption-order.input.d.ts +72 -0
  66. package/lib/typings/core-module-options.d.ts +34 -1
  67. package/lib/typings/custom-change-table.d.ts +70 -0
  68. package/lib/typings/find-stock.input.d.ts +14 -0
  69. package/lib/typings/get-batch.input.d.ts +16 -0
  70. package/lib/typings/index.d.ts +3 -0
  71. package/lib/typings/order-reference.input.d.ts +28 -0
  72. package/lib/typings/split-batch.input.d.ts +11 -0
  73. package/package.json +1 -1
@@ -0,0 +1,49 @@
1
+ import { WmsOrderType } from '../../../constants/order-type';
2
+ export declare const OrderReferenceEntity: unique symbol;
3
+ /**
4
+ * Why an order was opened, in the host's own vocabulary.
5
+ *
6
+ * Every order family in this package records *what* moved and *when*, and none
7
+ * of them records *what for*. A host that drives the warehouse from somewhere
8
+ * else — a work order, a purchase order, a repair job, a subcontract — has no
9
+ * way to ask "which stock movements happened because of this", and no way to
10
+ * show an operator which upstream document a transfer belongs to.
11
+ *
12
+ * One polymorphic table rather than three columns on each of the thirteen order
13
+ * entities: the reference is the same idea everywhere, a new order family picks
14
+ * it up for free, and a per-item reference (`itemId`) has somewhere to live
15
+ * without widening every item table too.
16
+ *
17
+ * `referenceType` / `referenceId` are opaque strings. This module never parses
18
+ * them and never resolves them to anything — what a `work-order` is belongs to
19
+ * the host, and `@rytass/wms-module-react`'s `referenceLinkResolver` is how a
20
+ * host turns one into a link.
21
+ *
22
+ * Not to be confused with `ShipInventoryOrderReferenceEntityClass`, which
23
+ * despite the name is a line-level shipment plan (it carries quantities and a
24
+ * removal timestamp), not a pointer at an upstream document. The two coexist.
25
+ */
26
+ export declare class OrderReferenceEntityClass {
27
+ id: string;
28
+ /** Which order family `orderId` belongs to. */
29
+ orderType: WmsOrderType;
30
+ orderId: string;
31
+ /**
32
+ * The order item this reference is about, when the reference is line-level —
33
+ * one order covering several upstream lines. `null` means it applies to the
34
+ * order as a whole.
35
+ */
36
+ itemId: string | null;
37
+ /** Host-defined kind of document, e.g. `work-order`, `purchase-order`. */
38
+ referenceType: string;
39
+ /** The upstream document's identifier, as the host knows it. */
40
+ referenceId: string;
41
+ /** The line within that document, when it has lines. */
42
+ referenceLine: string | null;
43
+ /**
44
+ * Anything else the host wants to carry along — an operation sequence, a
45
+ * component line, a reason code. Stored verbatim and never interpreted.
46
+ */
47
+ metadata: Record<string, unknown> | null;
48
+ createdAt: Date;
49
+ }
@@ -0,0 +1,95 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { PrimaryGeneratedColumn, Column, CreateDateColumn, Entity, Index } from 'typeorm';
3
+ import '../../../constants/order-type.js';
4
+
5
+ const OrderReferenceEntity = Symbol('OrderReferenceEntity');
6
+ /**
7
+ * Why an order was opened, in the host's own vocabulary.
8
+ *
9
+ * Every order family in this package records *what* moved and *when*, and none
10
+ * of them records *what for*. A host that drives the warehouse from somewhere
11
+ * else — a work order, a purchase order, a repair job, a subcontract — has no
12
+ * way to ask "which stock movements happened because of this", and no way to
13
+ * show an operator which upstream document a transfer belongs to.
14
+ *
15
+ * One polymorphic table rather than three columns on each of the thirteen order
16
+ * entities: the reference is the same idea everywhere, a new order family picks
17
+ * it up for free, and a per-item reference (`itemId`) has somewhere to live
18
+ * without widening every item table too.
19
+ *
20
+ * `referenceType` / `referenceId` are opaque strings. This module never parses
21
+ * them and never resolves them to anything — what a `work-order` is belongs to
22
+ * the host, and `@rytass/wms-module-react`'s `referenceLinkResolver` is how a
23
+ * host turns one into a link.
24
+ *
25
+ * Not to be confused with `ShipInventoryOrderReferenceEntityClass`, which
26
+ * despite the name is a line-level shipment plan (it carries quantities and a
27
+ * removal timestamp), not a pointer at an upstream document. The two coexist.
28
+ */
29
+ let OrderReferenceEntityClass = class OrderReferenceEntityClass {
30
+ id;
31
+ /** Which order family `orderId` belongs to. */
32
+ orderType;
33
+ orderId;
34
+ /**
35
+ * The order item this reference is about, when the reference is line-level —
36
+ * one order covering several upstream lines. `null` means it applies to the
37
+ * order as a whole.
38
+ */
39
+ itemId;
40
+ /** Host-defined kind of document, e.g. `work-order`, `purchase-order`. */
41
+ referenceType;
42
+ /** The upstream document's identifier, as the host knows it. */
43
+ referenceId;
44
+ /** The line within that document, when it has lines. */
45
+ referenceLine;
46
+ /**
47
+ * Anything else the host wants to carry along — an operation sequence, a
48
+ * component line, a reason code. Stored verbatim and never interpreted.
49
+ */
50
+ metadata;
51
+ createdAt;
52
+ };
53
+ __decorate([
54
+ PrimaryGeneratedColumn('uuid'),
55
+ __metadata("design:type", String)
56
+ ], OrderReferenceEntityClass.prototype, "id", void 0);
57
+ __decorate([
58
+ Column({ type: 'varchar' }),
59
+ __metadata("design:type", String)
60
+ ], OrderReferenceEntityClass.prototype, "orderType", void 0);
61
+ __decorate([
62
+ Column({ type: 'uuid' }),
63
+ __metadata("design:type", String)
64
+ ], OrderReferenceEntityClass.prototype, "orderId", void 0);
65
+ __decorate([
66
+ Column({ type: 'uuid', nullable: true }),
67
+ __metadata("design:type", Object)
68
+ ], OrderReferenceEntityClass.prototype, "itemId", void 0);
69
+ __decorate([
70
+ Column({ type: 'varchar' }),
71
+ __metadata("design:type", String)
72
+ ], OrderReferenceEntityClass.prototype, "referenceType", void 0);
73
+ __decorate([
74
+ Column({ type: 'varchar' }),
75
+ __metadata("design:type", String)
76
+ ], OrderReferenceEntityClass.prototype, "referenceId", void 0);
77
+ __decorate([
78
+ Column({ type: 'varchar', nullable: true }),
79
+ __metadata("design:type", Object)
80
+ ], OrderReferenceEntityClass.prototype, "referenceLine", void 0);
81
+ __decorate([
82
+ Column({ type: 'jsonb', nullable: true }),
83
+ __metadata("design:type", Object)
84
+ ], OrderReferenceEntityClass.prototype, "metadata", void 0);
85
+ __decorate([
86
+ CreateDateColumn({ type: 'timestamptz' }),
87
+ __metadata("design:type", Date)
88
+ ], OrderReferenceEntityClass.prototype, "createdAt", void 0);
89
+ OrderReferenceEntityClass = __decorate([
90
+ Entity('order_references'),
91
+ Index(['orderType', 'orderId']),
92
+ Index(['referenceType', 'referenceId'])
93
+ ], OrderReferenceEntityClass);
94
+
95
+ export { OrderReferenceEntity, OrderReferenceEntityClass };
@@ -8,8 +8,54 @@ export declare class BatchEntityClass extends BaseBatchEntity {
8
8
  customerId: string | null;
9
9
  vendorId: string | null;
10
10
  inspectionResult: boolean | null;
11
+ /**
12
+ * Whether anyone ever asked for this batch to be inspected.
13
+ *
14
+ * `inspectionResult IS NULL` on its own cannot answer that: null is also the
15
+ * state of every batch nobody ever intended to inspect, which is most of
16
+ * them. Reading it as "awaiting inspection" made `StockStatus`
17
+ * `PENDING_INSPECTION` return the whole warehouse.
18
+ *
19
+ * Set when a receive order item carrying `requireInspection` lands without a
20
+ * result yet; cleared by nothing, because the pending filter also requires
21
+ * `inspectionResult IS NULL` and an inspection fills that in.
22
+ */
23
+ requiresInspection: boolean;
11
24
  transferId: string | null;
12
25
  held: boolean;
13
26
  inShipment: boolean;
27
+ /**
28
+ * The batch this one was first split out of, or `null` for a batch that was
29
+ * created outright.
30
+ *
31
+ * Written once, at creation, and never updated — it is a genealogy line, not
32
+ * a current-parent pointer. Every status in this model is a flag on the batch
33
+ * rather than a column on the stock row, so holding, transferring or shipping
34
+ * *part* of a batch splits a child off first (see
35
+ * `HoldInventoryOrderService`); before this column those children were
36
+ * orphans, and the only way back to the original batch was to read the stock
37
+ * ledger. Following `parentBatchId` upwards now yields the root batch, which
38
+ * is what a label or a shipping document should print.
39
+ *
40
+ * `BatchService.splitBatch` reuses an existing sibling when one already
41
+ * carries the requested attributes, so a reused batch keeps the parent it was
42
+ * first created from. The quantity ledger in `stocks` remains the authority
43
+ * on what actually moved.
44
+ */
45
+ parentBatchId: string | null;
46
+ /**
47
+ * Host-defined attributes describing this batch, stored verbatim.
48
+ *
49
+ * The module reads nothing out of this and validates nothing in it: what a
50
+ * grade, a bin code or a die count means belongs to the host, and a schema
51
+ * enforced here would be a second, weaker copy of the host's own. It exists
52
+ * because `batchEntity` overrides solve the storage half of the problem but
53
+ * not the display half — a column the module does not know about cannot be
54
+ * carried through a split or shown on a batch row, and this can.
55
+ *
56
+ * Set at creation; two splits asking for different attributes produce two
57
+ * batches rather than one merged one.
58
+ */
59
+ attributes: Record<string, unknown> | null;
14
60
  batchGroup: BatchGroupEntityClass;
15
61
  }
@@ -14,12 +14,58 @@ let BatchEntityClass = class BatchEntityClass extends BatchEntity$1 {
14
14
  vendorId;
15
15
  // added when quality inspection, used to link to quality inspection order
16
16
  inspectionResult;
17
+ /**
18
+ * Whether anyone ever asked for this batch to be inspected.
19
+ *
20
+ * `inspectionResult IS NULL` on its own cannot answer that: null is also the
21
+ * state of every batch nobody ever intended to inspect, which is most of
22
+ * them. Reading it as "awaiting inspection" made `StockStatus`
23
+ * `PENDING_INSPECTION` return the whole warehouse.
24
+ *
25
+ * Set when a receive order item carrying `requireInspection` lands without a
26
+ * result yet; cleared by nothing, because the pending filter also requires
27
+ * `inspectionResult IS NULL` and an inspection fills that in.
28
+ */
29
+ requiresInspection;
17
30
  // added when transfer inventory, used to link to transfer order
18
31
  transferId;
19
32
  // added when hold inventory, used to link to hold inventory order
20
33
  held;
21
34
  // added when shipment inventory, used to link to shipment order
22
35
  inShipment;
36
+ /**
37
+ * The batch this one was first split out of, or `null` for a batch that was
38
+ * created outright.
39
+ *
40
+ * Written once, at creation, and never updated — it is a genealogy line, not
41
+ * a current-parent pointer. Every status in this model is a flag on the batch
42
+ * rather than a column on the stock row, so holding, transferring or shipping
43
+ * *part* of a batch splits a child off first (see
44
+ * `HoldInventoryOrderService`); before this column those children were
45
+ * orphans, and the only way back to the original batch was to read the stock
46
+ * ledger. Following `parentBatchId` upwards now yields the root batch, which
47
+ * is what a label or a shipping document should print.
48
+ *
49
+ * `BatchService.splitBatch` reuses an existing sibling when one already
50
+ * carries the requested attributes, so a reused batch keeps the parent it was
51
+ * first created from. The quantity ledger in `stocks` remains the authority
52
+ * on what actually moved.
53
+ */
54
+ parentBatchId;
55
+ /**
56
+ * Host-defined attributes describing this batch, stored verbatim.
57
+ *
58
+ * The module reads nothing out of this and validates nothing in it: what a
59
+ * grade, a bin code or a die count means belongs to the host, and a schema
60
+ * enforced here would be a second, weaker copy of the host's own. It exists
61
+ * because `batchEntity` overrides solve the storage half of the problem but
62
+ * not the display half — a column the module does not know about cannot be
63
+ * carried through a split or shown on a batch row, and this can.
64
+ *
65
+ * Set at creation; two splits asking for different attributes produce two
66
+ * batches rather than one merged one.
67
+ */
68
+ attributes;
23
69
  batchGroup;
24
70
  };
25
71
  __decorate([
@@ -46,6 +92,10 @@ __decorate([
46
92
  Column({ type: 'bool', nullable: true }),
47
93
  __metadata("design:type", Object)
48
94
  ], BatchEntityClass.prototype, "inspectionResult", void 0);
95
+ __decorate([
96
+ Column({ type: 'bool', default: false }),
97
+ __metadata("design:type", Boolean)
98
+ ], BatchEntityClass.prototype, "requiresInspection", void 0);
49
99
  __decorate([
50
100
  Column({ type: 'varchar', nullable: true }),
51
101
  __metadata("design:type", Object)
@@ -58,6 +108,14 @@ __decorate([
58
108
  Column({ type: 'bool', default: false }),
59
109
  __metadata("design:type", Boolean)
60
110
  ], BatchEntityClass.prototype, "inShipment", void 0);
111
+ __decorate([
112
+ Column({ type: 'uuid', nullable: true }),
113
+ __metadata("design:type", Object)
114
+ ], BatchEntityClass.prototype, "parentBatchId", void 0);
115
+ __decorate([
116
+ Column({ type: 'jsonb', nullable: true }),
117
+ __metadata("design:type", Object)
118
+ ], BatchEntityClass.prototype, "attributes", void 0);
61
119
  __decorate([
62
120
  ManyToOne('batch_groups', (batchGroup) => batchGroup.batches, {
63
121
  onDelete: 'CASCADE',
@@ -55,6 +55,10 @@ import { ScrapeOrderChangeEntity, ScrapeOrderChangeEntityClass } from './extensi
55
55
  import { InventoryCountOrderEntity, InventoryCountOrderEntityClass, InventoryCountOrderLocationEntity, InventoryCountOrderLocationEntityClass } from './extensions/inventory-count-order/inventory-count-order.entity.js';
56
56
  import { InventoryCountOrderItemEntity, InventoryCountOrderItemEntityClass } from './extensions/inventory-count-order/inventory-count-order-item.entity.js';
57
57
  import { InventoryCountOrderChangeEntity, InventoryCountOrderChangeEntityClass } from './extensions/inventory-count-order/inventory-count-order-change.entity.js';
58
+ import { ConsumptionOrderEntity, ConsumptionOrderEntityClass } from './extensions/consumption-order/consumption-order.entity.js';
59
+ import { ConsumptionOrderItemEntity, ConsumptionOrderItemEntityClass } from './extensions/consumption-order/consumption-order-item.entity.js';
60
+ import { ConsumptionOrderChangeEntity, ConsumptionOrderChangeEntityClass } from './extensions/consumption-order/consumption-order-change.entity.js';
61
+ import { OrderReferenceEntity, OrderReferenceEntityClass } from './extensions/order-reference/order-reference.entity.js';
58
62
 
59
63
  const entities = [
60
64
  [UnitEntity, UnitEntityClass],
@@ -113,6 +117,10 @@ const entities = [
113
117
  [InventoryCountOrderLocationEntity, InventoryCountOrderLocationEntityClass],
114
118
  [InventoryCountOrderItemEntity, InventoryCountOrderItemEntityClass],
115
119
  [InventoryCountOrderChangeEntity, InventoryCountOrderChangeEntityClass],
120
+ [OrderReferenceEntity, OrderReferenceEntityClass],
121
+ [ConsumptionOrderEntity, ConsumptionOrderEntityClass],
122
+ [ConsumptionOrderItemEntity, ConsumptionOrderItemEntityClass],
123
+ [ConsumptionOrderChangeEntity, ConsumptionOrderChangeEntityClass],
116
124
  ];
117
125
  /**
118
126
  * The overridable entities are deliberately absent: `WmsModuleCoreModule` binds
@@ -53,6 +53,10 @@ import '../models/extensions/scrape-order/scrape-order-change.entity.js';
53
53
  import '../models/extensions/inventory-count-order/inventory-count-order.entity.js';
54
54
  import '../models/extensions/inventory-count-order/inventory-count-order-item.entity.js';
55
55
  import '../models/extensions/inventory-count-order/inventory-count-order-change.entity.js';
56
+ import '../models/extensions/consumption-order/consumption-order.entity.js';
57
+ import '../models/extensions/consumption-order/consumption-order-item.entity.js';
58
+ import '../models/extensions/consumption-order/consumption-order-change.entity.js';
59
+ import '../models/extensions/order-reference/order-reference.entity.js';
56
60
  import { DataSource, Not, IsNull } from 'typeorm';
57
61
  import { HelperService } from './helper.service.js';
58
62
  import { MaterialService } from './material.service.js';
@@ -1,4 +1,4 @@
1
- import { Repository } from 'typeorm';
1
+ import { ObjectLiteral, Repository } from 'typeorm';
2
2
  import { StockEntityClass } from '../models';
3
3
  import { OrderEntity } from '@rytass/wms-base-nestjs-module';
4
4
  import { MaterialService } from './material.service';
@@ -14,11 +14,26 @@ export interface StockEntryParams {
14
14
  export interface Repositories {
15
15
  order: Repository<OrderEntity>;
16
16
  stock: Repository<StockEntityClass>;
17
- [key: string]: Repository<any>;
17
+ [key: string]: Repository<ObjectLiteral>;
18
18
  }
19
19
  /**
20
20
  * Base service for order operations that create/deduct stock entries.
21
- * Provides common methods for adding and deducting inventory across different order types.
21
+ * Provides common methods for adding and deducting inventory across different
22
+ * order types.
23
+ *
24
+ * Public API, with one precondition that is easy to miss.
25
+ *
26
+ * `add` and `deduct` write an `orders` row and `stocks` rows — and nothing else.
27
+ * They do **not** write a `*_order_changes` row, and both `StockChangeSubscriber`
28
+ * and `InventoryCountLockSubscriber` hook the insert of that row. So a host that
29
+ * extends this and registers `customChangeTables`, but leaves its own change row
30
+ * unwritten, gets neither the `stock.*` event nor the inventory count lock: its
31
+ * movements pass a running count in silence. Writing the change row is the
32
+ * host's job, exactly as it is for every service in this package.
33
+ *
34
+ * What extending it does buy is unit conversion and
35
+ * `StockService.validateStockAvailability` around the stock write. See
36
+ * {@link WmsCustomChangeTable} for the rest of what a custom family inherits.
22
37
  */
23
38
  export declare abstract class BaseOrderService {
24
39
  protected abstract materialService: MaterialService;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Base service for order operations that create/deduct stock entries.
3
+ * Provides common methods for adding and deducting inventory across different
4
+ * order types.
5
+ *
6
+ * Public API, with one precondition that is easy to miss.
7
+ *
8
+ * `add` and `deduct` write an `orders` row and `stocks` rows — and nothing else.
9
+ * They do **not** write a `*_order_changes` row, and both `StockChangeSubscriber`
10
+ * and `InventoryCountLockSubscriber` hook the insert of that row. So a host that
11
+ * extends this and registers `customChangeTables`, but leaves its own change row
12
+ * unwritten, gets neither the `stock.*` event nor the inventory count lock: its
13
+ * movements pass a running count in silence. Writing the change row is the
14
+ * host's job, exactly as it is for every service in this package.
15
+ *
16
+ * What extending it does buy is unit conversion and
17
+ * `StockService.validateStockAvailability` around the stock write. See
18
+ * {@link WmsCustomChangeTable} for the rest of what a custom family inherits.
19
+ */
20
+ class BaseOrderService {
21
+ /**
22
+ * Creates a new order and saves a positive quantity stock entry
23
+ * @param repos Repository map containing order and stock repositories
24
+ * @param params Stock entry parameters (materialId, batchId, quantity, locationId?, loaderId?, unitId?)
25
+ * @returns Created order ID
26
+ */
27
+ async add(repos, params) {
28
+ const { materialId, batchId, quantity, locationId, loaderId, unitId } = params;
29
+ // Create new order
30
+ const order = await repos.order.save({});
31
+ // Get conversion factor if unitId is provided
32
+ const conversionFactor = await this.materialService.getConversionFactor(materialId, unitId);
33
+ // Create positive stock entry linked to this order
34
+ await repos.stock.save(repos.stock.create({
35
+ orderId: order.id,
36
+ materialId,
37
+ batchId,
38
+ locationId: this.stockService.resolveLocationId(locationId),
39
+ loaderId: this.stockService.resolveLoaderId(loaderId),
40
+ quantity: quantity * conversionFactor,
41
+ }));
42
+ return order.id;
43
+ }
44
+ /**
45
+ * Creates a negative quantity stock entry linked to a source order
46
+ * Used to deduct stock from an existing status (FREE, ALLOCATED, IN_TRANSFER, etc.)
47
+ * @param repos Repository map containing order and stock repositories
48
+ * @param sourceOrderId The order ID to link the deduction to (typically an existing allocated/transferred order)
49
+ * @param params Stock entry parameters (materialId, batchId, quantity, locationId?, loaderId?, unitId?)
50
+ */
51
+ async deduct(repos, params) {
52
+ const { materialId, batchId, quantity, locationId, loaderId, unitId } = params;
53
+ const order = await repos.order.save({});
54
+ // Get conversion factor if unitId is provided
55
+ const conversionFactor = await this.materialService.getConversionFactor(materialId, unitId);
56
+ // Create negative stock entry linked to source order
57
+ // This allows the status calculation to determine what status is being deducted from
58
+ await this.stockService.validateStockAvailability({
59
+ materialId,
60
+ batchId,
61
+ locationId: this.stockService.resolveLocationId(locationId),
62
+ loaderId: this.stockService.resolveLoaderId(loaderId),
63
+ quantity: quantity * conversionFactor,
64
+ }, repos.stock.manager);
65
+ await repos.stock.save(repos.stock.create({
66
+ orderId: order.id,
67
+ materialId,
68
+ batchId,
69
+ locationId: this.stockService.resolveLocationId(locationId),
70
+ loaderId: this.stockService.resolveLoaderId(loaderId),
71
+ quantity: -1 * quantity * conversionFactor,
72
+ }));
73
+ }
74
+ }
75
+
76
+ export { BaseOrderService };
@@ -19,6 +19,23 @@ export declare class BatchService<T extends BatchEntityClass = BatchEntityClass>
19
19
  * - Bottom tier: inspectionResult → can go UP to middle or top tier, but cannot change inspectionResult
20
20
  */
21
21
  private validateStateTransition;
22
+ /**
23
+ * Find the unsplit batch carrying `key` for this material, or create it.
24
+ *
25
+ * `parentBatchId` and `attributes` are write-on-create only: the lookup still
26
+ * matches on key, material and the unsplit condition alone, so a caller that
27
+ * passes them for a key that already exists gets the existing batch back
28
+ * untouched. `key` is the batch's identity in this model — `batches` carries
29
+ * `UNIQUE (key, materialId)`, so there is exactly one row per key — and
30
+ * attributes describe a batch rather than distinguish one. A host that needs
31
+ * two distinct batches gives them two keys; asking for two here fails on the
32
+ * constraint.
33
+ *
34
+ * Deliberately **not** filtered on `requiresInspection`: a receipt awaiting
35
+ * inspection may flag the batch in place, and the flag must not then hide the
36
+ * key from the next lookup — which, given the unique constraint, would leave
37
+ * it trying to create a duplicate.
38
+ */
22
39
  getBatch({ manager, ...options }: GetBatchInput & {
23
40
  manager?: EntityManager;
24
41
  }): Promise<T>;
@@ -1,6 +1,6 @@
1
1
  import { __decorate, __param, __metadata } from 'tslib';
2
2
  import { Injectable, Inject } from '@nestjs/common';
3
- import { DataSource, IsNull } from 'typeorm';
3
+ import { DataSource, IsNull, Raw } from 'typeorm';
4
4
  import { BatchEntity } from '../models/metadata/batch.entity.js';
5
5
  import { BatchGroupEntity } from '../models/metadata/batch-group.entity.js';
6
6
  import '../models/metadata/loader.entity.js';
@@ -54,6 +54,10 @@ import '../models/extensions/scrape-order/scrape-order-change.entity.js';
54
54
  import '../models/extensions/inventory-count-order/inventory-count-order.entity.js';
55
55
  import '../models/extensions/inventory-count-order/inventory-count-order-item.entity.js';
56
56
  import '../models/extensions/inventory-count-order/inventory-count-order-change.entity.js';
57
+ import '../models/extensions/consumption-order/consumption-order.entity.js';
58
+ import '../models/extensions/consumption-order/consumption-order-item.entity.js';
59
+ import '../models/extensions/consumption-order/consumption-order-change.entity.js';
60
+ import '../models/extensions/order-reference/order-reference.entity.js';
57
61
 
58
62
  let BatchService = class BatchService {
59
63
  dataSource;
@@ -124,6 +128,23 @@ let BatchService = class BatchService {
124
128
  throw new Error('Inspection result already set, cannot modify');
125
129
  }
126
130
  }
131
+ /**
132
+ * Find the unsplit batch carrying `key` for this material, or create it.
133
+ *
134
+ * `parentBatchId` and `attributes` are write-on-create only: the lookup still
135
+ * matches on key, material and the unsplit condition alone, so a caller that
136
+ * passes them for a key that already exists gets the existing batch back
137
+ * untouched. `key` is the batch's identity in this model — `batches` carries
138
+ * `UNIQUE (key, materialId)`, so there is exactly one row per key — and
139
+ * attributes describe a batch rather than distinguish one. A host that needs
140
+ * two distinct batches gives them two keys; asking for two here fails on the
141
+ * constraint.
142
+ *
143
+ * Deliberately **not** filtered on `requiresInspection`: a receipt awaiting
144
+ * inspection may flag the batch in place, and the flag must not then hide the
145
+ * key from the next lookup — which, given the unique constraint, would leave
146
+ * it trying to create a duplicate.
147
+ */
127
148
  async getBatch({ manager = this.dataSource.manager, ...options }) {
128
149
  const batchRepository = manager.getRepository(this.batchEntity);
129
150
  const batchGroupRepository = manager.getRepository(this.batchGroupEntity);
@@ -188,6 +209,21 @@ let BatchService = class BatchService {
188
209
  transferId: orNull(mergedBatch.transferId),
189
210
  held: mergedBatch.held ?? false,
190
211
  inShipment: mergedBatch.inShipment ?? false,
212
+ // Part of the batch's identity: material waiting on an inspection must
213
+ // not be merged back into the free stock it was split away from.
214
+ requiresInspection: mergedBatch.requiresInspection ?? false,
215
+ /*
216
+ * Attributes take part in the identity check, so a split that asks for
217
+ * `{ bin: 'B1' }` never lands on the sibling holding `{ bin: 'B2' }`.
218
+ * Compared as `jsonb`, whose equality is by content rather than by the
219
+ * text of the document, so key order and whitespace do not matter — which
220
+ * a plain string comparison on the serialized column would get wrong.
221
+ */
222
+ attributes: mergedBatch.attributes === null || mergedBatch.attributes === undefined
223
+ ? IsNull()
224
+ : Raw((alias) => `${alias} = cast(:batchAttributes as jsonb)`, {
225
+ batchAttributes: JSON.stringify(mergedBatch.attributes),
226
+ }),
191
227
  };
192
228
  // Check if a batch with these exact metrics already exists in the same group
193
229
  const existingBatch = await batchRepository.findOne({
@@ -200,6 +236,10 @@ let BatchService = class BatchService {
200
236
  return batchRepository.save(batchRepository.create({
201
237
  ...mergedBatch,
202
238
  key: `${batch.batchGroup.key}_${Date.now().toString()}`,
239
+ // Not inherited from `mergedBatch`: spreading the source batch would
240
+ // copy *its* parent and flatten the chain by one link. The parent of
241
+ // the batch being created is the batch it was split out of.
242
+ parentBatchId: batch.id,
203
243
  id: undefined,
204
244
  }));
205
245
  }
@@ -0,0 +1,75 @@
1
+ import { DataSource, EntityManager, EntityTarget, Repository } from 'typeorm';
2
+ import { ConsumptionOrderEntityClass, ConsumptionOrderItemEntityClass, StockEntityClass } from '../models';
3
+ import { ConsumptionOrderActionInput, ConsumptionOrderItemProgress, CreateConsumptionOrderInput, FindConsumptionOrderInput, UpdateConsumptionOrderInput } from '../typings/consumption-order.input';
4
+ import { WmsEntities } from '../models/wms-entities';
5
+ import { HelperService } from './helper.service';
6
+ import { MaterialService } from './material.service';
7
+ import { StockService } from './stock.service';
8
+ /**
9
+ * Material handed to a process that consumes it: issue it out, take back what
10
+ * came home, settle what was used.
11
+ *
12
+ * The three actions share one order because they are one story, and because
13
+ * that is the grammar the rest of this package already speaks — hold/release,
14
+ * allocate/deallocate and transfer/cancel are each a single order too.
15
+ *
16
+ * No new stock status. An issue is a location move and nothing else: status
17
+ * here is a flag on the *batch*, so a "being consumed" status would force every
18
+ * partial issue to split a child batch off it, and one batch key per issue is a
19
+ * worse answer than one location. What the process actually is — a work order,
20
+ * a repair job, a subcontract — belongs in `order_references`, which can say
21
+ * *which* one; a status could only ever say "some".
22
+ */
23
+ export declare class ConsumptionOrderService<T extends ConsumptionOrderEntityClass = ConsumptionOrderEntityClass, K extends ConsumptionOrderItemEntityClass = ConsumptionOrderItemEntityClass> {
24
+ private readonly dataSource;
25
+ private readonly entities;
26
+ private readonly helperService;
27
+ private readonly materialService;
28
+ private readonly stockService;
29
+ readonly consumptionOrderEntity: EntityTarget<T>;
30
+ readonly consumptionOrderItemEntity: EntityTarget<K>;
31
+ readonly stockEntity: EntityTarget<StockEntityClass>;
32
+ private readonly seqPrefix;
33
+ readonly consumptionOrderRepository: Repository<T>;
34
+ constructor(dataSource: DataSource, entities: WmsEntities, helperService: HelperService, materialService: MaterialService, stockService: StockService, consumptionOrderEntity: EntityTarget<T>, consumptionOrderItemEntity: EntityTarget<K>, stockEntity: EntityTarget<StockEntityClass>);
35
+ private getRepositories;
36
+ private itemRow;
37
+ createConsumptionOrder(options: CreateConsumptionOrderInput): Promise<T>;
38
+ /**
39
+ * Replace the order's lines. Refused once anything has moved: the changes
40
+ * point at items, so swapping the items out from under them would leave the
41
+ * ledger describing lines that no longer exist.
42
+ */
43
+ updateConsumptionOrder(options: UpdateConsumptionOrderInput): Promise<T>;
44
+ removeConsumptionOrder(id: string): Promise<boolean>;
45
+ /**
46
+ * How much of each line has moved, **in base units**.
47
+ *
48
+ * The changes are the only record of that — nothing is denormalised onto the
49
+ * item — so `issue`, `return` and `settle` all read it back before they write.
50
+ *
51
+ * Base units on both sides is the point. `quantityChanged` is written in base
52
+ * units (the stock ledger's own unit), while `targetConsumedQuantity` is
53
+ * stored in whatever unit the line was written in. Reporting the two side by
54
+ * side without converting made every comparison in `act` wrong by the
55
+ * conversion factor. `ReceiveInventoryOrderService` resolves the same tension
56
+ * the same way.
57
+ */
58
+ getProgress(orderId: string, manager?: EntityManager): Promise<ConsumptionOrderItemProgress[]>;
59
+ /**
60
+ * Hand material to the process: it leaves the source location and appears at
61
+ * the consuming one. Nothing about the batch changes.
62
+ */
63
+ issue(options: ConsumptionOrderActionInput): Promise<boolean>;
64
+ /** Take back material the process did not use. */
65
+ return(options: ConsumptionOrderActionInput): Promise<boolean>;
66
+ /** Close out material the process used up: it leaves inventory. */
67
+ settle(options: ConsumptionOrderActionInput): Promise<boolean>;
68
+ private act;
69
+ /** `amount` is in base units; `act` has already converted. */
70
+ private writeMovement;
71
+ findMany(options: FindConsumptionOrderInput): Promise<[T[], number]>;
72
+ findOne(id: string): Promise<T>;
73
+ /** Every line of the given orders, for a DataLoader batching one round trip. */
74
+ findItemsByOrders(orderIds: readonly string[]): Promise<ConsumptionOrderItemEntityClass[]>;
75
+ }