@rytass/wms-module-core 0.6.0 → 0.8.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.
package/README.md CHANGED
@@ -9,7 +9,7 @@ This package only provides the data and service layer. Pair it with [`@rytass/wm
9
9
  ```bash
10
10
  yarn add @rytass/wms-module-core
11
11
  # peer deps
12
- yarn add @nestjs/common @nestjs/typeorm typeorm rxjs reflect-metadata
12
+ yarn add @nestjs/common @nestjs/typeorm typeorm reflect-metadata @rytass/wms-base-nestjs-module
13
13
  ```
14
14
 
15
15
  ## Quick start
@@ -109,7 +109,9 @@ WmsModuleCoreModule.forRootAsync({
109
109
  **盤點單 (Inventory Count Order)**
110
110
  - `InventoryCountOrderEntity` / `InventoryCountOrderEntityClass` — 盤點單主檔(`countDate` 為盤差記帳基準日)
111
111
  - `InventoryCountOrderLocationEntity` / `InventoryCountOrderLocationEntityClass` — 盤點範圍,已展開至所有下層儲位(`isRoot` 標示使用者實際選的節點)
112
- - `InventoryCountOrderItemEntity` / `InventoryCountOrderItemEntityClass` — 盤點單身(`isAddition` 標示盤盈新增列)
112
+ - `InventoryCountOrderItemEntity` / `InventoryCountOrderItemEntityClass` — 盤點單身(`isAddition` 標示盤盈新增列)。
113
+ 開始盤點時另外快照 8 個當下屬性,供檢視頁顯示與篩選,之後不再隨庫存變動:
114
+ `held`、`inShipment`、`inspectionResult`、`transferId`、`vendorId`、`customerId`、`saleId`、`saleSerialId`
113
115
  - `InventoryCountOrderChangeEntity` / `InventoryCountOrderChangeEntityClass` — 盤差異動(正=盤盈、負=盤虧)
114
116
  - 來源: `lib/models/extensions/inventory-count-order/`
115
117
 
@@ -213,7 +215,7 @@ WmsModuleCoreModule.forRootAsync({
213
215
  | `MergeBatchOrderService<T>` | `merge` | 批號合併 | `lib/services/merge-batch-order.service.ts` |
214
216
  | `ReclassifyInventoryOrderService<T>` | `reclassify` | 庫存轉料號 | `lib/services/reclassify-inventory-order.service.ts` |
215
217
  | `ScrapeService<T>` | `scrape` | 庫存報廢 | `lib/services/scrape.service.ts` |
216
- | `InventoryCountOrderService<T>` | `findMany`, `findOne`, `create`, `update`, `start`, `count`, `addItem`, `removeItem`, `reset`, `cancel`, `settle` | 盤點單管理。`start` 會鎖定盤點範圍內的儲位,`settle` 是唯一會改動庫存的方法 | `lib/services/inventory-count-order.service.ts` |
218
+ | `InventoryCountOrderService<T>` | `findMany`, `findOne`, `findItems`, `create`, `update`, `start`, `count`, `addItem`, `removeItem`, `reset`, `cancel`, `settle` | 盤點單管理。`start` 會鎖定盤點範圍內的儲位,`settle` 是唯一會改動庫存的方法。`findItems` 是單身的分頁查詢,支援 9 個欄位篩選與「只看盤差」 | `lib/services/inventory-count-order.service.ts` |
217
219
  | `QualityInspectionOrderService<T>` | `inspect` | 品質檢驗 | `lib/services/quality-inspection-order.service.ts` |
218
220
  | `SaleOrderService` | (DataSource 直接操作) | 銷售訂單查詢 | `lib/services/sale-order.service.ts` |
219
221
  | `HelperService` | `getSeq` | 序號產生工具 | `lib/services/helper.service.ts` |
@@ -246,6 +248,9 @@ WmsModuleCoreModule.forRootAsync({
246
248
 
247
249
  **庫存**
248
250
  - `FindStockInput<U extends object>` (extends `PaginationInput`) — 來源: `lib/typings/find-stock.input.ts`
251
+ - 除了 `materialKey` / `batchKey` / `locationKey` / `loaderKey`(皆為 ILIKE 模糊比對),另可用批號上的四個商業屬性
252
+ `vendorId` / `customerId` / `saleId` / `saleSerialId` 篩選。這四個是**完全比對**,不是模糊比對——它們是上游系統的識別碼,
253
+ 模糊比對會讓 `SO-1` 撈到 `SO-10`。傳 `null` 等同不篩選。
249
254
  - `AggregatedStock`, `ValidateStockDeductionParams`, `ChangeLog` — 來源: `lib/typings/aggregated-stock.ts`
250
255
 
251
256
  **批號**
@@ -321,7 +326,7 @@ enum InventoryCountStatus { PENDING, COUNTING, COMPLETED, CANCELLED }
321
326
 
322
327
  ### `WmsOperationName` (type) / `WMS_OPERATION_NAMES` (const)
323
328
  ```ts
324
- type WmsOperationName = 'material:read' | 'material:create' | /* …58 項… */;
329
+ type WmsOperationName = 'material:read' | 'material:create' | /* …59 項… */;
325
330
  const WMS_OPERATION_NAMES: readonly WmsOperationName[];
326
331
  ```
327
332
  本套件所有 root operation 的 `` `${resource}:${action}` `` 名稱。同一組字串有三個用途:
@@ -340,23 +340,44 @@ The `DEFAULT` location/loader/loaderType returned by the second query was seeded
340
340
 
341
341
  ### 4.6 Version compatibility matrix
342
342
 
343
- Tested combinations as of 0.1.2:
344
-
345
- | Package | Tested version | Notes |
346
- |----------------------------------|-------------------------|--------------------------------------------------------------------|
347
- | NestJS (`@nestjs/*`) | 11.x | 10.x untested; some Express-5-related APIs differ |
348
- | `@nestjs/graphql` | 13.x | Required for `@nestjs/apollo@13` |
349
- | `@nestjs/apollo` | 13.0.x – 13.1.x | 13.2+ requires @apollo/server@^5 which breaks lib's v4 plugin usage |
350
- | `@apollo/server` | 4.x | v5 is breaking; not supported |
351
- | `@as-integrations/express5` | 1.x | Required runtime peer |
352
- | TypeORM | 0.3.x | 0.2.x not supported (different DataSource API) |
353
- | PostgreSQL | 14+ | Native dialect |
354
- | `graphql` | 16.x | 15.x untested |
355
- | Node.js | 20 LTS or 22 | 18 deprecated, 24 untested |
356
- | Next.js | 15.x Pages Router | App Router unsupported (see §13.11) |
357
- | React | 19.x | 18.x likely works but untested |
358
- | `@mezzanine-ui/react` | 1.3.x | Earlier versions untested |
359
- | `nuqs` | 2.x (Pages adapter) | App Router adapter untested (see §13.11) |
343
+ Two different questions, so two columns. **Accepted** is what the published
344
+ `peerDependencies` allow — a version outside it fails to install. **Tested** is the
345
+ combination the integration suite actually runs against.
346
+
347
+ | Package | Accepted (peer range) | Tested | Notes |
348
+ |--------------------------|------------------------|--------------|-----------------------------------------------------------------------------|
349
+ | `@nestjs/common` | 10.x – 11.x | 11.1.x | **12.x is not accepted**: the whole NestJS 12 line is ESM-only, which this package (dual CJS+ESM) and a webpack-bundled host cannot consume yet |
350
+ | `@nestjs/typeorm` | 10.x – 11.x | 11.0.x | Three import sites (`InjectDataSource`, `forFeature`), stable across both |
351
+ | TypeORM | 0.3.x – 1.x | 1.1.1 | The suite is run against both 0.3.31 and 1.1.1. 0.2.x is not supported (different DataSource API). Note 0.3.x is now tagged `legacy` on npm |
352
+ | `@nestjs/typeorm` | 10.x – 11.x | 11.0.3 | **TypeORM 1.x needs `@nestjs/typeorm` >= 11.0.1** — earlier releases peer `^0.3.0` only |
353
+ | `reflect-metadata` | 0.1.13+ / 0.2.x | 0.1.x | Ambient requirement of the decorators |
354
+ | `rxjs` | not a peer | — | Never imported by this package; `@nestjs/common` peers it for you |
355
+ | `@rytass/wms-base-nestjs-module` | 0.4.x | 0.4.0 | **A peer since 0.7.0**, not a bundled dependency. It was pinned exactly under `dependencies`, which cannot prevent a second copy — it *causes* one as soon as you ask for any other 0.4.x. Two copies means two sets of entity classes and DI Symbols, the split-brain this package's Symbol discipline exists to avoid. Install it yourself so there is one |
356
+ | PostgreSQL | — | 14+ | Native dialect |
357
+ | Node.js | — | 20 LTS / 22 | 18 deprecated, 24 untested |
358
+
359
+ ### Upgrading to TypeORM 1.x
360
+
361
+ Both majors are supported and both are exercised by the integration suite, so you can move
362
+ at your own pace. Two things changed upstream that are worth knowing before you do:
363
+
364
+ 1. **`relations` no longer accepts an array.** `relations: ['items']` becomes
365
+ `relations: { items: true }`. The object form works in 0.3.x too, so it is safe to convert
366
+ before you upgrade.
367
+ 2. **A bare `null` in a `where` is now an error**, not a silently-never-matching condition.
368
+ TypeORM 1.x raises `Null value encountered in property '…' of a where condition` and tells
369
+ you to use `IsNull()`. This is worth welcoming rather than working around: in 0.3.x such a
370
+ condition compiled to `= NULL`, which is never true in SQL, so the query quietly returned
371
+ nothing. Upgrading found exactly one such bug in this package — a batch-reuse lookup that
372
+ had been splitting duplicates instead of matching the batch already there.
373
+
374
+ If you have too many call sites to fix at once, TypeORM offers
375
+ `invalidWhereValuesBehavior.null` in the DataSource options as an escape hatch. Prefer
376
+ fixing them: each one is a query that was returning the wrong answer.
377
+
378
+ The GraphQL-side packages (`@nestjs/graphql`, `@nestjs/apollo`, `@apollo/server`,
379
+ `@as-integrations/express5`) are not peers of this package — see
380
+ [`@rytass/wms-module-graphql`](https://www.npmjs.com/package/@rytass/wms-module-graphql) §4.6.
360
381
 
361
382
  ---
362
383
 
package/index.cjs.js CHANGED
@@ -2537,6 +2537,26 @@ exports.InventoryCountOrderItemEntityClass = class InventoryCountOrderItemEntity
2537
2537
  countedQuantity;
2538
2538
  /** `true` for a line added during counting for unbooked stock (盤盈). */
2539
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;
2540
2560
  location;
2541
2561
  loader;
2542
2562
  order;
@@ -2588,6 +2608,38 @@ tslib.__decorate([
2588
2608
  typeorm.Column({ type: 'boolean', default: false }),
2589
2609
  tslib.__metadata("design:type", Boolean)
2590
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);
2591
2643
  tslib.__decorate([
2592
2644
  typeorm.ManyToOne('locations'),
2593
2645
  typeorm.JoinColumn({ name: 'locationId', referencedColumnName: 'id' }),
@@ -3025,6 +3077,30 @@ exports.StockService = class StockService {
3025
3077
  queryBuilder.innerJoin(exports.LoadersEntityClass, 'lk', 'lk.id = stock."loaderId" AND lk."serialId" ILIKE :loaderKey', {
3026
3078
  loaderKey: `%${options.loaderKey}%`,
3027
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
+ }
3028
3104
  if (options.offset !== undefined && options.offset >= 0)
3029
3105
  queryBuilder.skip(options.offset);
3030
3106
  if (options.limit !== undefined && options.limit > 0)
@@ -3701,7 +3777,7 @@ exports.BatchService = class BatchService {
3701
3777
  const batchRepository = manager.getRepository(this.batchEntity);
3702
3778
  const batch = await batchRepository.findOneOrFail({
3703
3779
  where: { id: options.id },
3704
- relations: ['batchGroup'],
3780
+ relations: { batchGroup: true },
3705
3781
  });
3706
3782
  // Validate state transition before proceeding
3707
3783
  this.validateStateTransition(batch, options);
@@ -3711,15 +3787,24 @@ exports.BatchService = class BatchService {
3711
3787
  ...options,
3712
3788
  groupId: batch.batchGroup.id,
3713
3789
  };
3714
- // Build where condition dynamically to handle optional fields
3790
+ /*
3791
+ * Absent attributes have to be matched with `IsNull()`, not with a bare
3792
+ * `null`. A `null` on the right of a find condition compiles to `= NULL`,
3793
+ * which is never true in SQL — so this lookup used to miss every batch whose
3794
+ * attributes were unset and split off a duplicate instead of reusing the one
3795
+ * already there. `getBatch` above has always done it this way; this call
3796
+ * site did not. TypeORM 1.x refuses a bare `null` here outright, which is
3797
+ * how the bug surfaced.
3798
+ */
3799
+ const orNull = (value) => value === null || value === undefined ? typeorm.IsNull() : value;
3715
3800
  const whereCondition = {
3716
3801
  groupId: mergedBatch.groupId,
3717
- saleId: mergedBatch.saleId ?? null,
3718
- saleSerialId: mergedBatch.saleSerialId ?? null,
3719
- customerId: mergedBatch.customerId ?? null,
3720
- vendorId: mergedBatch.vendorId ?? null,
3721
- inspectionResult: mergedBatch.inspectionResult ?? null,
3722
- transferId: mergedBatch.transferId ?? null,
3802
+ saleId: orNull(mergedBatch.saleId),
3803
+ saleSerialId: orNull(mergedBatch.saleSerialId),
3804
+ customerId: orNull(mergedBatch.customerId),
3805
+ vendorId: orNull(mergedBatch.vendorId),
3806
+ inspectionResult: orNull(mergedBatch.inspectionResult),
3807
+ transferId: orNull(mergedBatch.transferId),
3723
3808
  held: mergedBatch.held ?? false,
3724
3809
  inShipment: mergedBatch.inShipment ?? false,
3725
3810
  };
@@ -4039,7 +4124,7 @@ exports.ReceiveInventoryOrderService = class ReceiveInventoryOrderService {
4039
4124
  const stockRepository = manager.getRepository(this.entities.stock);
4040
4125
  const items = await itemRepository.find({
4041
4126
  where: { id: typeorm.In(options.map((o) => o.itemId)) },
4042
- relations: ['changes'],
4127
+ relations: { changes: true },
4043
4128
  });
4044
4129
  const itemMap = new Map(items.map((i) => [i.id, i]));
4045
4130
  await Promise.all(options.map(async (option) => {
@@ -4402,7 +4487,7 @@ exports.ShipInventoryOrderService = class ShipInventoryOrderService {
4402
4487
  // Find all items with changes to calculate cancellable quantities
4403
4488
  const items = await itemRepository.find({
4404
4489
  where: { orderId: id },
4405
- relations: ['changes'],
4490
+ relations: { changes: true },
4406
4491
  });
4407
4492
  // Build cancel inputs for items with remaining prepared quantity
4408
4493
  const cancelInputs = [];
@@ -4444,7 +4529,7 @@ exports.ShipInventoryOrderService = class ShipInventoryOrderService {
4444
4529
  const stockRepository = manager.getRepository(this.entities.stock);
4445
4530
  const items = await itemRepository.find({
4446
4531
  where: { id: typeorm.In(options.map((o) => o.itemId)) },
4447
- relations: ['changes'],
4532
+ relations: { changes: true },
4448
4533
  });
4449
4534
  const itemMap = new Map(items.map((item) => [item.id, item]));
4450
4535
  await Promise.all(options.map(async (option) => {
@@ -4601,7 +4686,7 @@ exports.ShipInventoryOrderService = class ShipInventoryOrderService {
4601
4686
  const stockRepository = manager.getRepository(this.entities.stock);
4602
4687
  const items = await itemRepository.find({
4603
4688
  where: { id: typeorm.In(options.map((option) => option.itemId)) },
4604
- relations: ['changes'],
4689
+ relations: { changes: true },
4605
4690
  });
4606
4691
  const itemMap = new Map(items.map((item) => [item.id, item]));
4607
4692
  await Promise.all(options.map(async (option) => {
@@ -4873,7 +4958,7 @@ exports.TransferOrderService = class TransferOrderService {
4873
4958
  const repos = this.getRepositories(manager);
4874
4959
  const items = await repos.transferOrderItem.find({
4875
4960
  where: { id: typeorm.In(options.map((o) => o.itemId)) },
4876
- relations: ['changes'],
4961
+ relations: { changes: true },
4877
4962
  });
4878
4963
  const itemMap = new Map(items.map((item) => [item.id, item]));
4879
4964
  // Whole-loader transfer cancel validation (Phase 2d-sync).
@@ -4972,7 +5057,7 @@ exports.TransferOrderService = class TransferOrderService {
4972
5057
  // Find all items with changes to calculate cancellable quantities
4973
5058
  const items = await repos.transferOrderItem.find({
4974
5059
  where: { orderId: id },
4975
- relations: ['changes'],
5060
+ relations: { changes: true },
4976
5061
  });
4977
5062
  // Build cancel inputs for items with remaining pending quantity
4978
5063
  const cancelInputs = [];
@@ -5181,7 +5266,7 @@ exports.TransferOrderService = class TransferOrderService {
5181
5266
  const stockRepository = manager.getRepository(this.stockEntity);
5182
5267
  const items = await itemRepository.find({
5183
5268
  where: { id: typeorm.In(options.map((o) => o.itemId)) },
5184
- relations: ['changes'],
5269
+ relations: { changes: true },
5185
5270
  });
5186
5271
  const itemMap = new Map(items.map((item) => [item.id, item]));
5187
5272
  const inputMap = new Map(options.map((o) => [o.itemId, o]));
@@ -5207,7 +5292,7 @@ exports.TransferOrderService = class TransferOrderService {
5207
5292
  if (orderId) {
5208
5293
  const allOrderItems = await itemRepository.find({
5209
5294
  where: { orderId },
5210
- relations: ['changes'],
5295
+ relations: { changes: true },
5211
5296
  });
5212
5297
  for (const orderItem of allOrderItems) {
5213
5298
  if (orderItem.removedAt)
@@ -5688,7 +5773,7 @@ exports.AllocateInventoryOrderService = class AllocateInventoryOrderService {
5688
5773
  if (items?.length) {
5689
5774
  const existingItemIds = new Set((await repos.allocateInventoryOrderItem.find({
5690
5775
  where: { orderId: id },
5691
- relations: ['changes'],
5776
+ relations: { changes: true },
5692
5777
  })).map((item) => item.id));
5693
5778
  const newItems = [];
5694
5779
  const existingItems = [];
@@ -6308,7 +6393,7 @@ exports.TransferVendorOrderService = class TransferVendorOrderService {
6308
6393
  if (items?.length) {
6309
6394
  const existingItemIds = new Set((await repos.transferVendorOrderItem.find({
6310
6395
  where: { orderId: id },
6311
- relations: ['changes'],
6396
+ relations: { changes: true },
6312
6397
  })).map((item) => item.id));
6313
6398
  const newItems = [];
6314
6399
  const existingItems = [];
@@ -6613,7 +6698,7 @@ exports.TransferCustomerOrderService = class TransferCustomerOrderService {
6613
6698
  if (items?.length) {
6614
6699
  const existingItemIds = new Set((await repos.transferCustomerOrderItem.find({
6615
6700
  where: { orderId: id },
6616
- relations: ['changes'],
6701
+ relations: { changes: true },
6617
6702
  })).map((item) => item.id));
6618
6703
  const newItems = [];
6619
6704
  const existingItems = [];
@@ -6812,17 +6897,34 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6812
6897
  if (!locationIds.length) {
6813
6898
  return [];
6814
6899
  }
6900
+ // The batch table is joined by name rather than through its repository
6901
+ // because it is only read for its attribute columns — the same thing
6902
+ // `StockService.selectQueryBuilder` does. Single-table inheritance means
6903
+ // every configured batch entity shares this table, so the join is override
6904
+ // safe; the name still comes from the configured entity's metadata rather
6905
+ // than being hard-coded.
6906
+ const batchTable = manager.getRepository(this.entities.batch).metadata
6907
+ .tableName;
6815
6908
  // Through the repository, not raw SQL on the table: the stock entity is
6816
6909
  // overridable, and the repository is what applies the right
6817
6910
  // single-table-inheritance discriminator.
6818
6911
  const rows = await manager
6819
6912
  .getRepository(this.entities.stock)
6820
6913
  .createQueryBuilder('stock')
6914
+ .leftJoin(batchTable, 'batch', 'batch.id = stock."batchId"')
6821
6915
  .select('stock.materialId', 'materialId')
6822
6916
  .addSelect('stock.batchId', 'batchId')
6823
6917
  .addSelect('stock.locationId', 'locationId')
6824
6918
  .addSelect('stock.loaderId', 'loaderId')
6825
6919
  .addSelect('SUM(stock.quantity)', 'quantity')
6920
+ .addSelect('batch.held', 'held')
6921
+ .addSelect('batch."inShipment"', 'inShipment')
6922
+ .addSelect('batch."inspectionResult"', 'inspectionResult')
6923
+ .addSelect('batch."transferId"', 'transferId')
6924
+ .addSelect('batch."vendorId"', 'vendorId')
6925
+ .addSelect('batch."customerId"', 'customerId')
6926
+ .addSelect('batch."saleId"', 'saleId')
6927
+ .addSelect('batch."saleSerialId"', 'saleSerialId')
6826
6928
  .where('stock.locationId IN (:...locationIds)', {
6827
6929
  locationIds: [...locationIds],
6828
6930
  })
@@ -6830,6 +6932,16 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6830
6932
  .addGroupBy('stock.batchId')
6831
6933
  .addGroupBy('stock.locationId')
6832
6934
  .addGroupBy('stock.loaderId')
6935
+ // Functionally dependent on batchId, but PostgreSQL only infers that from
6936
+ // the grouped table's own primary key, so they have to be listed.
6937
+ .addGroupBy('batch.held')
6938
+ .addGroupBy('batch."inShipment"')
6939
+ .addGroupBy('batch."inspectionResult"')
6940
+ .addGroupBy('batch."transferId"')
6941
+ .addGroupBy('batch."vendorId"')
6942
+ .addGroupBy('batch."customerId"')
6943
+ .addGroupBy('batch."saleId"')
6944
+ .addGroupBy('batch."saleSerialId"')
6833
6945
  .having('SUM(stock.quantity) > 0')
6834
6946
  .getRawMany();
6835
6947
  return rows.map((row) => ({
@@ -6838,6 +6950,16 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6838
6950
  locationId: row.locationId,
6839
6951
  loaderId: row.loaderId,
6840
6952
  quantity: Number(row.quantity),
6953
+ attributes: {
6954
+ held: row.held ?? null,
6955
+ inShipment: row.inShipment ?? null,
6956
+ inspectionResult: row.inspectionResult ?? null,
6957
+ transferId: row.transferId ?? null,
6958
+ vendorId: row.vendorId ?? null,
6959
+ customerId: row.customerId ?? null,
6960
+ saleId: row.saleId ?? null,
6961
+ saleSerialId: row.saleSerialId ?? null,
6962
+ },
6841
6963
  }));
6842
6964
  }
6843
6965
  positionKey(position) {
@@ -6889,6 +7011,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6889
7011
  const item = byKey.get(key);
6890
7012
  if (item) {
6891
7013
  item.bookQuantity = position.quantity;
7014
+ Object.assign(item, position.attributes);
6892
7015
  await repos.item.save(item);
6893
7016
  continue;
6894
7017
  }
@@ -6902,6 +7025,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6902
7025
  countedQuantity: null,
6903
7026
  unitId: null,
6904
7027
  isAddition: false,
7028
+ ...position.attributes,
6905
7029
  }));
6906
7030
  }
6907
7031
  // A position that emptied out between two rebuilds is no longer on the
@@ -6967,6 +7091,75 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
6967
7091
  async findOne(id, manager = this.dataSource.manager) {
6968
7092
  return this.loadOrderOrFail(id, manager);
6969
7093
  }
7094
+ /**
7095
+ * The count sheet, filtered and paginated.
7096
+ *
7097
+ * Server-side rather than handing the whole sheet to the client: a count over
7098
+ * a whole warehouse is thousands of lines, and the operator's job is to narrow
7099
+ * to the shelf in front of them.
7100
+ */
7101
+ async findItems(orderId, options = {}, manager = this.dataSource.manager) {
7102
+ const tableOf = (entity) => manager.getRepository(entity).metadata.tableName;
7103
+ const query = this.getRepositories(manager)
7104
+ .item.createQueryBuilder('item')
7105
+ .leftJoin(tableOf(this.entities.material), 'material', 'material.id = item."materialId"')
7106
+ .leftJoin(tableOf(this.entities.batch), 'batch', 'batch.id = item."batchId"')
7107
+ .leftJoin(tableOf(this.entities.location), 'location', 'location.id = item."locationId"')
7108
+ .leftJoin(exports.LoadersEntityClass, 'loader', 'loader.id = item."loaderId"')
7109
+ .where('item."orderId" = :orderId', { orderId });
7110
+ const like = (column, value, parameter) => {
7111
+ if (!value)
7112
+ return;
7113
+ query.andWhere(`${column} ILIKE :${parameter}`, {
7114
+ [parameter]: `%${value}%`,
7115
+ });
7116
+ };
7117
+ like('material.key', options.materialKey, 'materialKey');
7118
+ like('material.description', options.materialDescription, 'materialDescription');
7119
+ like('batch.key', options.batchKey, 'batchKey');
7120
+ like('location.key', options.locationKey, 'locationKey');
7121
+ like('loader."serialId"', options.loaderSerialId, 'loaderSerialId');
7122
+ const exact = (column, value, parameter) => {
7123
+ if (!value)
7124
+ return;
7125
+ query.andWhere(`${column} = :${parameter}`, { [parameter]: value });
7126
+ };
7127
+ exact('item."vendorId"', options.vendorId, 'vendorId');
7128
+ exact('item."customerId"', options.customerId, 'customerId');
7129
+ exact('item."saleId"', options.saleId, 'saleId');
7130
+ exact('item."saleSerialId"', options.saleSerialId, 'saleSerialId');
7131
+ if (options.onlyVariance) {
7132
+ // The counted quantity is expressed in the line's unit, so it has to be
7133
+ // converted before it can be compared with the base-unit book quantity —
7134
+ // the same conversion settlement applies.
7135
+ query
7136
+ .leftJoin(exports.MaterialUnitEntityClass, 'unit', 'unit.id = item."unitId"')
7137
+ .andWhere('item."countedQuantity" IS NOT NULL')
7138
+ .andWhere('item."countedQuantity" * COALESCE(unit."conversionFactor", 1) <> item."bookQuantity"');
7139
+ }
7140
+ // Counted before ordering and paginating: `getCount()` rewrites the query
7141
+ // into a COUNT, and an ORDER BY on a joined column it does not select makes
7142
+ // that rewrite fail.
7143
+ const total = await query.getCount();
7144
+ // Additions first — they are what the operator just typed — then a stable
7145
+ // order so paging cannot repeat or skip a line.
7146
+ query
7147
+ .orderBy('item."isAddition"', 'DESC')
7148
+ .addOrderBy('material.key', 'ASC')
7149
+ .addOrderBy('batch.key', 'ASC')
7150
+ .addOrderBy('item.id', 'ASC');
7151
+ // `limit`/`offset` rather than `take`/`skip`: the latter wraps the query in a
7152
+ // DISTINCT subquery to survive one-to-many joins, and then cannot map an
7153
+ // ORDER BY on a joined column into it. Every join here is many-to-one, so no
7154
+ // row multiplication and no need for that machinery.
7155
+ if (options.offset !== undefined && options.offset >= 0) {
7156
+ query.offset(options.offset);
7157
+ }
7158
+ if (options.limit !== undefined && options.limit > 0) {
7159
+ query.limit(options.limit);
7160
+ }
7161
+ return [await query.getMany(), total];
7162
+ }
6970
7163
  async create(input, manager = this.dataSource.manager) {
6971
7164
  if (!input.locationIds.length) {
6972
7165
  throw new common.BadRequestException('An inventory count needs at least one location in scope');
@@ -7087,6 +7280,18 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
7087
7280
  bookQuantity: 0,
7088
7281
  countedQuantity: input.countedQuantity,
7089
7282
  isAddition: true,
7283
+ // Snapshotted from the batch the same way a scoped line is, so an added
7284
+ // line renders through the identical columns. A brand-new batch carries
7285
+ // the defaults, which is exactly right: unbooked stock is not held, not
7286
+ // in transfer and not inspected.
7287
+ held: batch.held ?? null,
7288
+ inShipment: batch.inShipment ?? null,
7289
+ inspectionResult: batch.inspectionResult ?? null,
7290
+ transferId: batch.transferId ?? null,
7291
+ vendorId: batch.vendorId ?? null,
7292
+ customerId: batch.customerId ?? null,
7293
+ saleId: batch.saleId ?? null,
7294
+ saleSerialId: batch.saleSerialId ?? null,
7090
7295
  }));
7091
7296
  }
7092
7297
  /** Remove an added line. Scoped lines are part of the sheet and never removed. */
@@ -7769,6 +7974,7 @@ const WMS_OPERATION_NAMES = [
7769
7974
  'inventory-count-order:count',
7770
7975
  'inventory-count-order:create',
7771
7976
  'inventory-count-order:read',
7977
+ 'inventory-count-order:read-items',
7772
7978
  'inventory-count-order:remove-item',
7773
7979
  'inventory-count-order:reset',
7774
7980
  'inventory-count-order:settle',
@@ -26,7 +26,7 @@
26
26
  * `loader:create` 3 each, and 7 more cover 2). Disabling a name disables every
27
27
  * field carrying it — use `disabledFields` when you need finer granularity.
28
28
  */
29
- export type WmsOperationName = 'allocate-inventory-order:create' | 'allocate-inventory-order:deallocate' | 'allocate-inventory-order:read' | 'allocate-inventory-order:update' | 'batch:merge' | 'batch:read' | 'batch:split' | 'hold-inventory-order:create' | 'hold-inventory-order:read' | 'hold-inventory-order:release' | 'hold-inventory-order:update' | 'inventory-count-order:add-item' | 'inventory-count-order:cancel' | 'inventory-count-order:count' | 'inventory-count-order:create' | 'inventory-count-order:read' | 'inventory-count-order:remove-item' | 'inventory-count-order:reset' | 'inventory-count-order:settle' | 'inventory-count-order:start' | 'inventory-count-order:update' | 'loader:create' | 'loader:read' | 'loader:update' | 'location:create' | 'location:read' | 'location:update' | 'material:create' | 'material:read' | 'material:update' | 'quality-inspection-order:inspect' | 'receive-inventory-order:create' | 'receive-inventory-order:read' | 'receive-inventory-order:receive' | 'receive-inventory-order:update' | 'reclassify-inventory-order:reclassify' | 'sale-order:read' | 'scrape-order:scrape' | 'ship-inventory-order:cancel' | 'ship-inventory-order:create' | 'ship-inventory-order:read' | 'ship-inventory-order:ship' | 'ship-inventory-order:update' | 'stock:read' | 'transfer-customer-order:create' | 'transfer-customer-order:return' | 'transfer-customer-order:update' | 'transfer-order:cancel' | 'transfer-order:create' | 'transfer-order:read' | 'transfer-order:transfer' | 'transfer-order:update' | 'transfer-vendor-order:create' | 'transfer-vendor-order:return' | 'transfer-vendor-order:update' | 'unit:read' | 'warehouse-map:read' | 'warehouse-map:update';
29
+ export type WmsOperationName = 'allocate-inventory-order:create' | 'allocate-inventory-order:deallocate' | 'allocate-inventory-order:read' | 'allocate-inventory-order:update' | 'batch:merge' | 'batch:read' | 'batch:split' | 'hold-inventory-order:create' | 'hold-inventory-order:read' | 'hold-inventory-order:release' | 'hold-inventory-order:update' | 'inventory-count-order:add-item' | 'inventory-count-order:cancel' | 'inventory-count-order:count' | 'inventory-count-order:create' | 'inventory-count-order:read' | 'inventory-count-order:read-items' | 'inventory-count-order:remove-item' | 'inventory-count-order:reset' | 'inventory-count-order:settle' | 'inventory-count-order:start' | 'inventory-count-order:update' | 'loader:create' | 'loader:read' | 'loader:update' | 'location:create' | 'location:read' | 'location:update' | 'material:create' | 'material:read' | 'material:update' | 'quality-inspection-order:inspect' | 'receive-inventory-order:create' | 'receive-inventory-order:read' | 'receive-inventory-order:receive' | 'receive-inventory-order:update' | 'reclassify-inventory-order:reclassify' | 'sale-order:read' | 'scrape-order:scrape' | 'ship-inventory-order:cancel' | 'ship-inventory-order:create' | 'ship-inventory-order:read' | 'ship-inventory-order:ship' | 'ship-inventory-order:update' | 'stock:read' | 'transfer-customer-order:create' | 'transfer-customer-order:return' | 'transfer-customer-order:update' | 'transfer-order:cancel' | 'transfer-order:create' | 'transfer-order:read' | 'transfer-order:transfer' | 'transfer-order:update' | 'transfer-vendor-order:create' | 'transfer-vendor-order:return' | 'transfer-vendor-order:update' | 'unit:read' | 'warehouse-map:read' | 'warehouse-map:update';
30
30
  /**
31
31
  * Runtime counterpart of {@link WmsOperationName}. Iterate it to build a UI, to
32
32
  * diff against a host's own allow-list, or to assert the invariant above.
@@ -19,6 +19,7 @@ const WMS_OPERATION_NAMES = [
19
19
  'inventory-count-order:count',
20
20
  'inventory-count-order:create',
21
21
  'inventory-count-order:read',
22
+ 'inventory-count-order:read-items',
22
23
  'inventory-count-order:remove-item',
23
24
  'inventory-count-order:reset',
24
25
  'inventory-count-order:settle',
@@ -32,6 +32,15 @@ export declare class InventoryCountOrderItemEntityClass {
32
32
  countedQuantity: number | null;
33
33
  /** `true` for a line added during counting for unbooked stock (盤盈). */
34
34
  isAddition: boolean;
35
+ held: boolean | null;
36
+ inShipment: boolean | null;
37
+ /** `null` = 待檢驗, `false` = 檢驗失敗, `true` = passed. */
38
+ inspectionResult: boolean | null;
39
+ transferId: string | null;
40
+ vendorId: string | null;
41
+ customerId: string | null;
42
+ saleId: string | null;
43
+ saleSerialId: string | null;
35
44
  location: LocationEntityClass;
36
45
  loader: LoadersEntityClass;
37
46
  order: InventoryCountOrderEntityClass;
@@ -45,6 +45,26 @@ let InventoryCountOrderItemEntityClass = class InventoryCountOrderItemEntityClas
45
45
  countedQuantity;
46
46
  /** `true` for a line added during counting for unbooked stock (盤盈). */
47
47
  isAddition;
48
+ // ── Batch attributes, snapshotted when counting starts ─────────────────── //
49
+ //
50
+ // The count sheet shows whether each position was awaiting inspection, held or
51
+ // in transfer, and which vendor / customer / sale order it belonged to. All of
52
+ // those live on the batch, which keeps moving after the count is settled — so
53
+ // they are copied here rather than resolved live. A count completed in June has
54
+ // to keep showing what June looked like, otherwise the sheet stops being an
55
+ // audit record of what was found.
56
+ //
57
+ // Filled by `start()` for scoped lines and by `addItem()` for additions;
58
+ // `null` before counting has started.
59
+ held;
60
+ inShipment;
61
+ /** `null` = 待檢驗, `false` = 檢驗失敗, `true` = passed. */
62
+ inspectionResult;
63
+ transferId;
64
+ vendorId;
65
+ customerId;
66
+ saleId;
67
+ saleSerialId;
48
68
  location;
49
69
  loader;
50
70
  order;
@@ -96,6 +116,38 @@ __decorate([
96
116
  Column({ type: 'boolean', default: false }),
97
117
  __metadata("design:type", Boolean)
98
118
  ], InventoryCountOrderItemEntityClass.prototype, "isAddition", void 0);
119
+ __decorate([
120
+ Column({ type: 'boolean', nullable: true }),
121
+ __metadata("design:type", Object)
122
+ ], InventoryCountOrderItemEntityClass.prototype, "held", void 0);
123
+ __decorate([
124
+ Column({ type: 'boolean', nullable: true }),
125
+ __metadata("design:type", Object)
126
+ ], InventoryCountOrderItemEntityClass.prototype, "inShipment", void 0);
127
+ __decorate([
128
+ Column({ type: 'boolean', nullable: true }),
129
+ __metadata("design:type", Object)
130
+ ], InventoryCountOrderItemEntityClass.prototype, "inspectionResult", void 0);
131
+ __decorate([
132
+ Column({ type: 'uuid', nullable: true }),
133
+ __metadata("design:type", Object)
134
+ ], InventoryCountOrderItemEntityClass.prototype, "transferId", void 0);
135
+ __decorate([
136
+ Column({ type: 'varchar', nullable: true }),
137
+ __metadata("design:type", Object)
138
+ ], InventoryCountOrderItemEntityClass.prototype, "vendorId", void 0);
139
+ __decorate([
140
+ Column({ type: 'varchar', nullable: true }),
141
+ __metadata("design:type", Object)
142
+ ], InventoryCountOrderItemEntityClass.prototype, "customerId", void 0);
143
+ __decorate([
144
+ Column({ type: 'varchar', nullable: true }),
145
+ __metadata("design:type", Object)
146
+ ], InventoryCountOrderItemEntityClass.prototype, "saleId", void 0);
147
+ __decorate([
148
+ Column({ type: 'varchar', nullable: true }),
149
+ __metadata("design:type", Object)
150
+ ], InventoryCountOrderItemEntityClass.prototype, "saleSerialId", void 0);
99
151
  __decorate([
100
152
  ManyToOne('locations'),
101
153
  JoinColumn({ name: 'locationId', referencedColumnName: 'id' }),
@@ -170,7 +170,7 @@ let AllocateInventoryOrderService = class AllocateInventoryOrderService {
170
170
  if (items?.length) {
171
171
  const existingItemIds = new Set((await repos.allocateInventoryOrderItem.find({
172
172
  where: { orderId: id },
173
- relations: ['changes'],
173
+ relations: { changes: true },
174
174
  })).map((item) => item.id));
175
175
  const newItems = [];
176
176
  const existingItems = [];
@@ -158,7 +158,7 @@ let BatchService = class BatchService {
158
158
  const batchRepository = manager.getRepository(this.batchEntity);
159
159
  const batch = await batchRepository.findOneOrFail({
160
160
  where: { id: options.id },
161
- relations: ['batchGroup'],
161
+ relations: { batchGroup: true },
162
162
  });
163
163
  // Validate state transition before proceeding
164
164
  this.validateStateTransition(batch, options);
@@ -168,15 +168,24 @@ let BatchService = class BatchService {
168
168
  ...options,
169
169
  groupId: batch.batchGroup.id,
170
170
  };
171
- // Build where condition dynamically to handle optional fields
171
+ /*
172
+ * Absent attributes have to be matched with `IsNull()`, not with a bare
173
+ * `null`. A `null` on the right of a find condition compiles to `= NULL`,
174
+ * which is never true in SQL — so this lookup used to miss every batch whose
175
+ * attributes were unset and split off a duplicate instead of reusing the one
176
+ * already there. `getBatch` above has always done it this way; this call
177
+ * site did not. TypeORM 1.x refuses a bare `null` here outright, which is
178
+ * how the bug surfaced.
179
+ */
180
+ const orNull = (value) => value === null || value === undefined ? IsNull() : value;
172
181
  const whereCondition = {
173
182
  groupId: mergedBatch.groupId,
174
- saleId: mergedBatch.saleId ?? null,
175
- saleSerialId: mergedBatch.saleSerialId ?? null,
176
- customerId: mergedBatch.customerId ?? null,
177
- vendorId: mergedBatch.vendorId ?? null,
178
- inspectionResult: mergedBatch.inspectionResult ?? null,
179
- transferId: mergedBatch.transferId ?? null,
183
+ saleId: orNull(mergedBatch.saleId),
184
+ saleSerialId: orNull(mergedBatch.saleSerialId),
185
+ customerId: orNull(mergedBatch.customerId),
186
+ vendorId: orNull(mergedBatch.vendorId),
187
+ inspectionResult: orNull(mergedBatch.inspectionResult),
188
+ transferId: orNull(mergedBatch.transferId),
180
189
  held: mergedBatch.held ?? false,
181
190
  inShipment: mergedBatch.inShipment ?? false,
182
191
  };
@@ -16,6 +16,29 @@ export interface FindInventoryCountOrderInput {
16
16
  readonly offset?: number;
17
17
  readonly limit?: number;
18
18
  }
19
+ /**
20
+ * Filters for the count sheet. All optional; combined with AND.
21
+ *
22
+ * The key filters match on the related entity's human-readable key rather than
23
+ * its id, because that is what the operator types and what the sheet shows.
24
+ * The vendor / customer / sale filters read the line's own snapshot columns, so
25
+ * they keep matching what the sheet displays even after the batch has moved on.
26
+ */
27
+ export interface FindInventoryCountOrderItemInput {
28
+ readonly materialKey?: string | null;
29
+ readonly materialDescription?: string | null;
30
+ readonly batchKey?: string | null;
31
+ readonly locationKey?: string | null;
32
+ readonly loaderSerialId?: string | null;
33
+ readonly vendorId?: string | null;
34
+ readonly customerId?: string | null;
35
+ readonly saleId?: string | null;
36
+ readonly saleSerialId?: string | null;
37
+ /** Only lines whose counted quantity differs from the books (顯示盤差項目). */
38
+ readonly onlyVariance?: boolean | null;
39
+ readonly offset?: number;
40
+ readonly limit?: number;
41
+ }
19
42
  export interface CreateInventoryCountOrderInput {
20
43
  readonly name: string;
21
44
  /** The base date the settlement is reported under. `YYYY-MM-DD`. */
@@ -99,6 +122,14 @@ export declare class InventoryCountOrderService<T extends InventoryCountOrderEnt
99
122
  /** Filters for the list page. All optional; combined with AND. */
100
123
  findMany(options: FindInventoryCountOrderInput, manager?: EntityManager): Promise<[InventoryCountOrderEntityClass[], number]>;
101
124
  findOne(id: string, manager?: EntityManager): Promise<InventoryCountOrderEntityClass>;
125
+ /**
126
+ * The count sheet, filtered and paginated.
127
+ *
128
+ * Server-side rather than handing the whole sheet to the client: a count over
129
+ * a whole warehouse is thousands of lines, and the operator's job is to narrow
130
+ * to the shelf in front of them.
131
+ */
132
+ findItems(orderId: string, options?: FindInventoryCountOrderItemInput, manager?: EntityManager): Promise<[InventoryCountOrderItemEntityClass[], number]>;
102
133
  create(input: CreateInventoryCountOrderInput, manager?: EntityManager): Promise<T>;
103
134
  update(id: string, input: UpdateInventoryCountOrderInput, manager?: EntityManager): Promise<T>;
104
135
  /**
@@ -4,12 +4,12 @@ import { DataSource, In } from 'typeorm';
4
4
  import { InventoryCountStatus } from '../constants/inventory-count-status.js';
5
5
  import '../models/metadata/batch.entity.js';
6
6
  import '../models/metadata/batch-group.entity.js';
7
- import '../models/metadata/loader.entity.js';
7
+ import { LoadersEntityClass } from '../models/metadata/loader.entity.js';
8
8
  import '../models/metadata/loader-type.entity.js';
9
9
  import '../models/metadata/loader-unit.entity.js';
10
10
  import '../models/metadata/location.entity.js';
11
11
  import '../models/metadata/material.entity.js';
12
- import '../models/metadata/material-unit.entity.js';
12
+ import { MaterialUnitEntityClass } from '../models/metadata/material-unit.entity.js';
13
13
  import '@rytass/wms-base-nestjs-module';
14
14
  import '../models/metadata/sale-order.entity.js';
15
15
  import '../models/metadata/stock.entity.js';
@@ -136,17 +136,34 @@ let InventoryCountOrderService = class InventoryCountOrderService {
136
136
  if (!locationIds.length) {
137
137
  return [];
138
138
  }
139
+ // The batch table is joined by name rather than through its repository
140
+ // because it is only read for its attribute columns — the same thing
141
+ // `StockService.selectQueryBuilder` does. Single-table inheritance means
142
+ // every configured batch entity shares this table, so the join is override
143
+ // safe; the name still comes from the configured entity's metadata rather
144
+ // than being hard-coded.
145
+ const batchTable = manager.getRepository(this.entities.batch).metadata
146
+ .tableName;
139
147
  // Through the repository, not raw SQL on the table: the stock entity is
140
148
  // overridable, and the repository is what applies the right
141
149
  // single-table-inheritance discriminator.
142
150
  const rows = await manager
143
151
  .getRepository(this.entities.stock)
144
152
  .createQueryBuilder('stock')
153
+ .leftJoin(batchTable, 'batch', 'batch.id = stock."batchId"')
145
154
  .select('stock.materialId', 'materialId')
146
155
  .addSelect('stock.batchId', 'batchId')
147
156
  .addSelect('stock.locationId', 'locationId')
148
157
  .addSelect('stock.loaderId', 'loaderId')
149
158
  .addSelect('SUM(stock.quantity)', 'quantity')
159
+ .addSelect('batch.held', 'held')
160
+ .addSelect('batch."inShipment"', 'inShipment')
161
+ .addSelect('batch."inspectionResult"', 'inspectionResult')
162
+ .addSelect('batch."transferId"', 'transferId')
163
+ .addSelect('batch."vendorId"', 'vendorId')
164
+ .addSelect('batch."customerId"', 'customerId')
165
+ .addSelect('batch."saleId"', 'saleId')
166
+ .addSelect('batch."saleSerialId"', 'saleSerialId')
150
167
  .where('stock.locationId IN (:...locationIds)', {
151
168
  locationIds: [...locationIds],
152
169
  })
@@ -154,6 +171,16 @@ let InventoryCountOrderService = class InventoryCountOrderService {
154
171
  .addGroupBy('stock.batchId')
155
172
  .addGroupBy('stock.locationId')
156
173
  .addGroupBy('stock.loaderId')
174
+ // Functionally dependent on batchId, but PostgreSQL only infers that from
175
+ // the grouped table's own primary key, so they have to be listed.
176
+ .addGroupBy('batch.held')
177
+ .addGroupBy('batch."inShipment"')
178
+ .addGroupBy('batch."inspectionResult"')
179
+ .addGroupBy('batch."transferId"')
180
+ .addGroupBy('batch."vendorId"')
181
+ .addGroupBy('batch."customerId"')
182
+ .addGroupBy('batch."saleId"')
183
+ .addGroupBy('batch."saleSerialId"')
157
184
  .having('SUM(stock.quantity) > 0')
158
185
  .getRawMany();
159
186
  return rows.map((row) => ({
@@ -162,6 +189,16 @@ let InventoryCountOrderService = class InventoryCountOrderService {
162
189
  locationId: row.locationId,
163
190
  loaderId: row.loaderId,
164
191
  quantity: Number(row.quantity),
192
+ attributes: {
193
+ held: row.held ?? null,
194
+ inShipment: row.inShipment ?? null,
195
+ inspectionResult: row.inspectionResult ?? null,
196
+ transferId: row.transferId ?? null,
197
+ vendorId: row.vendorId ?? null,
198
+ customerId: row.customerId ?? null,
199
+ saleId: row.saleId ?? null,
200
+ saleSerialId: row.saleSerialId ?? null,
201
+ },
165
202
  }));
166
203
  }
167
204
  positionKey(position) {
@@ -213,6 +250,7 @@ let InventoryCountOrderService = class InventoryCountOrderService {
213
250
  const item = byKey.get(key);
214
251
  if (item) {
215
252
  item.bookQuantity = position.quantity;
253
+ Object.assign(item, position.attributes);
216
254
  await repos.item.save(item);
217
255
  continue;
218
256
  }
@@ -226,6 +264,7 @@ let InventoryCountOrderService = class InventoryCountOrderService {
226
264
  countedQuantity: null,
227
265
  unitId: null,
228
266
  isAddition: false,
267
+ ...position.attributes,
229
268
  }));
230
269
  }
231
270
  // A position that emptied out between two rebuilds is no longer on the
@@ -291,6 +330,75 @@ let InventoryCountOrderService = class InventoryCountOrderService {
291
330
  async findOne(id, manager = this.dataSource.manager) {
292
331
  return this.loadOrderOrFail(id, manager);
293
332
  }
333
+ /**
334
+ * The count sheet, filtered and paginated.
335
+ *
336
+ * Server-side rather than handing the whole sheet to the client: a count over
337
+ * a whole warehouse is thousands of lines, and the operator's job is to narrow
338
+ * to the shelf in front of them.
339
+ */
340
+ async findItems(orderId, options = {}, manager = this.dataSource.manager) {
341
+ const tableOf = (entity) => manager.getRepository(entity).metadata.tableName;
342
+ const query = this.getRepositories(manager)
343
+ .item.createQueryBuilder('item')
344
+ .leftJoin(tableOf(this.entities.material), 'material', 'material.id = item."materialId"')
345
+ .leftJoin(tableOf(this.entities.batch), 'batch', 'batch.id = item."batchId"')
346
+ .leftJoin(tableOf(this.entities.location), 'location', 'location.id = item."locationId"')
347
+ .leftJoin(LoadersEntityClass, 'loader', 'loader.id = item."loaderId"')
348
+ .where('item."orderId" = :orderId', { orderId });
349
+ const like = (column, value, parameter) => {
350
+ if (!value)
351
+ return;
352
+ query.andWhere(`${column} ILIKE :${parameter}`, {
353
+ [parameter]: `%${value}%`,
354
+ });
355
+ };
356
+ like('material.key', options.materialKey, 'materialKey');
357
+ like('material.description', options.materialDescription, 'materialDescription');
358
+ like('batch.key', options.batchKey, 'batchKey');
359
+ like('location.key', options.locationKey, 'locationKey');
360
+ like('loader."serialId"', options.loaderSerialId, 'loaderSerialId');
361
+ const exact = (column, value, parameter) => {
362
+ if (!value)
363
+ return;
364
+ query.andWhere(`${column} = :${parameter}`, { [parameter]: value });
365
+ };
366
+ exact('item."vendorId"', options.vendorId, 'vendorId');
367
+ exact('item."customerId"', options.customerId, 'customerId');
368
+ exact('item."saleId"', options.saleId, 'saleId');
369
+ exact('item."saleSerialId"', options.saleSerialId, 'saleSerialId');
370
+ if (options.onlyVariance) {
371
+ // The counted quantity is expressed in the line's unit, so it has to be
372
+ // converted before it can be compared with the base-unit book quantity —
373
+ // the same conversion settlement applies.
374
+ query
375
+ .leftJoin(MaterialUnitEntityClass, 'unit', 'unit.id = item."unitId"')
376
+ .andWhere('item."countedQuantity" IS NOT NULL')
377
+ .andWhere('item."countedQuantity" * COALESCE(unit."conversionFactor", 1) <> item."bookQuantity"');
378
+ }
379
+ // Counted before ordering and paginating: `getCount()` rewrites the query
380
+ // into a COUNT, and an ORDER BY on a joined column it does not select makes
381
+ // that rewrite fail.
382
+ const total = await query.getCount();
383
+ // Additions first — they are what the operator just typed — then a stable
384
+ // order so paging cannot repeat or skip a line.
385
+ query
386
+ .orderBy('item."isAddition"', 'DESC')
387
+ .addOrderBy('material.key', 'ASC')
388
+ .addOrderBy('batch.key', 'ASC')
389
+ .addOrderBy('item.id', 'ASC');
390
+ // `limit`/`offset` rather than `take`/`skip`: the latter wraps the query in a
391
+ // DISTINCT subquery to survive one-to-many joins, and then cannot map an
392
+ // ORDER BY on a joined column into it. Every join here is many-to-one, so no
393
+ // row multiplication and no need for that machinery.
394
+ if (options.offset !== undefined && options.offset >= 0) {
395
+ query.offset(options.offset);
396
+ }
397
+ if (options.limit !== undefined && options.limit > 0) {
398
+ query.limit(options.limit);
399
+ }
400
+ return [await query.getMany(), total];
401
+ }
294
402
  async create(input, manager = this.dataSource.manager) {
295
403
  if (!input.locationIds.length) {
296
404
  throw new BadRequestException('An inventory count needs at least one location in scope');
@@ -411,6 +519,18 @@ let InventoryCountOrderService = class InventoryCountOrderService {
411
519
  bookQuantity: 0,
412
520
  countedQuantity: input.countedQuantity,
413
521
  isAddition: true,
522
+ // Snapshotted from the batch the same way a scoped line is, so an added
523
+ // line renders through the identical columns. A brand-new batch carries
524
+ // the defaults, which is exactly right: unbooked stock is not held, not
525
+ // in transfer and not inspected.
526
+ held: batch.held ?? null,
527
+ inShipment: batch.inShipment ?? null,
528
+ inspectionResult: batch.inspectionResult ?? null,
529
+ transferId: batch.transferId ?? null,
530
+ vendorId: batch.vendorId ?? null,
531
+ customerId: batch.customerId ?? null,
532
+ saleId: batch.saleId ?? null,
533
+ saleSerialId: batch.saleSerialId ?? null,
414
534
  }));
415
535
  }
416
536
  /** Remove an added line. Scoped lines are part of the sheet and never removed. */
@@ -314,7 +314,7 @@ let ReceiveInventoryOrderService = class ReceiveInventoryOrderService {
314
314
  const stockRepository = manager.getRepository(this.entities.stock);
315
315
  const items = await itemRepository.find({
316
316
  where: { id: In(options.map((o) => o.itemId)) },
317
- relations: ['changes'],
317
+ relations: { changes: true },
318
318
  });
319
319
  const itemMap = new Map(items.map((i) => [i.id, i]));
320
320
  await Promise.all(options.map(async (option) => {
@@ -325,7 +325,7 @@ let ShipInventoryOrderService = class ShipInventoryOrderService {
325
325
  // Find all items with changes to calculate cancellable quantities
326
326
  const items = await itemRepository.find({
327
327
  where: { orderId: id },
328
- relations: ['changes'],
328
+ relations: { changes: true },
329
329
  });
330
330
  // Build cancel inputs for items with remaining prepared quantity
331
331
  const cancelInputs = [];
@@ -367,7 +367,7 @@ let ShipInventoryOrderService = class ShipInventoryOrderService {
367
367
  const stockRepository = manager.getRepository(this.entities.stock);
368
368
  const items = await itemRepository.find({
369
369
  where: { id: In(options.map((o) => o.itemId)) },
370
- relations: ['changes'],
370
+ relations: { changes: true },
371
371
  });
372
372
  const itemMap = new Map(items.map((item) => [item.id, item]));
373
373
  await Promise.all(options.map(async (option) => {
@@ -524,7 +524,7 @@ let ShipInventoryOrderService = class ShipInventoryOrderService {
524
524
  const stockRepository = manager.getRepository(this.entities.stock);
525
525
  const items = await itemRepository.find({
526
526
  where: { id: In(options.map((option) => option.itemId)) },
527
- relations: ['changes'],
527
+ relations: { changes: true },
528
528
  });
529
529
  const itemMap = new Map(items.map((item) => [item.id, item]));
530
530
  await Promise.all(options.map(async (option) => {
@@ -263,6 +263,30 @@ let StockService = class StockService {
263
263
  queryBuilder.innerJoin(LoadersEntityClass, 'lk', 'lk.id = stock."loaderId" AND lk."serialId" ILIKE :loaderKey', {
264
264
  loaderKey: `%${options.loaderKey}%`,
265
265
  });
266
+ /*
267
+ * Vendor / customer / sale order live on the batch, so they need their own
268
+ * join. One join for all four rather than four joins: they are conditions on
269
+ * the same row, and repeating the join would multiply nothing but the plan.
270
+ *
271
+ * Exact match, not ILIKE: these are identifiers handed over by the host
272
+ * system, and a partial match on 「SO-1」 quietly sweeping in 「SO-10」 is the
273
+ * kind of wrong answer nobody notices. It also keeps this in step with the
274
+ * inventory count sheet, whose four filters match the same way.
275
+ */
276
+ const batchAttributeFilters = [
277
+ ['vendorId', options.vendorId],
278
+ ['customerId', options.customerId],
279
+ ['saleId', options.saleId],
280
+ ['saleSerialId', options.saleSerialId],
281
+ ].filter(([, value]) => Boolean(value));
282
+ if (batchAttributeFilters.length) {
283
+ queryBuilder.innerJoin(this.entities.batch, 'ba', 'ba.id = stock."batchId"');
284
+ for (const [column, value] of batchAttributeFilters) {
285
+ queryBuilder.andWhere(`ba."${column}" = :${column}`, {
286
+ [column]: value,
287
+ });
288
+ }
289
+ }
266
290
  if (options.offset !== undefined && options.offset >= 0)
267
291
  queryBuilder.skip(options.offset);
268
292
  if (options.limit !== undefined && options.limit > 0)
@@ -174,7 +174,7 @@ let TransferCustomerOrderService = class TransferCustomerOrderService {
174
174
  if (items?.length) {
175
175
  const existingItemIds = new Set((await repos.transferCustomerOrderItem.find({
176
176
  where: { orderId: id },
177
- relations: ['changes'],
177
+ relations: { changes: true },
178
178
  })).map((item) => item.id));
179
179
  const newItems = [];
180
180
  const existingItems = [];
@@ -162,7 +162,7 @@ let TransferOrderService = class TransferOrderService {
162
162
  const repos = this.getRepositories(manager);
163
163
  const items = await repos.transferOrderItem.find({
164
164
  where: { id: In(options.map((o) => o.itemId)) },
165
- relations: ['changes'],
165
+ relations: { changes: true },
166
166
  });
167
167
  const itemMap = new Map(items.map((item) => [item.id, item]));
168
168
  // Whole-loader transfer cancel validation (Phase 2d-sync).
@@ -261,7 +261,7 @@ let TransferOrderService = class TransferOrderService {
261
261
  // Find all items with changes to calculate cancellable quantities
262
262
  const items = await repos.transferOrderItem.find({
263
263
  where: { orderId: id },
264
- relations: ['changes'],
264
+ relations: { changes: true },
265
265
  });
266
266
  // Build cancel inputs for items with remaining pending quantity
267
267
  const cancelInputs = [];
@@ -470,7 +470,7 @@ let TransferOrderService = class TransferOrderService {
470
470
  const stockRepository = manager.getRepository(this.stockEntity);
471
471
  const items = await itemRepository.find({
472
472
  where: { id: In(options.map((o) => o.itemId)) },
473
- relations: ['changes'],
473
+ relations: { changes: true },
474
474
  });
475
475
  const itemMap = new Map(items.map((item) => [item.id, item]));
476
476
  const inputMap = new Map(options.map((o) => [o.itemId, o]));
@@ -496,7 +496,7 @@ let TransferOrderService = class TransferOrderService {
496
496
  if (orderId) {
497
497
  const allOrderItems = await itemRepository.find({
498
498
  where: { orderId },
499
- relations: ['changes'],
499
+ relations: { changes: true },
500
500
  });
501
501
  for (const orderItem of allOrderItems) {
502
502
  if (orderItem.removedAt)
@@ -174,7 +174,7 @@ let TransferVendorOrderService = class TransferVendorOrderService {
174
174
  if (items?.length) {
175
175
  const existingItemIds = new Set((await repos.transferVendorOrderItem.find({
176
176
  where: { orderId: id },
177
- relations: ['changes'],
177
+ relations: { changes: true },
178
178
  })).map((item) => item.id));
179
179
  const newItems = [];
180
180
  const existingItems = [];
@@ -18,4 +18,20 @@ export type FindStockInput<U extends object> = PaginationInput & {
18
18
  batchKey?: string;
19
19
  locationKey?: string;
20
20
  loaderKey?: string;
21
+ /**
22
+ * Commercial attributes of the stock's batch.
23
+ *
24
+ * They live on the batch table, not on stock, which is why they need their own
25
+ * join rather than a plain `andWhere` — the same four columns the aggregated
26
+ * projection already selects (`vendorId` / `customerId` / `saleId` /
27
+ * `saleSerialId`), so filtering and displaying stay in step.
28
+ *
29
+ * `null` is accepted and treated as "not filtering": the aggregated-stock
30
+ * lookups pass a whole `AggregatedStock` through here, and those columns are
31
+ * nullable on the batch.
32
+ */
33
+ vendorId?: string | null;
34
+ customerId?: string | null;
35
+ saleId?: string | null;
36
+ saleSerialId?: string | null;
21
37
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rytass/wms-module-core",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Rytass WMS Module — NestJS services and TypeORM entities for warehouse management",
5
5
  "keywords": [
6
6
  "rytass",
@@ -41,13 +41,13 @@
41
41
  "access": "public"
42
42
  },
43
43
  "dependencies": {
44
- "@rytass/wms-base-nestjs-module": "0.4.0"
44
+ "luxon": "^3.0.0"
45
45
  },
46
46
  "peerDependencies": {
47
- "@nestjs/common": "^11.0.0",
48
- "@nestjs/typeorm": "^11.0.0",
47
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
48
+ "@nestjs/typeorm": "^10.0.0 || ^11.0.0",
49
+ "@rytass/wms-base-nestjs-module": "^0.4.0",
49
50
  "reflect-metadata": "^0.1.13 || ^0.2.0",
50
- "rxjs": "^7.8.0",
51
- "typeorm": "^0.3.0"
51
+ "typeorm": "^0.3.0 || ^1.0.0"
52
52
  }
53
53
  }