Inventory Service
@nx/inventory quản lý tồn kho vật lý cho merchant: địa điểm, item, các bucket stock (on-hand / available / reserved), một vết kiểm toán bất biến, danh mục vendor, đơn mua hàng, vật tư với recipe (bill-of-materials), và các phiếu workflow inventory. Service trừ stock khi thanh toán đơn bán thành công (Kafka), bung recipe khi item bếp đổi trạng thái, và phát sự kiện sang finance khi nhận hàng.
1. Tham chiếu nhanh
| Thuộc tính | Giá trị |
|---|---|
| Package | @nx/inventory |
| Code | SVC-00050-INVENTORY |
| Loại | Microservice |
| Runtime | Bun |
| Base Class | VerifierApplication |
| Vị trí | packages/inventory |
| Base Path | /v1/api/inventory |
| Dev Port | 31050 |
| Container Port | 3000 (external 31050) |
| Snowflake ID | 5 |
| DB Schema | inventory (17 bảng — xem Mô hình miền) |
| Binding Namespace | @nx/inventory |
2. Mục đích & Phạm vi
| Bao gồm | Loại trừ |
|---|---|
| Inventory locations (warehouse) có phân cấp + default-per-merchant | Reservation theo quota / báo giá đơn bán (P3) |
| InventoryItem đa hình (Material / ProductVariant) | Định giá tồn kho đa tiền tệ |
| Stock buckets (on-hand, available, reserved) theo (item, location, lot, serial) | Tích hợp đầy đủ quét mã vạch (chỉ data model) |
| Vết kiểm toán bất biến InventoryTracking | Stock-count audit có locking |
| 19 tracking type cố định + reason tùy biến | Bắt buộc kiểm soát hạn dùng / FEFO / batch (chỉ data) |
| Danh mục Vendor + VendorItem M:N có snapshot | Bắt buộc yield/scrap BOM nhiều cấp |
| Purchase Orders: aggregate API, vòng đời, các chế độ nhận hàng | Chuyển stock giữa các merchant |
| Danh mục vật tư + recipe (BOM) + bung recipe runtime | Báo cáo định giá tồn kho |
| Production order | Mutation trực tiếp quantityReserved từ bên ngoài service |
| Inventory ticket (transfer, adjust, count, return, scrap) | |
| Danh mục unit-of-measure 3 cấp |
3. Tech Stack
External:
| Thư viện | Mục đích |
|---|---|
@venizia/ignis | IoC container, DI, BaseService, BaseController, ControllerFactory |
@venizia/ignis-helpers | Logger, KafkaProducerHelper, KafkaConsumerHelper, Redis helper |
@platformatic/kafka | Kafka client (idempotent producer, lz4 compression, ALL acks) |
hono | HTTP server (qua IGNIS) |
@hono/zod-openapi | Sinh OpenAPI từ Zod schema |
@scalar/hono-api-reference | Trình duyệt OpenAPI tại /doc |
drizzle-orm | Truy xuất DB qua PostgresCoreDataSource |
pg | PostgreSQL driver |
lodash | Utilities |
Internal:
| Package | Mục đích |
|---|---|
@nx/core | Toàn bộ schemas, repositories (re-export), VerifierApplication, KafkaTopics, CDCKafkaTopics, PurchaseOrderStatuses, MaterialRecipeStatuses, MerchantScopedService |
4. Cấu trúc Dự án
packages/inventory/
├── src/
│ ├── application.ts # VerifierApplication subclass
│ ├── index.ts # bootstrapApplication()
│ ├── migrate.ts # bootstrapMigration()
│ ├── common/
│ │ ├── constants.ts # InventoryTrackingNotes, ReceivePurchaseOrderItemModes
│ │ ├── keys.ts # BindingKeys (mở rộng @nx/core)
│ │ ├── rest-paths.ts # 15 RestPaths
│ │ ├── types.ts # alias kiểu cục bộ
│ │ └── websocket.ts # InventoryWebSocketTopics, Rooms
│ ├── components/
│ │ ├── kafka/ # ApplicationKafkaComponent (5 topic inbound)
│ │ └── websocket/ # ApplicationWebSocketComponent
│ ├── controllers/ # 15 controller (mỗi controller một thư mục)
│ ├── datasources/ # PostgresCoreDataSource
│ ├── migrations/processes/ # 5 process seed/backfill
│ ├── models/ # zod request/response schema
│ ├── repositories/ # re-export từ @nx/core
│ └── services/ # 19 service
├── package.json
└── tsconfig.json5. Kiến trúc
Chi tiết: xem Kiến trúc.
6. Tổng quan miền
ERD đầy đủ + bảng theo entity: xem Mô hình miền.
7. Tóm tắt Bề mặt
REST controllers — tham chiếu đầy đủ render trực tiếp từ /v1/api/inventory/doc/openapi.json (live spec — Scalar viewer tại /doc, gateway portal):
| Controller | Base path | Lifecycle/aggregate route |
|---|---|---|
InventoryItemController | /inventory-items | CRUD merchant-scoped |
InventoryLocationController | /inventory-locations | + set-default, activate, deactivate, archive |
InventoryStockController | /inventory-stocks | CRUD |
InventoryTrackingController | /inventory-trackings | CRUD chỉ đọc (audit) |
InventoryIdentifierController | /inventory-identifiers | CRUD |
InventoryTicketController | /inventory-tickets | CRUD + lifecycle |
InventoryTicketItemController | /inventory-ticket-items | CRUD |
PurchaseOrderController | /purchase-orders | + aggregate, items, confirm, revert, receive, cancel, complete, close |
MaterialController | /materials | + aggregate |
MaterialIdentifierController | /material-identifiers | CRUD |
MaterialRecipeController | /material-recipes | + aggregate, flatten |
ProductionOrderController | /production-orders | CRUD |
VendorController | /vendors | + aggregate |
VendorItemController | /vendor-items | + set-preferred, activate, deactivate |
UnitOfMeasureController | /unit-of-measures | CRUD (system + merchant-scoped) |
Bề mặt bất đồng bộ — tham chiếu đầy đủ trong API Sự kiện:
| Hướng | Kênh | Số lượng |
|---|---|---|
| Inbound | Kafka | 5 (PAYMENT_SUCCESS, KITCHEN_TICKET_ITEM_STATUS_CHANGED, MATERIAL_TRANSFERRED, MERCHANT CDC, PRODUCT_VARIANT CDC) |
| Outbound | Kafka | 3 (PURCHASE_ORDER_RECEIVED, MATERIAL_STOCK_CHANGED, MATERIAL_TRANSFERRED) |
| Outbound | WebSocket | 1 topic (observation/inventory/inventory-stock) × 3 loại room (merchant / location / item) |
8. Components
| Component | File | Mục đích |
|---|---|---|
ApplicationKafkaComponent | src/components/kafka/component.ts | Producer idempotent + consumer (autocommit=false); subscribe 5 topic; dispatch qua switch _dispatchMessage |
ApplicationWebSocketComponent | src/components/websocket/component.ts | WS emitter dùng Redis cho broadcast thay đổi stock |
| Redis cache (tùy chọn) | bind tại BindingKeys.APPLICATION_REDIS_CACHE | Cache permission cho authorization (lookup bởi Casbin) |
9. Services
| Service | File | Mô tả ngắn |
|---|---|---|
InventoryService | inventory.service.ts | Polymorphic principal refs + multi-location seeding + ghi nhận PO receive |
InventoryWorkerService | inventory-worker.service.ts | Kafka handler: payment success, material transferred, merchant CDC, product variant CDC |
InventoryStockService | inventory-stock.service.ts | CRUD merchant-scoped trên stock bucket |
InventoryTrackingService | inventory-tracking.service.ts | CRUD merchant-scoped trên audit trail |
InventoryItemService | inventory-item.service.ts | CRUD merchant-scoped trên item đa hình |
InventoryIdentifierService | inventory-identifier.service.ts | CRUD merchant-scoped trên SKU/barcode/serial identifier |
InventoryLocationService | inventory-location.service.ts | Locations + vòng đời setDefault/activate/deactivate/archive |
InventoryTicketService | inventory-ticket.service.ts | CRUD merchant-scoped trên ticket workflow |
InventoryTicketItemService | inventory-ticket-item.service.ts | Dòng ticket + adjust stock liên kết |
PurchaseOrderService | purchase-order.service.ts | Vòng đời PO đầy đủ, aggregate API, receive (OVERRIDE/ACCUMULATIVE) |
PurchaseOrderItemService | purchase-order-item.service.ts | Cập nhật line item + tính lại summary |
VendorService | vendor.service.ts | Vendor + aggregate (Vendor + VendorItem batch) |
VendorItemService | vendor-item.service.ts | Catalog M:N: setPreferred, activate, deactivate, recordPurchase, batch upsert/omit |
MaterialService | material.service.ts | Catalog Material + aggregate (kèm tùy chọn VendorItem batch) |
MaterialIdentifierService | material-identifier.service.ts | CRUD identifier SYSTEM/SLUG |
MaterialRecipeService | material-recipe.service.ts | Aggregate Recipe (BOM) + flatten đa cấp |
MaterialWorkerService | material-worker.service.ts | Tiêu thụ kitchen ticket, reserve material cho sale order, bung recipe |
ProductionOrderService | production-order.service.ts | CRUD production order |
UnitOfMeasureService | unit-of-measure.service.ts | Catalog UoM hệ thống + merchant |
10. Repositories
| Repository | Nguồn | Phương thức tùy biến đáng chú ý |
|---|---|---|
InventoryStockRepository | @nx/core | adjustStock — UPDATE atomic với guard forceNonNegative |
InventoryLocationRepository | @nx/core | ensureDefaultLocation, setDefaultAtomic, findParentChain |
InventoryTrackingRepository | @nx/core | (chỉ CRUD — audit bất biến, không có mutator tùy biến) |
InventoryItemRepository | @nx/core | ensureInventoryItem (idempotent theo (merchantId, itemType, itemId)) |
VendorItemRepository | @nx/core | setPreferredAtomic |
PurchaseOrderRepository | @nx/core | updateSummaryFromItems |
InventoryIdentifierRepository | @nx/core | — |
InventoryTicketRepository | @nx/core | — |
InventoryTicketItemRepository | @nx/core | — |
MaterialRepository | @nx/core | — |
MaterialIdentifierRepository | @nx/core | — |
MaterialRecipeRepository | @nx/core | — |
MaterialRecipeItemRepository | @nx/core | — |
ProductionOrderRepository | @nx/core | — |
PurchaseOrderItemRepository | @nx/core | — |
VendorRepository | @nx/core | — |
UnitOfMeasureRepository | @nx/core | — |
ProductRepository, ProductVariantRepository, CategoryRepository, DiscriminationTypeRepository, PermissionRepository, PolicyDefinitionRepository | @nx/core | Truy cập đọc xuyên package |
11. Điểm vào
| File | Mục đích |
|---|---|
src/index.ts | Service entry → bootstrapApplication() |
src/migrate.ts | Migration entry → bootstrapMigration() |
src/application.ts | Application extends VerifierApplication |
12. Cấu hình
Env vars + feature flags + dữ liệu seed: xem Cấu hình.
13. Vận hành
Deployment + observability + security + runbook: xem Vận hành.
14. Trang liên quan
Khái niệm — tại sao/cách hệ thống được định hình:
- Kiến trúc
- Mô hình miền
- Tích hợp — hợp đồng với sale, finance, commerce, identity
Tham chiếu — bảng tra cứu:
- API Sự kiện
- Cấu hình
- Vận hành
- REST endpoint — OpenAPI live tại
/v1/api/inventory/doc/openapi.json(live spec — Scalar viewer tại/doc, gateway portal)
Tính năng — đào sâu:
- Inventory Stock
- Inventory Tracking
- Inventory Location
- Inventory Ticket
- Purchase Order
- Material & BOM
- Vendor & VendorItem
Quyết định: