@rytass/wms-module-core 0.9.0 → 0.10.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 (143) hide show
  1. package/README.md +15 -2
  2. package/docs/README.md +2 -2
  3. package/docs/api-reference.md +129 -10
  4. package/docs/host-integration.md +172 -0
  5. package/docs/integration-guide.md +84 -43
  6. package/index.cjs.js +2454 -1658
  7. package/index.d.ts +2 -0
  8. package/lib/events/inventory-count-lock.subscriber.d.ts +17 -5
  9. package/lib/models/metadata/index.d.ts +1 -0
  10. package/lib/models/metadata/sequence.entity.d.ts +9 -0
  11. package/lib/models/models.module.d.ts +7 -0
  12. package/lib/services/allocate-inventory-order.service.d.ts +3 -3
  13. package/lib/services/batch.service.d.ts +13 -1
  14. package/lib/services/consumption-order.service.d.ts +6 -6
  15. package/lib/services/helper.service.d.ts +10 -4
  16. package/lib/services/hold-inventory-order.service.d.ts +3 -3
  17. package/lib/services/index.d.ts +1 -0
  18. package/lib/services/inventory-count-order.service.d.ts +28 -9
  19. package/lib/services/loader.service.d.ts +11 -3
  20. package/lib/services/material.service.d.ts +1 -1
  21. package/lib/services/merge-batch-order.service.d.ts +2 -2
  22. package/lib/services/quality-inspection-order.service.d.ts +1 -1
  23. package/lib/services/receive-inventory-order.service.d.ts +4 -4
  24. package/lib/services/reclassify-inventory-order.service.d.ts +2 -2
  25. package/lib/services/scrape.service.d.ts +1 -1
  26. package/lib/services/sequence.service.d.ts +58 -0
  27. package/lib/services/ship-inventory-order.service.d.ts +6 -6
  28. package/lib/services/split-batch-order.service.d.ts +2 -2
  29. package/lib/services/stock.service.d.ts +48 -2
  30. package/lib/services/transfer-customer-order.service.d.ts +3 -3
  31. package/lib/services/transfer-order.service.d.ts +7 -5
  32. package/lib/services/transfer-vendor-order.service.d.ts +3 -3
  33. package/lib/table-prefix/logical-table-name.d.ts +21 -0
  34. package/lib/table-prefix/table-prefix.d.ts +30 -0
  35. package/lib/typings/core-module-options.d.ts +31 -0
  36. package/lib/typings/create-transfer-order.input.d.ts +2 -0
  37. package/lib/typings/index.d.ts +20 -0
  38. package/lib/utils/run-in-transaction.d.ts +23 -0
  39. package/lib/utils/table-path.d.ts +13 -0
  40. package/package.json +9 -6
  41. package/index.js +0 -98
  42. package/lib/constants/consumption-change-kind.js +0 -20
  43. package/lib/constants/inventory-count-status.js +0 -22
  44. package/lib/constants/operations.js +0 -76
  45. package/lib/constants/order-type.js +0 -33
  46. package/lib/constants/stock-status.js +0 -61
  47. package/lib/core.module.js +0 -287
  48. package/lib/events/dispatch-scope.js +0 -29
  49. package/lib/events/inventory-count-lock.subscriber.js +0 -98
  50. package/lib/events/stock-change.subscriber.js +0 -252
  51. package/lib/events/wms-event.collector.js +0 -22
  52. package/lib/events/wms-event.dispatcher.js +0 -63
  53. package/lib/events/wms-event.tokens.js +0 -12
  54. package/lib/events/wms-operation-runner.js +0 -101
  55. package/lib/models/extensions/allocate-inventory-order/allocate-inventory-order-change.entity.js +0 -40
  56. package/lib/models/extensions/allocate-inventory-order/allocate-inventory-order-item.entity.js +0 -104
  57. package/lib/models/extensions/allocate-inventory-order/allocate-inventory-order.entity.js +0 -33
  58. package/lib/models/extensions/consumption-order/consumption-order-change.entity.js +0 -59
  59. package/lib/models/extensions/consumption-order/consumption-order-item.entity.js +0 -114
  60. package/lib/models/extensions/consumption-order/consumption-order.entity.js +0 -69
  61. package/lib/models/extensions/hold-inventory-order/hold-inventory-order-change.entity.js +0 -40
  62. package/lib/models/extensions/hold-inventory-order/hold-inventory-order-item.entity.js +0 -98
  63. package/lib/models/extensions/hold-inventory-order/hold-inventory-order.entity.js +0 -43
  64. package/lib/models/extensions/inventory-count-order/inventory-count-order-change.entity.js +0 -50
  65. package/lib/models/extensions/inventory-count-order/inventory-count-order-item.entity.js +0 -191
  66. package/lib/models/extensions/inventory-count-order/inventory-count-order.entity.js +0 -155
  67. package/lib/models/extensions/merge-batch-order/merge-batch-order-change.entity.js +0 -40
  68. package/lib/models/extensions/merge-batch-order/merge-batch-order-item.entity.js +0 -75
  69. package/lib/models/extensions/merge-batch-order/merge-batch-order.entity.js +0 -33
  70. package/lib/models/extensions/order-reference/order-reference.entity.js +0 -95
  71. package/lib/models/extensions/quality-inspection-order/quality-inspection-order-change.entity.js +0 -45
  72. package/lib/models/extensions/quality-inspection-order/quality-inspection-order-item.entity.js +0 -94
  73. package/lib/models/extensions/quality-inspection-order/quality-inspection-order.entity.js +0 -38
  74. package/lib/models/extensions/receive-inventory-order/receive-inventory-order-change.entity.js +0 -46
  75. package/lib/models/extensions/receive-inventory-order/receive-inventory-order-item.entity.js +0 -89
  76. package/lib/models/extensions/receive-inventory-order/receive-inventory-order.entity.js +0 -57
  77. package/lib/models/extensions/reclassify-inventory-order/reclassify-inventory-order-change.entity.js +0 -40
  78. package/lib/models/extensions/reclassify-inventory-order/reclassify-inventory-order-item.entity.js +0 -75
  79. package/lib/models/extensions/reclassify-inventory-order/reclassify-inventory-order.entity.js +0 -33
  80. package/lib/models/extensions/scrape-order/scrape-order-change.entity.js +0 -40
  81. package/lib/models/extensions/scrape-order/scrape-order-item.entity.js +0 -94
  82. package/lib/models/extensions/scrape-order/scrape-order.entity.js +0 -33
  83. package/lib/models/extensions/ship-inventory-order/ship-inventory-order-change.entity.js +0 -46
  84. package/lib/models/extensions/ship-inventory-order/ship-inventory-order-item.entity.js +0 -90
  85. package/lib/models/extensions/ship-inventory-order/ship-inventory-order-reference.entity.js +0 -65
  86. package/lib/models/extensions/ship-inventory-order/ship-inventory-order.entity.js +0 -56
  87. package/lib/models/extensions/split-batch-order/split-batch-order-change.entity.js +0 -40
  88. package/lib/models/extensions/split-batch-order/split-batch-order-item.entity.js +0 -75
  89. package/lib/models/extensions/split-batch-order/split-batch-order.entity.js +0 -33
  90. package/lib/models/extensions/transfer-customer-order/transfer-customer-order-change.entity.js +0 -40
  91. package/lib/models/extensions/transfer-customer-order/transfer-customer-order-item.entity.js +0 -99
  92. package/lib/models/extensions/transfer-customer-order/transfer-customer-order.entity.js +0 -33
  93. package/lib/models/extensions/transfer-order/transfer-order-change.entity.js +0 -40
  94. package/lib/models/extensions/transfer-order/transfer-order-item.entity.js +0 -109
  95. package/lib/models/extensions/transfer-order/transfer-order.entity.js +0 -53
  96. package/lib/models/extensions/transfer-vendor-order/transfer-vendor-order-change.entity.js +0 -40
  97. package/lib/models/extensions/transfer-vendor-order/transfer-vendor-order-item.entity.js +0 -99
  98. package/lib/models/extensions/transfer-vendor-order/transfer-vendor-order.entity.js +0 -33
  99. package/lib/models/metadata/batch-group.entity.js +0 -31
  100. package/lib/models/metadata/batch.entity.js +0 -131
  101. package/lib/models/metadata/loader-type.entity.js +0 -43
  102. package/lib/models/metadata/loader-unit.entity.js +0 -21
  103. package/lib/models/metadata/loader.entity.js +0 -98
  104. package/lib/models/metadata/location.entity.js +0 -28
  105. package/lib/models/metadata/material-unit.entity.js +0 -51
  106. package/lib/models/metadata/material.entity.js +0 -28
  107. package/lib/models/metadata/order.entity.js +0 -5
  108. package/lib/models/metadata/sale-order.entity.js +0 -21
  109. package/lib/models/metadata/stock.entity.js +0 -29
  110. package/lib/models/metadata/unit.entity.js +0 -21
  111. package/lib/models/models.module.js +0 -158
  112. package/lib/models/wms-entities.js +0 -82
  113. package/lib/services/allocate-inventory-order.service.js +0 -310
  114. package/lib/services/base-order.service.js +0 -76
  115. package/lib/services/batch.service.js +0 -272
  116. package/lib/services/consumption-order.service.js +0 -504
  117. package/lib/services/helper.service.js +0 -28
  118. package/lib/services/hold-inventory-order.service.js +0 -296
  119. package/lib/services/inventory-count-order.service.js +0 -648
  120. package/lib/services/loader.service.js +0 -291
  121. package/lib/services/location.service.js +0 -139
  122. package/lib/services/material.service.js +0 -181
  123. package/lib/services/merge-batch-order.service.js +0 -206
  124. package/lib/services/order-reference.service.js +0 -136
  125. package/lib/services/quality-inspection-order.service.js +0 -146
  126. package/lib/services/receive-inventory-order.service.js +0 -468
  127. package/lib/services/reclassify-inventory-order.service.js +0 -192
  128. package/lib/services/sale-order.service.js +0 -20
  129. package/lib/services/scrape.service.js +0 -150
  130. package/lib/services/ship-inventory-order.service.js +0 -610
  131. package/lib/services/split-batch-order.service.js +0 -191
  132. package/lib/services/stock.service.js +0 -559
  133. package/lib/services/transfer-customer-order.service.js +0 -290
  134. package/lib/services/transfer-order.service.js +0 -641
  135. package/lib/services/transfer-vendor-order.service.js +0 -290
  136. package/lib/services/unit.service.js +0 -76
  137. package/lib/services/warehouse-map.service.js +0 -50
  138. package/lib/typings/core-module-options.js +0 -3
  139. package/lib/typings/entity-overrides.d.ts +0 -34
  140. package/lib/typings/entity-overrides.js +0 -7
  141. package/lib/typings/find-receive-inventory-order.input.js +0 -9
  142. package/lib/typings/find-ship-inventory-order.input.js +0 -9
  143. package/src/lib/models/extensions/README.md +0 -219
package/README.md CHANGED
@@ -48,6 +48,10 @@ export class AppModule {}
48
48
 
49
49
  Use `WmsModuleCoreModule.forRootAsync({ ... })` when you need to load options from a config service or async source. The async signature merges `WMSBaseModuleAsyncOptions` (factory / inject pattern from the base module) with the three `default*` keys above.
50
50
 
51
+ ## Table prefix and host transactions
52
+
53
+ To keep WMS tables out of your own namespace, wrap **every** `DataSource`'s options (runtime and migration CLI) with `withWmsTablePrefix(options, 'wms_')`. Every write method also accepts your transaction's `EntityManager`, so a WMS movement commits or rolls back with your own rows. See [`docs/host-integration.md`](./docs/host-integration.md).
54
+
51
55
  ## Injecting services
52
56
 
53
57
  Every domain service is exported and injectable once `WmsModuleCoreModule` is imported:
@@ -93,8 +97,16 @@ a surplus may name a batch that does not exist yet (it is created during settlem
93
97
  > any stock movement touching a location in its scope is refused with a `ConflictException`
94
98
  > naming the count — including movements your own code makes by calling a service
95
99
  > directly. The check sits on the insert of every `*_order_change` row, so it covers every
96
- > path without any service needing to know about it. This is what keeps the book snapshot
97
- > the variance is measured against from going stale.
100
+ > path without any service needing to know about it, and it looks at both ends of a
101
+ > movement: a transfer *into* a counted location is refused too. This is what keeps the
102
+ > book snapshot the variance is measured against from going stale.
103
+
104
+ Every mutating method runs in one transaction and takes an optional `EntityManager` as
105
+ its last argument to join one you already hold. `settle()` re-reads the ledger before it
106
+ writes and refuses with a `ConflictException` if a scoped line's `bookQuantity` no longer
107
+ matches it — the lock makes that impossible through this package, so a mismatch means
108
+ something wrote to `stocks` around it.
109
+
98
110
 
99
111
  ## Operation names
100
112
 
@@ -172,6 +184,7 @@ Full documentation is shipped inside this package under the `docs/` directory (a
172
184
  | [`docs/integration-guide.md`](./docs/integration-guide.md) | Step-by-step wiring guide for NestJS + Next.js consumers |
173
185
  | [`docs/api-reference.md`](./docs/api-reference.md) | Complete export catalog with signatures and usage examples |
174
186
  | [`docs/custom-entities.md`](./docs/custom-entities.md) | Using your own entity as the WMS material master, and the audit of the other entity options |
187
+ | [`docs/host-integration.md`](./docs/host-integration.md) | Using the core as a service layer inside your own transactions: table prefix, external `EntityManager`, post-commit events, deduction locks, counters, default rows |
175
188
 
176
189
  GitHub hosted links (always up-to-date):
177
190
 
package/docs/README.md CHANGED
@@ -7,7 +7,7 @@ Reference material for consumers of `@rytass/wms-module-{core,graphql,react}`.
7
7
  | Document | Description |
8
8
  |------------------------------------------------|---------------------------------------------------------------------------------------------------|
9
9
  | [Integration Guide](./integration-guide.md) | Step-by-step instructions for wiring the three packages into a new consumer project (NestJS + Next.js + PostgreSQL). Includes ready-to-paste `_app.tsx`, `app.module.ts`, `next.config.ts`, the 19 Pages Router shell pattern, AuthGuard stub, seed script template, deployment notes, and known issues. |
10
- | [API Reference](./api-reference.md) | Complete export catalog for all three packages — every NestJS module, TypeORM entity, GraphQL resolver, DTO, React component, hook, and utility, organized by role with source paths and usage examples. Mirrors the actual `src/index.ts` barrel exports of v0.1.2. |
10
+ | [API Reference](./api-reference.md) | Complete export catalog for all three packages — every NestJS module, TypeORM entity, GraphQL resolver, DTO, React component, hook, and utility, organized by role with source paths and usage examples. Mirrors the actual `src/index.ts` barrel exports. |
11
11
  | [Custom Entities](./custom-entities.md) | How to make a downstream project's own table serve as the WMS's own — the `materialEntity` override, why entity classes are configured synchronously, what single-table inheritance means for existing rows, and an audit of the entity options that are not honoured above the base layer yet. |
12
12
 
13
13
  ## Quick links
@@ -30,6 +30,6 @@ Reference material for consumers of `@rytass/wms-module-{core,graphql,react}`.
30
30
 
31
31
  ## Versioning
32
32
 
33
- These documents track the **latest published `0.1.x` release**. Anything in `main` that has not yet been released is marked clearly inline; otherwise assume the documented signature matches the current npm-published library.
33
+ These documents track the **latest published release**. Anything in `main` that has not yet been released is marked clearly inline; otherwise assume the documented signature matches the current npm-published library.
34
34
 
35
35
  When you upgrade the lib, check each package's `CHANGELOG.md` for breaking changes that may affect the snippets here.
@@ -6,7 +6,7 @@ Complete export catalog for the three publishable libraries:
6
6
  - `@rytass/wms-module-graphql` — GraphQL resolvers, DTOs, DataLoader helpers
7
7
  - `@rytass/wms-module-react` — React components, hooks, Apollo client, GraphQL operations
8
8
 
9
- Current versions: **0.1.2** (all three packages).
9
+ 本文件不另記版本號;各 package 的現行版本以其 `package.json` 與 `CHANGELOG.md` 為準。
10
10
 
11
11
  This document mirrors the actual `src/index.ts` barrel exports and is generated by static analysis of the lib sources. For runtime behavior changes between versions, see each package's `CHANGELOG.md`.
12
12
 
@@ -104,7 +104,7 @@ WmsModuleCoreModule.forRootAsync({
104
104
 
105
105
  ## TypeORM Entities(Extensions — 訂單與作業)
106
106
 
107
- 同樣每個都有 Symbol + EntityClass 雙匯出,共 37 個:
107
+ 同樣每個都有 Symbol + EntityClass 雙匯出。以下依領域列出,並非逐一窮舉;完整清單見 `lib/models/extensions/index.ts`(Symbol 共 45 個):
108
108
 
109
109
  **盤點單 (Inventory Count Order)**
110
110
  - `InventoryCountOrderEntity` / `InventoryCountOrderEntityClass` — 盤點單主檔(`countDate` 為盤差記帳基準日)
@@ -188,6 +188,20 @@ WmsModuleCoreModule.forRootAsync({
188
188
  - `ScrapeOrderChangeEntity` / `ScrapeOrderChangeEntityClass`
189
189
  - 來源: `lib/models/extensions/scrape-order/`
190
190
 
191
+ **耗料訂單 (Consumption Order)** — 交給加工流程的物料:領料(issue)、退料(return)、消耗(settle)
192
+ - `ConsumptionOrderEntity` / `ConsumptionOrderEntityClass`
193
+ - `ConsumptionOrderItemEntity` / `ConsumptionOrderItemEntityClass`
194
+ - `ConsumptionOrderChangeEntity` / `ConsumptionOrderChangeEntityClass` — 另有 `kind` 欄位(`ISSUE` / `RETURN` / `SETTLE`),因為退料與消耗都是負數,符號無法區分
195
+ - 來源: `lib/models/extensions/consumption-order/`
196
+
197
+ **單據參考 (Order Reference)** — 訂單開立於宿主的哪份文件(`order_references`,多型表)
198
+ - `OrderReferenceEntity` / `OrderReferenceEntityClass`
199
+ - 來源: `lib/models/extensions/order-reference/`
200
+ - 注意:與 `ShipInventoryOrderReferenceEntity`(出庫單的行級出貨計畫)不是同一個東西,兩者並存。
201
+
202
+ **計數器(僅 `sequenceStorage: 'table'` 時使用)**
203
+ - `SequenceEntity` / `SequenceEntityClass` — 來源: `lib/models/metadata/sequence.entity.ts`
204
+
191
205
  **另有輔助 provider**
192
206
  - `ResolvedEntitiesProviders: Provider[]` — 由 `ModelsModule` 內部使用,把所有 [Symbol, EntityClass] pair 轉為 NestJS DI providers,供服務注入實體 class。
193
207
  - 來源: `lib/models/models.module.ts`
@@ -203,7 +217,7 @@ WmsModuleCoreModule.forRootAsync({
203
217
  | `BatchService<T>` | `getBatch`, `splitBatch`, `findMany` | 批號管理 | `lib/services/batch.service.ts` |
204
218
  | `LoaderService<T, K>` | `createLoader`, `createBatchLoaders`, `updateLoader`, `createLoaderType`, `updateLoaderType`, `getSeq`, `findManyLoaders`, `findManyLoaderTypes` | 載具與類型 CRUD | `lib/services/loader.service.ts` |
205
219
  | `LocationService<T>` | `createLocation`, `updateLocation`, `findMany` | 庫位 CRUD | `lib/services/location.service.ts` |
206
- | `StockService<T>` | `findMany`, `findManyGroupedByMaterialId`, `findAggregatedStock`, `validateStockAvailability`, `findAggregatedStocks`, `findChangeLogs`, `resolveLoaderId`, `resolveLocationId` | 庫存查詢與聚合 | `lib/services/stock.service.ts` |
220
+ | `StockService<T>` | `findMany`, `findManyGroupedByMaterialId`, `findAggregatedStock`, `findAggregatedStocks`, `findChangeLogs`, `lockStockSlots`, `validateStockAvailability`, `resolveLoaderId`, `resolveLocationId` | 庫存查詢與聚合;扣帳前的鎖與可用量檢查(需在交易內呼叫,見下方「寫入方法與 EntityManager」) | `lib/services/stock.service.ts` |
207
221
  | `ReceiveInventoryOrderService<T>` | `createReceiveInventoryOrder`, `updateReceiveInventoryOrder`, `removeReceiveInventoryOrder`, `findMany`, `receive` | 入庫單管理 | `lib/services/receive-inventory-order.service.ts` |
208
222
  | `ShipInventoryOrderService<T>` | `createShipInventoryOrder`, `updateShipInventoryOrder`, `removeShipInventoryOrder`, `findMany`, `addShipInventoryOrderItems`, `ship`, `cancelShip` | 出庫單管理 | `lib/services/ship-inventory-order.service.ts` |
209
223
  | `TransferOrderService<T>` | `createTransferOrder`, `updateTransferOrder`, `findMany`, `transfer`, `cancelTransfer`, `removeTransferOrder` | 調撥單管理 | `lib/services/transfer-order.service.ts` |
@@ -218,16 +232,82 @@ WmsModuleCoreModule.forRootAsync({
218
232
  | `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` |
219
233
  | `QualityInspectionOrderService<T>` | `inspect` | 品質檢驗 | `lib/services/quality-inspection-order.service.ts` |
220
234
  | `SaleOrderService` | (DataSource 直接操作) | 銷售訂單查詢 | `lib/services/sale-order.service.ts` |
235
+ | `ConsumptionOrderService<T>` | `createConsumptionOrder`, `updateConsumptionOrder`, `removeConsumptionOrder`, `issue`, `return`, `settle`, `getProgress`, `findMany`, `findOne`, `findItemsByOrders` | 耗料單。沒有 `IN_PRODUCTION` 狀態:未消耗的部分以位置表示(領料後的批號落在消耗位置);`getProgress` 每次都從異動列回算,不做非正規化欄位 | `lib/services/consumption-order.service.ts` |
236
+ | `OrderReferenceService` | `attach`, `replace`, `detach`, `findMany`, `findByOrders` | 訂單對宿主文件的參照(`order_references`) | `lib/services/order-reference.service.ts` |
237
+ | `WmsSequenceService` | `reserve` | 訂單號與載具序號的計數器(取號,不用 `CURRVAL`) | `lib/services/sequence.service.ts` |
238
+ | `BaseOrderService` (abstract) | `add`, `deduct`(皆為 `protected`,供子類別呼叫) | 各訂單 service 的共用基底(以 class 匯出);只寫 `orders` 與 `stocks`,**不寫** `*_order_changes`,直接繼承的宿主要自行負責異動列與 `stock.*` 事件 | `lib/services/base-order.service.ts` |
221
239
  | `HelperService` | `getSeq` | 序號產生工具 | `lib/services/helper.service.ts` |
222
240
  | `WarehouseMapDataService` | `onApplicationBootstrap` | 倉庫地圖資料初始化,implements `OnApplicationBootstrap` | `lib/services/warehouse-map.service.ts` |
223
241
 
224
242
  ---
225
243
 
244
+ ## 寫入方法與 EntityManager
245
+
246
+ 凡是寫入 `stocks` 或 `*_order_changes` 的公開方法,都接受一個可選的 `EntityManager`,讓宿主可以把 WMS 異動與自己的寫入放進**同一個交易**。傳入方式有兩種:
247
+
248
+ - **尾端參數**:`outerManager?` / `manager?`(例如 `ship(options, outerManager?)`)
249
+ - **options 物件內的 `manager`**:例如 `createReceiveInventoryOrder({ manager, ...input })`、`updateTransferOrder({ manager, ...input })`
250
+
251
+ 方法內部統一經由 `runInTransaction(dataSource, manager, work)`(見下方「Utilities」)執行:傳入的 manager 已在交易中就直接沿用;沒有傳入則開新交易。交易內的**每一個**讀寫都必須走收到的 manager,不可改用 `this.dataSource` 或注入的 repository,否則會在另一條連線上執行,等待交易持有的庫存鎖而死鎖。
252
+
253
+ | Service | 寫入方法 | manager 位置 |
254
+ |---|---|---|
255
+ | `StockService` | `lockStockSlots(slots, manager)`、`validateStockAvailability(params, manager)` | **必填**(第 2 個參數);必須在進行中的交易內,否則拋錯 |
256
+ | `StockService` | `findAggregatedStock`、`findAggregatedStocks` | 讀取;可選,預設 `dataSource.manager` |
257
+ | `WmsSequenceService` | `reserve(name, count?, manager?, options?)` | 第 3 個參數 |
258
+ | `HelperService` | `getSeq(prefix, manager?)` | 第 2 個參數 |
259
+ | `LoaderService` | `getSeq(prefix, count, manager?, maxDigits?)` | 第 3 個參數 |
260
+ | `LoaderService` | `createLoader`、`updateLoader`、`createLoaderType`、`updateLoaderType` | options 物件內的 `manager` |
261
+ | `LoaderService` | `createBatchLoaders({ options, manager })` | 物件內的 `manager` |
262
+ | `BatchService` | `getBatch`、`splitBatch` | options 物件內的 `manager` |
263
+ | `MaterialService` | `createMaterial`、`updateMaterial`、`getConversionFactor(materialId, unitId?, manager?)` | options 物件內的 `manager`;`getConversionFactor` 為尾端參數 |
264
+ | `OrderReferenceService` | `attach`、`replace` | options 物件內的 `manager` |
265
+ | `OrderReferenceService` | `detach(id, manager?)` | 第 2 個參數 |
266
+ | `ReceiveInventoryOrderService` | `createReceiveInventoryOrder`、`updateReceiveInventoryOrder` | options 物件內的 `manager` |
267
+ | `ReceiveInventoryOrderService` | `receive(options, outerManager?)`、`removeReceiveInventoryOrder(id, manager?)` | 尾端參數 |
268
+ | `ShipInventoryOrderService` | `createShipInventoryOrder`、`updateShipInventoryOrder` | options 物件內的 `manager` |
269
+ | `ShipInventoryOrderService` | `removeShipInventoryOrder`、`addShipInventoryOrderItems`、`ship`、`cancelShip` | 尾端參數 `outerManager?` |
270
+ | `TransferOrderService` | `createTransferOrder`、`transfer`、`cancelTransfer`、`removeTransferOrder` | 尾端參數 `outerManager?` |
271
+ | `TransferOrderService` | `updateTransferOrder` | options 物件內的 `manager` |
272
+ | `TransferCustomerOrderService` / `TransferVendorOrderService` | `createTransferCustomerOrder` / `createTransferVendorOrder`、`returnTransferCustomerOrder` / `returnTransferVendorOrder` | 尾端參數 `outerManager?` |
273
+ | `TransferCustomerOrderService` / `TransferVendorOrderService` | `updateTransferCustomerOrder` / `updateTransferVendorOrder` | options 物件內的 `manager` |
274
+ | `HoldInventoryOrderService` | `createHoldInventoryOrder` | 尾端參數 `outerManager?` |
275
+ | `HoldInventoryOrderService` | `updateHoldInventoryOrder` | options 物件內的 `manager` |
276
+ | `HoldInventoryOrderService` | `release(options, outerManager?)` | 尾端參數 |
277
+ | `AllocateInventoryOrderService` | `createAllocateInventoryOrder`、`updateAllocateInventoryOrder` | 尾端參數(create)/options 物件內的 `manager`(update) |
278
+ | `AllocateInventoryOrderService` | `deallocate(options, outerManager?)` | 尾端參數 |
279
+ | `SplitBatchOrderService` / `MergeBatchOrderService` | `split(options, outerManager?)`、`merge(options, outerManager?)` | 尾端參數 |
280
+ | `ReclassifyInventoryOrderService` | `reclassify(options, outerManager?)` | 尾端參數 |
281
+ | `ScrapeService` | `scrape(items, outerManager?)` | 尾端參數 |
282
+ | `QualityInspectionOrderService` | `inspect({ manager, options })` | 物件內的 `manager` |
283
+ | `InventoryCountOrderService` | `create`、`update`、`start`、`count`、`addItem`、`removeItem`、`reset`、`cancel`、`settle` | 尾端參數 `outerManager?`;`findMany` / `findOne` / `findItems` 為讀取,預設 `dataSource.manager` |
284
+ | `ConsumptionOrderService` | `createConsumptionOrder`、`updateConsumptionOrder`、`removeConsumptionOrder`、`issue`、`return`、`settle` | 尾端參數 `outerManager?` / `manager?`;`getProgress` 為讀取,預設 `dataSource.manager` |
285
+
286
+ `StockService.lockStockSlots` 與 `validateStockAvailability` 的 manager 是**必填**的,而不是可選:沒有交易的 manager 會在鎖被釋放後才做檢查,所以直接拒絕。`lockStockSlots` 收到缺 `materialId` 或 `batchId` 的 slot 也會拋錯,而不是靜默略過。
287
+
288
+ > 使用範例(宿主在同一交易內扣庫存與寫自己的 outbox):
289
+ > ```ts
290
+ > await dataSource.transaction(async (manager) => {
291
+ > await stockService.validateStockAvailability({ materialId, batchId, quantity }, manager);
292
+ > await shipService.ship({ /* … */ }, manager);
293
+ > await manager.insert(OutboxEntity, { /* … */ });
294
+ > });
295
+ > ```
296
+
297
+ ---
298
+
226
299
  ## Interfaces / Types
227
300
 
228
301
  ### 模組選項
229
- - `WmsModuleCoreModuleOptions` — `{ defaultLoaderSerialId: string; defaultLoaderTypeKey: string; defaultLocationKey: string; }`
302
+ - `WmsModuleCoreModuleOptions` — 必填:`defaultLoaderSerialId`、`defaultLoaderTypeKey`、`defaultLocationKey`;選填:
303
+ - `tablePrefix?: string` — 宣告期望的資料表前綴,只做檢查:啟動時若資料表沒有此前綴就失敗(表示忘了在 runtime `DataSource` 上呼叫 `withWmsTablePrefix`)。實際套用前綴的是 `withWmsTablePrefix`,必須在 `DataSource` 初始化前完成,因為 options 解析得太晚。
304
+ - `sequenceStorage?: 'sequence' | 'table'`(預設 `'sequence'`)— 計數器存放位置。`'sequence'` 使用每個計數器一個 PostgreSQL sequence(既有部署的編號會延續);`'table'` 使用 `sequences` 表,單一 `INSERT … ON CONFLICT … RETURNING`,執行期不做 DDL,且交易回滾時不留空號。`'table'` 從 1 開始,既有部署不可直接切換,否則會重發號碼。
305
+ - `seedDefaults?: boolean`(預設 `true`)— 啟動時建立預設載具類型、庫位與載具(冪等)。設為 `false` 時,宿主必須自行建立這些預設值,且它們需在第一筆庫存異動前存在,否則啟動失敗。
306
+ - `enrichStockEvents?: boolean` — 為 `true` 時,每個 `stock.*` 事件會補上 `materialId / batchId / locationId / loaderId`(同交易內每事件一次主鍵查詢)。預設關閉。
307
+ - `customChangeTables?: readonly WmsCustomChangeTable[]` — 宿主自有的異動表,讓其 `stock.*` 事件仍會發出;詳見 `typings/custom-change-table.ts`。
308
+ - 事件接線(`WmsEventWiringOptions`):`beforeHooks?`、`afterListeners?`、`actorExtractor?`、`eventEmitterBridge?`。`WmsModuleGraphqlModule.forRootAsync` 會把這些往下轉交給此處,確保每個 token 只綁定一次。
230
309
  - `WmsModuleCoreModuleAsyncOptions` — `WMSBaseModuleAsyncOptions & WmsModuleCoreModuleOptions`
310
+ - `WmsSequenceStorage` — `'sequence' | 'table'`
231
311
  - 來源: `lib/typings/core-module-options.ts`
232
312
 
233
313
  ### 服務輸入 (Service Input Types)
@@ -297,6 +377,42 @@ WmsModuleCoreModule.forRootAsync({
297
377
 
298
378
  ---
299
379
 
380
+ ## Utilities(Table Prefix / Transaction / Sequence)
381
+
382
+ ### `withWmsTablePrefix<T extends object>(options: T, prefix: string): T`
383
+ - 用途: 在 `DataSource` 初始化**之前**,為本套件與 `@rytass/wms-base-nestjs-module` 擁有的資料表套上前綴(如 `wms_`),並原樣回傳 options。依 class 身分判斷:宿主自己的同名 `LocationEntity`(表名 `locations`)不受影響。TypeORM 的 metadata 是 process 全域的,同一 process 只能有一個前綴;以相同前綴重複呼叫是冪等的,不同前綴會拋錯。獨立的 `data-source.ts`(TypeORM migration CLI)也要呼叫。
384
+ - 來源: `lib/table-prefix/table-prefix.ts`
385
+
386
+ ### `applyWmsTablePrefix(prefix: string): void`
387
+ - 同上,但直接套用前綴,不包裝 options。`prefix` 須為小寫字母、數字與底線組成、以字母開頭;空字串表示不加前綴。
388
+ - 來源: `lib/table-prefix/table-prefix.ts`
389
+
390
+ ### `getWmsTablePrefix(): string`
391
+ - 回傳目前 process 生效的前綴;未套用時為 `''`。
392
+ - 來源: `lib/table-prefix/logical-table-name.ts`(由 `table-prefix.ts` 再匯出)
393
+
394
+ ### `wmsLogicalTableName(tableName: string): string`
395
+ - 把已加前綴的表名還原為宣告時的名稱(`wms_transfer_order_changes` → `transfer_order_changes`);非本套件的表原樣回傳。
396
+ - 用於 subscriber 比對表。**不要**用表名比對 WMS 表,宿主可能有同名的表。
397
+ - 來源: `lib/table-prefix/logical-table-name.ts`(由 `table-prefix.ts` 再匯出)
398
+
399
+ ### `runInTransaction<R>(dataSource: DataSource, manager: EntityManager | undefined, work: (manager: EntityManager) => Promise<R>): Promise<R>`
400
+ - 用途: 在呼叫方的交易內執行 `work`。
401
+ - manager 已綁定進行中的交易:直接沿用(不建 savepoint,也不另開連線)。
402
+ - manager 未綁定交易(例如 `dataSource.manager`):為它開一個交易。在 autocommit 下,鎖會被當下的陳述式立即釋放,因此不能不包交易直接執行。
403
+ - 沒有 manager:開新交易。
404
+ - `work` 內所有讀寫都必須透過收到的 `manager`。
405
+ - 來源: `lib/utils/run-in-transaction.ts`(由 barrel 匯出)
406
+
407
+ ### `WmsSequenceService.reserve(name: string, count = 1, manager?: EntityManager, options?: { consecutive?: boolean; maxValue?: number }): Promise<number>`
408
+ - 用途: 保留 `count` 個號碼,回傳第一個。計數器不依賴 `CURRVAL`(後者是每個 session 各自的,連線池會重發號碼),也不會因刻意失敗的陳述式而中止呼叫方的交易。
409
+ - `consecutive`:要求號碼連續且不被其他取號插隊(載具序號用)。`count > 1` 或設定 `maxValue` 時預設為 `true`。
410
+ - `maxValue`:此計數器可發出的最大號碼。超過時會在計數器前進**之前**拋出 `SEQUENCE_OUT_OF_RANGE`。
411
+ - 儲存方式由 `sequenceStorage` 決定(見 `WmsModuleCoreModuleOptions`)。
412
+ - 來源: `lib/services/sequence.service.ts`
413
+
414
+ ---
415
+
300
416
  ## Enums / Constants
301
417
 
302
418
  ### `StockStatus` (enum)
@@ -315,7 +431,8 @@ enum ChangeType {
315
431
  VENDOR_TRANSFERRED, VENDOR_RETURNED, HELD, RELEASED,
316
432
  CUSTOMER_HELD, CUSTOMER_RETURNED, SPLITTED, MERGED,
317
433
  ALLOCATED, DEALLOCATED, RECLASSIFIED, SCRAPED,
318
- COUNT_GAINED, COUNT_LOST
434
+ COUNT_GAINED, COUNT_LOST,
435
+ ISSUED, RETURNED, CONSUMED // 耗料單:ConsumptionChangeKind 的 ISSUE / RETURN / SETTLE 分別對應這三者(見 events/stock-change.subscriber.ts)
319
436
  }
320
437
  ```
321
438
  來源: `lib/constants/stock-status.ts`
@@ -330,7 +447,7 @@ enum InventoryCountStatus { PENDING, COUNTING, COMPLETED, CANCELLED }
330
447
 
331
448
  ### `WmsOperationName` (type) / `WMS_OPERATION_NAMES` (const)
332
449
  ```ts
333
- type WmsOperationName = 'material:read' | 'material:create' | /* …59 項… */;
450
+ type WmsOperationName = 'material:read' | 'material:create' | /* …68 項… */;
334
451
  const WMS_OPERATION_NAMES: readonly WmsOperationName[];
335
452
  ```
336
453
  本套件所有 root operation 的 `` `${resource}:${action}` `` 名稱。同一組字串有三個用途:
@@ -365,6 +482,8 @@ enum ShipInventoryOrderStatus { PENDING, PARTIAL_SHIPPED, SHIPPED, REMOVED }
365
482
 
366
483
  # @rytass/wms-module-graphql
367
484
 
485
+ > 本段的來源路徑皆相對於 `libs/graphql/src/`。權威版本請見 [`libs/graphql/docs/api-reference.md`](../../graphql/docs/api-reference.md)。
486
+
368
487
  ## NestJS Modules
369
488
 
370
489
  ### `WmsModuleGraphqlModule`
@@ -646,6 +765,8 @@ interface LoaderType<T> {
646
765
 
647
766
  # @rytass/wms-module-react
648
767
 
768
+ > 本段的來源路徑皆相對於 `libs/react/src/`。權威版本請見 [`libs/react/docs/api-reference.md`](../../react/docs/api-reference.md)。
769
+
649
770
  > **Public API vs Library Internals**: this package exposes a curated public barrel
650
771
  > (`src/index.ts`). Only the symbols listed under **Public API (in barrel)** below can be
651
772
  > imported directly from `@rytass/wms-module-react`. Everything listed under
@@ -666,9 +787,7 @@ interface LoaderType<T> {
666
787
  export const createApolloClient: () => ApolloClient<NormalizedCacheObject>
667
788
  ```
668
789
 
669
- As of 0.1.2, this factory takes **no parameters** and returns a fresh instance with `/graphql`
670
- as the endpoint URI (the same as the default singleton). A URL/header override parameter is
671
- planned for 0.2.0 (semver minor, non-breaking addition).
790
+ 目前此工廠**不接受參數**,回傳一個新實例,endpoint 為 `/graphql`(與預設單例相同)。URL / header 覆寫參數尚未提供。
672
791
 
673
792
  #### `ApolloClient` (named export — singleton instance)
674
793
  - Purpose: The pre-built Apollo client singleton created by `createApolloClient()`. Re-exported
@@ -772,7 +891,7 @@ useRoutes(): Array<{
772
891
  }>
773
892
  ```
774
893
  Returns the full WMS sidebar navigation tree. Titles are hardcoded zh-TW strings; there is
775
- no i18n mechanism in 0.1.x (see §13.9 in the integration guide for workarounds).
894
+ no i18n mechanism (see §13.9 in the integration guide for workarounds).
776
895
 
777
896
  #### `useTablePageState(usePageQs?: boolean)`
778
897
  - Source: `hooks/useTablePagination.ts`
@@ -0,0 +1,172 @@
1
+ # Using the core as a host's stock ledger
2
+
3
+ This guide is for a NestJS application that uses `@rytass/wms-module-core` **as a
4
+ service layer only** — no `@rytass/wms-module-graphql`, no React pages — and puts
5
+ WMS movements in the same database transactions as its own writes.
6
+
7
+ It covers five things a host has to get right, in the order it meets them:
8
+
9
+ 1. [Table prefix](#1-table-prefix) — keep WMS tables out of your namespace
10
+ 2. [Transactions](#2-joining-the-hosts-transaction) — one commit for WMS and your own rows
11
+ 3. [Events](#3-events-after-commit) — when `stock.*` and operation events fire
12
+ 4. [Concurrency](#4-concurrent-deductions) — what stops two deductions overselling
13
+ 5. [Counters and startup](#5-counters-and-startup) — order keys, loader serials, default rows
14
+
15
+ ## 1. Table prefix
16
+
17
+ Every table declared by this package and by `@rytass/wms-base-nestjs-module`
18
+ can carry a prefix, so `locations` becomes `wms_locations` and leaves your own
19
+ `locations` alone. The default is no prefix, which is what every existing
20
+ deployment has.
21
+
22
+ ```ts
23
+ import { withWmsTablePrefix } from '@rytass/wms-module-core';
24
+
25
+ // apps/api/src/app/app.module.ts — the runtime DataSource
26
+ TypeOrmModule.forRootAsync({
27
+ useFactory: () => withWmsTablePrefix({ type: 'postgres', /* … */ }, 'wms_'),
28
+ }),
29
+ WmsModuleCoreModule.forRootAsync({
30
+ useFactory: () => ({}),
31
+ defaultLoaderSerialId: 'DEFAULT',
32
+ defaultLoaderTypeKey: 'DEFAULT',
33
+ defaultLocationKey: 'DEFAULT',
34
+ tablePrefix: 'wms_', // a check, see below
35
+ }),
36
+
37
+ // apps/api/src/database/data-source.ts — the migration CLI's DataSource
38
+ export default new DataSource(withWmsTablePrefix({ type: 'postgres', /* … */ }, 'wms_'));
39
+ ```
40
+
41
+ **Wrap every `DataSource` the host builds.** The migration CLI loads
42
+ `data-source.ts` in a process of its own; forget it there and `migration:generate`
43
+ proposes renaming every WMS table back. The runtime one is checked for you:
44
+ with `tablePrefix` set, the module refuses to start when the tables did not end
45
+ up prefixed.
46
+
47
+ How it works, and what it does not touch:
48
+
49
+ - TypeORM reads table names from decorator metadata when a `DataSource`
50
+ initialises, not when the decorator runs. `withWmsTablePrefix` rewrites that
51
+ metadata in place before the first `DataSource` initialises — no environment
52
+ variable, no import-order rule.
53
+ - WMS entities are recognised by **class identity**, never by name. A host
54
+ `class LocationEntity` on `@Entity('locations')` — exactly what the base
55
+ package declares — is a different class and keeps its name.
56
+ - String relation targets declared on WMS entities (`@ManyToOne('locations')`)
57
+ are rewritten with the table, so your own `locations` cannot capture them.
58
+ - Your `namingStrategy` is not replaced. Every primary key, foreign key and
59
+ index name it derives for **your** entities is byte-for-byte what it was;
60
+ WMS constraint names follow the prefixed table names.
61
+ - A `@ChildEntity()` of a WMS root (an entity override) shares the root's table
62
+ and is prefixed with it.
63
+ - TypeORM's metadata storage is **process-global**: every `DataSource` in one
64
+ process sees the same prefix. Calling it again with the same prefix is a
65
+ no-op; a different prefix throws.
66
+ - Counters stored as PostgreSQL sequences take the prefix too
67
+ (`wms_TO_20261102`, `wms_P_SEQ`).
68
+
69
+ ## 2. Joining the host's transaction
70
+
71
+ Every public method that writes `stocks` or a `*_order_changes` row takes an
72
+ optional `EntityManager` — as the trailing argument, or as `manager` inside the
73
+ options object for the methods that already took one (`createReceiveInventoryOrder`,
74
+ `updateTransferOrder`, `createLoader`, …):
75
+
76
+ ```ts
77
+ await dataSource.transaction(async (manager) => {
78
+ await transferOrderService.transfer({ itemId, quantity: 5 }, manager);
79
+ await outbox.save({ … }, manager); // your own row
80
+ await requisitions.markPosted(id, manager); // your own row
81
+ });
82
+ // all three commit together, or none does
83
+ ```
84
+
85
+ - A manager inside an active transaction is used as is: no savepoint, no second
86
+ connection.
87
+ - A manager **without** a transaction (`dataSource.manager`) gets one opened on
88
+ it; no manager at all opens one on the data source. Either way the method is
89
+ atomic on its own, as before.
90
+ - The helper behind this is exported as `runInTransaction(dataSource, manager, work)`
91
+ for a host writing its own order family.
92
+
93
+ ## 3. Events after commit
94
+
95
+ `stock.*` events are collected by a TypeORM subscriber and operation events by
96
+ `WmsOperationRunner`; both are flushed by the **outermost** `runner.run`. So put
97
+ the runner **outside** your transaction:
98
+
99
+ ```ts
100
+ await runner.run({}, () =>
101
+ dataSource.transaction((manager) => consumptionOrderService.issue(input, manager)),
102
+ );
103
+ ```
104
+
105
+ - Runner outside the transaction: listeners run after commit; a rollback
106
+ delivers nothing.
107
+ - Runner inside the transaction: listeners run before your commit — they can
108
+ observe, and act on, a movement that is then rolled back.
109
+ - No runner: stock events have nowhere to go and are dropped.
110
+
111
+ ## 4. Concurrent deductions
112
+
113
+ Every deduction takes a transaction-scoped advisory lock on the
114
+ **(material, batch)** it draws from before it sums what is available, so of two
115
+ transactions deducting the same stock the second waits for the first to commit
116
+ and then sees its deduction. Multi-line operations lock all their source batches
117
+ up front, deduplicated and sorted, so overlapping operations acquire them in the
118
+ same order.
119
+
120
+ - The lock key is (material, batch), not the full slot: a check names location
121
+ and loader only when the caller does, and a finer key would let a check across
122
+ locations run beside one at a single location over the same rows.
123
+ The flip side: a host that keeps one default batch per material serialises
124
+ every deduction of that material, across all locations. Give batches real
125
+ keys if that queue matters.
126
+ - It relies on **READ COMMITTED** (PostgreSQL's default). Under REPEATABLE READ
127
+ or SERIALIZABLE the waiting transaction's snapshot predates the first commit
128
+ and still sees the old total.
129
+ - `StockService.lockStockSlots(slots, manager)` is public, for a host's own order
130
+ family. Call it once, before the item loop, with every (material, batch) the
131
+ operation draws from. It and `validateStockAvailability` take a **required**
132
+ manager and **throw** unless it is inside an active transaction — in autocommit
133
+ the lock would be released by the statement that took it, before the check it
134
+ guards. A slot without a `materialId` or `batchId` throws as well.
135
+ - Splitting a batch (`BatchService.splitBatch`) locks the batch's group, so two
136
+ transactions asking for the same child state share one child. Take stock locks
137
+ before splitting, never after.
138
+ - Two host transactions that take WMS locks and locks of their own in opposite
139
+ orders can still deadlock. PostgreSQL detects it and aborts one with
140
+ `40P01`; retry it.
141
+
142
+ `allowNegativeStock` (a `@rytass/wms-base-nestjs-module` option) has no effect on
143
+ this package: the core never goes through the base `OrderService`, and every
144
+ deduction here is checked by `validateStockAvailability`.
145
+
146
+ ## 5. Counters and startup
147
+
148
+ ### Order keys and loader serials
149
+
150
+ `sequenceStorage` chooses where they are counted:
151
+
152
+ | value | storage | runtime DDL | rollback | use when |
153
+ | --- | --- | --- | --- | --- |
154
+ | `'sequence'` (default) | one PostgreSQL sequence per counter | `CREATE SEQUENCE IF NOT EXISTS` on first use, on a second connection (once per counter per process) | number consumed | existing deployments |
155
+ | `'table'` | rows of the `sequences` table | none | number returned | schema changes only through migrations |
156
+
157
+ `'table'` mode advances a counter with one
158
+ `INSERT … ON CONFLICT DO UPDATE … RETURNING`; its row lock is held to commit, so
159
+ callers of one counter queue behind each other. It starts from 1 — switching an
160
+ existing deployment over would reissue numbers.
161
+
162
+ Loader serials are reserved as one consecutive run under a lock, so concurrent
163
+ `createLoader` calls never issue the same serial (#185).
164
+
165
+ ### Default rows
166
+
167
+ At startup the module resolves the default loader type, location and loader
168
+ named by `defaultLoaderTypeKey` / `defaultLocationKey` / `defaultLoaderSerialId`,
169
+ creating any that are missing. The find-or-create holds an advisory lock, so
170
+ several instances starting at once create one of each. Pass
171
+ `seedDefaults: false` to seed them yourself; startup then fails if they are
172
+ missing.