Appearance
PostgreSQL Database Architecture & Prisma Schema (115+ Models)
File cấu hình apps/backend/prisma/schema.prisma (dài 6.977 dòng, được đồng bộ sang apps/zalo-be/prisma/schema.prisma) định nghĩa hơn 115 Prisma models trên nền PostgreSQL 16. Để dễ tra cứu và nắm bắt cấu trúc dữ liệu, tài liệu này phân nhóm 115+ bảng vào 8 Data Domains kèm sơ đồ Entity-Relationship Diagram (ERD).
1. Core Database Design Patterns
- Primary Key
BigInt(@id @default(autoincrement())): Hầu hết các bảng giao dịch và master data lớn dùngBigInt(int8) làm primary key để chịu tải hàng tỷ bản ghi SGTIN/VC/Movement. Khi serialize qua JSON API, hệ thống chuyển đổiBigIntsangstringthông qua interceptor hoặc mapper. - Multi-Tenancy & Tenant Isolation (qua
company_id): Mọi bảng dữ liệu thuộc sở hữu doanh nghiệp đều có cộtcompany_id BigIntliên kết tới bảngcompanies(id). - Immutable Append-Only Ledger (
sgtin_movements): Bảngsgtin_movementsđược gắn PostgreSQL Triggertrg_sgtin_movements_no_updatechặn mọi thao tácUPDATEhoặcDELETEnhằm bảo vệ tính bất biến (immutability) của lịch sử dịch chuyển tem SGTIN. - PostgreSQL Transactional Advisory Lock (
pg_advisory_xact_lock): Để sinh mã tuần tự không trùng lặp trong môi trường chạy Cluster nhiều instances mà không gây table-level lock, hệ thống sử dụngpg_advisory_xact_lockcủa PostgreSQL với các lock namespaces tách biệt:910000 + provinceId: Sinh mã bếp ăn học đường (BAHD-{PROV}-{SEQ}).920001: Sinh mã định mức chi phí suất ăn (MCN-{SEQ}).920002: Sinh mã bảng tính chi phí suất ăn (MCS-{YYYYMMDD}-{SEQ}).920003: Sinh mã công khai chi phí (PCD-{YYYYMMDD}-{SEQ}).920052: Sinh mã phản ánh phụ huynh (FB-{YYYYMMDD}-{SEQ}).hashtext(sgtinCode): Lock tuần tự hóa phát hành W3C VC cho từng mã SGTIN.
- Accent-Insensitive Vietnamese Search (
immutable_unaccent): Sử dụng hàm wrapperimmutable_unaccent(lower(...))kết hợp GIN/B-Tree index để full-text search tên sản phẩm, mã lô, tên doanh nghiệp tiếng Việt không dấu với tốc độ cao.
2. ERD & Model Catalog theo 8 Data Domains
Domain 1: Tenant Management, Users, Subscriptions & RBAC
Rendering diagram...
| Model Name (DB Table) | Vai trò & Các Cột Trọng yếu |
|---|---|
Company (companies) | Tenant/Pháp nhân trên hệ thống: tax_code, company_name, platform_type (GOTRACE | NDA), organization_types (ENTERPRISE, SCHOOL, CATERING, DISTRIBUTOR...), did, gcp, token, administrative_unit_id, unit_path. |
User (users) | Tài khoản đăng nhập: email, password (bcrypt), role (1=ADMIN, 2=BUSINESS, 3=AGENT), company_id, token_version (instant JWT revocation), zalo_user_id, is_active, deleted_at. |
Role (roles) & RoleAssignment (role_assignments) | Dynamic RBAC: Role chứa mảng JSON permissions ([{ resource, actions }]). RoleAssignment gắn user_id với role_id kèm scope_type, scope_unit_id, include_children, scope_industry_codes, và thời hạn valid_from / valid_to. |
CompanySubscription (company_subscriptions) | Quản lý vòng đời gói dịch vụ doanh nghiệp (TXNG-F46): status (PENDING, ACTIVE, EXPIRED, SUSPENDED, TERMINATED), start_date, end_date, grace_days (kiểm soát bởi enforceServiceGate). |
Registration (registrations) & VietqrLookup (vietqr_lookups) | Đơn đăng ký doanh nghiệp mới trực tuyến, cache kết quả tra cứu mã số thuế từ VietQR và workflow Admin phê duyệt (approve / reject). |
LookupCategory & LookupItem (lookup_categories, lookup_items) | Master lookup toàn hệ thống, đặc biệt lưu cây đơn vị hành chính (DVHCVN) và cơ quan nhà nước (CO_QUAN_NN) với cột unit_path phục vụ phân quyền địa bàn. |
Domain 2: Multi-Industry Taxonomy (F41), Input Sources & Zones
Rendering diagram...
| Model Name (DB Table) | Vai trò & Các Cột Trọng yếu |
|---|---|
Industry (industries) & Segment/Family/Class/Brick | Danh mục ngành kinh tế VSIC 2025 (vsic_code, industry_group_code) và phân loại sản phẩm GS1 GPC 4 cấp. |
AttributeTemplate & AttributeDefinition | Dynamic Attribute Templates theo ngành (attr_key, data_type, is_required, unit, options). |
InputSource (input_sources) & InputSourceSupplier | Nguồn đầu vào đa ngành (GENETIC, RAW_MATERIAL, COMPONENT, CONSUMABLE, OTHER), lưu dynamic attributes trong cột JSONB attributes, chứng từ nhập khẩu và liên kết tới DigitalProductPassport (digital_product_passports). |
Material (materials) | Danh mục vật tư sản xuất, hoạt chất, nhà sản xuất, trạng thái phê duyệt và cảnh báo an toàn. |
RawMaterialZone (raw_material_zones) & Facility (facilities) | Vùng nguyên liệu (tọa độ bản đồ, diện tích, chỉ số môi trường) và cơ sở sản xuất/chế biến. |
Domain 3: Products (GTIN), Production Plans, Batches & Logs
Rendering diagram...
| Model Name (DB Table) | Vai trò & Các Cột Trọng yếu |
|---|---|
Gtin (gtins) & GtinReview (gtin_reviews) | Sản phẩm thương phẩm (nda_gtin_code GTIN-14, name, brick_id, shelf_life, images) và đánh giá từ người tiêu dùng (rating, helpful_count). |
ProductionPlan (production_plans) & PlanInputLink (plan_input_links) | Kế hoạch sản xuất (plan_code, status) và bảng liên kết định lượng nguyên liệu đầu vào (source_type: MATERIAL, INPUT_SOURCE, BATCH, PURCHASE_ORDER) gắn vào từng batch sản xuất. |
Batch (batches) & BatchHistory (batch_histories) | Lô sản xuất (code unique toàn cục, gtin_id, quantity, production_type, status, recalled_at, cancelled_at). |
ProductionProcess, CultivationEventType, ProductionLog | Quy trình sản xuất mẫu, các bước công đoạn và nhật ký thực hiện thực tế trên từng batch. |
Domain 4: SGTIN Stamps, Immutable Movement Ledger, Packaging & Warehouse
Rendering diagram...
| Model Name (DB Table) | Vai trò & Các Cột Trọng yếu |
|---|---|
Stamp, BlankStamp, StampPrintPlan, BatchStampHistories | Quản lý quota tem, phôi tem trắng, kế hoạch in tem và cấu hình hiển thị QR của batch. |
Sgtin (sgtins) & SgtinMovement (sgtin_movements) | Bảng định danh đơn chiếc (sgtin_code, lifecycle_status, current_location_type, current_company_id, public_activated_at) và Immutable Movement Ledger. |
PackagingPlan, PackagingUnit, ComboAssembly | Kế hoạch đóng gói đa cấp (Box/Carton/Pallet SSCC) và lắp ráp sản phẩm Combo (TXNG-F32). |
Warehouse, WarehouseInventory, StockTransfer, StockTake | Hệ thống kho bãi, tồn kho theo Batch/SGTIN/PackagingUnit, phiếu điều chuyển nội bộ và phiếu kiểm kê kho. |
Domain 5: B2B Purchase Orders, Cross-Enterprise Shipments, POS & Recall
| Model Name (DB Table) | Vai trò & Các Cột Trọng yếu |
|---|---|
PurchaseOrder (purchase_orders) & PurchaseOrderItem | Đơn mua hàng giữa doanh nghiệp mua (hoặc bếp ăn trường học) và nhà cung cấp (po_code, buyer_company_id, supplier_company_id, status). |
ShipmentOrder (shipment_orders), ShipmentOrderBatch, TransportDriver, Vehicle | Đơn vận chuyển nội bộ và liên doanh nghiệp, gắn phương tiện (vehicles), tài xế (transport_drivers), điểm đi/đến và danh sách batches/kiện hàng/SGTIN bàn giao. |
SalePoint (sale_points), PosTransaction (pos_transactions), BuyerConfirmation | Điểm bán hàng, giao dịch bán lẻ tại quầy POS (kèm PosSimulationRun) và lượt xác nhận mua hàng trên Zalo MiniApp / Web. |
RecallBatch (recall_batches) | Hồ sơ thu hồi batch (cascade_source: MANUAL | CASCADE_COMBO, parent_recall_id, severity). |
Domain 6: W3C Verifiable Credentials & Spores Blockchain Anchor
| Model Name (DB Table) | Vai trò & Các Cột Trọng yếu |
|---|---|
IssuerKey (issuer_keys) | Quản lý Decentralized Identifier (did) và cặp khóa ký Ed25519 của doanh nghiệp (private key được mã hóa AES-256-GCM). |
VcOutbox (vc_outbox) & SgtinVc (sgtin_vcs) | Bảng Transactional Outbox phát hành VC (idempotency_key, cte_event_code, payload, status) và bảng lưu trữ W3C VC đã ký cho từng mã SGTIN. |
VcAnchorBatch (vc_anchor_batches) & VcAnchorLeaf (vc_anchor_leaves) | Gom các bản ghi VC thành Merkle Tree (merkle_root, merkle_proof) và lưu bằng chứng giao dịch trên Spores Blockchain (tx_hash, block_number). |
Domain 7: Bếp ăn Học đường, Nutrition Engine & Parent Portal (BAHD)
| Model Name (DB Table) | Vai trò & Các Cột Trọng yếu |
|---|---|
SchoolCafeteria (school_cafeterias) | Hồ sơ bếp ăn trường học (cafeteria_program_code, công suất, mô hình vận hành, đơn vị hành chính). |
FoodGroup, NutrientCode, FoodCompositionItem, RdaStandard, NutritionThreshold | Cơ sở dữ liệu dinh dưỡng chuẩn của Viện Dinh dưỡng / FAO và ngưỡng RDA theo độ tuổi. |
MenuRecipe, MenuPlan, MealSet, NutritionBalanceLog | Công thức món ăn, thực đơn tuần/ngày, cấu trúc suất ăn và kết quả đánh giá từ Nutrition Engine. |
IngredientDemand & MealProcessingOrder | Dự trù nguyên liệu và lệnh chế biến bếp ăn gắn với các batches thực phẩm đầu vào. |
MealCostNorm, MealCostSheet, FinanceLedger, FinanceThreshold, CostReconciliation, PublicCostDisclosure | Chuỗi quản trị tài chính suất ăn: Định mức → Bảng tính giá ngày → Finance Ledger → Cost Reconciliation → Công khai chi phí. |
MenuQrCode, ParentFeedback, ParentRep, PublicPortalConfig | Mã QR thực đơn hàng ngày, phản ánh của phụ huynh (FB-YYYYMMDD-xxxx), Ban đại diện cha mẹ học sinh và cấu hình cổng công khai. |
Domain 8: Government Oversight (QLNN) & Integration Gateway
| Model Name (DB Table) | Vai trò & Các Cột Trọng yếu |
|---|---|
Personnel (personnel), TradingVenue (trading_venues), FormTemplate (form_templates) | Hồ sơ cán bộ thanh kiểm tra, mạng lưới chợ/điểm kinh doanh và dynamic inspection form templates. |
OversightPlan, OversightInspection, OversightViolation, OversightRemediation | Chu trình thanh kiểm tra nhà nước: Kế hoạch → Biên bản kiểm tra → Vi phạm hành chính → Hồ sơ khắc phục hậu kiểm. |
Alert (alerts), OversightAlert (oversight_alerts), ThresholdEvent | Alert Rule Engine & hệ thống cảnh báo tự động cho cả doanh nghiệp và cơ quan quản lý nhà nước. |
IntegrationOutbox, IntegrationDelivery, IntegrationConnectorState, IntegrationCompanyCredential, IntegrationExternalIdMap | Hạ tầng đồng bộ dữ liệu của apps/integration-gateway: Transactional Outbox queue, quản lý trạng thái delivery từng connector (ordering_key, lease_until), credentials mã hóa AES-256-GCM, và bảng mapping ID nội bộ ↔ ID cổng quốc gia. |