Skip to content

Tổng quan kiến trúc

Kiến trúc 3 lớp với Gateway API (Hono + Workers), Portal UI (React + Pages) và Data Layer (D1, R2, KV) trên nền Cloudflare.

Tóm tắt

Haravan Invoice MVP sử dụng kiến trúc Gateway + Portal tách biệt, với Adapter Pattern cho TVAN provider, cho phép swap nhà cung cấp T-VAN mà không thay đổi code business logic.

Kiến trúc tổng thể

Hình 1: Kiến trúc 3 lớp của Haravan Invoice MVP

Lớp 1 — Portal UI (Frontend)

Vị trí: apps/portal/

Thuộc tínhGiá trị
FrameworkReact 18 + TypeScript
RouterReact Router DOM
BuildVite → Cloudflare Pages
StylingCSS custom + Tabler Icons
AuthMock JWT (localStorage)

Cấu trúc thư mục

apps/portal/src/
├── App.tsx              # Router config (24 routes)
├── main.tsx             # Entry point
├── components/
│   └── Layout.tsx       # Sidebar + Topbar layout
├── hooks/
│   └── useAuth.ts       # Auth hook
└── pages/               # 24 page components
    ├── Dashboard.tsx
    ├── InvoiceList.tsx
    ├── InvoiceCreate.tsx
    ├── InvoiceDetail.tsx
    ├── InvoiceCorrect.tsx
    ├── CustomerList.tsx
    ├── CustomerDetail.tsx
    ├── ProductList.tsx
    ├── Analytics.tsx
    ├── Notifications.tsx
    ├── Reports.tsx
    ├── ReportSales.tsx
    ├── ReportLedger.tsx
    ├── ReportQuarterly.tsx
    ├── ReportReplaced.tsx
    ├── ReportModified.tsx
    ├── ReportDeleted.tsx
    ├── ComplianceCenter.tsx
    ├── DailyAggregate.tsx
    ├── Settings.tsx
    ├── SettingsTemplates.tsx
    ├── SettingsAutomation.tsx
    ├── SettingsPlan.tsx
    ├── ComingSoon.tsx
    └── Login.tsx

Portal có 2 nhóm navigation chính:

Main Navigation:

  • Tổng quan (Dashboard)
  • Thông báo
  • Hóa đơn (Tạo, Xử lý sai sót, Danh sách)
  • Khách hàng
  • Sản phẩm
  • Phân tích
  • Báo cáo (6 loại báo cáo)

Configuration Navigation:

  • Thông tin doanh nghiệp
  • Chữ ký số
  • Mẫu hóa đơn
  • Tự động hóa
  • Gói dịch vụ

Lớp 2 — Gateway API (Backend)

Vị trí: apps/api/

Thuộc tínhGiá trị
FrameworkHono (lightweight web framework)
RuntimeCloudflare Workers
LanguageTypeScript
AuthMock JWT middleware

Route Structure

apps/api/src/
├── index.ts              # App entry, mount routes
├── middleware/
│   └── auth.ts           # JWT auth middleware
├── routes/
│   ├── index.ts          # Route exports
│   ├── auth.ts           # POST /api/v1/auth/login
│   ├── health.ts         # GET /api/v1/health
│   ├── invoices.ts       # CRUD invoices
│   ├── one-click.ts      # POST /api/v1/invoices/one-click
│   ├── customers.ts      # Customer CRUD
│   ├── customer-analytics.ts
│   ├── products.ts       # Product listing
│   ├── reports.ts        # Reports endpoints
│   ├── analytics.ts      # Analytics endpoints
│   ├── settings.ts       # Settings (templates, automation, plan)
│   ├── notifications.ts  # Notifications
│   ├── aggregate.ts      # Daily aggregate
│   ├── mst-lookup.ts     # MST tax code lookup
│   ├── config.ts         # Merchant config
│   ├── audit.ts          # Audit trail
│   └── pdf.ts            # PDF download
├── services/
│   ├── invoice-service.ts
│   └── pdf-service.ts
├── adapters/
│   ├── index.ts
│   ├── factory.ts        # Adapter factory
│   ├── mock-adapter.ts   # Mock TVAN adapter
│   └── types.ts
└── test/
    ├── fixtures.ts
    ├── helpers.ts
    └── test-utils.ts

API Endpoints Summary

PrefixEndpointsMô tả
/api/v1/authPOST /loginMock login → JWT token
/api/v1/healthGET /Health check (DB, KV)
/api/v1/invoicesPOST, GET, GET/:id, POST/:id/replace, POST/:id/adjust, POST/:id/one-clickInvoice CRUD + operations
/api/v1/invoices/:idGET /pdf, GET /auditPDF download, audit trail
/api/v1/customersGET, GET/:idCustomer list + detail
/api/v1/customers/:idGET /analyticsPer-customer analytics
/api/v1/productsGETProduct catalog (auto-extracted)
/api/v1/reportsGET /summary, GET /monthlyKPI + monthly reports
/api/v1/analyticsGET /channels, /top-customers, /top-skusAnalytics data
/api/v1/settingsGET/PATCH /templates, /automation, GET /planSettings management
/api/v1/notificationsGET, PATCH/:id/read, POST /read-all, GET /unread-countNotifications
/api/v1/aggregateGETDaily aggregate data
/api/v1/mstGET /lookup?mst=Tax code lookup
/api/v1/configGET, PATCHMerchant config

Lớp 3 — Data Layer

D1 (SQLite Edge Database)

6 tables:

TableMô tảKey columns
invoicesHóa đơn chínhid, status, buyer/seller, totals
audit_logsNhật ký thao tácinvoice_id, action, actor
merchant_configCấu hình merchantauto_issue, tax_rate, tvan_provider
idempotency_keysChống duplicatekey, merchant_id, response
customersKhách hàngid, name, mst, email

8 indexes cho query performance: status, haravan_id, buyer_mst, issue_date, created_at, audit foreign keys, customer MST.

R2 (Object Storage)

  • Lưu trữ file PDF hóa đơn
  • Cache PDF để download nhanh

KV (Key-Value Store)

  • Session management
  • Idempotency keys (TTL 24h)
  • Cache dữ liệu

Adapter Pattern — TVAN Provider Abstraction

Hình 2: Adapter Pattern cho TVAN Provider

Lợi ích:

  • Zero code change khi swap provider
  • MockAdapter cho development/testing (5% error rate simulation)
  • Interface TVANAdapter định nghĩa trong @haravan/shared
  • Factory pattern tại apps/api/src/adapters/factory.ts

Shared Package

Vị trí: packages/shared/

FileNội dung
invoice.tsTypes: Invoice, Party, LineItem, InvoiceStatus, Channel, TaxRate
adapter.tsInterface: TVANAdapter, TVANResult
api.tsTypes: ApiResponse, PaginatedResponse, HealthCheckResponse
validation.tsvalidateMST, validateTaxRate, amountToWords, validateInvoice
config.tsConstants: STATUS_LABELS, STATUS_COLORS, CHANNEL_LABELS

Luồng request điển hình

Hình 3: Luồng request phát hành hóa đơn

Security

LớpCơ chế
AuthBearer JWT token (mock → Haravan SSO)
IdempotencyX-Idempotency-Key header + KV cache
ValidationShared validation package (MST, tax rate, invoice)
CORSEnabled cho Portal domain
Request IDhono/request-id middleware

Testing

PackageTest filesTest cases
apps/api14 filesRoute tests, adapter tests, service tests
apps/portal14 filesComponent render tests
packages/shared1 fileValidation tests
Total29 files98+ tests passing

Liên kết liên quan

Phát hành theo giấy phép MIT.