Skip to content

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ínhGiá trị
Package@nx/finance
CodeSVC-00040-FINANCE
LoạiMicroservice
RuntimeBun
Base ClassVerifierApplication
Vị trípackages/finance
Base Path/v1/api/finance
Dev Port31040
Container Port3000 (external 31040)
Snowflake ID4
DB Schemafinance (6 bảng)
Binding Namespace@nx/finance

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

Bao gồmKhô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/CREDITVò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_ADJUSTEDLoyalty / đ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 onboardingChuyể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ệnMục đích
@venizia/ignisIoC container, DI, BaseService, BaseController, ControllerFactory
@venizia/ignis-helpersLogger, KafkaProducerHelper / KafkaConsumerHelper, WebSocketEmitter, float()
@platformatic/kafkaKafka client (producer + consumer)
honoHTTP server (qua IGNIS)
@hono/zod-openapiSinh OpenAPI từ schema Zod
@scalar/hono-api-referenceOpenAPI explorer tại /doc
drizzle-ormTruy cập DB qua PostgresCoreDataSource
pgPostgreSQL driver
lodashTiện ích

Nội bộ:

PackageMục đích
@nx/coreSchema, repository (re-export), VerifierApplication, FinanceVoucherService, FinanceAccountService, PaymentIntegrationService, KafkaTopics/CDCKafkaTopics, mọi hằng số finance
@nx/assetApplicationAssetBanksVNComponent — 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.json

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

ControllerBase pathGhi chú
FinanceAccountController/finance-accountsCRUD + overview; scope theo merchant qua Casbin GROUP policies (non-admin chỉ thấy merchant được cấp)
FinanceCategoryController/finance-categoriesCRUD (thiên đọc; danh mục hệ thống + tùy chỉnh)
FinanceTransactionController/finance-transactionsCRUD (dòng ledger; chủ yếu đọc)
FinanceVoucherController/finance-vouchersCRUD chỉ-đọc (count/find/findById/findOne) + action tùy chỉnh: createDraft, updateDraft, deleteDraft, approve, issueDirect, voidVoucher, overview
PaymentIntegrationController/payment-integrationsProvider / merchant-config / terminal-config; credential được mask trong response

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

HướngChannelSố lượng
InboundKafka (4 domain + 1 CDC)5 topic
OutboundKafka0 (producer khởi tạo cho tương lai; chưa publish gì)
OutboundWebSocketemitter đã đăng ký (finance-ws-emitter); chưa nối domain topic nào

8. Components

ComponentFileMục đích
ApplicationKafkaComponentsrc/components/kafka/component.tsProducer idempotent (acks=ALL, lz4) + consumer (autocommit off, fallback latest) subscribe 5 topic, dispatch tới FinanceWorkerService
ApplicationWebSocketComponentsrc/components/websocket/component.tsWebSocketEmitter backed bởi Redis (single hoặc cluster) + FinanceSocketEventService
ApplicationAssetBanksVNComponenttừ @nx/assetDữ liệu tham chiếu ngân hàng Việt Nam
Cache RedisuseCacheRedis() (parent)Cache permission cho authorization

9. Services

ServiceFileMô tả ngắn
FinanceWorkerServicesrc/services/finance-worker.service.tsHandler 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
FinanceIntegrationServicesrc/services/finance-integration.service.tsMask 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/coreTạo tài khoản với opening-balance, update, getOverview
PaymentIntegrationService@nx/coreCRUD 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 schema finance; phần còn lại là đọc cross-package.

RepositoryBảng / NguồnGhi chú
FinanceAccountRepositoryfinance.FinanceAccount+ assertAccountsOwnedByMerchant
FinanceTransactionRepositoryfinance.FinanceTransactiondòng ledger
FinanceCategoryRepositoryfinance.FinanceCategoryhệ thống + tùy chỉnh
FinanceVoucherRepositoryfinance.FinanceVoucher+ lookup số next, findExistingForSource(Event), getOverview
FinanceVoucherSequenceRepositoryfinance.FinanceVoucherSequence+ next (theo merchant/type/yearMonth)
PaymentIntegrationRepositoryfinance.PaymentIntegrationcredential đượ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/coreresolve PO + vendor party cho phiếu PAYMENT
PermissionRepository / RoleRepository / PolicyDefinitionRepository@nx/coreseed + lọc tài khoản theo merchant

11. Entry Points

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

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:

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