@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,50 @@
1
+ import { DataSource, EntityManager, EntityTarget, Repository } from 'typeorm';
2
+ import { OrderReferenceEntityClass } from '../models/extensions/order-reference/order-reference.entity';
3
+ import { WmsOrderType } from '../constants/order-type';
4
+ import { AttachOrderReferencesInput, FindOrderReferenceInput } from '../typings/order-reference.input';
5
+ /**
6
+ * Reads and writes the link between an order in this package and the host
7
+ * document it was opened for.
8
+ *
9
+ * Deliberately a service of its own rather than an argument threaded through
10
+ * thirteen `create*` signatures: the link is the same shape for every family,
11
+ * including families added later, and a host driving the warehouse from its own
12
+ * transaction can attach references in that transaction by passing `manager`.
13
+ */
14
+ export declare class OrderReferenceService {
15
+ private readonly dataSource;
16
+ readonly orderReferenceEntity: EntityTarget<OrderReferenceEntityClass>;
17
+ readonly orderReferenceRepository: Repository<OrderReferenceEntityClass>;
18
+ constructor(dataSource: DataSource, orderReferenceEntity: EntityTarget<OrderReferenceEntityClass>);
19
+ private repository;
20
+ /**
21
+ * Record why an order was opened.
22
+ *
23
+ * Additive: calling it twice adds two sets of references rather than
24
+ * replacing the first. Pass `manager` to join the caller's transaction, so a
25
+ * host that creates an order and attaches its references sees both rows land
26
+ * together or neither.
27
+ */
28
+ attach({ manager, ...options }: AttachOrderReferencesInput & {
29
+ manager?: EntityManager;
30
+ }): Promise<OrderReferenceEntityClass[]>;
31
+ /**
32
+ * Replace every reference on an order with the given set. An empty
33
+ * `references` clears them.
34
+ */
35
+ replace({ manager, ...options }: AttachOrderReferencesInput & {
36
+ manager?: EntityManager;
37
+ }): Promise<OrderReferenceEntityClass[]>;
38
+ detach(id: string, manager?: EntityManager): Promise<void>;
39
+ /**
40
+ * Both directions of the link in one query: give it an order to list what
41
+ * that order was for, or a `referenceType` / `referenceId` to list every
42
+ * order opened for that document.
43
+ */
44
+ findMany(options: FindOrderReferenceInput): Promise<[OrderReferenceEntityClass[], number]>;
45
+ /**
46
+ * Every reference on each of the given orders, for a DataLoader batching one
47
+ * round trip across a page of orders.
48
+ */
49
+ findByOrders(orderType: WmsOrderType, orderIds: readonly string[]): Promise<OrderReferenceEntityClass[]>;
50
+ }
@@ -0,0 +1,136 @@
1
+ import { __decorate, __param, __metadata } from 'tslib';
2
+ import { Injectable, Inject } from '@nestjs/common';
3
+ import { DataSource, In } from 'typeorm';
4
+ import { OrderReferenceEntity } from '../models/extensions/order-reference/order-reference.entity.js';
5
+
6
+ /**
7
+ * Reads and writes the link between an order in this package and the host
8
+ * document it was opened for.
9
+ *
10
+ * Deliberately a service of its own rather than an argument threaded through
11
+ * thirteen `create*` signatures: the link is the same shape for every family,
12
+ * including families added later, and a host driving the warehouse from its own
13
+ * transaction can attach references in that transaction by passing `manager`.
14
+ */
15
+ let OrderReferenceService = class OrderReferenceService {
16
+ dataSource;
17
+ orderReferenceEntity;
18
+ orderReferenceRepository;
19
+ constructor(dataSource, orderReferenceEntity) {
20
+ this.dataSource = dataSource;
21
+ this.orderReferenceEntity = orderReferenceEntity;
22
+ this.orderReferenceRepository =
23
+ this.dataSource.getRepository(this.orderReferenceEntity);
24
+ }
25
+ repository(manager) {
26
+ return manager
27
+ ? manager.getRepository(this.orderReferenceEntity)
28
+ : this.orderReferenceRepository;
29
+ }
30
+ /**
31
+ * Record why an order was opened.
32
+ *
33
+ * Additive: calling it twice adds two sets of references rather than
34
+ * replacing the first. Pass `manager` to join the caller's transaction, so a
35
+ * host that creates an order and attaches its references sees both rows land
36
+ * together or neither.
37
+ */
38
+ async attach({ manager, ...options }) {
39
+ if (!options.references.length)
40
+ return [];
41
+ const repository = this.repository(manager);
42
+ return repository.save(options.references.map((reference) => repository.create({
43
+ orderType: options.orderType,
44
+ orderId: options.orderId,
45
+ itemId: reference.itemId ?? null,
46
+ referenceType: reference.referenceType,
47
+ referenceId: reference.referenceId,
48
+ referenceLine: reference.referenceLine ?? null,
49
+ metadata: reference.metadata ?? null,
50
+ })));
51
+ }
52
+ /**
53
+ * Replace every reference on an order with the given set. An empty
54
+ * `references` clears them.
55
+ */
56
+ async replace({ manager, ...options }) {
57
+ const repository = this.repository(manager);
58
+ await repository.delete({
59
+ orderType: options.orderType,
60
+ orderId: options.orderId,
61
+ });
62
+ return this.attach({ ...options, manager });
63
+ }
64
+ async detach(id, manager) {
65
+ await this.repository(manager).delete({ id });
66
+ }
67
+ /**
68
+ * Both directions of the link in one query: give it an order to list what
69
+ * that order was for, or a `referenceType` / `referenceId` to list every
70
+ * order opened for that document.
71
+ */
72
+ async findMany(options) {
73
+ /*
74
+ * A lowercase alias on purpose: the conditions below are raw SQL fragments,
75
+ * and Postgres folds an unquoted identifier to lowercase — a camelCase
76
+ * alias would compile to `orderreference."orderType"` and fail with
77
+ * `missing FROM-clause entry`.
78
+ */
79
+ const queryBuilder = this.orderReferenceRepository.createQueryBuilder('reference');
80
+ if (options.orderType)
81
+ queryBuilder.andWhere('reference."orderType" = :orderType', {
82
+ orderType: options.orderType,
83
+ });
84
+ if (options.orderId)
85
+ queryBuilder.andWhere('reference."orderId" = :orderId', {
86
+ orderId: options.orderId,
87
+ });
88
+ if (options.itemId)
89
+ queryBuilder.andWhere('reference."itemId" = :itemId', {
90
+ itemId: options.itemId,
91
+ });
92
+ /*
93
+ * Matched exactly, never with ILIKE. These are identifiers the host system
94
+ * owns, and a substring match on 「WO-1」 would quietly return 「WO-10」 as
95
+ * well — the same reasoning that governs the batch commercial attributes on
96
+ * the stock queries.
97
+ */
98
+ if (options.referenceType)
99
+ queryBuilder.andWhere('reference."referenceType" = :referenceType', {
100
+ referenceType: options.referenceType,
101
+ });
102
+ if (options.referenceId)
103
+ queryBuilder.andWhere('reference."referenceId" = :referenceId', {
104
+ referenceId: options.referenceId,
105
+ });
106
+ if (options.referenceLine)
107
+ queryBuilder.andWhere('reference."referenceLine" = :referenceLine', {
108
+ referenceLine: options.referenceLine,
109
+ });
110
+ queryBuilder.orderBy('reference."createdAt"', 'ASC');
111
+ if (options.offset !== undefined && options.offset >= 0)
112
+ queryBuilder.skip(options.offset);
113
+ if (options.limit !== undefined && options.limit > 0)
114
+ queryBuilder.take(options.limit);
115
+ return queryBuilder.getManyAndCount();
116
+ }
117
+ /**
118
+ * Every reference on each of the given orders, for a DataLoader batching one
119
+ * round trip across a page of orders.
120
+ */
121
+ async findByOrders(orderType, orderIds) {
122
+ if (!orderIds.length)
123
+ return [];
124
+ return this.orderReferenceRepository.find({
125
+ where: { orderType, orderId: In([...orderIds]) },
126
+ order: { createdAt: 'ASC' },
127
+ });
128
+ }
129
+ };
130
+ OrderReferenceService = __decorate([
131
+ Injectable(),
132
+ __param(1, Inject(OrderReferenceEntity)),
133
+ __metadata("design:paramtypes", [DataSource, Object])
134
+ ], OrderReferenceService);
135
+
136
+ export { OrderReferenceService };
@@ -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 } from 'typeorm';
57
61
  import { BatchService } from './batch.service.js';
58
62
  import { MaterialService } from './material.service.js';
@@ -55,6 +55,10 @@ import '../models/extensions/scrape-order/scrape-order-change.entity.js';
55
55
  import '../models/extensions/inventory-count-order/inventory-count-order.entity.js';
56
56
  import '../models/extensions/inventory-count-order/inventory-count-order-item.entity.js';
57
57
  import '../models/extensions/inventory-count-order/inventory-count-order-change.entity.js';
58
+ import '../models/extensions/consumption-order/consumption-order.entity.js';
59
+ import '../models/extensions/consumption-order/consumption-order-item.entity.js';
60
+ import '../models/extensions/consumption-order/consumption-order-change.entity.js';
61
+ import '../models/extensions/order-reference/order-reference.entity.js';
58
62
  import { MaterialService } from './material.service.js';
59
63
  import { BatchService } from './batch.service.js';
60
64
  import { HelperService } from './helper.service.js';
@@ -312,89 +316,139 @@ let ReceiveInventoryOrderService = class ReceiveInventoryOrderService {
312
316
  const locationRepository = manager.getRepository(this.entities.location);
313
317
  const loaderRepository = manager.getRepository(LoadersEntityClass);
314
318
  const stockRepository = manager.getRepository(this.entities.stock);
319
+ const batchRepository = manager.getRepository(this.entities.batch);
315
320
  const items = await itemRepository.find({
316
321
  where: { id: In(options.map((o) => o.itemId)) },
317
322
  relations: { changes: true },
318
323
  });
319
324
  const itemMap = new Map(items.map((i) => [i.id, i]));
320
- await Promise.all(options.map(async (option) => {
321
- const item = itemMap.get(option.itemId);
322
- if (!item)
323
- return;
324
- if (!item.batchId && option.batchKey) {
325
- // if batchKey is provided but item doesn't have batchId, attempt to find or create batch and update item with batchId
326
- item.batchId = await this.batchService
327
- .getBatch({
328
- manager,
329
- key: option.batchKey,
330
- materialId: item.materialId,
331
- })
332
- .then(async (b) => {
333
- await itemRepository.update({ id: item.id }, { batchId: b.id });
334
- return b.id;
335
- });
336
- }
337
- const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId || undefined);
338
- const totalChanged = item.changes.reduce((sum, change) => sum + Number(change.quantityChanged), 0);
339
- const remainingQuantity = conversionFactor * item.targetReceivedQuantity - totalChanged;
340
- if (remainingQuantity - option.quantity * conversionFactor < 0) {
341
- throw new Error(`Receiving quantity exceeds target for item ${option.itemId}`);
342
- }
343
- const newOrder = await orderRepository.save(orderRepository.create());
344
- let batchId = item.batchId;
345
- if (option.batchKey)
346
- batchId = await this.batchService
347
- .getBatch({
348
- manager,
349
- key: option.batchKey,
350
- materialId: item.materialId,
351
- })
352
- .then(({ id }) => id);
353
- if (!batchId)
354
- batchId = await this.batchService
355
- .getBatch({
356
- manager,
357
- key: await this.helperService.getSeq('BATCH'),
358
- materialId: item.materialId,
359
- })
360
- .then(({ id }) => id);
361
- const inspectionResult = item.requireInspection === false
362
- ? true
363
- : (option.inspectionResult ?? null);
364
- if (inspectionResult != null)
365
- batchId = await this.batchService
366
- .splitBatch({
367
- manager,
368
- id: batchId,
369
- inspectionResult,
370
- })
371
- .then(({ id }) => id);
372
- let locationId = item.locationId;
373
- if (option.locationKey && !locationId)
374
- locationId = await locationRepository
375
- .findOneByOrFail({ key: option.locationKey })
376
- .then(({ id }) => id);
377
- let loaderId = item.loaderId;
378
- if (option.loaderKey && !loaderId)
379
- loaderId = await loaderRepository
380
- .findOneByOrFail({ serialId: option.loaderKey })
381
- .then(({ id }) => id);
382
- await Promise.all([
383
- changeRepository.save(changeRepository.create({
384
- itemId: option.itemId,
385
- quantityChanged: option.quantity * conversionFactor,
386
- id: newOrder.id,
387
- })),
388
- stockRepository.save(stockRepository.create({
389
- batchId: batchId || undefined,
390
- locationId: this.stockService.resolveLocationId(locationId),
391
- loaderId: this.stockService.resolveLoaderId(loaderId),
392
- materialId: item.materialId,
393
- quantity: option.quantity * conversionFactor,
394
- orderId: newOrder.id,
395
- })),
396
- ]);
397
- }));
325
+ /*
326
+ * Sequential, not `Promise.all`. Two options for one item both reach the
327
+ * batch lookups below before either has written, so `splitBatch`'s
328
+ * read-then-create misses twice and one receipt ends up fragmented across
329
+ * two batch identities. A receive order has a handful of lines; ordering
330
+ * them costs nothing worth measuring.
331
+ */
332
+ for (const option of options) {
333
+ await (async () => {
334
+ const item = itemMap.get(option.itemId);
335
+ if (!item)
336
+ return;
337
+ if (!item.batchId && option.batchKey) {
338
+ // if batchKey is provided but item doesn't have batchId, attempt to find or create batch and update item with batchId
339
+ item.batchId = await this.batchService
340
+ .getBatch({
341
+ manager,
342
+ key: option.batchKey,
343
+ materialId: item.materialId,
344
+ })
345
+ .then(async (b) => {
346
+ await itemRepository.update({ id: item.id }, { batchId: b.id });
347
+ return b.id;
348
+ });
349
+ }
350
+ const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId || undefined);
351
+ const totalChanged = item.changes.reduce((sum, change) => sum + Number(change.quantityChanged), 0);
352
+ const remainingQuantity = conversionFactor * item.targetReceivedQuantity - totalChanged;
353
+ if (remainingQuantity - option.quantity * conversionFactor < 0) {
354
+ throw new Error(`Receiving quantity exceeds target for item ${option.itemId}`);
355
+ }
356
+ const newOrder = await orderRepository.save(orderRepository.create());
357
+ let batchId = item.batchId;
358
+ if (option.batchKey)
359
+ batchId = await this.batchService
360
+ .getBatch({
361
+ manager,
362
+ key: option.batchKey,
363
+ materialId: item.materialId,
364
+ })
365
+ .then(({ id }) => id);
366
+ if (!batchId)
367
+ batchId = await this.batchService
368
+ .getBatch({
369
+ manager,
370
+ key: await this.helperService.getSeq('BATCH'),
371
+ materialId: item.materialId,
372
+ })
373
+ .then(({ id }) => id);
374
+ const inspectionResult = item.requireInspection === false
375
+ ? true
376
+ : (option.inspectionResult ?? null);
377
+ if (inspectionResult != null) {
378
+ batchId = await this.batchService
379
+ .splitBatch({
380
+ manager,
381
+ id: batchId,
382
+ inspectionResult,
383
+ })
384
+ .then(({ id }) => id);
385
+ }
386
+ else if (item.requireInspection) {
387
+ /*
388
+ * Somebody asked for this to be inspected and it has not been yet.
389
+ * Recording that on the batch is what lets `PENDING_INSPECTION`
390
+ * mean "awaiting inspection" rather than "never inspected" -- the
391
+ * latter being true of almost every batch in the warehouse.
392
+ *
393
+ * Split only when the batch already holds something. `require-
394
+ * Inspection` defaults to **true**, so this is the ordinary receive
395
+ * path, not an edge case: splitting unconditionally moved every
396
+ * default receipt off the batch key the caller asked for and onto a
397
+ * synthetic child, which an exact-id lookup then could not find.
398
+ *
399
+ * A batch with nothing on it yet has nothing to commingle with, so
400
+ * flagging it in place is both sufficient and invisible. Only a
401
+ * receipt joining stock that is already there needs its own batch,
402
+ * which is the same thing holding or shipping part of a batch does.
403
+ */
404
+ const onHand = await stockRepository
405
+ .createQueryBuilder('stock')
406
+ .select('COALESCE(SUM(stock.quantity), 0)', 'total')
407
+ .where('stock."batchId" = :batchId', { batchId })
408
+ .getRawOne()
409
+ .then((row) => parseFloat(row?.total ?? '0'));
410
+ if (onHand > 0) {
411
+ batchId = await this.batchService
412
+ .splitBatch({
413
+ manager,
414
+ id: batchId,
415
+ requiresInspection: true,
416
+ })
417
+ .then(({ id }) => id);
418
+ }
419
+ else {
420
+ await batchRepository.update({ id: batchId }, {
421
+ requiresInspection: true,
422
+ });
423
+ }
424
+ }
425
+ let locationId = item.locationId;
426
+ if (option.locationKey && !locationId)
427
+ locationId = await locationRepository
428
+ .findOneByOrFail({ key: option.locationKey })
429
+ .then(({ id }) => id);
430
+ let loaderId = item.loaderId;
431
+ if (option.loaderKey && !loaderId)
432
+ loaderId = await loaderRepository
433
+ .findOneByOrFail({ serialId: option.loaderKey })
434
+ .then(({ id }) => id);
435
+ await Promise.all([
436
+ changeRepository.save(changeRepository.create({
437
+ itemId: option.itemId,
438
+ quantityChanged: option.quantity * conversionFactor,
439
+ id: newOrder.id,
440
+ })),
441
+ stockRepository.save(stockRepository.create({
442
+ batchId: batchId || undefined,
443
+ locationId: this.stockService.resolveLocationId(locationId),
444
+ loaderId: this.stockService.resolveLoaderId(loaderId),
445
+ materialId: item.materialId,
446
+ quantity: option.quantity * conversionFactor,
447
+ orderId: newOrder.id,
448
+ })),
449
+ ]);
450
+ })();
451
+ }
398
452
  return true;
399
453
  });
400
454
  }
@@ -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 } from 'typeorm';
57
61
  import { MaterialService } from './material.service.js';
58
62
  import { BatchService } from './batch.service.js';
@@ -53,6 +53,10 @@ import { ScrapeOrderChangeEntityClass } from '../models/extensions/scrape-order/
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 } from 'typeorm';
57
61
  import { HelperService } from './helper.service.js';
58
62
  import { MaterialService } from './material.service.js';
@@ -55,6 +55,10 @@ import '../models/extensions/scrape-order/scrape-order-change.entity.js';
55
55
  import '../models/extensions/inventory-count-order/inventory-count-order.entity.js';
56
56
  import '../models/extensions/inventory-count-order/inventory-count-order-item.entity.js';
57
57
  import '../models/extensions/inventory-count-order/inventory-count-order-change.entity.js';
58
+ import '../models/extensions/consumption-order/consumption-order.entity.js';
59
+ import '../models/extensions/consumption-order/consumption-order-item.entity.js';
60
+ import '../models/extensions/consumption-order/consumption-order-change.entity.js';
61
+ import '../models/extensions/order-reference/order-reference.entity.js';
58
62
  import { MaterialService } from './material.service.js';
59
63
  import { BatchService } from './batch.service.js';
60
64
  import { StockService } from './stock.service.js';
@@ -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 } from 'typeorm';
57
61
  import { MaterialService } from './material.service.js';
58
62
  import { BatchService } from './batch.service.js';
@@ -91,64 +95,83 @@ let SplitBatchOrderService = class SplitBatchOrderService {
91
95
  const originalBatch = await batchRepository.findOneOrFail({
92
96
  where: { id: options.batchId },
93
97
  });
98
+ /*
99
+ * `batches` carries `UNIQUE (key, materialId)`, so two items aiming at the
100
+ * same target key cannot both create one. Left alone they race
101
+ * `getBatch`'s read-then-create and the second insert aborts the whole
102
+ * split with a constraint violation that names neither item.
103
+ */
104
+ const duplicateKey = options.items
105
+ .map(({ batchKey }) => batchKey)
106
+ .find((batchKey, index, keys) => keys.indexOf(batchKey) !== index);
107
+ if (duplicateKey) {
108
+ throw new Error(`Split order names batch key "${duplicateKey}" more than once; each child needs its own key.`);
109
+ }
94
110
  const key = await this.helperService.getSeq(this.seqPrefix, manager);
95
111
  const order = await splitBatchOrderRepository.save(splitBatchOrderRepository.create({
96
112
  key,
97
113
  }));
98
114
  // Get conversion factor for unit conversion
99
115
  const conversionFactor = await this.materialService.getConversionFactor(originalBatch.materialId, options.unitId || undefined);
100
- // Process each item split
101
- await Promise.all(options.items.map(async (item) => {
102
- // Get or create target batch
103
- const targetBatch = await this.batchService.getBatch({
104
- key: item.batchKey,
105
- materialId: originalBatch.materialId,
106
- manager,
107
- });
108
- // Create base order record
109
- const baseOrder = await orderRepository.save({});
110
- // Create split batch order item
111
- const splitItem = await splitBatchOrderItemRepository.save(splitBatchOrderItemRepository.create({
112
- targetSplitQuantity: item.quantity,
113
- locationId: this.stockService.resolveLocationId(item.locationId),
114
- loaderId: item.loaderId,
115
- orderId: order.id,
116
- }));
117
- // Record the change
118
- await splitBatchOrderChangeRepository.save(splitBatchOrderChangeRepository.create({
119
- itemId: splitItem.id,
120
- id: baseOrder.id,
121
- quantityChanged: item.quantity * conversionFactor,
122
- }));
123
- // Update stock: deduct from original batch and add to target batch
124
- await this.stockService.validateStockAvailability({
125
- materialId: originalBatch.materialId,
126
- batchId: options.batchId,
127
- locationId: this.stockService.resolveLocationId(item.locationId),
128
- loaderId: this.stockService.resolveLoaderId(item.loaderId),
129
- quantity: item.quantity * conversionFactor,
130
- }, manager);
131
- await stockRepository.save(stockRepository.create([
132
- // Deduct from original batch
133
- {
134
- orderId: baseOrder.id,
116
+ // Sequential: two items can reference the same *source* batch, and the
117
+ // availability check below reads the ledger the earlier item just wrote.
118
+ for (const item of options.items) {
119
+ await (async () => {
120
+ // Get or create target batch. The genealogy link and the host's
121
+ // attributes only land when this call creates the batch — reusing an
122
+ // existing key keeps whatever it already carries.
123
+ const targetBatch = await this.batchService.getBatch({
124
+ key: item.batchKey,
135
125
  materialId: originalBatch.materialId,
136
- batchId: options.batchId,
126
+ parentBatchId: options.batchId,
127
+ attributes: item.attributes ?? null,
128
+ manager,
129
+ });
130
+ // Create base order record
131
+ const baseOrder = await orderRepository.save({});
132
+ // Create split batch order item
133
+ const splitItem = await splitBatchOrderItemRepository.save(splitBatchOrderItemRepository.create({
134
+ targetSplitQuantity: item.quantity,
137
135
  locationId: this.stockService.resolveLocationId(item.locationId),
138
- loaderId: this.stockService.resolveLoaderId(item.loaderId),
139
- quantity: -1 * item.quantity * conversionFactor,
140
- },
141
- // Add to target batch
142
- {
143
- orderId: baseOrder.id,
136
+ loaderId: item.loaderId,
137
+ orderId: order.id,
138
+ }));
139
+ // Record the change
140
+ await splitBatchOrderChangeRepository.save(splitBatchOrderChangeRepository.create({
141
+ itemId: splitItem.id,
142
+ id: baseOrder.id,
143
+ quantityChanged: item.quantity * conversionFactor,
144
+ }));
145
+ // Update stock: deduct from original batch and add to target batch
146
+ await this.stockService.validateStockAvailability({
144
147
  materialId: originalBatch.materialId,
145
- batchId: targetBatch.id,
148
+ batchId: options.batchId,
146
149
  locationId: this.stockService.resolveLocationId(item.locationId),
147
150
  loaderId: this.stockService.resolveLoaderId(item.loaderId),
148
151
  quantity: item.quantity * conversionFactor,
149
- },
150
- ]));
151
- }));
152
+ }, manager);
153
+ await stockRepository.save(stockRepository.create([
154
+ // Deduct from original batch
155
+ {
156
+ orderId: baseOrder.id,
157
+ materialId: originalBatch.materialId,
158
+ batchId: options.batchId,
159
+ locationId: this.stockService.resolveLocationId(item.locationId),
160
+ loaderId: this.stockService.resolveLoaderId(item.loaderId),
161
+ quantity: -1 * item.quantity * conversionFactor,
162
+ },
163
+ // Add to target batch
164
+ {
165
+ orderId: baseOrder.id,
166
+ materialId: originalBatch.materialId,
167
+ batchId: targetBatch.id,
168
+ locationId: this.stockService.resolveLocationId(item.locationId),
169
+ loaderId: this.stockService.resolveLoaderId(item.loaderId),
170
+ quantity: item.quantity * conversionFactor,
171
+ },
172
+ ]));
173
+ })();
174
+ }
152
175
  return order;
153
176
  });
154
177
  }