Skip to content

Pricing Service

@nx/pricing là một service IGNIS độc lập (REST API + Kafka CDC worker) định giá các dòng bán được: nó chọn fare thắng cho mỗi product variant, tính thuế kép, theo dõi giá vốn variant, và quản lý khuyến mãi. Service anh em gọi nó qua HTTP và import types request/response cộng vài runtime snapshot const container từ @nx/pricing/contracts — họ không mount nó như một component.

1. Tham chiếu nhanh

Thuộc tínhGiá trị
Package@nx/pricing
CodeSVC-00070-PRICING
TypeMicroservice
RuntimeBun
Base ClassVerifierApplication
Locationpackages/pricing
Base Path/v1/api/pricing
Dev Port31070
Container Port3000 (ngoài 31070)
Snowflake ID7
DB Schemapricing (9 bảng)
Binding Namespace@nx/pricing
Run Modesapi (REST + Kafka CDC consumer lúc boot) · migrate

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

Bao gồmLoại trừ
Chọn fare cho mỗi ProductVariant (default / OVERRIDE / child fare theo rule)Lưu order (sở hữu bởi @nx/sale)
Tính thuế kép, gom theo priority (cấp item + order)Phát hành hoá đơn / HĐĐT (sở hữu bởi @nx/invoice)
Pricing snapshot (bất biến theo từng dòng + từng order, v2)Thay đổi stock / inventory (sở hữu bởi @nx/inventory)
Theo dõi giá vốn variant với khoảng ngày hiệu lựcXử lý thanh toán (sở hữu bởi @nx/mq-pay)
CRUD Promotion / PromotionMethod / RuleTính giảm giá/phí (entity tồn tại; calculator chưa wire)
Seed FareSet qua CDC từ sự kiện ProductVariantSở hữu bất kỳ DB schema nào — mọi schema nằm trong @nx/core
Hai pipeline tính: /simulation (v1) + /simulation-v2 (v2, canonical)

3. Tech Stack

External:

LibraryMục đích
@venizia/ignisIoC container, DI, BaseService, BaseController, ControllerFactory
@venizia/ignis-helpersLogger, toán tiền float(x, 4), Redis helper, Axios
@platformatic/kafkaKafka producer + CDC consumer (idempotent, lz4, SASL tuỳ chọn)
hono + @hono/zod-openapiHTTP server + sinh OpenAPI từ Zod
@scalar/hono-api-referenceOpenAPI explorer tại /doc
drizzle-orm / pgTruy cập DB qua PostgresCoreDataSource
lodashget() cho đánh giá rule theo attribute-path

Internal:

PackageMục đích
@nx/coreMọi schema (Fare, FareSet, Tax, TaxSet, TaxType, Rule, Cost, Promotion, PromotionMethod), VerifierApplication, CDCKafkaTopics, FareTypes, RuleOperators, IdGenerator

4. Cấu trúc dự án

packages/pricing/
├── src/
│   ├── application.ts              # subclass VerifierApplication
│   ├── index.ts                    # bootstrapApplication()
│   ├── migrate.ts                  # bootstrapMigration()
│   ├── common/                     # RestPaths, BindingKeys, constants, env keys
│   ├── components/kafka/           # ApplicationKafkaComponent (producer + CDC consumer)
│   ├── contracts/                  # Types publish + snapshot const container (sale import cái này)
│   ├── controllers/                # 11 REST controller
│   ├── datasources/                # PostgresCoreDataSource
│   ├── errors/                     # Danh mục lỗi domain
│   ├── migrations/processes/       # 2 seed (permissions, role-permissions)
│   ├── models/                     # zod request/response schema
│   ├── repositories/               # re-export + wrapper mỏng trên @nx/core
│   └── services/
│       ├── core/                   # pipeline tính v1 (/simulation)
│       ├── core-v2/                # tính v2 + module pricing-snapshot (/simulation-v2)
│       ├── management/             # CRUD + service aggregate
│       └── pricing-worker.service.ts  # subscriber CDC ProductVariant
├── package.json
└── tsconfig.json

5. Kiến trúc

Chi tiết: xem Architecture.

6. Ảnh chụp Domain

ERD đầy đủ + bảng theo từng entity: xem Domain Model.

7. Tổng quan bề mặt

REST controllers — tham chiếu đầy đủ render trực tiếp từ /v1/api/pricing/doc/openapi.json (Scalar viewer tại /doc, portal gateway):

ControllerBase pathRoute tuỳ chỉnh
FareController/faresPOST /groups, POST /children
FareSetController/fare-sets
CostController/costsPUT /current, GET /product-variant/{id}/current
TaxController/taxes
TaxSetController/tax-setsPATCH /{id}/aggregate
TaxTypeController/tax-types
PromotionController/promotionsPOST /aggregate, PATCH /{id}/aggregate
PromotionMethodController/promotion-methods
RuleController/rules
SimulationController/simulationPOST /calculate (v1, flat)
SimulationV2Controller/simulation-v2POST /calculate (v2, snapshot)

Bề mặt async — tham chiếu đầy đủ trong API Events:

HướngKênhSố lượng
InboundKafka CDC (CDCKafkaTopics.PRODUCT_VARIANT)1
OutboundKafka0 (producer bound nhưng không dùng bởi domain logic)
WebSocket out0
BullMQ jobs0 (không BullMQ / QueueComponent)

8. Components

ComponentFileMục đích
ApplicationKafkaComponentsrc/components/kafka/component.tsProducer lz4 idempotent + CDC consumer trên PRODUCT_VARIANT; dispatch tới PricingWorkerService
Redis cache (parent)bound tại BindingKeys.APPLICATION_REDIS_CACHE qua useCacheRedis()Chỉ cache permission authorization

9. Services

ServiceFileMột dòng
PricingServicecore/pricing.service.tsOrchestrator v1 — mỗi item: chọn fare → tính thuế → cộng (concurrency 5); áp thuế cấp order khi có merchantId
PricingFareCalculatorServicecore/pricing-fare-calculator.service.tsNạp FareSet active, phân loại fare, chọn thắng (OVERRIDE trước, không thì thấp nhất)
PricingRuleEvaluatorServicecore/pricing-rule-evaluator.service.tsĐánh giá rule logic AND qua lodash get() theo attribute path
PricingTaxCalculatorServicecore/pricing-tax-calculator.service.tsEngine thuế kép, gom theo priority; back-calc inclusive, điều kiện số lượng
ItemPriceCalculatorcore/item-price-calculator.service.tsHelper giá theo item cho pipeline v1
PricingV2Servicecore-v2/pricing-v2.service.tsOrchestrator v2 → pricing snapshot đầy đủ (rule áp theo dòng + tổng order theo bearer)
FareCalculatorServicecore-v2/fare-calculator.service.tsChọn fare v2 tạo TAppliedPrice
TaxCalculatorServicecore-v2/tax-calculator.service.tsEngine thuế v2 tạo TAppliedTax[]
BaseCalculatorServicecore-v2/base-calculator.service.tsHelper money/float dùng chung cho calculator v2
FareServicemanagement/fare.service.tsCRUD aggregate Fare / fare-group / child-fare / variant-pricing
CostServicemanagement/cost.service.tsCRUD giá vốn variant với khoảng ngày (getCurrentCost hardcode principalType:'ProductVariant')
TaxSetServicemanagement/tax-set.service.tsCRUD aggregate TaxSet + thuế của nó
PromotionServicemanagement/promotion.service.tsCRUD aggregate Promotion + method + rules
PricingWorkerServiceservices/pricing-worker.service.tsSubscriber CDC ProductVariant — seed FareSet + default fare; seed FBT override child fare

v1 và v2 chia sẻ ~90% logic fare/tax — sửa thường cần áp cả hai. CRUD PromotionService tồn tại nhưng chưa có discount calculator wire vào pipeline nào.

10. Repositories

RepositoryTableSourceMethod tuỳ chỉnh
FareRepositoryFare@nx/corefindByFareId, updateChildrenCount, updateRulesCount
FareSetRepositoryFareSet@nx/core
RuleRepositoryRule@nx/corefindByFareId
TaxRepositoryTax@nx/core
TaxSetRepositoryTaxSet@nx/core
TaxTypeRepositoryTaxType@nx/core
CostRepositoryCost@nx/core
PromotionRepositoryPromotion@nx/core
PromotionMethodRepositoryPromotionMethod@nx/core
PermissionRepository, RoleRepository, PolicyDefinitionRepository, MigrationRepository@nx/coreAuthorization + bookkeeping migration

11. Entry Points

FileMục đích
src/index.tsEntry service → bootstrapApplication()
src/migrate.tsEntry migration → bootstrapMigration()
src/application.tsApplication extends VerifierApplication

12. Configuration

Env vars + dữ liệu seed: xem Configuration.

13. Operations

Triển khai + observability + bảo mật + runbook: xem Operations.

14. Trang liên quan

Khái niệm — vì sao/như thế nào:

Tham chiếu — tra cứu:

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

Decisions:

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