Commerce Service
@nx/commerce là dịch vụ catalog và tenant trung tâm: nó sở hữu products, variants, options, categories, merchants, organizers, sale channels, devices, receipt templates và các tích hợp provider được mã hóa. Đây là nguồn sự thật CDC — Debezium đọc Postgres WAL của nó và nhiều dịch vụ chị em (search, pricing, taxation, invoice, inventory) tự khởi tạo dữ liệu từ đây. Nó đăng ký Kafka chỉ producer và sao chép sản phẩm giữa các merchant qua EventBus in-process + hàng đợi BullMQ.
1. Tham khảo nhanh
| Thuộc tính | Giá trị |
|---|---|
| Package | @nx/commerce |
| Code | SVC-00020-COMMERCE |
| Type | Microservice |
| Runtime | Bun |
| Base Class | VerifierApplication (xác thực JWT dựa trên JWKS) |
| Location | packages/commerce |
| Base Path | /v1/api/commerce |
| Dev Port | 31020 |
| Container Port | 3000 (external 31020) |
| Snowflake ID | 2 |
| DB Schema | public (+ allocation) — schema thuộc @nx/core |
| Binding Namespace | @nx/commerce |
| Live OpenAPI | /v1/api/commerce/doc/openapi.json |
2. Mục đích & Phạm vi
| Bao gồm | Loại trừ |
|---|---|
| Catalog product / variant / option (CRUD aggregate) | Định giá động — fares/rules (ủy thác cho @nx/pricing) |
| Phân cấp category (SYSTEM + tùy biến) | Cấp phát quy tắc thuế (@nx/taxation) |
| Quản lý & onboarding merchant + organizer (tenant) | Mức tồn kho / InventoryItem (ủy thác cho @nx/inventory) |
Cấu hình kênh bán + liên kết SaleChannelProduct | Vòng đời order / checkout (ủy thác cho @nx/sale) |
| Device, receipt template, setting, discrimination type | Phát hành hóa đơn điện tử (ủy thác cho @nx/invoice) |
| Thông tin đăng nhập tích hợp provider được mã hóa (AES-256-GCM) | Engine đánh chỉ mục tìm kiếm (Typesense — đồng bộ qua CDC @nx/search) |
| Sao chép sản phẩm đa merchant nền (EventBus → BullMQ) | Push trực tiếp tới inventory (thay bằng CDC) |
Thu thập thông tin thuế merchant (Merchant.metadata.tax) → CDC → TaxInfo | |
| WebSocket emitter cho sự kiện merchant thời gian thực |
3. Tech Stack
Bên ngoài:
| Thư viện | Mục đích |
|---|---|
@venizia/ignis | IoC container, DI, BaseService/Controller, ControllerFactory |
@venizia/ignis-helpers | Logger, KafkaProducerHelper, BullMQHelper, WebSocketEmitter, AES |
@platformatic/kafka | Kafka client (chỉ producer) |
eventemitter3 | EventBus in-process cho sự kiện product aggregate |
hono + @hono/zod-openapi | HTTP server + sinh OpenAPI |
@scalar/hono-api-reference | Trình khám phá OpenAPI tại /doc |
drizzle-orm + pg | Truy cập DB qua PostgresCoreDataSource |
minio | Lưu trữ object (qua @nx/asset) |
typesense | Client engine tìm kiếm (qua @nx/search) |
Nội bộ:
| Package | Mục đích |
|---|---|
@nx/core | Schemas, repositories, VerifierApplication, CDCKafkaTopics, status/type enums |
@nx/asset | ApplicationAssetComponent — media Minio + MetaLinks |
@nx/search | Các component search + embedding + Typesense + CDC consumer |
@nx/mq-sms | Phụ thuộc được khai báo; không được import trong src/ |
4. Cấu trúc dự án
packages/commerce/
├── src/
│ ├── application.ts # Lớp con VerifierApplication
│ ├── index.ts / migrate.ts # điểm vào bootstrap
│ ├── common/
│ │ ├── constants.ts # ApplicationRoles (api/worker)
│ │ ├── keys.ts # BindingKeys (Kafka/BullMQ/EventBus)
│ │ ├── event.ts # khóa sự kiện EVENT_EMITTER product
│ │ ├── rest-paths.ts # RestPaths
│ │ └── environments.ts # khóa env Redis BullMQ
│ ├── components/
│ │ ├── kafka/ # ApplicationKafkaComponent (chỉ producer)
│ │ ├── redis/ # kết nối Redis BullMQ
│ │ ├── queues/ # SYNC_PRODUCT_QUEUE
│ │ ├── event-bus/ # bus EventEmitter3 + registry
│ │ ├── workers/ # SyncProductWorker + WorkerComponent
│ │ └── websocket/ # CommerceSocketEventService
│ ├── controllers/ # 18 thư mục → 17 controller được đăng ký
│ ├── datasources/ # PostgresCoreDataSource
│ ├── events/ # emitters + listener product aggregate
│ ├── services/ # gồm services/product, services/allocation
│ ├── migrations/processes/ # 9 process seed/backfill
│ └── models/ # zod request/response schemas
├── package.json
└── tsconfig.json5. Kiến trúc
Chi tiết: xem Kiến trúc.
6. Ảnh chụp Domain
ERD đầy đủ + bảng theo từng thực thể: xem Domain Model.
7. Tóm tắt Bề mặt
REST controllers — tham khảo đầy đủ render trực tiếp từ /v1/api/commerce/doc/openapi.json (trình xem Scalar tại /doc, cổng gateway). 17 controller được đăng ký; tất cả xác thực qua strategies: ['jwt', 'basic'].
| Controller | Base path | Ghi chú |
|---|---|---|
ProductController | /products | + create/update /aggregate |
ProductVariantController | /product-variants | + create/update /aggregate |
ProductOptionController | /product-options | định nghĩa option |
ProductOptionValueController | /product-option-values | giá trị option |
ProductVariantOptionController | /product-variant-options | chọn variant↔option |
CategoryController | /categories | SYSTEM + tùy biến; không có CategoryService |
MerchantController | /merchants | + aggregate, footer-summary, deletion-policy |
OrganizerController | /organizers | + on-boarding (đồng bộ) |
SaleChannelController | /sale-channels | phân giải identifier |
ConfigurationController | /configurations | + /provider-integrations (mã hóa) |
DeviceController | /devices | registry thiết bị POS |
DiscriminationTypeController | /discrimination-types | phân loại nhóm |
ReceiptTemplateController | /receipt-templates | mẫu in |
SettingController | /settings | cài đặt đa hình |
AllocationLayoutController | /allocation-layouts | sơ đồ mặt bằng |
AllocationZoneController | /allocation-zones | khu vực/phân vùng |
AllocationUnitController | /allocation-units | bàn/ghế |
SaleChannelInventoryLocationController+SaleChannelInventoryLocationServicetồn tại trongsrc/nhưng không được đăng ký.
Bề mặt async — tham khảo đầy đủ trong API Events:
| Hướng | Kênh | Số lượng |
|---|---|---|
| Outbound | CDC (Debezium) | 9+ bảng được tiêu thụ bởi search/pricing/taxation/invoice/inventory |
| Nội bộ | EventBus (eventemitter3) | 2 sự kiện (product.aggregate.{created,updated}) |
| Nội bộ | BullMQ | 1 hàng đợi (SYNC_PRODUCT_QUEUE) × job create/update |
| Outbound | WebSocket | phát thời gian thực merchant (emitter được đăng ký) |
| Outbound | Kafka produce | producer được bind; không có call site .send() trong src/ |
8. Components
Đăng ký trong application.ts:configureComponents() (theo thứ tự):
| Component | File / nguồn | Mục đích |
|---|---|---|
ApplicationSearchComponent | @nx/search | Tích hợp tìm kiếm Typesense |
ApplicationEmbeddingConfigurationComponent | @nx/search | Cấu hình embedding cho tìm kiếm ngữ nghĩa |
TypesenseSearchEngineComponent | @nx/search | Đấu nối engine Typesense |
ApplicationCdcComponent | @nx/search | chỉ vai trò WORKER — Debezium CDC → Typesense |
ApplicationAssetComponent | @nx/asset | Media nền Minio + MetaLinks |
useCacheRedis(...) | core helper | Cache Redis (cũng là authorization Redis) |
RedisComponent | components/redis/ | Redis BullMQ riêng (single/cluster) |
QueueComponent | components/queues/ | Tạo SYNC_PRODUCT_QUEUE |
EventBusComponent | components/event-bus/ | Bus EventEmitter3 + listener product aggregate |
WorkerComponent | components/workers/ | Đăng ký worker từ APP_ENV_WORKERS |
ApplicationKafkaComponent | components/kafka/ | Khởi tạo producer Kafka (không .send() trong src/) |
ApplicationWebSocketComponent | components/websocket/ | WebSocketEmitter cho sự kiện thời gian thực |
Hai kết nối Redis (cache + BullMQ). Khóa
APPLICATION_KAFKA_CONSUMERđược khai báo nhưng không có consumer nào được đấu nối.
9. Services
Đăng ký trong application.ts:configureServices():
| Service | Mô tả một dòng |
|---|---|
ProductService | Đọc product + phân giải identifier; ủy thác aggregate cho service create/update |
ProductCreateService / ProductUpdateService | Logic transaction aggregate; phát sự kiện product EventBus |
ProductCreateSyncService / ProductUpdateSyncService | syncToAdditionalMerchants() (worker BullMQ) |
ProductVariantService | CRUD aggregate variant (chỉ catalog — không inject pricing) |
ProductOptionService | Quản lý option / option-value |
MerchantService | Aggregate merchant, tax→metadata, cache footer-summary |
OrganizerService | onBoarding() — organizer + merchant + policies + kênh mặc định |
CategoryService | Logic category SYSTEM/tùy biến |
SaleChannelService | Tra cứu theo identifier |
ConfigurationService | Config hệ thống + tích hợp provider được mã hóa |
EncryptService | Mã hóa/giải mã AES-256-GCM (nội bộ) |
DeletionPolicyService | Thực thi xóa nghiêm ngặt theo merchant |
AllocationLayoutService / AllocationZoneService (+ Create/Update) | Sơ đồ phân bổ ghế/khu vực |
ReceiptTemplateService | CRUD mẫu hóa đơn |
WebhookDispatcherService | Re-export từ @nx/core |
SaleChannelInventoryLocationServicetồn tại nhưng không được đăng ký.
10. Repositories
Re-export từ @nx/core và đăng ký trong configureRepositories(). Bao gồm các bảng do commerce sở hữu (Product, ProductVariant, ProductInfo, ProductIdentifier, ProductOption(Value), ProductVariantOption, ProductVariantMapping, ProductBundler, ProductCategory, Category, Merchant, Organizer, SaleChannel(Product), Configuration, Device, DiscriminationType, ReceiptTemplate, Setting, MetaLink) cộng với các đọc cross-package (SaleOrder(Item), Inventory*, Invoice, Material, Fare(Set), Tax*, FinanceAccount, TaxInfo, Permission, Role, PolicyDefinition, Notification, WebhookConfig, Customer).
Theo quy ước, không có repo wrapper mỏng — các method tùy biến (ví dụ
MerchantRepository.markOnboardingStepComplete,SaleOrderRepository.sumWindowCompletedOrders,InventoryStockRepository.getOverview) có chỗ đứng nhờ logic không tầm thường.
11. Điểm vào
| File | Mục đích |
|---|---|
src/index.ts | Điểm vào dịch vụ → bootstrapApplication() |
src/migrate.ts | Điểm vào migration → bootstrapMigration() |
src/application.ts | Application extends VerifierApplication |
12. Cấu hình
Biến env + dữ liệu seed: xem Cấu hình.
13. Vận hành
Triển khai + observability + bảo mật + runbook: xem Vận hành.
14. Trang liên quan
Khái niệm — tại sao/như thế nào:
- Kiến trúc
- Domain Model
- Tích hợp — seam CDC + hợp đồng dịch vụ chị em
Tham khảo — tra cứu:
- API Events
- Cấu hình
- Vận hành
- REST endpoints — OpenAPI trực tiếp tại
/v1/api/commerce/doc/openapi.json
Tính năng — đào sâu:
Quyết định: