Finance Service
@nx/finance là động cơ ghi sổ kế toán. Nó sở hữu các tài khoản (ví) và một ledger ghi sổ kép được xây từ các phiếu sổ cái (RECEIPT / PAYMENT / TRANSFER / ADJUSTMENT), mỗi phiếu hạch toán các dòng FinanceTransaction DEBIT/CREDIT cân bằng. Nó ưu tiên theo sự kiện: phần lớn hạch toán được tạo tự động bằng cách phản ứng với các Kafka topic từ sale, inventory, và merchant CDC — REST trực tiếp chỉ dành cho phiếu thủ công, quản lý tài khoản, và báo cáo.
1. Tham chiếu nhanh
| Thuộc tính | Giá trị |
|---|---|
| Package | @nx/finance |
| Code | SVC-00040-FINANCE |
| Loại | Microservice |
| Runtime | Bun |
| Base Class | VerifierApplication |
| Vị trí | packages/finance |
| Base Path | /v1/api/finance |
| Dev Port | 31040 |
| Container Port | 3000 (external 31040) |
| Snowflake ID | 4 |
| DB Schema | finance (6 bảng) |
| Binding Namespace | @nx/finance |
2. Mục đích & Phạm vi
| Bao gồm | Không bao gồm |
|---|---|
| Tài khoản / ví (CASH, BANK, QR_CODE, MOBILE_POS) + tài khoản kiểm soát nội bộ (INVENTORY, COGS) | Xử lý provider/gateway thanh toán (do @nx/mq-pay sở hữu) |
| Phiếu ghi sổ kép (RECEIPT / PAYMENT / TRANSFER / ADJUSTMENT) với dòng ledger DEBIT/CREDIT | Vòng đời sale-order (do @nx/sale sở hữu) |
Đánh số phiếu theo merchant/type (PT/PC/PCK/PKT) | Số lượng tồn / tính giá vốn (do @nx/inventory sở hữu) |
| Phân cấp danh mục thu/chi (14 danh mục hệ thống được seed) | Phát hành hóa đơn thuế (do @nx/invoice sở hữu) |
Auto-posting từ PAYMENT_SUCCESS, PURCHASE_ORDER_RECEIVED, INVENTORY_ISSUED_FOR_SALE, INVENTORY_ADJUSTED | Loyalty / điểm khách hàng (do @nx/sale sở hữu) |
| Đối soát tài khoản mặc định khi merchant CDC + bước onboarding | Chuyển đổi đa tiền tệ (một tiền tệ mỗi phiếu; exchangeRate dự trữ) |
| Lưu credential tích hợp thanh toán (mask, theo merchant/terminal) | — |
| Hủy phiếu (void) qua bút toán đảo cân bằng | — |
3. Tech Stack
Bên ngoài:
| Thư viện | Mục đích |
|---|---|
@venizia/ignis | IoC container, DI, BaseService, BaseController, ControllerFactory |
@venizia/ignis-helpers | Logger, KafkaProducerHelper / KafkaConsumerHelper, WebSocketEmitter, float() |
@platformatic/kafka | Kafka client (producer + consumer) |
hono | HTTP server (qua IGNIS) |
@hono/zod-openapi | Sinh OpenAPI từ schema Zod |
@scalar/hono-api-reference | OpenAPI explorer tại /doc |
drizzle-orm | Truy cập DB qua PostgresCoreDataSource |
pg | PostgreSQL driver |
lodash | Tiện ích |
Nội bộ:
| Package | Mục đích |
|---|---|
@nx/core | Schema, repository (re-export), VerifierApplication, FinanceVoucherService, FinanceAccountService, PaymentIntegrationService, KafkaTopics/CDCKafkaTopics, mọi hằng số finance |
@nx/asset | ApplicationAssetBanksVNComponent — dữ liệu tham chiếu ngân hàng Việt Nam |
4. Cấu trúc Project
packages/finance/
├── src/
│ ├── application.ts # lớp con VerifierApplication
│ ├── index.ts # bootstrapApplication()
│ ├── migrate.ts # bootstrapMigration()
│ ├── common/
│ │ ├── keys.ts # BindingKeys (Kafka producer/consumer, Redis cache)
│ │ ├── rest-paths.ts # 5 RestPaths
│ │ └── types.ts # local types
│ ├── components/
│ │ ├── kafka/ # ApplicationKafkaComponent (producer + consumer 5 topic)
│ │ └── websocket/ # ApplicationWebSocketComponent + FinanceSocketEventService
│ ├── controllers/ # 5 thư mục controller (account, category, transaction, voucher, payment-integration)
│ ├── datasources/ # PostgresCoreDataSource
│ ├── migrations/processes/ # 3 migration (categories, permissions, role-permissions)
│ ├── models/ # zod request/response schemas
│ ├── repositories/ # re-export từ @nx/core
│ ├── resources/ # app-info.json, banner.txt
│ └── services/ # FinanceWorkerService, FinanceIntegrationService
├── package.json
└── tsconfig.json5. Architecture
Chi tiết: xem Architecture.
6. Snapshot 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/finance/doc/openapi.json (spec trực tiếp — Scalar viewer tại /doc, gateway portal):
| Controller | Base path | Ghi chú |
|---|---|---|
FinanceAccountController | /finance-accounts | CRUD + overview; scope theo merchant qua Casbin GROUP policies (non-admin chỉ thấy merchant được cấp) |
FinanceCategoryController | /finance-categories | CRUD (thiên đọc; danh mục hệ thống + tùy chỉnh) |
FinanceTransactionController | /finance-transactions | CRUD (dòng ledger; chủ yếu đọc) |
FinanceVoucherController | /finance-vouchers | CRUD chỉ-đọc (count/find/findById/findOne) + action tùy chỉnh: createDraft, updateDraft, deleteDraft, approve, issueDirect, voidVoucher, overview |
PaymentIntegrationController | /payment-integrations | Provider / merchant-config / terminal-config; credential được mask trong response |
Bề mặt async — tham chiếu đầy đủ trong API Events:
| Hướng | Channel | Số lượng |
|---|---|---|
| Inbound | Kafka (4 domain + 1 CDC) | 5 topic |
| Outbound | Kafka | 0 (producer khởi tạo cho tương lai; chưa publish gì) |
| Outbound | WebSocket | emitter đã đăng ký (finance-ws-emitter); chưa nối domain topic nào |
8. Components
| Component | File | Mục đích |
|---|---|---|
ApplicationKafkaComponent | src/components/kafka/component.ts | Producer idempotent (acks=ALL, lz4) + consumer (autocommit off, fallback latest) subscribe 5 topic, dispatch tới FinanceWorkerService |
ApplicationWebSocketComponent | src/components/websocket/component.ts | WebSocketEmitter backed bởi Redis (single hoặc cluster) + FinanceSocketEventService |
ApplicationAssetBanksVNComponent | từ @nx/asset | Dữ liệu tham chiếu ngân hàng Việt Nam |
| Cache Redis | useCacheRedis() (parent) | Cache permission cho authorization |
9. Services
| Service | File | Mô tả ngắn |
|---|---|---|
FinanceWorkerService | src/services/finance-worker.service.ts | Handler sự kiện Kafka — biến sự kiện sale/inventory/merchant thành phiếu; đối soát tài khoản mặc định + kiểm soát khi merchant CDC |
FinanceIntegrationService | src/services/finance-integration.service.ts | Mask credential payment-integration trong response tài khoản; build/đính kèm integration bundle |
FinanceVoucherService | @nx/core | Động cơ hạch toán ghi sổ kép: issueDirect, vòng đời draft, void (đảo cân bằng), getOverview, toán balance/posting-sequence |
FinanceAccountService | @nx/core | Tạo tài khoản với opening-balance, update, getOverview |
PaymentIntegrationService | @nx/core | CRUD payment-integration + mã hóa credential |
10. Repositories
Tất cả re-export từ
@nx/core(src/repositories/index.ts). Bảng được sở hữu trong schemafinance; phần còn lại là đọc cross-package.
| Repository | Bảng / Nguồn | Ghi chú |
|---|---|---|
FinanceAccountRepository | finance.FinanceAccount | + assertAccountsOwnedByMerchant |
FinanceTransactionRepository | finance.FinanceTransaction | dòng ledger |
FinanceCategoryRepository | finance.FinanceCategory | hệ thống + tùy chỉnh |
FinanceVoucherRepository | finance.FinanceVoucher | + lookup số next, findExistingForSource(Event), getOverview |
FinanceVoucherSequenceRepository | finance.FinanceVoucherSequence | + next (theo merchant/type/yearMonth) |
PaymentIntegrationRepository | finance.PaymentIntegration | credential được mask |
ConfigurationRepository | @nx/core | đọc system config DEFAULT_FINANCE_ACCOUNTS |
MerchantRepository / OrganizerRepository | @nx/core | đối soát merchant CDC + bước onboarding |
PurchaseOrderRepository / VendorRepository | @nx/core | resolve PO + vendor party cho phiếu PAYMENT |
PermissionRepository / RoleRepository / PolicyDefinitionRepository | @nx/core | seed + lọc tài khoản theo merchant |
11. Entry Points
| File | Mục đích |
|---|---|
src/index.ts | Service entry → bootstrapApplication() |
src/migrate.ts | Migration entry → bootstrapMigration() |
src/application.ts | Application extends VerifierApplication |
12. Configuration
Env vars + dữ liệu seed: xem Configuration.
13. Operations
Deployment + observability + security + runbook: xem Operations.
14. Trang liên quan
Khái niệm — tại sao/như thế nào:
- Architecture
- Domain Model
- Integration — contract sale / inventory / commerce CDC / identity
Tham chiếu — tra cứu:
- API Events
- Configuration
- Operations
- REST endpoints — OpenAPI trực tiếp tại
/v1/api/finance/doc/openapi.json(spec trực tiếp — Scalar viewer tại/doc, gateway portal)
Decisions: