Skip to content

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ínhGiá trị
Package@nx/inventory
CodeSVC-00050-INVENTORY
LoạiMicroservice
RuntimeBun
Base ClassVerifierApplication
Vị trípackages/inventory
Base Path/v1/api/inventory
Dev Port31050
Container Port3000 (external 31050)
Snowflake ID5
DB Schemainventory (17 bảng — xem Mô hình miền)
Binding Namespace@nx/inventory

2. Mục đích & Phạm vi

Bao gồmLoại trừ
Inventory locations (warehouse) có phân cấp + default-per-merchantReservation 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 InventoryTrackingStock-count audit có locking
19 tracking type cố định + reason tùy biếnBắt buộc kiểm soát hạn dùng / FEFO / batch (chỉ data)
Danh mục Vendor + VendorItem M:N có snapshotBắt buộc yield/scrap BOM nhiều cấp
Purchase Orders: aggregate API, vòng đời, các chế độ nhận hàngChuyển stock giữa các merchant
Danh mục vật tư + recipe (BOM) + bung recipe runtimeBáo cáo định giá tồn kho
Production orderMutation 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ệnMục đích
@venizia/ignisIoC container, DI, BaseService, BaseController, ControllerFactory
@venizia/ignis-helpersLogger, KafkaProducerHelper, KafkaConsumerHelper, Redis helper
@platformatic/kafkaKafka client (idempotent producer, lz4 compression, ALL acks)
honoHTTP server (qua IGNIS)
@hono/zod-openapiSinh OpenAPI từ Zod schema
@scalar/hono-api-referenceTrình duyệt OpenAPI tại /doc
drizzle-ormTruy xuất DB qua PostgresCoreDataSource
pgPostgreSQL driver
lodashUtilities

Internal:

PackageMục đích
@nx/coreToà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.json

5. 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):

ControllerBase pathLifecycle/aggregate route
InventoryItemController/inventory-itemsCRUD merchant-scoped
InventoryLocationController/inventory-locations+ set-default, activate, deactivate, archive
InventoryStockController/inventory-stocksCRUD
InventoryTrackingController/inventory-trackingsCRUD chỉ đọc (audit)
InventoryIdentifierController/inventory-identifiersCRUD
InventoryTicketController/inventory-ticketsCRUD + lifecycle
InventoryTicketItemController/inventory-ticket-itemsCRUD
PurchaseOrderController/purchase-orders+ aggregate, items, confirm, revert, receive, cancel, complete, close
MaterialController/materials+ aggregate
MaterialIdentifierController/material-identifiersCRUD
MaterialRecipeController/material-recipes+ aggregate, flatten
ProductionOrderController/production-ordersCRUD
VendorController/vendors+ aggregate
VendorItemController/vendor-items+ set-preferred, activate, deactivate
UnitOfMeasureController/unit-of-measuresCRUD (system + merchant-scoped)

Bề mặt bất đồng bộ — tham chiếu đầy đủ trong API Sự kiện:

HướngKênhSố lượng
InboundKafka5 (PAYMENT_SUCCESS, KITCHEN_TICKET_ITEM_STATUS_CHANGED, MATERIAL_TRANSFERRED, MERCHANT CDC, PRODUCT_VARIANT CDC)
OutboundKafka3 (PURCHASE_ORDER_RECEIVED, MATERIAL_STOCK_CHANGED, MATERIAL_TRANSFERRED)
OutboundWebSocket1 topic (observation/inventory/inventory-stock) × 3 loại room (merchant / location / item)

8. Components

ComponentFileMục đích
ApplicationKafkaComponentsrc/components/kafka/component.tsProducer idempotent + consumer (autocommit=false); subscribe 5 topic; dispatch qua switch _dispatchMessage
ApplicationWebSocketComponentsrc/components/websocket/component.tsWS emitter dùng Redis cho broadcast thay đổi stock
Redis cache (tùy chọn)bind tại BindingKeys.APPLICATION_REDIS_CACHECache permission cho authorization (lookup bởi Casbin)

9. Services

ServiceFileMô tả ngắn
InventoryServiceinventory.service.tsPolymorphic principal refs + multi-location seeding + ghi nhận PO receive
InventoryWorkerServiceinventory-worker.service.tsKafka handler: payment success, material transferred, merchant CDC, product variant CDC
InventoryStockServiceinventory-stock.service.tsCRUD merchant-scoped trên stock bucket
InventoryTrackingServiceinventory-tracking.service.tsCRUD merchant-scoped trên audit trail
InventoryItemServiceinventory-item.service.tsCRUD merchant-scoped trên item đa hình
InventoryIdentifierServiceinventory-identifier.service.tsCRUD merchant-scoped trên SKU/barcode/serial identifier
InventoryLocationServiceinventory-location.service.tsLocations + vòng đời setDefault/activate/deactivate/archive
InventoryTicketServiceinventory-ticket.service.tsCRUD merchant-scoped trên ticket workflow
InventoryTicketItemServiceinventory-ticket-item.service.tsDòng ticket + adjust stock liên kết
PurchaseOrderServicepurchase-order.service.tsVòng đời PO đầy đủ, aggregate API, receive (OVERRIDE/ACCUMULATIVE)
PurchaseOrderItemServicepurchase-order-item.service.tsCập nhật line item + tính lại summary
VendorServicevendor.service.tsVendor + aggregate (Vendor + VendorItem batch)
VendorItemServicevendor-item.service.tsCatalog M:N: setPreferred, activate, deactivate, recordPurchase, batch upsert/omit
MaterialServicematerial.service.tsCatalog Material + aggregate (kèm tùy chọn VendorItem batch)
MaterialIdentifierServicematerial-identifier.service.tsCRUD identifier SYSTEM/SLUG
MaterialRecipeServicematerial-recipe.service.tsAggregate Recipe (BOM) + flatten đa cấp
MaterialWorkerServicematerial-worker.service.tsTiêu thụ kitchen ticket, reserve material cho sale order, bung recipe
ProductionOrderServiceproduction-order.service.tsCRUD production order
UnitOfMeasureServiceunit-of-measure.service.tsCatalog UoM hệ thống + merchant

10. Repositories

RepositoryNguồnPhương thức tùy biến đáng chú ý
InventoryStockRepository@nx/coreadjustStock — UPDATE atomic với guard forceNonNegative
InventoryLocationRepository@nx/coreensureDefaultLocation, setDefaultAtomic, findParentChain
InventoryTrackingRepository@nx/core(chỉ CRUD — audit bất biến, không có mutator tùy biến)
InventoryItemRepository@nx/coreensureInventoryItem (idempotent theo (merchantId, itemType, itemId))
VendorItemRepository@nx/coresetPreferredAtomic
PurchaseOrderRepository@nx/coreupdateSummaryFromItems
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/coreTruy cập đọc xuyên package

11. Điểm vào

FileMục đích
src/index.tsService entry → bootstrapApplication()
src/migrate.tsMigration entry → bootstrapMigration()
src/application.tsApplication 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:

Tham chiếu — bảng tra cứu:

Tính năng — đào sâu:

Quyết định:

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.