@rytass/wms-module-core 0.5.0 → 0.6.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 (49) hide show
  1. package/README.md +43 -1
  2. package/docs/api-reference.md +32 -1
  3. package/index.cjs.js +963 -5
  4. package/index.js +7 -0
  5. package/lib/constants/index.d.ts +2 -0
  6. package/lib/constants/inventory-count-status.d.ts +19 -0
  7. package/lib/constants/inventory-count-status.js +22 -0
  8. package/lib/constants/operations.d.ts +34 -0
  9. package/lib/constants/operations.js +66 -0
  10. package/lib/constants/stock-status.d.ts +2 -0
  11. package/lib/constants/stock-status.js +4 -0
  12. package/lib/core.module.js +9 -1
  13. package/lib/events/index.d.ts +1 -0
  14. package/lib/events/inventory-count-lock.subscriber.d.ts +38 -0
  15. package/lib/events/inventory-count-lock.subscriber.js +98 -0
  16. package/lib/events/stock-change.subscriber.js +6 -0
  17. package/lib/events/wms-event.types.d.ts +2 -2
  18. package/lib/models/extensions/index.d.ts +3 -0
  19. package/lib/models/extensions/inventory-count-order/inventory-count-order-change.entity.d.ts +20 -0
  20. package/lib/models/extensions/inventory-count-order/inventory-count-order-change.entity.js +50 -0
  21. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.d.ts +39 -0
  22. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.js +123 -0
  23. package/lib/models/extensions/inventory-count-order/inventory-count-order.entity.d.ts +50 -0
  24. package/lib/models/extensions/inventory-count-order/inventory-count-order.entity.js +155 -0
  25. package/lib/models/models.module.js +7 -0
  26. package/lib/services/allocate-inventory-order.service.js +3 -0
  27. package/lib/services/batch.service.js +3 -0
  28. package/lib/services/hold-inventory-order.service.js +3 -0
  29. package/lib/services/index.d.ts +1 -0
  30. package/lib/services/inventory-count-order.service.d.ts +143 -0
  31. package/lib/services/inventory-count-order.service.js +521 -0
  32. package/lib/services/loader.service.js +3 -0
  33. package/lib/services/location.service.js +3 -0
  34. package/lib/services/material.service.js +3 -0
  35. package/lib/services/merge-batch-order.service.js +3 -0
  36. package/lib/services/quality-inspection-order.service.js +3 -0
  37. package/lib/services/receive-inventory-order.service.js +3 -0
  38. package/lib/services/reclassify-inventory-order.service.js +3 -0
  39. package/lib/services/scrape.service.js +3 -0
  40. package/lib/services/ship-inventory-order.service.js +3 -0
  41. package/lib/services/split-batch-order.service.js +3 -0
  42. package/lib/services/stock.service.js +3 -0
  43. package/lib/services/transfer-customer-order.service.js +3 -0
  44. package/lib/services/transfer-order.service.js +3 -0
  45. package/lib/services/transfer-vendor-order.service.js +3 -0
  46. package/lib/services/unit.service.js +3 -0
  47. package/lib/services/warehouse-map.service.d.ts +11 -1
  48. package/lib/services/warehouse-map.service.js +13 -4
  49. package/package.json +1 -1
package/index.cjs.js CHANGED
@@ -452,6 +452,10 @@ exports.ChangeType = void 0;
452
452
  ChangeType["DEALLOCATED"] = "DEALLOCATED";
453
453
  // reclassify-inventory-order-change.entity.ts
454
454
  ChangeType["RECLASSIFIED"] = "RECLASSIFIED";
455
+ // inventory-count-order-change.entity.ts, change > 0
456
+ ChangeType["COUNT_GAINED"] = "COUNT_GAINED";
457
+ // inventory-count-order-change.entity.ts, change < 0
458
+ ChangeType["COUNT_LOST"] = "COUNT_LOST";
455
459
  // scrape-order-change.entity.ts
456
460
  ChangeType["SCRAPED"] = "SCRAPED";
457
461
  })(exports.ChangeType || (exports.ChangeType = {}));
@@ -2343,6 +2347,315 @@ exports.ScrapeOrderChangeEntityClass = tslib.__decorate([
2343
2347
  typeorm.Entity('scrape_order_changes')
2344
2348
  ], exports.ScrapeOrderChangeEntityClass);
2345
2349
 
2350
+ /**
2351
+ * The lifecycle of an inventory count order, matching the four states the
2352
+ * design shows on the list page.
2353
+ *
2354
+ * Only `COUNTING` accepts counted quantities, and only `COUNTING` locks the
2355
+ * scoped locations; `COMPLETED` is reached exclusively by settling the variance,
2356
+ * so an order that was counted but never settled stays `COUNTING` for as long as
2357
+ * it takes.
2358
+ */
2359
+ exports.InventoryCountStatus = void 0;
2360
+ (function (InventoryCountStatus) {
2361
+ /** 尚未執行 — created, scope fixed, nothing counted, nothing locked. */
2362
+ InventoryCountStatus["PENDING"] = "PENDING";
2363
+ /** 盤點中 — book quantities snapshotted and the scoped locations locked. */
2364
+ InventoryCountStatus["COUNTING"] = "COUNTING";
2365
+ /** 已完成 — the variance was settled and stock adjusted. */
2366
+ InventoryCountStatus["COMPLETED"] = "COMPLETED";
2367
+ /** 已取消 — abandoned from either PENDING or COUNTING; nothing adjusted. */
2368
+ InventoryCountStatus["CANCELLED"] = "CANCELLED";
2369
+ })(exports.InventoryCountStatus || (exports.InventoryCountStatus = {}));
2370
+
2371
+ const InventoryCountOrderEntity = Symbol('InventoryCountOrderEntity');
2372
+ exports.InventoryCountOrderEntityClass = class InventoryCountOrderEntityClass {
2373
+ id;
2374
+ key;
2375
+ name;
2376
+ /**
2377
+ * The count's base date, chosen when the order is created.
2378
+ *
2379
+ * It is the *business* date of the whole exercise: the settlement's stock
2380
+ * adjustments are reported under this date, not under the day someone happened
2381
+ * to press "執行盤差". `createdAt` keeps the real wall-clock time for auditing,
2382
+ * so the two never have to lie for each other.
2383
+ */
2384
+ countDate;
2385
+ status;
2386
+ /** Who created the order, in whatever id space the host uses. */
2387
+ createdBy;
2388
+ /** When counting started — the moment `bookQuantity` was snapshotted. */
2389
+ startedAt;
2390
+ /** When the variance was settled. */
2391
+ settledAt;
2392
+ cancelledAt;
2393
+ createdAt;
2394
+ items;
2395
+ locations;
2396
+ };
2397
+ tslib.__decorate([
2398
+ typeorm.PrimaryGeneratedColumn('uuid'),
2399
+ tslib.__metadata("design:type", String)
2400
+ ], exports.InventoryCountOrderEntityClass.prototype, "id", void 0);
2401
+ tslib.__decorate([
2402
+ typeorm.Column({ type: 'varchar', unique: true }),
2403
+ typeorm.Index(),
2404
+ tslib.__metadata("design:type", String)
2405
+ ], exports.InventoryCountOrderEntityClass.prototype, "key", void 0);
2406
+ tslib.__decorate([
2407
+ typeorm.Column({ type: 'varchar' }),
2408
+ tslib.__metadata("design:type", String)
2409
+ ], exports.InventoryCountOrderEntityClass.prototype, "name", void 0);
2410
+ tslib.__decorate([
2411
+ typeorm.Column({ type: 'date' }),
2412
+ typeorm.Index(),
2413
+ tslib.__metadata("design:type", String)
2414
+ ], exports.InventoryCountOrderEntityClass.prototype, "countDate", void 0);
2415
+ tslib.__decorate([
2416
+ typeorm.Column({
2417
+ type: 'enum',
2418
+ enum: exports.InventoryCountStatus,
2419
+ default: exports.InventoryCountStatus.PENDING,
2420
+ }),
2421
+ typeorm.Index(),
2422
+ tslib.__metadata("design:type", String)
2423
+ ], exports.InventoryCountOrderEntityClass.prototype, "status", void 0);
2424
+ tslib.__decorate([
2425
+ typeorm.Column({ type: 'varchar', nullable: true }),
2426
+ tslib.__metadata("design:type", Object)
2427
+ ], exports.InventoryCountOrderEntityClass.prototype, "createdBy", void 0);
2428
+ tslib.__decorate([
2429
+ typeorm.Column({ type: 'timestamptz', nullable: true }),
2430
+ tslib.__metadata("design:type", Object)
2431
+ ], exports.InventoryCountOrderEntityClass.prototype, "startedAt", void 0);
2432
+ tslib.__decorate([
2433
+ typeorm.Column({ type: 'timestamptz', nullable: true }),
2434
+ tslib.__metadata("design:type", Object)
2435
+ ], exports.InventoryCountOrderEntityClass.prototype, "settledAt", void 0);
2436
+ tslib.__decorate([
2437
+ typeorm.Column({ type: 'timestamptz', nullable: true }),
2438
+ tslib.__metadata("design:type", Object)
2439
+ ], exports.InventoryCountOrderEntityClass.prototype, "cancelledAt", void 0);
2440
+ tslib.__decorate([
2441
+ typeorm.CreateDateColumn({ type: 'timestamptz' }),
2442
+ tslib.__metadata("design:type", Date)
2443
+ ], exports.InventoryCountOrderEntityClass.prototype, "createdAt", void 0);
2444
+ tslib.__decorate([
2445
+ typeorm.OneToMany('inventory_count_order_items', (item) => item.order),
2446
+ tslib.__metadata("design:type", Array)
2447
+ ], exports.InventoryCountOrderEntityClass.prototype, "items", void 0);
2448
+ tslib.__decorate([
2449
+ typeorm.OneToMany('inventory_count_order_locations', (scope) => scope.order),
2450
+ tslib.__metadata("design:type", Array)
2451
+ ], exports.InventoryCountOrderEntityClass.prototype, "locations", void 0);
2452
+ exports.InventoryCountOrderEntityClass = tslib.__decorate([
2453
+ typeorm.Entity('inventory_count_orders'),
2454
+ typeorm.TableInheritance({ column: { type: 'varchar', name: 'entityName' } })
2455
+ ], exports.InventoryCountOrderEntityClass);
2456
+ const InventoryCountOrderLocationEntity = Symbol('InventoryCountOrderLocationEntity');
2457
+ /**
2458
+ * One row per location in the order's scope, **already expanded** to include
2459
+ * every descendant of the locations the user picked.
2460
+ *
2461
+ * The scope is materialised at creation instead of being recomputed from the
2462
+ * chosen roots because it is read on the hot path: while an order is counting,
2463
+ * every single stock movement in the system has to ask "is this location
2464
+ * locked?". `LocationEntity` is a plain `parent`/`children` adjacency list with
2465
+ * no materialised path, so answering that from the tree would mean a recursive
2466
+ * CTE per movement.
2467
+ */
2468
+ exports.InventoryCountOrderLocationEntityClass = class InventoryCountOrderLocationEntityClass {
2469
+ id;
2470
+ orderId;
2471
+ locationId;
2472
+ /** `true` for the locations the user picked, `false` for descendants. */
2473
+ isRoot;
2474
+ order;
2475
+ location;
2476
+ };
2477
+ tslib.__decorate([
2478
+ typeorm.PrimaryGeneratedColumn('uuid'),
2479
+ tslib.__metadata("design:type", String)
2480
+ ], exports.InventoryCountOrderLocationEntityClass.prototype, "id", void 0);
2481
+ tslib.__decorate([
2482
+ typeorm.Column({ type: 'uuid' }),
2483
+ typeorm.Index(),
2484
+ tslib.__metadata("design:type", String)
2485
+ ], exports.InventoryCountOrderLocationEntityClass.prototype, "orderId", void 0);
2486
+ tslib.__decorate([
2487
+ typeorm.Column({ type: 'uuid' }),
2488
+ typeorm.Index(),
2489
+ tslib.__metadata("design:type", String)
2490
+ ], exports.InventoryCountOrderLocationEntityClass.prototype, "locationId", void 0);
2491
+ tslib.__decorate([
2492
+ typeorm.Column({ type: 'boolean', default: false }),
2493
+ tslib.__metadata("design:type", Boolean)
2494
+ ], exports.InventoryCountOrderLocationEntityClass.prototype, "isRoot", void 0);
2495
+ tslib.__decorate([
2496
+ typeorm.ManyToOne('inventory_count_orders', (order) => order.locations),
2497
+ typeorm.JoinColumn({ name: 'orderId', referencedColumnName: 'id' }),
2498
+ tslib.__metadata("design:type", exports.InventoryCountOrderEntityClass)
2499
+ ], exports.InventoryCountOrderLocationEntityClass.prototype, "order", void 0);
2500
+ tslib.__decorate([
2501
+ typeorm.ManyToOne('locations'),
2502
+ typeorm.JoinColumn({ name: 'locationId', referencedColumnName: 'id' }),
2503
+ tslib.__metadata("design:type", exports.LocationEntityClass)
2504
+ ], exports.InventoryCountOrderLocationEntityClass.prototype, "location", void 0);
2505
+ exports.InventoryCountOrderLocationEntityClass = tslib.__decorate([
2506
+ typeorm.Entity('inventory_count_order_locations')
2507
+ ], exports.InventoryCountOrderLocationEntityClass);
2508
+
2509
+ const InventoryCountOrderItemEntity = Symbol('InventoryCountOrderItemEntity');
2510
+ /**
2511
+ * One line of the count sheet.
2512
+ *
2513
+ * Two flavours share the table, told apart by {@link isAddition}:
2514
+ *
2515
+ * - a **scoped line**, expanded from the order's locations when the order is
2516
+ * created. `bookQuantity` is the snapshot taken at "開始盤點".
2517
+ * - an **addition** (盤盈), added by hand during counting for stock the books do
2518
+ * not know about at all. `bookQuantity` is `0` by definition, and it is the
2519
+ * only flavour a user may delete.
2520
+ */
2521
+ exports.InventoryCountOrderItemEntityClass = class InventoryCountOrderItemEntityClass {
2522
+ id;
2523
+ orderId;
2524
+ materialId;
2525
+ batchId;
2526
+ locationId;
2527
+ loaderId;
2528
+ /**
2529
+ * The unit the counted quantity is expressed in; `null` means the material's
2530
+ * base unit. Settlement converts through the material's conversion factor
2531
+ * before comparing with {@link bookQuantity}, which is always in base units.
2532
+ */
2533
+ unitId;
2534
+ /** Ledger quantity in base units, frozen when counting started. */
2535
+ bookQuantity;
2536
+ /** What was actually found, in {@link unitId}. `null` until someone counts. */
2537
+ countedQuantity;
2538
+ /** `true` for a line added during counting for unbooked stock (盤盈). */
2539
+ isAddition;
2540
+ location;
2541
+ loader;
2542
+ order;
2543
+ changes;
2544
+ };
2545
+ tslib.__decorate([
2546
+ typeorm.PrimaryGeneratedColumn('uuid'),
2547
+ tslib.__metadata("design:type", String)
2548
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "id", void 0);
2549
+ tslib.__decorate([
2550
+ typeorm.Column({ type: 'uuid' }),
2551
+ typeorm.Index(),
2552
+ tslib.__metadata("design:type", String)
2553
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "orderId", void 0);
2554
+ tslib.__decorate([
2555
+ typeorm.Column({ type: 'uuid' }),
2556
+ typeorm.Index(),
2557
+ tslib.__metadata("design:type", String)
2558
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "materialId", void 0);
2559
+ tslib.__decorate([
2560
+ typeorm.Column({ type: 'uuid' }),
2561
+ typeorm.Index(),
2562
+ tslib.__metadata("design:type", String)
2563
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "batchId", void 0);
2564
+ tslib.__decorate([
2565
+ typeorm.Column({ type: 'uuid', nullable: true }),
2566
+ typeorm.Index(),
2567
+ tslib.__metadata("design:type", Object)
2568
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "locationId", void 0);
2569
+ tslib.__decorate([
2570
+ typeorm.Column({ type: 'uuid', nullable: true }),
2571
+ typeorm.Index(),
2572
+ tslib.__metadata("design:type", Object)
2573
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "loaderId", void 0);
2574
+ tslib.__decorate([
2575
+ typeorm.Column({ type: 'uuid', nullable: true }),
2576
+ typeorm.Index(),
2577
+ tslib.__metadata("design:type", Object)
2578
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "unitId", void 0);
2579
+ tslib.__decorate([
2580
+ typeorm.Column({ type: 'numeric', default: 0 }),
2581
+ tslib.__metadata("design:type", Number)
2582
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "bookQuantity", void 0);
2583
+ tslib.__decorate([
2584
+ typeorm.Column({ type: 'numeric', nullable: true }),
2585
+ tslib.__metadata("design:type", Object)
2586
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "countedQuantity", void 0);
2587
+ tslib.__decorate([
2588
+ typeorm.Column({ type: 'boolean', default: false }),
2589
+ tslib.__metadata("design:type", Boolean)
2590
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "isAddition", void 0);
2591
+ tslib.__decorate([
2592
+ typeorm.ManyToOne('locations'),
2593
+ typeorm.JoinColumn({ name: 'locationId', referencedColumnName: 'id' }),
2594
+ tslib.__metadata("design:type", exports.LocationEntityClass)
2595
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "location", void 0);
2596
+ tslib.__decorate([
2597
+ typeorm.ManyToOne('loaders'),
2598
+ typeorm.JoinColumn({ name: 'loaderId', referencedColumnName: 'id' }),
2599
+ tslib.__metadata("design:type", exports.LoadersEntityClass)
2600
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "loader", void 0);
2601
+ tslib.__decorate([
2602
+ typeorm.ManyToOne('inventory_count_orders', (order) => order.items),
2603
+ typeorm.JoinColumn({ name: 'orderId', referencedColumnName: 'id' }),
2604
+ tslib.__metadata("design:type", exports.InventoryCountOrderEntityClass)
2605
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "order", void 0);
2606
+ tslib.__decorate([
2607
+ typeorm.OneToMany('inventory_count_order_changes', (change) => change.item),
2608
+ tslib.__metadata("design:type", Array)
2609
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "changes", void 0);
2610
+ exports.InventoryCountOrderItemEntityClass = tslib.__decorate([
2611
+ typeorm.Entity('inventory_count_order_items'),
2612
+ typeorm.TableInheritance({ column: { type: 'varchar', name: 'entityName' } })
2613
+ ], exports.InventoryCountOrderItemEntityClass);
2614
+
2615
+ const InventoryCountOrderChangeEntity = Symbol('InventoryCountOrderChangeEntity');
2616
+ /**
2617
+ * The stock movement a settled count line produced.
2618
+ *
2619
+ * `quantityChanged` carries the sign, exactly like every other `*_order_change`
2620
+ * table: positive is a surplus (盤盈), negative a shortage (盤虧).
2621
+ * `StockChangeSubscriber` reads the sign to pick between `stock.count-gained`
2622
+ * and `stock.count-lost`, so nothing here has to emit events itself.
2623
+ *
2624
+ * Lines whose count matched the books produce no row at all.
2625
+ */
2626
+ exports.InventoryCountOrderChangeEntityClass = class InventoryCountOrderChangeEntityClass {
2627
+ id;
2628
+ itemId;
2629
+ quantityChanged;
2630
+ order;
2631
+ item;
2632
+ };
2633
+ tslib.__decorate([
2634
+ typeorm.PrimaryGeneratedColumn('uuid'),
2635
+ tslib.__metadata("design:type", String)
2636
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "id", void 0);
2637
+ tslib.__decorate([
2638
+ typeorm.Column({ type: 'uuid' }),
2639
+ tslib.__metadata("design:type", String)
2640
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "itemId", void 0);
2641
+ tslib.__decorate([
2642
+ typeorm.Column({ type: 'numeric' }),
2643
+ tslib.__metadata("design:type", Number)
2644
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "quantityChanged", void 0);
2645
+ tslib.__decorate([
2646
+ typeorm.OneToOne('orders'),
2647
+ typeorm.JoinColumn({ name: 'id', referencedColumnName: 'id' }),
2648
+ tslib.__metadata("design:type", wmsBaseNestjsModule.OrderEntity)
2649
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "order", void 0);
2650
+ tslib.__decorate([
2651
+ typeorm.ManyToOne('inventory_count_order_items', (item) => item.changes),
2652
+ typeorm.JoinColumn({ name: 'itemId', referencedColumnName: 'id' }),
2653
+ tslib.__metadata("design:type", exports.InventoryCountOrderItemEntityClass)
2654
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "item", void 0);
2655
+ exports.InventoryCountOrderChangeEntityClass = tslib.__decorate([
2656
+ typeorm.Entity('inventory_count_order_changes')
2657
+ ], exports.InventoryCountOrderChangeEntityClass);
2658
+
2346
2659
  const entities = [
2347
2660
  [UnitEntity, exports.UnitEntityClass],
2348
2661
  [MaterialEntity, exports.MaterialEntityClass],
@@ -2396,6 +2709,10 @@ const entities = [
2396
2709
  [ScrapeOrderEntity, exports.ScrapeOrderEntityClass],
2397
2710
  [ScrapeOrderItemEntity, exports.ScrapeOrderItemEntityClass],
2398
2711
  [ScrapeOrderChangeEntity, exports.ScrapeOrderChangeEntityClass],
2712
+ [InventoryCountOrderEntity, exports.InventoryCountOrderEntityClass],
2713
+ [InventoryCountOrderLocationEntity, exports.InventoryCountOrderLocationEntityClass],
2714
+ [InventoryCountOrderItemEntity, exports.InventoryCountOrderItemEntityClass],
2715
+ [InventoryCountOrderChangeEntity, exports.InventoryCountOrderChangeEntityClass],
2399
2716
  ];
2400
2717
  /**
2401
2718
  * The overridable entities are deliberately absent: `WmsModuleCoreModule` binds
@@ -6419,6 +6736,464 @@ exports.SaleOrderService = tslib.__decorate([
6419
6736
  tslib.__metadata("design:paramtypes", [typeorm.DataSource])
6420
6737
  ], exports.SaleOrderService);
6421
6738
 
6739
+ /**
6740
+ * Inventory counting: compare the ledger against what is physically there, then
6741
+ * adjust the ledger to match.
6742
+ *
6743
+ * The shape follows the "D. 盤點" design flow. Three properties are worth
6744
+ * stating up front because everything else follows from them:
6745
+ *
6746
+ * - **Counting never moves stock between locations.** A line that is in the
6747
+ * wrong place is a transfer, not a count; `transfer-order:create` already does
6748
+ * that. This service only ever adjusts quantity, up or down, in place.
6749
+ * - **Nothing touches stock until settlement.** Counted quantities are working
6750
+ * notes ("暫存的對帳資料"); only {@link settle} writes changes, and it does so
6751
+ * in a single transaction.
6752
+ * - **Starting a count locks its locations.** The book snapshot taken at
6753
+ * {@link start} would be worthless if stock kept moving underneath it, so
6754
+ * `InventoryCountLockSubscriber` refuses every other stock movement in the
6755
+ * scope until the order settles or is cancelled.
6756
+ */
6757
+ exports.InventoryCountOrderService = class InventoryCountOrderService {
6758
+ dataSource;
6759
+ entities;
6760
+ helperService;
6761
+ materialService;
6762
+ stockService;
6763
+ batchService;
6764
+ inventoryCountOrderEntity;
6765
+ seqPrefix = 'ICO';
6766
+ constructor(dataSource, entities, helperService, materialService, stockService, batchService, inventoryCountOrderEntity) {
6767
+ this.dataSource = dataSource;
6768
+ this.entities = entities;
6769
+ this.helperService = helperService;
6770
+ this.materialService = materialService;
6771
+ this.stockService = stockService;
6772
+ this.batchService = batchService;
6773
+ this.inventoryCountOrderEntity = inventoryCountOrderEntity;
6774
+ }
6775
+ getRepositories(manager) {
6776
+ return {
6777
+ order: manager.getRepository(this.inventoryCountOrderEntity),
6778
+ scope: manager.getRepository(exports.InventoryCountOrderLocationEntityClass),
6779
+ item: manager.getRepository(exports.InventoryCountOrderItemEntityClass),
6780
+ change: manager.getRepository(exports.InventoryCountOrderChangeEntityClass),
6781
+ baseOrder: manager.getRepository(this.entities.order),
6782
+ stock: manager.getRepository(this.entities.stock),
6783
+ };
6784
+ }
6785
+ /**
6786
+ * Expand chosen locations into themselves plus every descendant.
6787
+ *
6788
+ * `LocationEntity` is a plain adjacency list (`parent` / `children`) with no
6789
+ * materialised path, so the subtree needs a recursive CTE. It runs once per
6790
+ * scope change and the result is stored, precisely so the lock check never has
6791
+ * to run it.
6792
+ */
6793
+ async expandLocationScope(rootIds, manager) {
6794
+ if (!rootIds.length) {
6795
+ return [];
6796
+ }
6797
+ const table = manager.getRepository(this.entities.location).metadata
6798
+ .tableName;
6799
+ const rows = await manager.query(`WITH RECURSIVE subtree AS (
6800
+ SELECT id FROM "${table}" WHERE id = ANY($1)
6801
+ UNION
6802
+ SELECT child.id
6803
+ FROM "${table}" child
6804
+ JOIN subtree parent ON child."parentId" = parent.id
6805
+ )
6806
+ SELECT id FROM subtree`, [[...rootIds]]);
6807
+ const roots = new Set(rootIds);
6808
+ return rows.map(({ id }) => ({ id, isRoot: roots.has(id) }));
6809
+ }
6810
+ /** Current ledger quantity per physical position inside the scope. */
6811
+ async readPositions(locationIds, manager) {
6812
+ if (!locationIds.length) {
6813
+ return [];
6814
+ }
6815
+ // Through the repository, not raw SQL on the table: the stock entity is
6816
+ // overridable, and the repository is what applies the right
6817
+ // single-table-inheritance discriminator.
6818
+ const rows = await manager
6819
+ .getRepository(this.entities.stock)
6820
+ .createQueryBuilder('stock')
6821
+ .select('stock.materialId', 'materialId')
6822
+ .addSelect('stock.batchId', 'batchId')
6823
+ .addSelect('stock.locationId', 'locationId')
6824
+ .addSelect('stock.loaderId', 'loaderId')
6825
+ .addSelect('SUM(stock.quantity)', 'quantity')
6826
+ .where('stock.locationId IN (:...locationIds)', {
6827
+ locationIds: [...locationIds],
6828
+ })
6829
+ .groupBy('stock.materialId')
6830
+ .addGroupBy('stock.batchId')
6831
+ .addGroupBy('stock.locationId')
6832
+ .addGroupBy('stock.loaderId')
6833
+ .having('SUM(stock.quantity) > 0')
6834
+ .getRawMany();
6835
+ return rows.map((row) => ({
6836
+ materialId: row.materialId,
6837
+ batchId: row.batchId,
6838
+ locationId: row.locationId,
6839
+ loaderId: row.loaderId,
6840
+ quantity: Number(row.quantity),
6841
+ }));
6842
+ }
6843
+ positionKey(position) {
6844
+ return [
6845
+ position.materialId,
6846
+ position.batchId,
6847
+ position.locationId ?? '',
6848
+ position.loaderId ?? '',
6849
+ ].join('|');
6850
+ }
6851
+ async scopedLocationIds(orderId, manager) {
6852
+ const rows = await this.getRepositories(manager).scope.find({
6853
+ where: { orderId },
6854
+ select: { locationId: true },
6855
+ });
6856
+ return rows.map(({ locationId }) => locationId);
6857
+ }
6858
+ async loadOrderOrFail(id, manager) {
6859
+ const order = await this.getRepositories(manager).order.findOneBy({ id });
6860
+ if (!order) {
6861
+ throw new common.NotFoundException(`Inventory count order ${id} not found`);
6862
+ }
6863
+ return order;
6864
+ }
6865
+ assertStatus(order, allowed) {
6866
+ if (!allowed.includes(order.status)) {
6867
+ throw new common.BadRequestException(`Inventory count order ${order.id} is ${order.status}; this operation requires ${allowed.join(' or ')}`);
6868
+ }
6869
+ }
6870
+ /**
6871
+ * Rebuild the sheet from the current ledger.
6872
+ *
6873
+ * Called when the scope changes and again when counting starts. Additions
6874
+ * (盤盈 lines) are never touched — they describe stock the ledger does not know
6875
+ * about, so a rebuild has nothing to say about them.
6876
+ */
6877
+ async rebuildItems(orderId, manager) {
6878
+ const repos = this.getRepositories(manager);
6879
+ const locationIds = await this.scopedLocationIds(orderId, manager);
6880
+ const positions = await this.readPositions(locationIds, manager);
6881
+ const existing = await repos.item.find({
6882
+ where: { orderId, isAddition: false },
6883
+ });
6884
+ const byKey = new Map(existing.map((item) => [this.positionKey(item), item]));
6885
+ const seen = new Set();
6886
+ for (const position of positions) {
6887
+ const key = this.positionKey(position);
6888
+ seen.add(key);
6889
+ const item = byKey.get(key);
6890
+ if (item) {
6891
+ item.bookQuantity = position.quantity;
6892
+ await repos.item.save(item);
6893
+ continue;
6894
+ }
6895
+ await repos.item.save(repos.item.create({
6896
+ orderId,
6897
+ materialId: position.materialId,
6898
+ batchId: position.batchId,
6899
+ locationId: position.locationId,
6900
+ loaderId: position.loaderId,
6901
+ bookQuantity: position.quantity,
6902
+ countedQuantity: null,
6903
+ unitId: null,
6904
+ isAddition: false,
6905
+ }));
6906
+ }
6907
+ // A position that emptied out between two rebuilds is no longer on the
6908
+ // sheet; it cannot be counted and would settle to a meaningless zero.
6909
+ const stale = existing.filter((item) => !seen.has(this.positionKey(item)));
6910
+ if (stale.length) {
6911
+ await repos.item.delete({ id: typeorm.In(stale.map(({ id }) => id)) });
6912
+ }
6913
+ }
6914
+ /** Filters for the list page. All optional; combined with AND. */
6915
+ async findMany(options, manager = this.dataSource.manager) {
6916
+ const query = this.getRepositories(manager)
6917
+ // The alias is lowercase and is deliberately not `order`. `order` is a
6918
+ // PostgreSQL reserved word, so the raw fragments below would render
6919
+ // `order."countDate"` and fail to parse; and a camelCase alias would be
6920
+ // emitted quoted by the query builder while the unquoted references here
6921
+ // fold to lowercase, so the two would never match.
6922
+ .order.createQueryBuilder('count_order')
6923
+ .orderBy('count_order."countDate"', 'DESC')
6924
+ .addOrderBy('count_order."createdAt"', 'DESC');
6925
+ if (options.name) {
6926
+ query.andWhere('count_order.name ILIKE :name', {
6927
+ name: `%${options.name}%`,
6928
+ });
6929
+ }
6930
+ if (options.statuses?.length) {
6931
+ query.andWhere('count_order.status IN (:...statuses)', {
6932
+ statuses: options.statuses,
6933
+ });
6934
+ }
6935
+ if (options.createdBy) {
6936
+ query.andWhere('count_order."createdBy" = :createdBy', {
6937
+ createdBy: options.createdBy,
6938
+ });
6939
+ }
6940
+ if (options.countDateFrom) {
6941
+ query.andWhere('count_order."countDate" >= :from', {
6942
+ from: options.countDateFrom,
6943
+ });
6944
+ }
6945
+ if (options.countDateTo) {
6946
+ query.andWhere('count_order."countDate" <= :to', {
6947
+ to: options.countDateTo,
6948
+ });
6949
+ }
6950
+ if (options.locationIds?.length) {
6951
+ // Scope membership, not the roots the user picked: a count of a whole
6952
+ // aisle should surface when filtering by any shelf inside it.
6953
+ query.andWhere(`EXISTS (
6954
+ SELECT 1 FROM inventory_count_order_locations scope
6955
+ WHERE scope."orderId" = count_order.id
6956
+ AND scope."locationId" IN (:...locationIds)
6957
+ )`, { locationIds: options.locationIds });
6958
+ }
6959
+ if (options.offset !== undefined && options.offset >= 0) {
6960
+ query.skip(options.offset);
6961
+ }
6962
+ if (options.limit !== undefined && options.limit > 0) {
6963
+ query.take(options.limit);
6964
+ }
6965
+ return query.getManyAndCount();
6966
+ }
6967
+ async findOne(id, manager = this.dataSource.manager) {
6968
+ return this.loadOrderOrFail(id, manager);
6969
+ }
6970
+ async create(input, manager = this.dataSource.manager) {
6971
+ if (!input.locationIds.length) {
6972
+ throw new common.BadRequestException('An inventory count needs at least one location in scope');
6973
+ }
6974
+ const repos = this.getRepositories(manager);
6975
+ const key = await this.helperService.getSeq(this.seqPrefix, manager);
6976
+ const order = await repos.order.save(repos.order.create({
6977
+ key,
6978
+ name: input.name,
6979
+ countDate: input.countDate,
6980
+ status: exports.InventoryCountStatus.PENDING,
6981
+ createdBy: input.createdBy ?? null,
6982
+ }));
6983
+ const scope = await this.expandLocationScope(input.locationIds, manager);
6984
+ await repos.scope.save(scope.map(({ id, isRoot }) => repos.scope.create({ orderId: order.id, locationId: id, isRoot })));
6985
+ await this.rebuildItems(order.id, manager);
6986
+ return order;
6987
+ }
6988
+ async update(id, input, manager = this.dataSource.manager) {
6989
+ const repos = this.getRepositories(manager);
6990
+ const order = await this.loadOrderOrFail(id, manager);
6991
+ // The design keeps the info panel editable only while nothing has been
6992
+ // counted; afterwards the sheet is already anchored to this scope and date.
6993
+ this.assertStatus(order, [exports.InventoryCountStatus.PENDING]);
6994
+ if (input.name !== undefined)
6995
+ order.name = input.name;
6996
+ if (input.countDate !== undefined)
6997
+ order.countDate = input.countDate;
6998
+ await repos.order.save(order);
6999
+ if (input.locationIds) {
7000
+ if (!input.locationIds.length) {
7001
+ throw new common.BadRequestException('An inventory count needs at least one location in scope');
7002
+ }
7003
+ await repos.scope.delete({ orderId: id });
7004
+ const scope = await this.expandLocationScope(input.locationIds, manager);
7005
+ await repos.scope.save(scope.map(({ id: locationId, isRoot }) => repos.scope.create({ orderId: id, locationId, isRoot })));
7006
+ await this.rebuildItems(id, manager);
7007
+ }
7008
+ return order;
7009
+ }
7010
+ /**
7011
+ * Freeze the ledger and open the sheet for counting.
7012
+ *
7013
+ * The rebuild here is the snapshot: from this point `bookQuantity` is what the
7014
+ * variance is measured against, and the lock keeps it true.
7015
+ */
7016
+ async start(id, manager = this.dataSource.manager) {
7017
+ const repos = this.getRepositories(manager);
7018
+ const order = await this.loadOrderOrFail(id, manager);
7019
+ this.assertStatus(order, [exports.InventoryCountStatus.PENDING]);
7020
+ await this.rebuildItems(id, manager);
7021
+ order.status = exports.InventoryCountStatus.COUNTING;
7022
+ order.startedAt = new Date();
7023
+ await repos.order.save(order);
7024
+ return order;
7025
+ }
7026
+ /** Save counted quantities without touching stock ("暫存結果"). */
7027
+ async count(id, entries, manager = this.dataSource.manager) {
7028
+ const repos = this.getRepositories(manager);
7029
+ const order = await this.loadOrderOrFail(id, manager);
7030
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7031
+ if (!entries.length) {
7032
+ return order;
7033
+ }
7034
+ const items = await repos.item.find({
7035
+ where: { orderId: id, id: typeorm.In(entries.map(({ itemId }) => itemId)) },
7036
+ });
7037
+ const byId = new Map(items.map((item) => [item.id, item]));
7038
+ for (const entry of entries) {
7039
+ const item = byId.get(entry.itemId);
7040
+ if (!item) {
7041
+ throw new common.NotFoundException(`Item ${entry.itemId} does not belong to inventory count order ${id}`);
7042
+ }
7043
+ if (entry.countedQuantity !== null &&
7044
+ (!Number.isFinite(entry.countedQuantity) || entry.countedQuantity < 0)) {
7045
+ throw new common.BadRequestException(`Counted quantity for item ${entry.itemId} must be a non-negative number`);
7046
+ }
7047
+ item.countedQuantity = entry.countedQuantity;
7048
+ if (entry.unitId !== undefined) {
7049
+ item.unitId = entry.unitId;
7050
+ }
7051
+ await repos.item.save(item);
7052
+ }
7053
+ return order;
7054
+ }
7055
+ /**
7056
+ * Add a line for stock the ledger has no record of (盤盈).
7057
+ *
7058
+ * The batch is resolved by key and created when it does not exist, which is
7059
+ * what makes "the batch field's default is editable" in the design work.
7060
+ */
7061
+ async addItem(id, input, manager = this.dataSource.manager) {
7062
+ const repos = this.getRepositories(manager);
7063
+ const order = await this.loadOrderOrFail(id, manager);
7064
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7065
+ if (!Number.isFinite(input.countedQuantity) || input.countedQuantity <= 0) {
7066
+ throw new common.BadRequestException('An added inventory count line needs a positive counted quantity');
7067
+ }
7068
+ const scoped = await this.scopedLocationIds(id, manager);
7069
+ // Settlement writes stock at this location, so it has to be one the order
7070
+ // locked — otherwise the count would adjust a position other operations are
7071
+ // still free to move.
7072
+ if (!scoped.includes(input.locationId)) {
7073
+ throw new common.BadRequestException(`Location ${input.locationId} is outside the scope of inventory count order ${id}`);
7074
+ }
7075
+ const batch = await this.batchService.getBatch({
7076
+ key: input.batchKey,
7077
+ materialId: input.materialId,
7078
+ manager,
7079
+ });
7080
+ return repos.item.save(repos.item.create({
7081
+ orderId: id,
7082
+ materialId: input.materialId,
7083
+ batchId: batch.id,
7084
+ locationId: input.locationId,
7085
+ loaderId: input.loaderId ?? null,
7086
+ unitId: input.unitId ?? null,
7087
+ bookQuantity: 0,
7088
+ countedQuantity: input.countedQuantity,
7089
+ isAddition: true,
7090
+ }));
7091
+ }
7092
+ /** Remove an added line. Scoped lines are part of the sheet and never removed. */
7093
+ async removeItem(id, itemId, manager = this.dataSource.manager) {
7094
+ const repos = this.getRepositories(manager);
7095
+ const order = await this.loadOrderOrFail(id, manager);
7096
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7097
+ const item = await repos.item.findOneBy({ id: itemId, orderId: id });
7098
+ if (!item) {
7099
+ throw new common.NotFoundException(`Item ${itemId} does not belong to inventory count order ${id}`);
7100
+ }
7101
+ if (!item.isAddition) {
7102
+ throw new common.BadRequestException(`Item ${itemId} came from the counted scope and cannot be removed`);
7103
+ }
7104
+ await repos.item.delete({ id: itemId });
7105
+ return order;
7106
+ }
7107
+ /**
7108
+ * Throw the counting away and start over, without leaving the count.
7109
+ *
7110
+ * The scope stays locked and the status stays `COUNTING`: the point is a
7111
+ * re-measure after something went wrong on the floor, not an abandonment. The
7112
+ * book snapshot is deliberately *not* retaken — the lock means it has not
7113
+ * moved.
7114
+ */
7115
+ async reset(id, manager = this.dataSource.manager) {
7116
+ const repos = this.getRepositories(manager);
7117
+ const order = await this.loadOrderOrFail(id, manager);
7118
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7119
+ await repos.item.delete({ orderId: id, isAddition: true });
7120
+ await repos.item.update({ orderId: id }, { countedQuantity: null, unitId: null });
7121
+ return order;
7122
+ }
7123
+ async cancel(id, manager = this.dataSource.manager) {
7124
+ const repos = this.getRepositories(manager);
7125
+ const order = await this.loadOrderOrFail(id, manager);
7126
+ this.assertStatus(order, [
7127
+ exports.InventoryCountStatus.PENDING,
7128
+ exports.InventoryCountStatus.COUNTING,
7129
+ ]);
7130
+ order.status = exports.InventoryCountStatus.CANCELLED;
7131
+ order.cancelledAt = new Date();
7132
+ await repos.order.save(order);
7133
+ return order;
7134
+ }
7135
+ /**
7136
+ * Adjust the ledger to the counted reality ("執行盤差").
7137
+ *
7138
+ * Runs in one transaction and is awaited end to end, so the mutation
7139
+ * interceptor's post-commit guarantee holds: every `stock.count-gained` /
7140
+ * `stock.count-lost` event fires only after the adjustments are durable.
7141
+ *
7142
+ * Uncounted lines are left alone — "not counted" is not "counted as zero", and
7143
+ * treating it as zero would wipe out stock nobody looked at.
7144
+ */
7145
+ async settle(id, outerManager) {
7146
+ const run = async (manager) => {
7147
+ const repos = this.getRepositories(manager);
7148
+ const order = await this.loadOrderOrFail(id, manager);
7149
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7150
+ const items = await repos.item.find({ where: { orderId: id } });
7151
+ for (const item of items) {
7152
+ if (item.countedQuantity === null) {
7153
+ continue;
7154
+ }
7155
+ const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId ?? undefined);
7156
+ const counted = Number(item.countedQuantity) * conversionFactor;
7157
+ const delta = counted - Number(item.bookQuantity);
7158
+ if (delta === 0) {
7159
+ continue;
7160
+ }
7161
+ const baseOrder = await repos.baseOrder.save({});
7162
+ await repos.change.save(repos.change.create({
7163
+ item,
7164
+ order: baseOrder,
7165
+ quantityChanged: delta,
7166
+ }));
7167
+ await repos.stock.save(repos.stock.create({
7168
+ orderId: baseOrder.id,
7169
+ materialId: item.materialId,
7170
+ batchId: item.batchId,
7171
+ locationId: this.stockService.resolveLocationId(item.locationId),
7172
+ loaderId: this.stockService.resolveLoaderId(item.loaderId),
7173
+ quantity: delta,
7174
+ }));
7175
+ }
7176
+ order.status = exports.InventoryCountStatus.COMPLETED;
7177
+ order.settledAt = new Date();
7178
+ await repos.order.save(order);
7179
+ return order;
7180
+ };
7181
+ return outerManager
7182
+ ? run(outerManager)
7183
+ : this.dataSource.transaction((manager) => run(manager));
7184
+ }
7185
+ };
7186
+ exports.InventoryCountOrderService = tslib.__decorate([
7187
+ common.Injectable(),
7188
+ tslib.__param(6, common.Inject(InventoryCountOrderEntity)),
7189
+ tslib.__metadata("design:paramtypes", [typeorm.DataSource,
7190
+ exports.WmsEntities,
7191
+ exports.HelperService,
7192
+ exports.MaterialService,
7193
+ exports.StockService,
7194
+ exports.BatchService, Object])
7195
+ ], exports.InventoryCountOrderService);
7196
+
6422
7197
  exports.ScrapeService = class ScrapeService {
6423
7198
  dataSource;
6424
7199
  entities;
@@ -6512,11 +7287,20 @@ exports.WarehouseMapDataService = class WarehouseMapDataService {
6512
7287
  constructor(dataSource, entities) {
6513
7288
  this.dataSource = dataSource;
6514
7289
  this.entities = entities;
6515
- this.warehouseMapDataRepository =
6516
- this.dataSource.getRepository(this.entities.warehouseMap);
7290
+ this.warehouseMapDataRepository = this.dataSource.getRepository(this.entities.warehouseMap);
6517
7291
  }
6518
- onApplicationBootstrap() {
6519
- this.dataSource.transaction(async (manager) => {
7292
+ /**
7293
+ * Seed the default map row.
7294
+ *
7295
+ * `async` on purpose: Nest awaits a returned promise, so bootstrap does not
7296
+ * complete until the seed transaction has committed. Firing it off without
7297
+ * awaiting used to leave a transaction in flight after `app.init()` resolved
7298
+ * — an app that shut down promptly (a test, a short-lived worker) destroyed
7299
+ * the pool underneath it and the rejection surfaced as an unhandled
7300
+ * `QueryFailedError: Connection terminated` that killed the process.
7301
+ */
7302
+ async onApplicationBootstrap() {
7303
+ await this.dataSource.transaction(async (manager) => {
6520
7304
  const defaultMapData = await manager
6521
7305
  .getRepository(this.entities.warehouseMap)
6522
7306
  .findOneBy({ id: this.defaultMapDataKey });
@@ -6583,6 +7367,10 @@ const TABLE_TO_CHANGE_TYPE = new Map([
6583
7367
  ['merge_batch_order_changes', () => exports.ChangeType.MERGED],
6584
7368
  ['reclassify_inventory_order_changes', () => exports.ChangeType.RECLASSIFIED],
6585
7369
  ['scrape_order_changes', () => exports.ChangeType.SCRAPED],
7370
+ [
7371
+ 'inventory_count_order_changes',
7372
+ (q) => (q > 0 ? exports.ChangeType.COUNT_GAINED : exports.ChangeType.COUNT_LOST),
7373
+ ],
6586
7374
  ]);
6587
7375
  const CHANGE_TYPE_TO_EVENT = {
6588
7376
  [exports.ChangeType.RECEIVED]: 'stock.received',
@@ -6602,6 +7390,8 @@ const CHANGE_TYPE_TO_EVENT = {
6602
7390
  [exports.ChangeType.DEALLOCATED]: 'stock.deallocated',
6603
7391
  [exports.ChangeType.RECLASSIFIED]: 'stock.reclassified',
6604
7392
  [exports.ChangeType.SCRAPED]: 'stock.scraped',
7393
+ [exports.ChangeType.COUNT_GAINED]: 'stock.count-gained',
7394
+ [exports.ChangeType.COUNT_LOST]: 'stock.count-lost',
6605
7395
  };
6606
7396
  const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
6607
7397
  /**
@@ -6702,6 +7492,98 @@ StockChangeSubscriber = tslib.__decorate([
6702
7492
  exports.WmsEventCollector, Object])
6703
7493
  ], StockChangeSubscriber);
6704
7494
 
7495
+ /** The count's own settlement writes here; it must never lock itself out. */
7496
+ const INVENTORY_COUNT_CHANGE_TABLE = 'inventory_count_order_changes';
7497
+ /**
7498
+ * Refuse stock movements in locations a running inventory count has locked.
7499
+ *
7500
+ * Starting a count snapshots the ledger for its scope. That snapshot is what the
7501
+ * variance is measured against, so it has to stay true: if a transfer or a
7502
+ * shipment moved stock in the meantime, settlement would post the difference
7503
+ * between "what we counted" and "what the books said an hour ago" — silently
7504
+ * writing off someone else's legitimate movement.
7505
+ *
7506
+ * Why a subscriber rather than a check in each service
7507
+ * ---------------------------------------------------
7508
+ * Every stock movement in this package, without exception, ends in a row on some
7509
+ * `*_order_change` table — that is the same property `StockChangeSubscriber`
7510
+ * relies on to collect `stock.*` events without touching a single service. Doing
7511
+ * the lock check at the same choke point means:
7512
+ *
7513
+ * - the twelve domain services stay untouched;
7514
+ * - any future path that writes a change row is covered automatically;
7515
+ * - a consumer calling a service **directly**, bypassing the resolvers, is
7516
+ * covered too — which is exactly the case that matters, because a host with
7517
+ * its own inbound flow does precisely that.
7518
+ *
7519
+ * The check costs one indexed lookup per change row. That is deliberate: caching
7520
+ * the locked set would open a window right after `start()` in which a movement
7521
+ * slips through, and a lock with a window is not a lock.
7522
+ */
7523
+ exports.InventoryCountLockSubscriber = class InventoryCountLockSubscriber {
7524
+ constructor(dataSource) {
7525
+ dataSource.subscribers.push(this);
7526
+ }
7527
+ async beforeInsert(event) {
7528
+ const tableName = event.metadata.tableName;
7529
+ if (tableName === INVENTORY_COUNT_CHANGE_TABLE ||
7530
+ !tableName.endsWith('_order_changes')) {
7531
+ return;
7532
+ }
7533
+ const locationId = await this.resolveLocationId(event);
7534
+ if (!locationId) {
7535
+ // split / merge / reclassify items carry no location. They still move
7536
+ // stock, but only within a position the caller already named elsewhere;
7537
+ // there is nothing to match against the scope here.
7538
+ return;
7539
+ }
7540
+ const locks = await event.manager.query(`SELECT o."key"
7541
+ FROM inventory_count_order_locations l
7542
+ JOIN inventory_count_orders o ON o.id = l."orderId"
7543
+ WHERE l."locationId" = $1
7544
+ AND o.status = 'COUNTING'
7545
+ LIMIT 1`, [locationId]);
7546
+ if (!locks.length) {
7547
+ return;
7548
+ }
7549
+ // Naming the order is the difference between an operator who can go and
7550
+ // settle the count and one who just sees "denied".
7551
+ throw new common.ConflictException(`Location ${locationId} is locked by inventory count order ${locks[0].key}; finish or cancel that count before moving this stock.`);
7552
+ }
7553
+ /**
7554
+ * The location the change ultimately touches, taken from the change's order
7555
+ * item. `beforeInsert` may see the relation either already flattened to
7556
+ * `itemId` or still as the item object, depending on how the caller built the
7557
+ * row, so both are accepted.
7558
+ */
7559
+ async resolveLocationId(event) {
7560
+ const entity = event.entity;
7561
+ if (!entity) {
7562
+ return null;
7563
+ }
7564
+ if (entity.item && entity.item.locationId !== undefined) {
7565
+ return entity.item.locationId;
7566
+ }
7567
+ const itemId = entity.itemId ?? entity.item?.id;
7568
+ if (!itemId) {
7569
+ return null;
7570
+ }
7571
+ const itemRelation = event.metadata.relations.find((relation) => relation.propertyName === 'item');
7572
+ if (!itemRelation) {
7573
+ return null;
7574
+ }
7575
+ const item = await event.manager
7576
+ .getRepository(itemRelation.inverseEntityMetadata.target)
7577
+ .findOne({ where: { id: itemId } });
7578
+ return item?.locationId ?? null;
7579
+ }
7580
+ };
7581
+ exports.InventoryCountLockSubscriber = tslib.__decorate([
7582
+ common.Injectable(),
7583
+ tslib.__param(0, typeorm$1.InjectDataSource()),
7584
+ tslib.__metadata("design:paramtypes", [typeorm.DataSource])
7585
+ ], exports.InventoryCountLockSubscriber);
7586
+
6705
7587
  var WmsModuleCoreModule_1;
6706
7588
  /**
6707
7589
  * The entity Symbols a consumer can rebind, each paired with the base module's
@@ -6799,6 +7681,7 @@ const exportDependencies = [
6799
7681
  exports.MergeBatchOrderService,
6800
7682
  exports.ReclassifyInventoryOrderService,
6801
7683
  exports.ScrapeService,
7684
+ exports.InventoryCountOrderService,
6802
7685
  exports.QualityInspectionOrderService,
6803
7686
  exports.WarehouseMapDataService,
6804
7687
  ];
@@ -6811,9 +7694,13 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
6811
7694
  providers: [
6812
7695
  ...exportDependencies,
6813
7696
  StockChangeSubscriber,
7697
+ exports.InventoryCountLockSubscriber,
6814
7698
  ...resolvedEntityProviders,
6815
7699
  { provide: WMS_CORE_MODULE_OPTIONS, useValue: coreOptions },
6816
- { provide: WMS_STOCK_ENRICH, useValue: !!coreOptions.enrichStockEvents },
7700
+ {
7701
+ provide: WMS_STOCK_ENRICH,
7702
+ useValue: !!coreOptions.enrichStockEvents,
7703
+ },
6817
7704
  ],
6818
7705
  exports: [
6819
7706
  ...exportDependencies,
@@ -6833,6 +7720,7 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
6833
7720
  providers: [
6834
7721
  ...exportDependencies,
6835
7722
  StockChangeSubscriber,
7723
+ exports.InventoryCountLockSubscriber,
6836
7724
  ...resolvedEntityProviders,
6837
7725
  {
6838
7726
  provide: WMS_CORE_MODULE_OPTIONS,
@@ -6860,6 +7748,71 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = tslib.__decorate([
6860
7748
  })
6861
7749
  ], exports.WmsModuleCoreModule);
6862
7750
 
7751
+ /**
7752
+ * Runtime counterpart of {@link WmsOperationName}. Iterate it to build a UI, to
7753
+ * diff against a host's own allow-list, or to assert the invariant above.
7754
+ */
7755
+ const WMS_OPERATION_NAMES = [
7756
+ 'allocate-inventory-order:create',
7757
+ 'allocate-inventory-order:deallocate',
7758
+ 'allocate-inventory-order:read',
7759
+ 'allocate-inventory-order:update',
7760
+ 'batch:merge',
7761
+ 'batch:read',
7762
+ 'batch:split',
7763
+ 'hold-inventory-order:create',
7764
+ 'hold-inventory-order:read',
7765
+ 'hold-inventory-order:release',
7766
+ 'hold-inventory-order:update',
7767
+ 'inventory-count-order:add-item',
7768
+ 'inventory-count-order:cancel',
7769
+ 'inventory-count-order:count',
7770
+ 'inventory-count-order:create',
7771
+ 'inventory-count-order:read',
7772
+ 'inventory-count-order:remove-item',
7773
+ 'inventory-count-order:reset',
7774
+ 'inventory-count-order:settle',
7775
+ 'inventory-count-order:start',
7776
+ 'inventory-count-order:update',
7777
+ 'loader:create',
7778
+ 'loader:read',
7779
+ 'loader:update',
7780
+ 'location:create',
7781
+ 'location:read',
7782
+ 'location:update',
7783
+ 'material:create',
7784
+ 'material:read',
7785
+ 'material:update',
7786
+ 'quality-inspection-order:inspect',
7787
+ 'receive-inventory-order:create',
7788
+ 'receive-inventory-order:read',
7789
+ 'receive-inventory-order:receive',
7790
+ 'receive-inventory-order:update',
7791
+ 'reclassify-inventory-order:reclassify',
7792
+ 'sale-order:read',
7793
+ 'scrape-order:scrape',
7794
+ 'ship-inventory-order:cancel',
7795
+ 'ship-inventory-order:create',
7796
+ 'ship-inventory-order:read',
7797
+ 'ship-inventory-order:ship',
7798
+ 'ship-inventory-order:update',
7799
+ 'stock:read',
7800
+ 'transfer-customer-order:create',
7801
+ 'transfer-customer-order:return',
7802
+ 'transfer-customer-order:update',
7803
+ 'transfer-order:cancel',
7804
+ 'transfer-order:create',
7805
+ 'transfer-order:read',
7806
+ 'transfer-order:transfer',
7807
+ 'transfer-order:update',
7808
+ 'transfer-vendor-order:create',
7809
+ 'transfer-vendor-order:return',
7810
+ 'transfer-vendor-order:update',
7811
+ 'unit:read',
7812
+ 'warehouse-map:read',
7813
+ 'warehouse-map:update',
7814
+ ];
7815
+
6863
7816
  var WmsEventDispatcher_1;
6864
7817
  /**
6865
7818
  * Central event dispatcher. Runs consumer before-hooks (which may veto) and,
@@ -6930,6 +7883,10 @@ exports.BatchGroupEntity = BatchGroupEntity;
6930
7883
  exports.HoldInventoryOrderChangeEntity = HoldInventoryOrderChangeEntity;
6931
7884
  exports.HoldInventoryOrderEntity = HoldInventoryOrderEntity;
6932
7885
  exports.HoldInventoryOrderItemEntity = HoldInventoryOrderItemEntity;
7886
+ exports.InventoryCountOrderChangeEntity = InventoryCountOrderChangeEntity;
7887
+ exports.InventoryCountOrderEntity = InventoryCountOrderEntity;
7888
+ exports.InventoryCountOrderItemEntity = InventoryCountOrderItemEntity;
7889
+ exports.InventoryCountOrderLocationEntity = InventoryCountOrderLocationEntity;
6933
7890
  exports.LoaderTypeEntity = LoaderTypeEntity;
6934
7891
  exports.LoaderUnitEntity = LoaderUnitEntity;
6935
7892
  exports.LoadersEntity = LoadersEntity;
@@ -6975,6 +7932,7 @@ exports.WMS_ACTOR_EXTRACTOR = WMS_ACTOR_EXTRACTOR;
6975
7932
  exports.WMS_CORE_MODULE_OPTIONS = WMS_CORE_MODULE_OPTIONS;
6976
7933
  exports.WMS_EVENT_EMITTER_BRIDGE = WMS_EVENT_EMITTER_BRIDGE;
6977
7934
  exports.WMS_EVENT_OPTIONS = WMS_EVENT_OPTIONS;
7935
+ exports.WMS_OPERATION_NAMES = WMS_OPERATION_NAMES;
6978
7936
  exports.WMS_STOCK_ENRICH = WMS_STOCK_ENRICH;
6979
7937
  exports.WarehouseMapEntity = WarehouseMapEntity;
6980
7938
  exports.collectToScope = collectToScope;