@rytass/wms-module-core 0.5.0 → 0.7.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 (51) hide show
  1. package/README.md +44 -2
  2. package/docs/api-reference.md +37 -1
  3. package/docs/integration-guide.md +18 -17
  4. package/index.cjs.js +1160 -5
  5. package/index.js +7 -0
  6. package/lib/constants/index.d.ts +2 -0
  7. package/lib/constants/inventory-count-status.d.ts +19 -0
  8. package/lib/constants/inventory-count-status.js +22 -0
  9. package/lib/constants/operations.d.ts +34 -0
  10. package/lib/constants/operations.js +67 -0
  11. package/lib/constants/stock-status.d.ts +2 -0
  12. package/lib/constants/stock-status.js +4 -0
  13. package/lib/core.module.js +9 -1
  14. package/lib/events/index.d.ts +1 -0
  15. package/lib/events/inventory-count-lock.subscriber.d.ts +38 -0
  16. package/lib/events/inventory-count-lock.subscriber.js +98 -0
  17. package/lib/events/stock-change.subscriber.js +6 -0
  18. package/lib/events/wms-event.types.d.ts +2 -2
  19. package/lib/models/extensions/index.d.ts +3 -0
  20. package/lib/models/extensions/inventory-count-order/inventory-count-order-change.entity.d.ts +20 -0
  21. package/lib/models/extensions/inventory-count-order/inventory-count-order-change.entity.js +50 -0
  22. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.d.ts +48 -0
  23. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.js +175 -0
  24. package/lib/models/extensions/inventory-count-order/inventory-count-order.entity.d.ts +50 -0
  25. package/lib/models/extensions/inventory-count-order/inventory-count-order.entity.js +155 -0
  26. package/lib/models/models.module.js +7 -0
  27. package/lib/services/allocate-inventory-order.service.js +3 -0
  28. package/lib/services/batch.service.js +3 -0
  29. package/lib/services/hold-inventory-order.service.js +3 -0
  30. package/lib/services/index.d.ts +1 -0
  31. package/lib/services/inventory-count-order.service.d.ts +174 -0
  32. package/lib/services/inventory-count-order.service.js +641 -0
  33. package/lib/services/loader.service.js +3 -0
  34. package/lib/services/location.service.js +3 -0
  35. package/lib/services/material.service.js +3 -0
  36. package/lib/services/merge-batch-order.service.js +3 -0
  37. package/lib/services/quality-inspection-order.service.js +3 -0
  38. package/lib/services/receive-inventory-order.service.js +3 -0
  39. package/lib/services/reclassify-inventory-order.service.js +3 -0
  40. package/lib/services/scrape.service.js +3 -0
  41. package/lib/services/ship-inventory-order.service.js +3 -0
  42. package/lib/services/split-batch-order.service.js +3 -0
  43. package/lib/services/stock.service.js +27 -0
  44. package/lib/services/transfer-customer-order.service.js +3 -0
  45. package/lib/services/transfer-order.service.js +3 -0
  46. package/lib/services/transfer-vendor-order.service.js +3 -0
  47. package/lib/services/unit.service.js +3 -0
  48. package/lib/services/warehouse-map.service.d.ts +11 -1
  49. package/lib/services/warehouse-map.service.js +13 -4
  50. package/lib/typings/find-stock.input.d.ts +16 -0
  51. package/package.json +5 -5
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,367 @@ 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
+ // ── Batch attributes, snapshotted when counting starts ─────────────────── //
2541
+ //
2542
+ // The count sheet shows whether each position was awaiting inspection, held or
2543
+ // in transfer, and which vendor / customer / sale order it belonged to. All of
2544
+ // those live on the batch, which keeps moving after the count is settled — so
2545
+ // they are copied here rather than resolved live. A count completed in June has
2546
+ // to keep showing what June looked like, otherwise the sheet stops being an
2547
+ // audit record of what was found.
2548
+ //
2549
+ // Filled by `start()` for scoped lines and by `addItem()` for additions;
2550
+ // `null` before counting has started.
2551
+ held;
2552
+ inShipment;
2553
+ /** `null` = 待檢驗, `false` = 檢驗失敗, `true` = passed. */
2554
+ inspectionResult;
2555
+ transferId;
2556
+ vendorId;
2557
+ customerId;
2558
+ saleId;
2559
+ saleSerialId;
2560
+ location;
2561
+ loader;
2562
+ order;
2563
+ changes;
2564
+ };
2565
+ tslib.__decorate([
2566
+ typeorm.PrimaryGeneratedColumn('uuid'),
2567
+ tslib.__metadata("design:type", String)
2568
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "id", void 0);
2569
+ tslib.__decorate([
2570
+ typeorm.Column({ type: 'uuid' }),
2571
+ typeorm.Index(),
2572
+ tslib.__metadata("design:type", String)
2573
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "orderId", void 0);
2574
+ tslib.__decorate([
2575
+ typeorm.Column({ type: 'uuid' }),
2576
+ typeorm.Index(),
2577
+ tslib.__metadata("design:type", String)
2578
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "materialId", void 0);
2579
+ tslib.__decorate([
2580
+ typeorm.Column({ type: 'uuid' }),
2581
+ typeorm.Index(),
2582
+ tslib.__metadata("design:type", String)
2583
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "batchId", void 0);
2584
+ tslib.__decorate([
2585
+ typeorm.Column({ type: 'uuid', nullable: true }),
2586
+ typeorm.Index(),
2587
+ tslib.__metadata("design:type", Object)
2588
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "locationId", void 0);
2589
+ tslib.__decorate([
2590
+ typeorm.Column({ type: 'uuid', nullable: true }),
2591
+ typeorm.Index(),
2592
+ tslib.__metadata("design:type", Object)
2593
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "loaderId", void 0);
2594
+ tslib.__decorate([
2595
+ typeorm.Column({ type: 'uuid', nullable: true }),
2596
+ typeorm.Index(),
2597
+ tslib.__metadata("design:type", Object)
2598
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "unitId", void 0);
2599
+ tslib.__decorate([
2600
+ typeorm.Column({ type: 'numeric', default: 0 }),
2601
+ tslib.__metadata("design:type", Number)
2602
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "bookQuantity", void 0);
2603
+ tslib.__decorate([
2604
+ typeorm.Column({ type: 'numeric', nullable: true }),
2605
+ tslib.__metadata("design:type", Object)
2606
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "countedQuantity", void 0);
2607
+ tslib.__decorate([
2608
+ typeorm.Column({ type: 'boolean', default: false }),
2609
+ tslib.__metadata("design:type", Boolean)
2610
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "isAddition", void 0);
2611
+ tslib.__decorate([
2612
+ typeorm.Column({ type: 'boolean', nullable: true }),
2613
+ tslib.__metadata("design:type", Object)
2614
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "held", void 0);
2615
+ tslib.__decorate([
2616
+ typeorm.Column({ type: 'boolean', nullable: true }),
2617
+ tslib.__metadata("design:type", Object)
2618
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "inShipment", void 0);
2619
+ tslib.__decorate([
2620
+ typeorm.Column({ type: 'boolean', nullable: true }),
2621
+ tslib.__metadata("design:type", Object)
2622
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "inspectionResult", void 0);
2623
+ tslib.__decorate([
2624
+ typeorm.Column({ type: 'uuid', nullable: true }),
2625
+ tslib.__metadata("design:type", Object)
2626
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "transferId", void 0);
2627
+ tslib.__decorate([
2628
+ typeorm.Column({ type: 'varchar', nullable: true }),
2629
+ tslib.__metadata("design:type", Object)
2630
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "vendorId", void 0);
2631
+ tslib.__decorate([
2632
+ typeorm.Column({ type: 'varchar', nullable: true }),
2633
+ tslib.__metadata("design:type", Object)
2634
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "customerId", void 0);
2635
+ tslib.__decorate([
2636
+ typeorm.Column({ type: 'varchar', nullable: true }),
2637
+ tslib.__metadata("design:type", Object)
2638
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "saleId", void 0);
2639
+ tslib.__decorate([
2640
+ typeorm.Column({ type: 'varchar', nullable: true }),
2641
+ tslib.__metadata("design:type", Object)
2642
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "saleSerialId", void 0);
2643
+ tslib.__decorate([
2644
+ typeorm.ManyToOne('locations'),
2645
+ typeorm.JoinColumn({ name: 'locationId', referencedColumnName: 'id' }),
2646
+ tslib.__metadata("design:type", exports.LocationEntityClass)
2647
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "location", void 0);
2648
+ tslib.__decorate([
2649
+ typeorm.ManyToOne('loaders'),
2650
+ typeorm.JoinColumn({ name: 'loaderId', referencedColumnName: 'id' }),
2651
+ tslib.__metadata("design:type", exports.LoadersEntityClass)
2652
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "loader", void 0);
2653
+ tslib.__decorate([
2654
+ typeorm.ManyToOne('inventory_count_orders', (order) => order.items),
2655
+ typeorm.JoinColumn({ name: 'orderId', referencedColumnName: 'id' }),
2656
+ tslib.__metadata("design:type", exports.InventoryCountOrderEntityClass)
2657
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "order", void 0);
2658
+ tslib.__decorate([
2659
+ typeorm.OneToMany('inventory_count_order_changes', (change) => change.item),
2660
+ tslib.__metadata("design:type", Array)
2661
+ ], exports.InventoryCountOrderItemEntityClass.prototype, "changes", void 0);
2662
+ exports.InventoryCountOrderItemEntityClass = tslib.__decorate([
2663
+ typeorm.Entity('inventory_count_order_items'),
2664
+ typeorm.TableInheritance({ column: { type: 'varchar', name: 'entityName' } })
2665
+ ], exports.InventoryCountOrderItemEntityClass);
2666
+
2667
+ const InventoryCountOrderChangeEntity = Symbol('InventoryCountOrderChangeEntity');
2668
+ /**
2669
+ * The stock movement a settled count line produced.
2670
+ *
2671
+ * `quantityChanged` carries the sign, exactly like every other `*_order_change`
2672
+ * table: positive is a surplus (盤盈), negative a shortage (盤虧).
2673
+ * `StockChangeSubscriber` reads the sign to pick between `stock.count-gained`
2674
+ * and `stock.count-lost`, so nothing here has to emit events itself.
2675
+ *
2676
+ * Lines whose count matched the books produce no row at all.
2677
+ */
2678
+ exports.InventoryCountOrderChangeEntityClass = class InventoryCountOrderChangeEntityClass {
2679
+ id;
2680
+ itemId;
2681
+ quantityChanged;
2682
+ order;
2683
+ item;
2684
+ };
2685
+ tslib.__decorate([
2686
+ typeorm.PrimaryGeneratedColumn('uuid'),
2687
+ tslib.__metadata("design:type", String)
2688
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "id", void 0);
2689
+ tslib.__decorate([
2690
+ typeorm.Column({ type: 'uuid' }),
2691
+ tslib.__metadata("design:type", String)
2692
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "itemId", void 0);
2693
+ tslib.__decorate([
2694
+ typeorm.Column({ type: 'numeric' }),
2695
+ tslib.__metadata("design:type", Number)
2696
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "quantityChanged", void 0);
2697
+ tslib.__decorate([
2698
+ typeorm.OneToOne('orders'),
2699
+ typeorm.JoinColumn({ name: 'id', referencedColumnName: 'id' }),
2700
+ tslib.__metadata("design:type", wmsBaseNestjsModule.OrderEntity)
2701
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "order", void 0);
2702
+ tslib.__decorate([
2703
+ typeorm.ManyToOne('inventory_count_order_items', (item) => item.changes),
2704
+ typeorm.JoinColumn({ name: 'itemId', referencedColumnName: 'id' }),
2705
+ tslib.__metadata("design:type", exports.InventoryCountOrderItemEntityClass)
2706
+ ], exports.InventoryCountOrderChangeEntityClass.prototype, "item", void 0);
2707
+ exports.InventoryCountOrderChangeEntityClass = tslib.__decorate([
2708
+ typeorm.Entity('inventory_count_order_changes')
2709
+ ], exports.InventoryCountOrderChangeEntityClass);
2710
+
2346
2711
  const entities = [
2347
2712
  [UnitEntity, exports.UnitEntityClass],
2348
2713
  [MaterialEntity, exports.MaterialEntityClass],
@@ -2396,6 +2761,10 @@ const entities = [
2396
2761
  [ScrapeOrderEntity, exports.ScrapeOrderEntityClass],
2397
2762
  [ScrapeOrderItemEntity, exports.ScrapeOrderItemEntityClass],
2398
2763
  [ScrapeOrderChangeEntity, exports.ScrapeOrderChangeEntityClass],
2764
+ [InventoryCountOrderEntity, exports.InventoryCountOrderEntityClass],
2765
+ [InventoryCountOrderLocationEntity, exports.InventoryCountOrderLocationEntityClass],
2766
+ [InventoryCountOrderItemEntity, exports.InventoryCountOrderItemEntityClass],
2767
+ [InventoryCountOrderChangeEntity, exports.InventoryCountOrderChangeEntityClass],
2399
2768
  ];
2400
2769
  /**
2401
2770
  * The overridable entities are deliberately absent: `WmsModuleCoreModule` binds
@@ -2708,6 +3077,30 @@ exports.StockService = class StockService {
2708
3077
  queryBuilder.innerJoin(exports.LoadersEntityClass, 'lk', 'lk.id = stock."loaderId" AND lk."serialId" ILIKE :loaderKey', {
2709
3078
  loaderKey: `%${options.loaderKey}%`,
2710
3079
  });
3080
+ /*
3081
+ * Vendor / customer / sale order live on the batch, so they need their own
3082
+ * join. One join for all four rather than four joins: they are conditions on
3083
+ * the same row, and repeating the join would multiply nothing but the plan.
3084
+ *
3085
+ * Exact match, not ILIKE: these are identifiers handed over by the host
3086
+ * system, and a partial match on 「SO-1」 quietly sweeping in 「SO-10」 is the
3087
+ * kind of wrong answer nobody notices. It also keeps this in step with the
3088
+ * inventory count sheet, whose four filters match the same way.
3089
+ */
3090
+ const batchAttributeFilters = [
3091
+ ['vendorId', options.vendorId],
3092
+ ['customerId', options.customerId],
3093
+ ['saleId', options.saleId],
3094
+ ['saleSerialId', options.saleSerialId],
3095
+ ].filter(([, value]) => Boolean(value));
3096
+ if (batchAttributeFilters.length) {
3097
+ queryBuilder.innerJoin(this.entities.batch, 'ba', 'ba.id = stock."batchId"');
3098
+ for (const [column, value] of batchAttributeFilters) {
3099
+ queryBuilder.andWhere(`ba."${column}" = :${column}`, {
3100
+ [column]: value,
3101
+ });
3102
+ }
3103
+ }
2711
3104
  if (options.offset !== undefined && options.offset >= 0)
2712
3105
  queryBuilder.skip(options.offset);
2713
3106
  if (options.limit !== undefined && options.limit > 0)
@@ -6419,6 +6812,584 @@ exports.SaleOrderService = tslib.__decorate([
6419
6812
  tslib.__metadata("design:paramtypes", [typeorm.DataSource])
6420
6813
  ], exports.SaleOrderService);
6421
6814
 
6815
+ /**
6816
+ * Inventory counting: compare the ledger against what is physically there, then
6817
+ * adjust the ledger to match.
6818
+ *
6819
+ * The shape follows the "D. 盤點" design flow. Three properties are worth
6820
+ * stating up front because everything else follows from them:
6821
+ *
6822
+ * - **Counting never moves stock between locations.** A line that is in the
6823
+ * wrong place is a transfer, not a count; `transfer-order:create` already does
6824
+ * that. This service only ever adjusts quantity, up or down, in place.
6825
+ * - **Nothing touches stock until settlement.** Counted quantities are working
6826
+ * notes ("暫存的對帳資料"); only {@link settle} writes changes, and it does so
6827
+ * in a single transaction.
6828
+ * - **Starting a count locks its locations.** The book snapshot taken at
6829
+ * {@link start} would be worthless if stock kept moving underneath it, so
6830
+ * `InventoryCountLockSubscriber` refuses every other stock movement in the
6831
+ * scope until the order settles or is cancelled.
6832
+ */
6833
+ exports.InventoryCountOrderService = class InventoryCountOrderService {
6834
+ dataSource;
6835
+ entities;
6836
+ helperService;
6837
+ materialService;
6838
+ stockService;
6839
+ batchService;
6840
+ inventoryCountOrderEntity;
6841
+ seqPrefix = 'ICO';
6842
+ constructor(dataSource, entities, helperService, materialService, stockService, batchService, inventoryCountOrderEntity) {
6843
+ this.dataSource = dataSource;
6844
+ this.entities = entities;
6845
+ this.helperService = helperService;
6846
+ this.materialService = materialService;
6847
+ this.stockService = stockService;
6848
+ this.batchService = batchService;
6849
+ this.inventoryCountOrderEntity = inventoryCountOrderEntity;
6850
+ }
6851
+ getRepositories(manager) {
6852
+ return {
6853
+ order: manager.getRepository(this.inventoryCountOrderEntity),
6854
+ scope: manager.getRepository(exports.InventoryCountOrderLocationEntityClass),
6855
+ item: manager.getRepository(exports.InventoryCountOrderItemEntityClass),
6856
+ change: manager.getRepository(exports.InventoryCountOrderChangeEntityClass),
6857
+ baseOrder: manager.getRepository(this.entities.order),
6858
+ stock: manager.getRepository(this.entities.stock),
6859
+ };
6860
+ }
6861
+ /**
6862
+ * Expand chosen locations into themselves plus every descendant.
6863
+ *
6864
+ * `LocationEntity` is a plain adjacency list (`parent` / `children`) with no
6865
+ * materialised path, so the subtree needs a recursive CTE. It runs once per
6866
+ * scope change and the result is stored, precisely so the lock check never has
6867
+ * to run it.
6868
+ */
6869
+ async expandLocationScope(rootIds, manager) {
6870
+ if (!rootIds.length) {
6871
+ return [];
6872
+ }
6873
+ const table = manager.getRepository(this.entities.location).metadata
6874
+ .tableName;
6875
+ const rows = await manager.query(`WITH RECURSIVE subtree AS (
6876
+ SELECT id FROM "${table}" WHERE id = ANY($1)
6877
+ UNION
6878
+ SELECT child.id
6879
+ FROM "${table}" child
6880
+ JOIN subtree parent ON child."parentId" = parent.id
6881
+ )
6882
+ SELECT id FROM subtree`, [[...rootIds]]);
6883
+ const roots = new Set(rootIds);
6884
+ return rows.map(({ id }) => ({ id, isRoot: roots.has(id) }));
6885
+ }
6886
+ /** Current ledger quantity per physical position inside the scope. */
6887
+ async readPositions(locationIds, manager) {
6888
+ if (!locationIds.length) {
6889
+ return [];
6890
+ }
6891
+ // The batch table is joined by name rather than through its repository
6892
+ // because it is only read for its attribute columns — the same thing
6893
+ // `StockService.selectQueryBuilder` does. Single-table inheritance means
6894
+ // every configured batch entity shares this table, so the join is override
6895
+ // safe; the name still comes from the configured entity's metadata rather
6896
+ // than being hard-coded.
6897
+ const batchTable = manager.getRepository(this.entities.batch).metadata
6898
+ .tableName;
6899
+ // Through the repository, not raw SQL on the table: the stock entity is
6900
+ // overridable, and the repository is what applies the right
6901
+ // single-table-inheritance discriminator.
6902
+ const rows = await manager
6903
+ .getRepository(this.entities.stock)
6904
+ .createQueryBuilder('stock')
6905
+ .leftJoin(batchTable, 'batch', 'batch.id = stock."batchId"')
6906
+ .select('stock.materialId', 'materialId')
6907
+ .addSelect('stock.batchId', 'batchId')
6908
+ .addSelect('stock.locationId', 'locationId')
6909
+ .addSelect('stock.loaderId', 'loaderId')
6910
+ .addSelect('SUM(stock.quantity)', 'quantity')
6911
+ .addSelect('batch.held', 'held')
6912
+ .addSelect('batch."inShipment"', 'inShipment')
6913
+ .addSelect('batch."inspectionResult"', 'inspectionResult')
6914
+ .addSelect('batch."transferId"', 'transferId')
6915
+ .addSelect('batch."vendorId"', 'vendorId')
6916
+ .addSelect('batch."customerId"', 'customerId')
6917
+ .addSelect('batch."saleId"', 'saleId')
6918
+ .addSelect('batch."saleSerialId"', 'saleSerialId')
6919
+ .where('stock.locationId IN (:...locationIds)', {
6920
+ locationIds: [...locationIds],
6921
+ })
6922
+ .groupBy('stock.materialId')
6923
+ .addGroupBy('stock.batchId')
6924
+ .addGroupBy('stock.locationId')
6925
+ .addGroupBy('stock.loaderId')
6926
+ // Functionally dependent on batchId, but PostgreSQL only infers that from
6927
+ // the grouped table's own primary key, so they have to be listed.
6928
+ .addGroupBy('batch.held')
6929
+ .addGroupBy('batch."inShipment"')
6930
+ .addGroupBy('batch."inspectionResult"')
6931
+ .addGroupBy('batch."transferId"')
6932
+ .addGroupBy('batch."vendorId"')
6933
+ .addGroupBy('batch."customerId"')
6934
+ .addGroupBy('batch."saleId"')
6935
+ .addGroupBy('batch."saleSerialId"')
6936
+ .having('SUM(stock.quantity) > 0')
6937
+ .getRawMany();
6938
+ return rows.map((row) => ({
6939
+ materialId: row.materialId,
6940
+ batchId: row.batchId,
6941
+ locationId: row.locationId,
6942
+ loaderId: row.loaderId,
6943
+ quantity: Number(row.quantity),
6944
+ attributes: {
6945
+ held: row.held ?? null,
6946
+ inShipment: row.inShipment ?? null,
6947
+ inspectionResult: row.inspectionResult ?? null,
6948
+ transferId: row.transferId ?? null,
6949
+ vendorId: row.vendorId ?? null,
6950
+ customerId: row.customerId ?? null,
6951
+ saleId: row.saleId ?? null,
6952
+ saleSerialId: row.saleSerialId ?? null,
6953
+ },
6954
+ }));
6955
+ }
6956
+ positionKey(position) {
6957
+ return [
6958
+ position.materialId,
6959
+ position.batchId,
6960
+ position.locationId ?? '',
6961
+ position.loaderId ?? '',
6962
+ ].join('|');
6963
+ }
6964
+ async scopedLocationIds(orderId, manager) {
6965
+ const rows = await this.getRepositories(manager).scope.find({
6966
+ where: { orderId },
6967
+ select: { locationId: true },
6968
+ });
6969
+ return rows.map(({ locationId }) => locationId);
6970
+ }
6971
+ async loadOrderOrFail(id, manager) {
6972
+ const order = await this.getRepositories(manager).order.findOneBy({ id });
6973
+ if (!order) {
6974
+ throw new common.NotFoundException(`Inventory count order ${id} not found`);
6975
+ }
6976
+ return order;
6977
+ }
6978
+ assertStatus(order, allowed) {
6979
+ if (!allowed.includes(order.status)) {
6980
+ throw new common.BadRequestException(`Inventory count order ${order.id} is ${order.status}; this operation requires ${allowed.join(' or ')}`);
6981
+ }
6982
+ }
6983
+ /**
6984
+ * Rebuild the sheet from the current ledger.
6985
+ *
6986
+ * Called when the scope changes and again when counting starts. Additions
6987
+ * (盤盈 lines) are never touched — they describe stock the ledger does not know
6988
+ * about, so a rebuild has nothing to say about them.
6989
+ */
6990
+ async rebuildItems(orderId, manager) {
6991
+ const repos = this.getRepositories(manager);
6992
+ const locationIds = await this.scopedLocationIds(orderId, manager);
6993
+ const positions = await this.readPositions(locationIds, manager);
6994
+ const existing = await repos.item.find({
6995
+ where: { orderId, isAddition: false },
6996
+ });
6997
+ const byKey = new Map(existing.map((item) => [this.positionKey(item), item]));
6998
+ const seen = new Set();
6999
+ for (const position of positions) {
7000
+ const key = this.positionKey(position);
7001
+ seen.add(key);
7002
+ const item = byKey.get(key);
7003
+ if (item) {
7004
+ item.bookQuantity = position.quantity;
7005
+ Object.assign(item, position.attributes);
7006
+ await repos.item.save(item);
7007
+ continue;
7008
+ }
7009
+ await repos.item.save(repos.item.create({
7010
+ orderId,
7011
+ materialId: position.materialId,
7012
+ batchId: position.batchId,
7013
+ locationId: position.locationId,
7014
+ loaderId: position.loaderId,
7015
+ bookQuantity: position.quantity,
7016
+ countedQuantity: null,
7017
+ unitId: null,
7018
+ isAddition: false,
7019
+ ...position.attributes,
7020
+ }));
7021
+ }
7022
+ // A position that emptied out between two rebuilds is no longer on the
7023
+ // sheet; it cannot be counted and would settle to a meaningless zero.
7024
+ const stale = existing.filter((item) => !seen.has(this.positionKey(item)));
7025
+ if (stale.length) {
7026
+ await repos.item.delete({ id: typeorm.In(stale.map(({ id }) => id)) });
7027
+ }
7028
+ }
7029
+ /** Filters for the list page. All optional; combined with AND. */
7030
+ async findMany(options, manager = this.dataSource.manager) {
7031
+ const query = this.getRepositories(manager)
7032
+ // The alias is lowercase and is deliberately not `order`. `order` is a
7033
+ // PostgreSQL reserved word, so the raw fragments below would render
7034
+ // `order."countDate"` and fail to parse; and a camelCase alias would be
7035
+ // emitted quoted by the query builder while the unquoted references here
7036
+ // fold to lowercase, so the two would never match.
7037
+ .order.createQueryBuilder('count_order')
7038
+ .orderBy('count_order."countDate"', 'DESC')
7039
+ .addOrderBy('count_order."createdAt"', 'DESC');
7040
+ if (options.name) {
7041
+ query.andWhere('count_order.name ILIKE :name', {
7042
+ name: `%${options.name}%`,
7043
+ });
7044
+ }
7045
+ if (options.statuses?.length) {
7046
+ query.andWhere('count_order.status IN (:...statuses)', {
7047
+ statuses: options.statuses,
7048
+ });
7049
+ }
7050
+ if (options.createdBy) {
7051
+ query.andWhere('count_order."createdBy" = :createdBy', {
7052
+ createdBy: options.createdBy,
7053
+ });
7054
+ }
7055
+ if (options.countDateFrom) {
7056
+ query.andWhere('count_order."countDate" >= :from', {
7057
+ from: options.countDateFrom,
7058
+ });
7059
+ }
7060
+ if (options.countDateTo) {
7061
+ query.andWhere('count_order."countDate" <= :to', {
7062
+ to: options.countDateTo,
7063
+ });
7064
+ }
7065
+ if (options.locationIds?.length) {
7066
+ // Scope membership, not the roots the user picked: a count of a whole
7067
+ // aisle should surface when filtering by any shelf inside it.
7068
+ query.andWhere(`EXISTS (
7069
+ SELECT 1 FROM inventory_count_order_locations scope
7070
+ WHERE scope."orderId" = count_order.id
7071
+ AND scope."locationId" IN (:...locationIds)
7072
+ )`, { locationIds: options.locationIds });
7073
+ }
7074
+ if (options.offset !== undefined && options.offset >= 0) {
7075
+ query.skip(options.offset);
7076
+ }
7077
+ if (options.limit !== undefined && options.limit > 0) {
7078
+ query.take(options.limit);
7079
+ }
7080
+ return query.getManyAndCount();
7081
+ }
7082
+ async findOne(id, manager = this.dataSource.manager) {
7083
+ return this.loadOrderOrFail(id, manager);
7084
+ }
7085
+ /**
7086
+ * The count sheet, filtered and paginated.
7087
+ *
7088
+ * Server-side rather than handing the whole sheet to the client: a count over
7089
+ * a whole warehouse is thousands of lines, and the operator's job is to narrow
7090
+ * to the shelf in front of them.
7091
+ */
7092
+ async findItems(orderId, options = {}, manager = this.dataSource.manager) {
7093
+ const tableOf = (entity) => manager.getRepository(entity).metadata.tableName;
7094
+ const query = this.getRepositories(manager)
7095
+ .item.createQueryBuilder('item')
7096
+ .leftJoin(tableOf(this.entities.material), 'material', 'material.id = item."materialId"')
7097
+ .leftJoin(tableOf(this.entities.batch), 'batch', 'batch.id = item."batchId"')
7098
+ .leftJoin(tableOf(this.entities.location), 'location', 'location.id = item."locationId"')
7099
+ .leftJoin(exports.LoadersEntityClass, 'loader', 'loader.id = item."loaderId"')
7100
+ .where('item."orderId" = :orderId', { orderId });
7101
+ const like = (column, value, parameter) => {
7102
+ if (!value)
7103
+ return;
7104
+ query.andWhere(`${column} ILIKE :${parameter}`, {
7105
+ [parameter]: `%${value}%`,
7106
+ });
7107
+ };
7108
+ like('material.key', options.materialKey, 'materialKey');
7109
+ like('material.description', options.materialDescription, 'materialDescription');
7110
+ like('batch.key', options.batchKey, 'batchKey');
7111
+ like('location.key', options.locationKey, 'locationKey');
7112
+ like('loader."serialId"', options.loaderSerialId, 'loaderSerialId');
7113
+ const exact = (column, value, parameter) => {
7114
+ if (!value)
7115
+ return;
7116
+ query.andWhere(`${column} = :${parameter}`, { [parameter]: value });
7117
+ };
7118
+ exact('item."vendorId"', options.vendorId, 'vendorId');
7119
+ exact('item."customerId"', options.customerId, 'customerId');
7120
+ exact('item."saleId"', options.saleId, 'saleId');
7121
+ exact('item."saleSerialId"', options.saleSerialId, 'saleSerialId');
7122
+ if (options.onlyVariance) {
7123
+ // The counted quantity is expressed in the line's unit, so it has to be
7124
+ // converted before it can be compared with the base-unit book quantity —
7125
+ // the same conversion settlement applies.
7126
+ query
7127
+ .leftJoin(exports.MaterialUnitEntityClass, 'unit', 'unit.id = item."unitId"')
7128
+ .andWhere('item."countedQuantity" IS NOT NULL')
7129
+ .andWhere('item."countedQuantity" * COALESCE(unit."conversionFactor", 1) <> item."bookQuantity"');
7130
+ }
7131
+ // Counted before ordering and paginating: `getCount()` rewrites the query
7132
+ // into a COUNT, and an ORDER BY on a joined column it does not select makes
7133
+ // that rewrite fail.
7134
+ const total = await query.getCount();
7135
+ // Additions first — they are what the operator just typed — then a stable
7136
+ // order so paging cannot repeat or skip a line.
7137
+ query
7138
+ .orderBy('item."isAddition"', 'DESC')
7139
+ .addOrderBy('material.key', 'ASC')
7140
+ .addOrderBy('batch.key', 'ASC')
7141
+ .addOrderBy('item.id', 'ASC');
7142
+ // `limit`/`offset` rather than `take`/`skip`: the latter wraps the query in a
7143
+ // DISTINCT subquery to survive one-to-many joins, and then cannot map an
7144
+ // ORDER BY on a joined column into it. Every join here is many-to-one, so no
7145
+ // row multiplication and no need for that machinery.
7146
+ if (options.offset !== undefined && options.offset >= 0) {
7147
+ query.offset(options.offset);
7148
+ }
7149
+ if (options.limit !== undefined && options.limit > 0) {
7150
+ query.limit(options.limit);
7151
+ }
7152
+ return [await query.getMany(), total];
7153
+ }
7154
+ async create(input, manager = this.dataSource.manager) {
7155
+ if (!input.locationIds.length) {
7156
+ throw new common.BadRequestException('An inventory count needs at least one location in scope');
7157
+ }
7158
+ const repos = this.getRepositories(manager);
7159
+ const key = await this.helperService.getSeq(this.seqPrefix, manager);
7160
+ const order = await repos.order.save(repos.order.create({
7161
+ key,
7162
+ name: input.name,
7163
+ countDate: input.countDate,
7164
+ status: exports.InventoryCountStatus.PENDING,
7165
+ createdBy: input.createdBy ?? null,
7166
+ }));
7167
+ const scope = await this.expandLocationScope(input.locationIds, manager);
7168
+ await repos.scope.save(scope.map(({ id, isRoot }) => repos.scope.create({ orderId: order.id, locationId: id, isRoot })));
7169
+ await this.rebuildItems(order.id, manager);
7170
+ return order;
7171
+ }
7172
+ async update(id, input, manager = this.dataSource.manager) {
7173
+ const repos = this.getRepositories(manager);
7174
+ const order = await this.loadOrderOrFail(id, manager);
7175
+ // The design keeps the info panel editable only while nothing has been
7176
+ // counted; afterwards the sheet is already anchored to this scope and date.
7177
+ this.assertStatus(order, [exports.InventoryCountStatus.PENDING]);
7178
+ if (input.name !== undefined)
7179
+ order.name = input.name;
7180
+ if (input.countDate !== undefined)
7181
+ order.countDate = input.countDate;
7182
+ await repos.order.save(order);
7183
+ if (input.locationIds) {
7184
+ if (!input.locationIds.length) {
7185
+ throw new common.BadRequestException('An inventory count needs at least one location in scope');
7186
+ }
7187
+ await repos.scope.delete({ orderId: id });
7188
+ const scope = await this.expandLocationScope(input.locationIds, manager);
7189
+ await repos.scope.save(scope.map(({ id: locationId, isRoot }) => repos.scope.create({ orderId: id, locationId, isRoot })));
7190
+ await this.rebuildItems(id, manager);
7191
+ }
7192
+ return order;
7193
+ }
7194
+ /**
7195
+ * Freeze the ledger and open the sheet for counting.
7196
+ *
7197
+ * The rebuild here is the snapshot: from this point `bookQuantity` is what the
7198
+ * variance is measured against, and the lock keeps it true.
7199
+ */
7200
+ async start(id, manager = this.dataSource.manager) {
7201
+ const repos = this.getRepositories(manager);
7202
+ const order = await this.loadOrderOrFail(id, manager);
7203
+ this.assertStatus(order, [exports.InventoryCountStatus.PENDING]);
7204
+ await this.rebuildItems(id, manager);
7205
+ order.status = exports.InventoryCountStatus.COUNTING;
7206
+ order.startedAt = new Date();
7207
+ await repos.order.save(order);
7208
+ return order;
7209
+ }
7210
+ /** Save counted quantities without touching stock ("暫存結果"). */
7211
+ async count(id, entries, manager = this.dataSource.manager) {
7212
+ const repos = this.getRepositories(manager);
7213
+ const order = await this.loadOrderOrFail(id, manager);
7214
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7215
+ if (!entries.length) {
7216
+ return order;
7217
+ }
7218
+ const items = await repos.item.find({
7219
+ where: { orderId: id, id: typeorm.In(entries.map(({ itemId }) => itemId)) },
7220
+ });
7221
+ const byId = new Map(items.map((item) => [item.id, item]));
7222
+ for (const entry of entries) {
7223
+ const item = byId.get(entry.itemId);
7224
+ if (!item) {
7225
+ throw new common.NotFoundException(`Item ${entry.itemId} does not belong to inventory count order ${id}`);
7226
+ }
7227
+ if (entry.countedQuantity !== null &&
7228
+ (!Number.isFinite(entry.countedQuantity) || entry.countedQuantity < 0)) {
7229
+ throw new common.BadRequestException(`Counted quantity for item ${entry.itemId} must be a non-negative number`);
7230
+ }
7231
+ item.countedQuantity = entry.countedQuantity;
7232
+ if (entry.unitId !== undefined) {
7233
+ item.unitId = entry.unitId;
7234
+ }
7235
+ await repos.item.save(item);
7236
+ }
7237
+ return order;
7238
+ }
7239
+ /**
7240
+ * Add a line for stock the ledger has no record of (盤盈).
7241
+ *
7242
+ * The batch is resolved by key and created when it does not exist, which is
7243
+ * what makes "the batch field's default is editable" in the design work.
7244
+ */
7245
+ async addItem(id, input, manager = this.dataSource.manager) {
7246
+ const repos = this.getRepositories(manager);
7247
+ const order = await this.loadOrderOrFail(id, manager);
7248
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7249
+ if (!Number.isFinite(input.countedQuantity) || input.countedQuantity <= 0) {
7250
+ throw new common.BadRequestException('An added inventory count line needs a positive counted quantity');
7251
+ }
7252
+ const scoped = await this.scopedLocationIds(id, manager);
7253
+ // Settlement writes stock at this location, so it has to be one the order
7254
+ // locked — otherwise the count would adjust a position other operations are
7255
+ // still free to move.
7256
+ if (!scoped.includes(input.locationId)) {
7257
+ throw new common.BadRequestException(`Location ${input.locationId} is outside the scope of inventory count order ${id}`);
7258
+ }
7259
+ const batch = await this.batchService.getBatch({
7260
+ key: input.batchKey,
7261
+ materialId: input.materialId,
7262
+ manager,
7263
+ });
7264
+ return repos.item.save(repos.item.create({
7265
+ orderId: id,
7266
+ materialId: input.materialId,
7267
+ batchId: batch.id,
7268
+ locationId: input.locationId,
7269
+ loaderId: input.loaderId ?? null,
7270
+ unitId: input.unitId ?? null,
7271
+ bookQuantity: 0,
7272
+ countedQuantity: input.countedQuantity,
7273
+ isAddition: true,
7274
+ // Snapshotted from the batch the same way a scoped line is, so an added
7275
+ // line renders through the identical columns. A brand-new batch carries
7276
+ // the defaults, which is exactly right: unbooked stock is not held, not
7277
+ // in transfer and not inspected.
7278
+ held: batch.held ?? null,
7279
+ inShipment: batch.inShipment ?? null,
7280
+ inspectionResult: batch.inspectionResult ?? null,
7281
+ transferId: batch.transferId ?? null,
7282
+ vendorId: batch.vendorId ?? null,
7283
+ customerId: batch.customerId ?? null,
7284
+ saleId: batch.saleId ?? null,
7285
+ saleSerialId: batch.saleSerialId ?? null,
7286
+ }));
7287
+ }
7288
+ /** Remove an added line. Scoped lines are part of the sheet and never removed. */
7289
+ async removeItem(id, itemId, manager = this.dataSource.manager) {
7290
+ const repos = this.getRepositories(manager);
7291
+ const order = await this.loadOrderOrFail(id, manager);
7292
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7293
+ const item = await repos.item.findOneBy({ id: itemId, orderId: id });
7294
+ if (!item) {
7295
+ throw new common.NotFoundException(`Item ${itemId} does not belong to inventory count order ${id}`);
7296
+ }
7297
+ if (!item.isAddition) {
7298
+ throw new common.BadRequestException(`Item ${itemId} came from the counted scope and cannot be removed`);
7299
+ }
7300
+ await repos.item.delete({ id: itemId });
7301
+ return order;
7302
+ }
7303
+ /**
7304
+ * Throw the counting away and start over, without leaving the count.
7305
+ *
7306
+ * The scope stays locked and the status stays `COUNTING`: the point is a
7307
+ * re-measure after something went wrong on the floor, not an abandonment. The
7308
+ * book snapshot is deliberately *not* retaken — the lock means it has not
7309
+ * moved.
7310
+ */
7311
+ async reset(id, manager = this.dataSource.manager) {
7312
+ const repos = this.getRepositories(manager);
7313
+ const order = await this.loadOrderOrFail(id, manager);
7314
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7315
+ await repos.item.delete({ orderId: id, isAddition: true });
7316
+ await repos.item.update({ orderId: id }, { countedQuantity: null, unitId: null });
7317
+ return order;
7318
+ }
7319
+ async cancel(id, manager = this.dataSource.manager) {
7320
+ const repos = this.getRepositories(manager);
7321
+ const order = await this.loadOrderOrFail(id, manager);
7322
+ this.assertStatus(order, [
7323
+ exports.InventoryCountStatus.PENDING,
7324
+ exports.InventoryCountStatus.COUNTING,
7325
+ ]);
7326
+ order.status = exports.InventoryCountStatus.CANCELLED;
7327
+ order.cancelledAt = new Date();
7328
+ await repos.order.save(order);
7329
+ return order;
7330
+ }
7331
+ /**
7332
+ * Adjust the ledger to the counted reality ("執行盤差").
7333
+ *
7334
+ * Runs in one transaction and is awaited end to end, so the mutation
7335
+ * interceptor's post-commit guarantee holds: every `stock.count-gained` /
7336
+ * `stock.count-lost` event fires only after the adjustments are durable.
7337
+ *
7338
+ * Uncounted lines are left alone — "not counted" is not "counted as zero", and
7339
+ * treating it as zero would wipe out stock nobody looked at.
7340
+ */
7341
+ async settle(id, outerManager) {
7342
+ const run = async (manager) => {
7343
+ const repos = this.getRepositories(manager);
7344
+ const order = await this.loadOrderOrFail(id, manager);
7345
+ this.assertStatus(order, [exports.InventoryCountStatus.COUNTING]);
7346
+ const items = await repos.item.find({ where: { orderId: id } });
7347
+ for (const item of items) {
7348
+ if (item.countedQuantity === null) {
7349
+ continue;
7350
+ }
7351
+ const conversionFactor = await this.materialService.getConversionFactor(item.materialId, item.unitId ?? undefined);
7352
+ const counted = Number(item.countedQuantity) * conversionFactor;
7353
+ const delta = counted - Number(item.bookQuantity);
7354
+ if (delta === 0) {
7355
+ continue;
7356
+ }
7357
+ const baseOrder = await repos.baseOrder.save({});
7358
+ await repos.change.save(repos.change.create({
7359
+ item,
7360
+ order: baseOrder,
7361
+ quantityChanged: delta,
7362
+ }));
7363
+ await repos.stock.save(repos.stock.create({
7364
+ orderId: baseOrder.id,
7365
+ materialId: item.materialId,
7366
+ batchId: item.batchId,
7367
+ locationId: this.stockService.resolveLocationId(item.locationId),
7368
+ loaderId: this.stockService.resolveLoaderId(item.loaderId),
7369
+ quantity: delta,
7370
+ }));
7371
+ }
7372
+ order.status = exports.InventoryCountStatus.COMPLETED;
7373
+ order.settledAt = new Date();
7374
+ await repos.order.save(order);
7375
+ return order;
7376
+ };
7377
+ return outerManager
7378
+ ? run(outerManager)
7379
+ : this.dataSource.transaction((manager) => run(manager));
7380
+ }
7381
+ };
7382
+ exports.InventoryCountOrderService = tslib.__decorate([
7383
+ common.Injectable(),
7384
+ tslib.__param(6, common.Inject(InventoryCountOrderEntity)),
7385
+ tslib.__metadata("design:paramtypes", [typeorm.DataSource,
7386
+ exports.WmsEntities,
7387
+ exports.HelperService,
7388
+ exports.MaterialService,
7389
+ exports.StockService,
7390
+ exports.BatchService, Object])
7391
+ ], exports.InventoryCountOrderService);
7392
+
6422
7393
  exports.ScrapeService = class ScrapeService {
6423
7394
  dataSource;
6424
7395
  entities;
@@ -6512,11 +7483,20 @@ exports.WarehouseMapDataService = class WarehouseMapDataService {
6512
7483
  constructor(dataSource, entities) {
6513
7484
  this.dataSource = dataSource;
6514
7485
  this.entities = entities;
6515
- this.warehouseMapDataRepository =
6516
- this.dataSource.getRepository(this.entities.warehouseMap);
7486
+ this.warehouseMapDataRepository = this.dataSource.getRepository(this.entities.warehouseMap);
6517
7487
  }
6518
- onApplicationBootstrap() {
6519
- this.dataSource.transaction(async (manager) => {
7488
+ /**
7489
+ * Seed the default map row.
7490
+ *
7491
+ * `async` on purpose: Nest awaits a returned promise, so bootstrap does not
7492
+ * complete until the seed transaction has committed. Firing it off without
7493
+ * awaiting used to leave a transaction in flight after `app.init()` resolved
7494
+ * — an app that shut down promptly (a test, a short-lived worker) destroyed
7495
+ * the pool underneath it and the rejection surfaced as an unhandled
7496
+ * `QueryFailedError: Connection terminated` that killed the process.
7497
+ */
7498
+ async onApplicationBootstrap() {
7499
+ await this.dataSource.transaction(async (manager) => {
6520
7500
  const defaultMapData = await manager
6521
7501
  .getRepository(this.entities.warehouseMap)
6522
7502
  .findOneBy({ id: this.defaultMapDataKey });
@@ -6583,6 +7563,10 @@ const TABLE_TO_CHANGE_TYPE = new Map([
6583
7563
  ['merge_batch_order_changes', () => exports.ChangeType.MERGED],
6584
7564
  ['reclassify_inventory_order_changes', () => exports.ChangeType.RECLASSIFIED],
6585
7565
  ['scrape_order_changes', () => exports.ChangeType.SCRAPED],
7566
+ [
7567
+ 'inventory_count_order_changes',
7568
+ (q) => (q > 0 ? exports.ChangeType.COUNT_GAINED : exports.ChangeType.COUNT_LOST),
7569
+ ],
6586
7570
  ]);
6587
7571
  const CHANGE_TYPE_TO_EVENT = {
6588
7572
  [exports.ChangeType.RECEIVED]: 'stock.received',
@@ -6602,6 +7586,8 @@ const CHANGE_TYPE_TO_EVENT = {
6602
7586
  [exports.ChangeType.DEALLOCATED]: 'stock.deallocated',
6603
7587
  [exports.ChangeType.RECLASSIFIED]: 'stock.reclassified',
6604
7588
  [exports.ChangeType.SCRAPED]: 'stock.scraped',
7589
+ [exports.ChangeType.COUNT_GAINED]: 'stock.count-gained',
7590
+ [exports.ChangeType.COUNT_LOST]: 'stock.count-lost',
6605
7591
  };
6606
7592
  const QUALITY_INSPECTION_TABLE = 'quality_inspection_order_changes';
6607
7593
  /**
@@ -6702,6 +7688,98 @@ StockChangeSubscriber = tslib.__decorate([
6702
7688
  exports.WmsEventCollector, Object])
6703
7689
  ], StockChangeSubscriber);
6704
7690
 
7691
+ /** The count's own settlement writes here; it must never lock itself out. */
7692
+ const INVENTORY_COUNT_CHANGE_TABLE = 'inventory_count_order_changes';
7693
+ /**
7694
+ * Refuse stock movements in locations a running inventory count has locked.
7695
+ *
7696
+ * Starting a count snapshots the ledger for its scope. That snapshot is what the
7697
+ * variance is measured against, so it has to stay true: if a transfer or a
7698
+ * shipment moved stock in the meantime, settlement would post the difference
7699
+ * between "what we counted" and "what the books said an hour ago" — silently
7700
+ * writing off someone else's legitimate movement.
7701
+ *
7702
+ * Why a subscriber rather than a check in each service
7703
+ * ---------------------------------------------------
7704
+ * Every stock movement in this package, without exception, ends in a row on some
7705
+ * `*_order_change` table — that is the same property `StockChangeSubscriber`
7706
+ * relies on to collect `stock.*` events without touching a single service. Doing
7707
+ * the lock check at the same choke point means:
7708
+ *
7709
+ * - the twelve domain services stay untouched;
7710
+ * - any future path that writes a change row is covered automatically;
7711
+ * - a consumer calling a service **directly**, bypassing the resolvers, is
7712
+ * covered too — which is exactly the case that matters, because a host with
7713
+ * its own inbound flow does precisely that.
7714
+ *
7715
+ * The check costs one indexed lookup per change row. That is deliberate: caching
7716
+ * the locked set would open a window right after `start()` in which a movement
7717
+ * slips through, and a lock with a window is not a lock.
7718
+ */
7719
+ exports.InventoryCountLockSubscriber = class InventoryCountLockSubscriber {
7720
+ constructor(dataSource) {
7721
+ dataSource.subscribers.push(this);
7722
+ }
7723
+ async beforeInsert(event) {
7724
+ const tableName = event.metadata.tableName;
7725
+ if (tableName === INVENTORY_COUNT_CHANGE_TABLE ||
7726
+ !tableName.endsWith('_order_changes')) {
7727
+ return;
7728
+ }
7729
+ const locationId = await this.resolveLocationId(event);
7730
+ if (!locationId) {
7731
+ // split / merge / reclassify items carry no location. They still move
7732
+ // stock, but only within a position the caller already named elsewhere;
7733
+ // there is nothing to match against the scope here.
7734
+ return;
7735
+ }
7736
+ const locks = await event.manager.query(`SELECT o."key"
7737
+ FROM inventory_count_order_locations l
7738
+ JOIN inventory_count_orders o ON o.id = l."orderId"
7739
+ WHERE l."locationId" = $1
7740
+ AND o.status = 'COUNTING'
7741
+ LIMIT 1`, [locationId]);
7742
+ if (!locks.length) {
7743
+ return;
7744
+ }
7745
+ // Naming the order is the difference between an operator who can go and
7746
+ // settle the count and one who just sees "denied".
7747
+ throw new common.ConflictException(`Location ${locationId} is locked by inventory count order ${locks[0].key}; finish or cancel that count before moving this stock.`);
7748
+ }
7749
+ /**
7750
+ * The location the change ultimately touches, taken from the change's order
7751
+ * item. `beforeInsert` may see the relation either already flattened to
7752
+ * `itemId` or still as the item object, depending on how the caller built the
7753
+ * row, so both are accepted.
7754
+ */
7755
+ async resolveLocationId(event) {
7756
+ const entity = event.entity;
7757
+ if (!entity) {
7758
+ return null;
7759
+ }
7760
+ if (entity.item && entity.item.locationId !== undefined) {
7761
+ return entity.item.locationId;
7762
+ }
7763
+ const itemId = entity.itemId ?? entity.item?.id;
7764
+ if (!itemId) {
7765
+ return null;
7766
+ }
7767
+ const itemRelation = event.metadata.relations.find((relation) => relation.propertyName === 'item');
7768
+ if (!itemRelation) {
7769
+ return null;
7770
+ }
7771
+ const item = await event.manager
7772
+ .getRepository(itemRelation.inverseEntityMetadata.target)
7773
+ .findOne({ where: { id: itemId } });
7774
+ return item?.locationId ?? null;
7775
+ }
7776
+ };
7777
+ exports.InventoryCountLockSubscriber = tslib.__decorate([
7778
+ common.Injectable(),
7779
+ tslib.__param(0, typeorm$1.InjectDataSource()),
7780
+ tslib.__metadata("design:paramtypes", [typeorm.DataSource])
7781
+ ], exports.InventoryCountLockSubscriber);
7782
+
6705
7783
  var WmsModuleCoreModule_1;
6706
7784
  /**
6707
7785
  * The entity Symbols a consumer can rebind, each paired with the base module's
@@ -6799,6 +7877,7 @@ const exportDependencies = [
6799
7877
  exports.MergeBatchOrderService,
6800
7878
  exports.ReclassifyInventoryOrderService,
6801
7879
  exports.ScrapeService,
7880
+ exports.InventoryCountOrderService,
6802
7881
  exports.QualityInspectionOrderService,
6803
7882
  exports.WarehouseMapDataService,
6804
7883
  ];
@@ -6811,9 +7890,13 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
6811
7890
  providers: [
6812
7891
  ...exportDependencies,
6813
7892
  StockChangeSubscriber,
7893
+ exports.InventoryCountLockSubscriber,
6814
7894
  ...resolvedEntityProviders,
6815
7895
  { provide: WMS_CORE_MODULE_OPTIONS, useValue: coreOptions },
6816
- { provide: WMS_STOCK_ENRICH, useValue: !!coreOptions.enrichStockEvents },
7896
+ {
7897
+ provide: WMS_STOCK_ENRICH,
7898
+ useValue: !!coreOptions.enrichStockEvents,
7899
+ },
6817
7900
  ],
6818
7901
  exports: [
6819
7902
  ...exportDependencies,
@@ -6833,6 +7916,7 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = class WmsModuleCoreModule
6833
7916
  providers: [
6834
7917
  ...exportDependencies,
6835
7918
  StockChangeSubscriber,
7919
+ exports.InventoryCountLockSubscriber,
6836
7920
  ...resolvedEntityProviders,
6837
7921
  {
6838
7922
  provide: WMS_CORE_MODULE_OPTIONS,
@@ -6860,6 +7944,72 @@ exports.WmsModuleCoreModule = WmsModuleCoreModule_1 = tslib.__decorate([
6860
7944
  })
6861
7945
  ], exports.WmsModuleCoreModule);
6862
7946
 
7947
+ /**
7948
+ * Runtime counterpart of {@link WmsOperationName}. Iterate it to build a UI, to
7949
+ * diff against a host's own allow-list, or to assert the invariant above.
7950
+ */
7951
+ const WMS_OPERATION_NAMES = [
7952
+ 'allocate-inventory-order:create',
7953
+ 'allocate-inventory-order:deallocate',
7954
+ 'allocate-inventory-order:read',
7955
+ 'allocate-inventory-order:update',
7956
+ 'batch:merge',
7957
+ 'batch:read',
7958
+ 'batch:split',
7959
+ 'hold-inventory-order:create',
7960
+ 'hold-inventory-order:read',
7961
+ 'hold-inventory-order:release',
7962
+ 'hold-inventory-order:update',
7963
+ 'inventory-count-order:add-item',
7964
+ 'inventory-count-order:cancel',
7965
+ 'inventory-count-order:count',
7966
+ 'inventory-count-order:create',
7967
+ 'inventory-count-order:read',
7968
+ 'inventory-count-order:read-items',
7969
+ 'inventory-count-order:remove-item',
7970
+ 'inventory-count-order:reset',
7971
+ 'inventory-count-order:settle',
7972
+ 'inventory-count-order:start',
7973
+ 'inventory-count-order:update',
7974
+ 'loader:create',
7975
+ 'loader:read',
7976
+ 'loader:update',
7977
+ 'location:create',
7978
+ 'location:read',
7979
+ 'location:update',
7980
+ 'material:create',
7981
+ 'material:read',
7982
+ 'material:update',
7983
+ 'quality-inspection-order:inspect',
7984
+ 'receive-inventory-order:create',
7985
+ 'receive-inventory-order:read',
7986
+ 'receive-inventory-order:receive',
7987
+ 'receive-inventory-order:update',
7988
+ 'reclassify-inventory-order:reclassify',
7989
+ 'sale-order:read',
7990
+ 'scrape-order:scrape',
7991
+ 'ship-inventory-order:cancel',
7992
+ 'ship-inventory-order:create',
7993
+ 'ship-inventory-order:read',
7994
+ 'ship-inventory-order:ship',
7995
+ 'ship-inventory-order:update',
7996
+ 'stock:read',
7997
+ 'transfer-customer-order:create',
7998
+ 'transfer-customer-order:return',
7999
+ 'transfer-customer-order:update',
8000
+ 'transfer-order:cancel',
8001
+ 'transfer-order:create',
8002
+ 'transfer-order:read',
8003
+ 'transfer-order:transfer',
8004
+ 'transfer-order:update',
8005
+ 'transfer-vendor-order:create',
8006
+ 'transfer-vendor-order:return',
8007
+ 'transfer-vendor-order:update',
8008
+ 'unit:read',
8009
+ 'warehouse-map:read',
8010
+ 'warehouse-map:update',
8011
+ ];
8012
+
6863
8013
  var WmsEventDispatcher_1;
6864
8014
  /**
6865
8015
  * Central event dispatcher. Runs consumer before-hooks (which may veto) and,
@@ -6930,6 +8080,10 @@ exports.BatchGroupEntity = BatchGroupEntity;
6930
8080
  exports.HoldInventoryOrderChangeEntity = HoldInventoryOrderChangeEntity;
6931
8081
  exports.HoldInventoryOrderEntity = HoldInventoryOrderEntity;
6932
8082
  exports.HoldInventoryOrderItemEntity = HoldInventoryOrderItemEntity;
8083
+ exports.InventoryCountOrderChangeEntity = InventoryCountOrderChangeEntity;
8084
+ exports.InventoryCountOrderEntity = InventoryCountOrderEntity;
8085
+ exports.InventoryCountOrderItemEntity = InventoryCountOrderItemEntity;
8086
+ exports.InventoryCountOrderLocationEntity = InventoryCountOrderLocationEntity;
6933
8087
  exports.LoaderTypeEntity = LoaderTypeEntity;
6934
8088
  exports.LoaderUnitEntity = LoaderUnitEntity;
6935
8089
  exports.LoadersEntity = LoadersEntity;
@@ -6975,6 +8129,7 @@ exports.WMS_ACTOR_EXTRACTOR = WMS_ACTOR_EXTRACTOR;
6975
8129
  exports.WMS_CORE_MODULE_OPTIONS = WMS_CORE_MODULE_OPTIONS;
6976
8130
  exports.WMS_EVENT_EMITTER_BRIDGE = WMS_EVENT_EMITTER_BRIDGE;
6977
8131
  exports.WMS_EVENT_OPTIONS = WMS_EVENT_OPTIONS;
8132
+ exports.WMS_OPERATION_NAMES = WMS_OPERATION_NAMES;
6978
8133
  exports.WMS_STOCK_ENRICH = WMS_STOCK_ENRICH;
6979
8134
  exports.WarehouseMapEntity = WarehouseMapEntity;
6980
8135
  exports.collectToScope = collectToScope;