VIỆC XANH X — V4 Migration

Toàn bộ công việc cần làm để chuyển hệ thống hiện tại sang nền tảng dữ liệu lao động sống multi-tenant SaaS, với AI Core, Trust Layer và Financial Services.

92Tables
15Module Groups
6Sources
4Phases
10-13Months
7-8Devs
~65%Code Reuse

Mục lục nhanh

  1. Tổng quan hệ thống hiện tại — 6 sources
  2. V4 Vision — VIỆC XANH X + VIỆC XANH 247
  3. Gap Analysis — Hiện tại vs V4
  4. Complete Schema — 92 tables / 15 module groups
  5. Keep / Adapt / Rewrite / Drop Map
  6. Roadmap 4 Phases — 10-13 tháng
  7. Team Structure — 3 parallel tracks
  8. Risk Register
  9. Next Steps

1. Tổng quan — 6 Sources hiện tại

Hệ thống V3 đang production-stable, 13,500+ PHP files + 1,500+ TS/TSX files, 4 databases, 6 services độc lập.

backend/ PROD

Laravel 12 API · api.xanhvina.com.vn

  • 11,835 PHP files · 17 domains
  • 48 migrations · 167 tests
  • 114 services · 148 controllers
  • Sanctum 4 guards

backend-admin/ PROD

Laravel 12 + React SPA · admin.xanhvina.com.vn

  • 489 PHP + 566 TSX files
  • 9 domains · 257 pages
  • 164 hooks · 306 components
  • Vite 8 · React Router v7

frontend/ PROD

Next.js 16 · xanhvina.com.vn

  • 637 TS/TSX files · 89 routes
  • BFF pattern + HttpOnly cookies
  • 3 portals: Public · Worker · Employer
  • Tailwind v4 · Zustand · SWR

xanhvina-mobile/ DEV

Expo 55 + RN 0.83

  • 107 screens (9+64+27+7)
  • NativeWind + SWR + Zustand
  • Firebase Messaging + Socket.io
  • 61 unit tests

chat-service/ PROD

NestJS 11 + MongoDB

  • 350+ files · 3 LLMs
  • Claude + OpenAI + DeepSeek
  • Socket.io + Redis adapter
  • AI + Moderation + Admin SPA

zalo-mini-app/ SUNSET

React + zmp-sdk · Bắc Ninh only

  • 147 files · CTV revenue
  • Keep 6-12m as funnel
  • Deprecate entirely
  • No V4 code inheritance
Vấn đề chính: Hệ thống hoàn toàn single-tenant — 0 tenant_id columns trên 71 migrations. V4 yêu cầu multi-tenant SaaS + Trust Layer + AI Core + Workflow Engine + Integration Hub. Cần refactor kiến trúc sâu, không chỉ thêm features.

2. V4 Vision — Hai sản phẩm trên cùng nền tảng

VIỆC XANH X = nền tảng; VIỆC XANH 247 = app cho công nhân. Cùng lõi dữ liệu, khác trải nghiệm.

🏢 VIỆC XANH X — Platform

Multi-tenant SaaS cho nhà máy + nhà cung ứng

Nền tảng số trung tâm với kiến trúc 5 nhóm module + AI core cắm ngang + Trust Layer + Workflow Engine + Integration Hub.

  • Tenant types: factory · supplier · hybrid
  • AI agents: recruitment · worker mgmt · payroll · analytics · executive
  • Trust Layer: audit logs + entity versions + policy snapshots
  • Workflow Engine: state machines + SLA + escalation
  • Integration Hub: cross-tenant data sync + webhooks

📱 VIỆC XANH 247 — Worker App

Personal Labor OS — không chỉ app tìm việc

Ứng dụng trung tâm cho công nhân với 6 lớp sản phẩm. Hồ sơ lao động số là tài sản chiến lược lõi.

  • 6 lớp: discovery · search · detail · AI · profile · action
  • Hồ sơ số 9 cấu phần: định danh, giấy tờ, kỹ năng, kinh nghiệm, timeline, công lương...
  • AI advisor: ngôn ngữ tự nhiên, personalized
  • Financial services: ứng lương · vay · bảo hiểm · ví quyền lợi
  • 4 giai đoạn: users → transactions → infrastructure → financial
╔═══════════════════════════════════════════════════════════════════════════╗ ║ V4 ARCHITECTURE OVERVIEW ║ ╚═══════════════════════════════════════════════════════════════════════════╝ ┌─────────────────────────────────────┐ │ Tenant Orchestrator Layer │ ← routing, config, billing └──────────────┬──────────────────────┘┌───────────────┼───────────────┐ │ │ │ ┌────▼─────┐ ┌──────▼──────┐ ┌────▼────┐ │ Factory │ │ Supplier │ │ Hybrid │ ← Tenants │ Tenant A │ │ Tenant B │ │ Tenant C│ └────┬─────┘ └──────┬──────┘ └────┬────┘ └────────┬───────┴─────────────────┘ │ ┌───────▼────────┐ │ Trust Layer │ ← audit, versions, snapshots │ + Workflow │ ← state machines │ + Integration │ ← sync + webhooks └───────┬────────┘┌─────▼─────┐ │ AI Core │ ← 6 agents (chat-service rebuilt) └─────┬─────┘┌──────────┼──────────┬──────────────┐ │ │ │ │ ┌──▼──┐ ┌────▼────┐ ┌──▼──┐ ┌───────▼────────┐ │ Web │ │ Business│ │Admin│ │ VIỆC XANH 247 │ │(SEO)│ │ App │ │ SPA │ │ (Worker App) │ └─────┘ └─────────┘ └─────┘ └────────────────┘

3. Gap Analysis — Coverage 56% of V4 spec

Mapping 36 modules V4 yêu cầu với hiện trạng: 10 HAVE + 18 PARTIAL + 8 MISSING.

10 HAVE

Đã có production · cần adapt tenant layer

18 PARTIAL

Có một phần · cần mở rộng/refactor

8 MISSING

Chưa có · cần build from zero

Critical gaps cần ưu tiên

#V4 RequirementHiện trạngSeverity
1Multi-tenant SaaS (tenant_id trên mọi table)❌ Single-tenant hoàn toànCRITICAL
2Trust Layer (audit, snapshots, disputes, version)⚠ 30% (ActivityLog only)CRITICAL
3Ứng lương (salary advance) trên mobile❌ Chưa cóCRITICAL
4AI Advisor ngôn ngữ tự nhiên (mobile)❌ Chưa cóCRITICAL
5Workflow Engine (state machine framework)⚠ 25% (FSM scattered)HIGH
6AI Core Central (routing + permission boundary)⚠ 40% (chat-service isolated)HIGH
7Integration Hub (cross-tenant data sync)❌ Chưa cóHIGH
8Ví quyền lợi (unified wallet UI)⚠ Stubs onlyHIGH
9Hồ sơ số 9 cấu phần hoàn chỉnh⚠ 40% builtHIGH
10Formal vs Seasonal job logic split❌ Chưa phân biệtMEDIUM

4. Complete Schema — 92 tables / 15 module groups

PostgreSQL 16 · Tất cả bảng có tenant_id (trừ worker_accounts cross-tenant) · Money = NUMERIC(19,4).

Base: HTML blueprint 72 tables + 8 gap areas bổ sung (20 tables mới) = 92 tables đáp ứng 100% V4 brief.

4.1. Phase 1 — Foundation Modules (32 tables)

M1 — Tenant & Organization (9 tables)

  • tenants — factory · supplier · hybrid
  • tenant_modules — bật/tắt module per tenant
  • tenant_partnerships — NM ↔ NCC
  • tenant_subscriptions — billing plans
  • organizations · departments · positions
  • work_locations · shifts

M2 — Identity & Access (7 tables)

  • users — internal + workers unified
  • roles · permissions · role_permissions · user_roles
  • personal_access_tokens — Sanctum
  • login_logs — audit trail

V4 change: 358 permissions từ config → DB

M3 — Recruitment (10 tables)

  • jobs · candidates · applications · interviews
  • candidate_sources · candidate_documents
  • candidate_contact_logs · recruitment_campaigns
  • job_distributions NEW — NCC → NM
  • interview_rounds NEW — nhiều vòng PV

M4 — Worker Lifecycle (8 tables)

  • workers · employments
  • worker_onboardings · retention_milestones
  • worker_status_logs · worker_documents
  • leave_requests · referrals

🟢 KEEP 70% từ V3 Worker (21 models, 23 services)

4.2. Phase 2 — Operations Modules (26 tables)

M5 — Attendance & Timesheet (8 tables)

  • timesheet_periods · attendance_records
  • timesheet_summaries · attendance_imports
  • attendance_adjustments · attendance_anomalies
  • shift_assignments · holidays

Scale: ~30M records/tháng · Partition by work_date

M6 — Payroll & Compensation (8 tables)

  • salary_structures · payroll_cycles
  • payslips · payslip_items
  • bonuses · salary_advances
  • payment_records · salary_change_logs

⚠ Financial-grade — NUMERIC(19,4), invariants enforced

M7 — Platform Infrastructure (6 tables)

  • audit_logs · domain_events · notifications
  • file_attachments · system_settings · failed_jobs

Gap A — Workflow Engine (3 tables) NEW

  • workflow_definitions — state machine JSONB
  • workflow_instances — per entity
  • workflow_transitions — audit trail

Gap G — Entity Versioning (1 table) NEW

  • entity_versions — full snapshot mỗi change (entity_type, entity_id, version_num, snapshot JSONB, changed_fields, changed_by)

Critical: có thể replay bất kỳ entity state tại thời điểm xưa — foundation cho financial disputes

4.3. Phase 3 — Ecosystem Modules (22 tables)

M8 — Supplier Network (6 tables)

  • recruiters · collaborators · vendors
  • candidate_assignments
  • commission_rules · commission_payouts

Gap H — CTV Tree (1 table) NEW

  • collaborator_trees — materialized path (/1/5/23)
  • Fast ancestor/descendant query cho hoa hồng đa tầng

M9 — Factory Operations (5 tables)

  • manpower_plans — forecasting với AI
  • supplier_evaluations — NCC scorecard
  • factory_attendance_sources — raw clock data
  • factory_feedback · headcount_snapshots

M10 — Reconciliation (7 tables)

  • reconciliation_sessions · reconciliation_items
  • disputes · dispute_evidences
  • settlement_records · policy_snapshots
  • receivables_payables

Gap B — Integration Hub (3 tables) NEW

  • integration_sync_rules — field mappings, filters, frequency
  • integration_sync_logs — mỗi lần sync
  • webhook_subscriptions — 3rd party events + HMAC + retry

4.4. Phase 4 — AI + Worker App (22 tables)

M11 — AI & Intelligence (5 tables)

  • ai_sessions · ai_messages
  • ai_recommendations · ai_action_logs
  • prompt_templates

Gap C — AI Knowledge Base (3 tables) NEW

  • knowledge_documents
  • knowledge_embeddings (pgvector)
  • ai_tools — function registry

Gap D — Chat & Messaging (4 tables) NEW

  • conversations · conversation_participants
  • messages · message_reactions

M12 — Worker App (5 tables)

  • worker_accounts (cross-tenant!)
  • worker_account_links · saved_jobs
  • job_applications_mobile · worker_notifications

Gap F — Digital Profile 9 Parts (5 tables) NEW

  • worker_skills — verified skills library
  • worker_experiences — auto-populate từ employments
  • worker_certificates — chứng chỉ upload
  • worker_preferences — nhu cầu tìm việc
  • worker_timeline_events — activity feed

Gap E — Financial Products (4 tables) NEW

  • loan_products — catalog (consumer, emergency, advance)
  • loan_applications — credit score AI + disbursement
  • insurance_policies — partner (Bảo Việt, VBI)
  • wallet_balances — aggregate salary + advance + loan + points

4.5. Technical Design Decisions

Multi-tenant Pattern: Row-level tenant_id + middleware scoping + Row-Level Security (RLS) policies = defense-in-depth.
Worker Identity: worker_accounts (NO tenant_id) = cross-tenant identity. workers = hire record per tenant.
Money Handling: NUMERIC(19,4) on all money columns. NEVER float/double. VND needs 4 decimal.
Partitioning: attendance_records, audit_logs, domain_events, messages — partition by month (30M+ rows).
Extensions: uuid-ossp · pg_trgm · unaccent · pgcrypto · vector · pg_stat_statements
JSONB Usage: Flexible config + event payloads. KHÔNG dùng cho FK relations hoặc frequent query fields.

5. Keep / Adapt / Rewrite / Drop Map

Quyết định per-source · per-domain. Target ~60-65% code reuse thay vì greenfield 100%.

KEEP — reuse as-is
ADAPT — refactor for V4
REWRITE — build from zero
DROP — remove entirely

5.1. Executive Summary

SourceKEEPADAPTREWRITEDROPVerdict
backend/30%40%20%10%Mostly adapt + reuse
backend-admin/10%30%30%30%Heavy rewrite + drop HRM
frontend/40%35%15%10%Reuse UI + BFF
xanhvina-mobile/60%25%10%5%Good foundation, expand
chat-service/30%50%20%0%Refactor → AI Core
zalo-mini-app/0%0%0%100%Sunset entirely

5.2. backend/ — 17 Domains Decision

DomainQuy môDecisionV4 Target
Job16 models · 26 services · 21 controllersKEEP 80%M3 Recruitment + M4 (Dispatch FSM 10 states đã tested)
Worker21 models · 23 services · 34 controllersKEEP 70%M4 Worker Lifecycle
Finance22 models · 28 services · 12 controllersKEEP 80%M6 Payroll + Gap E Financial Products
Incentive10 models · 9 services · commission engineKEEP 80%M8 Supplier + M10 Reconciliation
Attendance9 models · 4 servicesKEEP 80%M5 Attendance
Employer · EmployerUser · Cluster · PartnerMultipleADAPTM1 Tenant + M2 IAM
WorkerManagement · InfrastructureShared utilitiesADAPTM4 + M7
SharedFramework-levelKEEPShared kernel
Dashboard · ApplicationSingle-tenant aggregatorsREWRITEM11 AI Analytics
Housing9 models · 14 servicesDROPNot in V4 brief
Community16 models · 18 servicesDROPNot in V4 brief
Content6 models · 5 servicesDROPMove to headless CMS
Factory (V2 alias)Backward-compatDROPKhông cần

5.3. Keep/Drop decision cho các sources khác

backend-admin/ React SPA

🟢 KEEP: Design system (306 components), form patterns, charts, DnD, TipTap, hooks boilerplate

🟡 ADAPT: 164 SWR hooks (add tenant), routing → /t/:slug/admin, auth store

🔴 REWRITE: Dashboard aggregation, PublicApiClient (20+ TODOs), permission seeding

⚫ DROP: HRM pages (60 pages, 35 models) — biggest drop

frontend/ Next.js 16

🟢 KEEP: Next.js 16 App Router, 251 UI components, BFF pattern, HttpOnly cookies, ISR

🟡 ADAPT: Routes Vietnamese → English, tenant context for employer ops, SWR hooks

🔴 REWRITE: 3 portal auth unification (single JWT)

⚫ DROP: Community pages, hardcoded route translations

xanhvina-mobile/ Expo RN

🟢 KEEP: Expo Router, SWR, Zustand stores, SecureStore, MMKV, 61 tests, Firebase

🟡 ADAPT: Auth store (tenant context), API client (tenant header)

🔴 REWRITE: Finance screens, Documents screen

🆕 ADD: AI Advisor tab, Financial Services tab, Leave flow, QR profile

Split: VIỆC XANH 247 (worker) + VIỆC XANH Business (employer)

chat-service/ NestJS

🟢 KEEP: NestJS + Fastify, Socket.io + Redis, BullMQ, MongoDB schema, 3 LLM providers, moderation, admin SPA

🟡 ADAPT: Rename → ai-service, unify JWT, tenant context, expose AI as REST

🆕 ADD: 5 new AI agents (recruitment, worker mgmt, payroll, analytics, executive)

⚫ DROP: Nothing — all valuable

zalo-mini-app/ — SUNSET ENTIRELY: Region-specific (Bắc Ninh), Zalo SDK limitations (no background sync, no rich native, no payment). Phase 1: banner redirect → VX247. Phase 2: freeze features. Phase 3: archive 12 months.

6. Roadmap — 4 Phases / 10-13 tháng

Phase 1 là MVP có thể bán. Phase 4 mở financial services — doanh thu bền vững.

📍 PHASE 1 — Foundation (Tháng 1–3) · 32 tables

MVP bán được · Tuyển dụng + quản lý CN · Multi-tenant từ đầu

ModuleTablesMục tiêuReuseEffort
M1 Tenant & Org9Tenant CRUD, RLS, sub-domain routing, onboarding0% (new)6-8w
M2 IAM7Sanctum 4-guard, JWT unified, permission DB60%4-5w
M3 Recruitment10Jobs, applications, interviews, Dispatch FSM port70%6-7w
M4 Worker Lifecycle8Workers, employments, milestones, leave, referral70%5-6w

📍 PHASE 2 — Operations (Tháng 4–6) · 26 tables

Dữ liệu lao động sống · Trust Layer · Workflow Engine

ModuleTablesMục tiêuReuseEffort
M5 Attendance8Chấm công, bảng công, import, anomaly AI, partition80%5-6w
M6 Payroll8Tính lương, phiếu lương, ứng lương, approvals80%6-7w
M7 Platform Infra6Audit, events, notifications, system settings50%3-4w
Gap A Workflow Engine3State machine framework reusable0% (new)4-5w
Gap G Entity Versioning1Snapshot + replay foundation0% (new)2w

📍 PHASE 3 — Ecosystem (Tháng 7–9) · 22 tables

Mở rộng NCC + Nhà máy · Đối soát tài chính · Integration Hub

ModuleTablesMục tiêuReuseEffort
M8 Supplier Network6Recruiters, CTV, vendors, commission payouts70%5-6w
Gap H CTV Tree1Materialized path cho multi-level commission0% (new)2w
M9 Factory Operations5Manpower plan, supplier eval, raw clock data20%4-5w
M10 Reconciliation7Đối soát NM ↔ NCC, disputes, settlement60%5-6w
Gap B Integration Hub3Cross-tenant sync rules + webhooks0% (new)4-5w

📍 PHASE 4 — AI + VIỆC XANH 247 (Tháng 10–13) · 22 tables

Ứng dụng lao động số hoàn chỉnh · AI Core · Financial Services

ModuleTablesMục tiêuReuseEffort
M11 AI & Intelligence5Sessions, messages, recommendations, action logs80%3-4w
Gap C AI Knowledge Base3Documents, pgvector embeddings, AI tools registry30%3-4w
Gap D Chat & Messaging4Conversations, participants, messages, reactions70%3w
M12 Worker App + Gap F Digital Profile10VX247 mobile, 9 cấu phần hồ sơ số75%6-8w
Gap E Financial Products4Loans, insurance, wallet, ứng lương UI50%5-6w

Tổng kết Roadmap

92 tables · 4 phases · 10-13 tháng · 7-8 devs · ~60-65% code reuse

Phase 1 là MVP có thể bán (32 tables · 3 tháng). Phase 2 hoàn thiện dữ liệu sống. Phase 3 mở ecosystem. Phase 4 tạo doanh thu bền vững từ tài chính + AI.

7. Team Structure — 3 Parallel Tracks

Chia work theo tracks độc lập để giảm contention và maximize throughput.

Track 1 · Platform Core

2 Backend + 1 QA · 4 months

  • M1 Tenant & Org
  • M2 IAM + JWT unified
  • M7 Platform Infra
  • Gap A Workflow Engine
  • Gap B Integration Hub
  • Gap G Entity Versioning

Track 2 · Business Domains

2 Backend + 1 QA · 5 months

  • M3 Recruitment (port Dispatch FSM)
  • M4 Worker Lifecycle
  • M5 Attendance (80% reuse)
  • M6 Payroll (80% reuse)
  • M8 Supplier + Gap H CTV Tree
  • M9 Factory + M10 Reconciliation

Track 3 · Frontend + Mobile

1 FE + 1 SPA + 2 Mobile + 1 QA · 6 months

  • Next.js adapt (tenant context)
  • Admin SPA pages rewrite
  • VIỆC XANH 247 app (worker)
  • VIỆC XANH Business app (employer)
  • AI Service expand (chat-service)
  • Shared design system (copy per app, no workspace tool)
Coordination: 1 Tech Lead + 1 Product Manager. Weekly arch review. Monthly stakeholder demo. Quarterly gate review.

8. Risk Register

Top risks với impact + probability + mitigation.

#RiskImpactProbabilityMitigation
1 Tenant data leak — query scoping bug cross-tenant CRITICAL MEDIUM RLS policies + integration tests 2+ tenants + penetration test pre-launch
2 State machine refactor break existing dispatches HIGH MEDIUM Event sourcing migration + replay capability + canary rollout
3 Permission config → DB migration break existing admin HIGH LOW Dual-read pattern (DB first, fallback config) + feature flag rollback
4 Attendance partition performance trên 30M+ rows/tháng MEDIUM MEDIUM Composite index (tenant_id, work_date) + query plan review + monitoring
5 AI cost spiral khi user tăng 10x MEDIUM HIGH Per-tenant rate limits + cache aggressively + route cheap LLM (DeepSeek)
6 Financial services compliance (loans, insurance) HIGH MEDIUM Partner-first launch (no license needed), legal review, conservative eligibility
7 Chat-service AI duplicate business logic với backend MEDIUM HIGH Clear boundary: AI = advisory, backend = source of truth. Contract review.
8 Team scaling không kịp — hiện chỉ có ~3 devs HIGH HIGH Phase-based hiring: 4 devs P1, peak 7-8 P2-P3, giảm dần P4

9. Next Steps

Sẵn sàng kick off ngay khi team + canary tenant được xác nhận.

📅 Tuần 1-2 — Preparation

  • Assemble team: hire/assign 4-5 devs Phase 1, plan ramp to 7-8
  • Tenant model workshop (confirm factory/supplier/hybrid design)
  • Setup PostgreSQL 16 staging environment
  • Identify 2-3 candidate canary tenants (engage customer success)
  • Provision V4 working directory /Users/trungnguyen/Sites/viecxanh-v4
  • Design review: Trust layer schema + permission DB migration plan

🚀 Tuần 3-4 — Kickoff Phase 1

  • Init V4 parent folder với 6 git repos độc lập (no workspace tool)
  • Extensions setup: pgvector, pg_trgm, unaccent
  • First PR: M1 Tenant schema + migrations
  • Setup migration tracking dashboard (tests, coverage, tenant count)
  • Weekly arch review cadence established
  • CI/CD pipeline (GitHub Actions: lint, test, build per PR)

💾 Tài liệu reference đi kèm

FileNội dung
00-cover-and-summary.mdExecutive summary
01-v4-complete-schema.md92 tables chi tiết + design decisions
02-keep-drop-rewrite-map.mdPer-source per-domain decisions
visuals/v4-migration-work-breakdown.htmlTài liệu này — scrollable overview
/Users/trungnguyen/Sites/xanhvina/Backup 9.9GB · 6 git repos với full history

✨ Ready to Build

Backup đã xong. Schema đã thiết kế. Kế hoạch đã rõ. Chỉ cần quyết team size và canary tenant để kick off Phase 1.

VIỆC XANH X V4 = hạ tầng dữ liệu lao động sống, AI-first, financial-ready.