diff --git a/.agents/skills/resetdb/SKILL.md b/.agents/skills/resetdb/SKILL.md
new file mode 100644
index 0000000..eeede60
--- /dev/null
+++ b/.agents/skills/resetdb/SKILL.md
@@ -0,0 +1,43 @@
+---
+name: resetdb
+description: >-
+ Reset toàn bộ cơ sở dữ liệu SSFRMS (SQL Server) về trạng thái hệ thống mới mở (zero customer activity).
+ Sử dụng khi người dùng yêu cầu reset database, làm sạch giao dịch, hoặc gõ /resetdb, /reset-db.
+---
+
+# Reset SSFRMS Database to Fresh Launch State
+
+This skill automates the complete reset of the SafeSpace (SSFRMS) SQL Server database (`SSFRMS`) to a Day 1 fresh operational state:
+- Zero customer transactions (reservations, contracts, payments, tickets, handovers, return inspections, overdue cases, assignments).
+- All 144 physical storage units (K01–K12 across 12 facilities) reset to `AVAILABLE` (decommissioned legacy units and non-K units removed).
+- All temporary test accounts and activity/login logs deleted.
+- Preserves all essential system master data: facilities, unit types, rental rates, policies, roles, permissions.
+- Preserves default system accounts: `admin`, `manager01`, `staff01`, `ops01` (`OPERATIONS`), `customer01`, `customer02`.
+
+---
+
+## Instructions for Agent
+
+When the user invokes `/resetdb` or asks to reset the database:
+
+### Step 1: Execute the Automated Reset Script
+Run the PowerShell reset script located in `scripts/reset-db.ps1`:
+
+```powershell
+powershell -NoProfile -ExecutionPolicy Bypass -File .agents/skills/resetdb/scripts/reset-db.ps1
+```
+
+### Step 2: Validate Verification Output
+Check the output from the script:
+- All transaction tables must display `[PASS] : 0 rows`.
+- Storage units status must show `AVAILABLE 144`.
+- Active seed accounts must list `admin`, `staff01`, `customer01`, `customer02`, `manager01`, `ops01`.
+
+### Step 3: Respond to User
+Inform the user that the database has been cleanly reset, and provide the credential table from [references/credentials.md](./references/credentials.md):
+- `admin` / `Admin@123`
+- `ops01` / `Ops@123` (`OPERATIONS`)
+- `manager01` / `Manager@123`
+- `staff01` / `Staff@123`
+- `customer01` / `Customer@123`
+- `customer02` / `Customer@123`
diff --git a/.agents/skills/resetdb/references/credentials.md b/.agents/skills/resetdb/references/credentials.md
new file mode 100644
index 0000000..ca37981
--- /dev/null
+++ b/.agents/skills/resetdb/references/credentials.md
@@ -0,0 +1,18 @@
+# SafeSpace (SSFRMS) — Default Seed Accounts
+
+After resetting the database with `/resetdb`, the following accounts are ready to use:
+
+| Role | Username | Password | Full Name | Facility Scope | Notes |
+|---|---|---|---|---|---|
+| **ADMIN** | `admin` | `Admin@123` | Hệ Thống Admin | Toàn hệ thống | Quản trị viên tối cao, toàn quyền cấu hình & phân quyền |
+| **OPERATIONS** | `ops01` | `Ops@123` | Lê Vận Hành | Cơ sở Nguyễn Lương Bằng | Quản lý vận hành kinh doanh, báo cáo & audit log |
+| **MANAGER** | `manager01` | `Manager@123` | Phạm Thu Hà | Cơ sở Nguyễn Lương Bằng | Quản lý cơ sở kho, duyệt gia hạn, phân bổ kho, đối soát |
+| **STAFF** | `staff01` | `Staff@123` | Trần Nhân Viên | Cơ sở Nguyễn Lương Bằng | Nhân viên vận hành, bàn giao, kiểm tra trả kho, đối soát |
+| **CUSTOMER** | `customer01` | `Customer@123` | Nguyễn Văn An | Khách hàng | Khách hàng mới, 0 đơn đặt chỗ, 0 hợp đồng |
+| **CUSTOMER** | `customer02` | `Customer@123` | Trần Thị Mai | Khách hàng | Khách hàng mới, 0 đơn đặt chỗ, 0 hợp đồng |
+
+## Storage Units Status
+- Total Units: 72
+- Available: 72 (100%)
+- Occupied: 0
+- Reserved: 0
diff --git a/.agents/skills/resetdb/scripts/reset-db.ps1 b/.agents/skills/resetdb/scripts/reset-db.ps1
new file mode 100644
index 0000000..cc88f8c
--- /dev/null
+++ b/.agents/skills/resetdb/scripts/reset-db.ps1
@@ -0,0 +1,95 @@
+# =========================================================================
+# reset-db.ps1: Automated reset script for SSFRMS
+# Can be run standalone or invoked by Antigravity /resetdb skill
+# =========================================================================
+
+param(
+ [string]$ServerInstance = ".\SQLEXPRESS",
+ [string]$Database = "SSFRMS"
+)
+
+$ErrorActionPreference = "Stop"
+$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
+$SqlFile = Join-Path $ScriptDir "reset_db.sql"
+
+Write-Host "======================================================" -ForegroundColor Cyan
+Write-Host " SafeSpace (SSFRMS) - Database Reset to Fresh State " -ForegroundColor Cyan
+Write-Host "======================================================" -ForegroundColor Cyan
+Write-Host "Target Server : $ServerInstance"
+Write-Host "Target Database : $Database"
+Write-Host "SQL Script : $SqlFile"
+Write-Host ""
+
+if (-not (Test-Path $SqlFile)) {
+ Write-Host "[ERROR] Cannot find SQL file: $SqlFile" -ForegroundColor Red
+ exit 1
+}
+
+# 1. Execute SQL reset script
+Write-Host "[1/3] Executing database cleanup..." -ForegroundColor Yellow
+$result = sqlcmd -I -S $ServerInstance -d $Database -i $SqlFile -b
+if ($LASTEXITCODE -ne 0) {
+ Write-Host "[ERROR] sqlcmd failed with exit code $LASTEXITCODE" -ForegroundColor Red
+ Write-Host $result
+ exit 1
+}
+Write-Host "Cleanup completed successfully." -ForegroundColor Green
+
+# 2. Verify transaction table counts
+Write-Host ""
+Write-Host "[2/3] Verifying clean transaction state..." -ForegroundColor Yellow
+$verifySql = @"
+SELECT 'reservations' as tbl, COUNT(*) as cnt FROM reservations
+UNION ALL SELECT 'rental_contracts', COUNT(*) FROM rental_contracts
+UNION ALL SELECT 'payments', COUNT(*) FROM payments
+UNION ALL SELECT 'support_tickets', COUNT(*) FROM support_tickets
+UNION ALL SELECT 'handover_records', COUNT(*) FROM handover_records
+UNION ALL SELECT 'return_inspections', COUNT(*) FROM return_inspections
+UNION ALL SELECT 'unit_assignments', COUNT(*) FROM unit_assignments
+UNION ALL SELECT 'maintenance_requests', COUNT(*) FROM maintenance_requests
+UNION ALL SELECT 'contract_renewals', COUNT(*) FROM contract_renewals
+UNION ALL SELECT 'overdue_cases', COUNT(*) FROM overdue_cases
+UNION ALL SELECT 'access_credentials', COUNT(*) FROM access_credentials
+UNION ALL SELECT 'activity_logs', COUNT(*) FROM activity_logs;
+"@
+
+$counts = sqlcmd -S $ServerInstance -d $Database -Q $verifySql -h -1 -W
+$allZero = $true
+$lines = $counts -split "`r?`n" | Where-Object { $_ -match '^\w+\s+\d+' }
+foreach ($line in $lines) {
+ $parts = $line.Trim() -split '\s+'
+ if ($parts.Length -ge 2) {
+ $table = $parts[0]
+ $cnt = [int]$parts[1]
+ if ($cnt -ne 0) {
+ Write-Host " [FAIL] $table : $cnt rows" -ForegroundColor Red
+ $allZero = $false
+ } else {
+ Write-Host " [PASS] $table : 0 rows" -ForegroundColor Gray
+ }
+ }
+}
+
+if (-not $allZero) {
+ Write-Host "[ERROR] Some tables still have remaining rows!" -ForegroundColor Red
+ exit 1
+}
+
+# 3. Verify storage unit availability & accounts
+Write-Host ""
+Write-Host "[3/3] Checking storage units & seed accounts..." -ForegroundColor Yellow
+
+$unitSql = "SELECT Status, COUNT(*) as cnt FROM storage_units GROUP BY Status;"
+$unitResult = sqlcmd -S $ServerInstance -d $Database -Q $unitSql -h -1 -W
+Write-Host "Storage Units status:" -ForegroundColor Cyan
+Write-Host $unitResult
+
+$userSql = "SELECT u.Username, r.RoleName FROM users u JOIN user_roles ur ON u.UserId = ur.UserId JOIN roles r ON ur.RoleId = r.RoleId ORDER BY u.UserId;"
+$userResult = sqlcmd -S $ServerInstance -d $Database -Q $userSql -h -1 -W
+Write-Host "Active Seed Accounts:" -ForegroundColor Cyan
+Write-Host $userResult
+
+Write-Host ""
+Write-Host "======================================================" -ForegroundColor Green
+Write-Host " DATABASE RESET COMPLETED - 100% CLEAN & READY! " -ForegroundColor Green
+Write-Host "======================================================" -ForegroundColor Green
diff --git a/.agents/skills/resetdb/scripts/reset_db.sql b/.agents/skills/resetdb/scripts/reset_db.sql
new file mode 100644
index 0000000..5efa973
--- /dev/null
+++ b/.agents/skills/resetdb/scripts/reset_db.sql
@@ -0,0 +1,88 @@
+-- =========================================================================
+-- reset_db.sql: Reset SSFRMS database to pristine "Day 1" launch state
+-- - Zero customer transactions / activity
+-- - All 72 storage units set to 'AVAILABLE'
+-- - Default seed roles, facilities, unit types, rates, policies preserved
+-- - Default accounts (admin, staff01, manager01, ops01, customer01, customer02) preserved
+-- - All temporary non-seeded accounts and logs deleted
+-- =========================================================================
+
+SET NOCOUNT ON;
+SET QUOTED_IDENTIFIER ON;
+SET ANSI_NULLS ON;
+
+-- 1. Disable all foreign key constraints
+EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all';
+
+-- 2. Clear all customer transaction & activity tables
+DELETE FROM [activity_logs];
+DELETE FROM [login_history];
+DELETE FROM [access_credentials];
+DELETE FROM [overdue_cases];
+DELETE FROM [contract_renewals];
+DELETE FROM [maintenance_requests];
+DELETE FROM [unit_assignments];
+DELETE FROM [unit_status_history];
+DELETE FROM [return_inspections];
+DELETE FROM [handover_records];
+DELETE FROM [support_tickets];
+DELETE FROM [payments];
+DELETE FROM [rental_contracts];
+DELETE FROM [reservations];
+
+-- 3. Reset identities on transaction tables so IDs start clean from 1
+IF OBJECT_ID('reservations') IS NOT NULL DBCC CHECKIDENT ('reservations', RESEED, 0);
+IF OBJECT_ID('rental_contracts') IS NOT NULL DBCC CHECKIDENT ('rental_contracts', RESEED, 0);
+IF OBJECT_ID('payments') IS NOT NULL DBCC CHECKIDENT ('payments', RESEED, 0);
+IF OBJECT_ID('support_tickets') IS NOT NULL DBCC CHECKIDENT ('support_tickets', RESEED, 0);
+IF OBJECT_ID('handover_records') IS NOT NULL DBCC CHECKIDENT ('handover_records', RESEED, 0);
+IF OBJECT_ID('return_inspections') IS NOT NULL DBCC CHECKIDENT ('return_inspections', RESEED, 0);
+IF OBJECT_ID('unit_assignments') IS NOT NULL DBCC CHECKIDENT ('unit_assignments', RESEED, 0);
+IF OBJECT_ID('maintenance_requests') IS NOT NULL DBCC CHECKIDENT ('maintenance_requests', RESEED, 0);
+IF OBJECT_ID('contract_renewals') IS NOT NULL DBCC CHECKIDENT ('contract_renewals', RESEED, 0);
+IF OBJECT_ID('overdue_cases') IS NOT NULL DBCC CHECKIDENT ('overdue_cases', RESEED, 0);
+IF OBJECT_ID('access_credentials') IS NOT NULL DBCC CHECKIDENT ('access_credentials', RESEED, 0);
+IF OBJECT_ID('activity_logs') IS NOT NULL DBCC CHECKIDENT ('activity_logs', RESEED, 0);
+IF OBJECT_ID('login_history') IS NOT NULL DBCC CHECKIDENT ('login_history', RESEED, 0);
+IF OBJECT_ID('unit_status_history') IS NOT NULL DBCC CHECKIDENT ('unit_status_history', RESEED, 0);
+
+-- 4. Delete non-seeded test users (keep only system seed accounts)
+DELETE FROM [user_roles]
+WHERE UserId IN (
+ SELECT UserId FROM [users]
+ WHERE Username NOT IN ('admin', 'staff01', 'manager01', 'ops01', 'customer01', 'customer02')
+);
+
+DELETE FROM [user_facilities]
+WHERE UserId IN (
+ SELECT UserId FROM [users]
+ WHERE Username NOT IN ('admin', 'staff01', 'manager01', 'ops01', 'customer01', 'customer02')
+);
+
+DELETE FROM [users]
+WHERE Username NOT IN ('admin', 'staff01', 'manager01', 'ops01', 'customer01', 'customer02');
+
+-- 5. Delete decommissioned legacy units (OUT_OF_SERVICE or non-K units)
+DELETE FROM [storage_units] WHERE [Status] IN ('OUT_OF_SERVICE', 'OUT OF SERVICE') OR [UnitNumber] NOT LIKE 'K%';
+
+-- 6. Inactivate legacy unit types and their rates (including Locker)
+UPDATE [unit_types] SET [Status] = 'INACTIVE'
+WHERE [TypeName] IN (
+ 'Kho Mini S (1m x 1m)',
+ 'Kho Tiêu Chuẩn M (2m x 2m)',
+ 'Kho Lớn L (3m x 3m)',
+ 'Kho Doanh Nghiệp XL (4m x 4m)',
+ 'Tủ Locker Cá Nhân (0.5m x 0.5m)'
+);
+UPDATE [rental_rates] SET [Status] = 'INACTIVE'
+WHERE [UnitTypeId] IN (SELECT [UnitTypeId] FROM [unit_types] WHERE [Status] = 'INACTIVE');
+
+-- 7. Reset all active storage units (K01-K12) to AVAILABLE
+UPDATE [storage_units] SET [Status] = 'AVAILABLE';
+
+-- 8. Re-enable and validate all foreign key constraints
+EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all';
+
+PRINT 'SSFRMS Database reset completed successfully!';
+
+
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
new file mode 100644
index 0000000..c2bae97
--- /dev/null
+++ b/.github/copilot-instructions.md
@@ -0,0 +1,3 @@
+# Repository instructions
+
+Read `AGENTS.md` first. For frontend changes, follow `docs/frontend-naming.md` and `SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md`. Consult the frontend `FRONTEND-MAP.md` before creating files. Run `npm run check:structure` in the frontend directory.
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..0ccf77f
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,120 @@
+# AGENTS.md — Sổ tay vận hành cho AI coding agent (SSFRMS / SafeSpace)
+
+> Đọc file này ĐẦU TIÊN trong mọi phiên. File này là bản đồ, không phải bách khoa:
+> chi tiết nằm trong `docs/` và các file được liên kết bên dưới. Giữ file dưới 200 dòng.
+
+## 1. Quy tắc bắt buộc (không được vi phạm)
+
+1. **Mỗi phiên chỉ làm MỘT tính năng** trong `feature_list.json` (WIP = 1). Không "tiện tay" sửa tính năng khác.
+2. **"Xong" = kiểm chứng pass**, không phải "code trông ổn". Chạy lệnh `verification` của tính năng + `./init.sh`.
+3. **Không tự đổi `state` sang `passing`** khi chưa có bằng chứng (output lệnh, commit). `passing` không bao giờ lùi về trạng thái khác nếu không có lý do ghi trong `progress.md`.
+4. **Figma là chuẩn cho giao diện khách hàng.** Backend sửa theo giao diện, không sửa giao diện cho khớp backend (xem `DECISIONS.md` D01).
+ Figma đã rà hết mâu thuẫn ngày 26/09/2026 (D11). Ảnh, giá, số liệu trong Figma chỉ là minh hoạ — lấy từ backend.
+5. **Không đưa chữ "demo", "dữ liệu mẫu", "sample"… lên giao diện.** Sản phẩm phải trông như sản phẩm chính thức (D07).
+6. **Không commit bí mật**: chuỗi kết nối thật, JWT secret thật, `.env.local`, `appsettings.*.json`.
+7. **Không sửa migration đã có.** Thay đổi schema → tạo migration mới (`dotnet ef migrations add `).
+8. **Không đảo ngược quyết định trong `DECISIONS.md`** mà không ghi quyết định mới kèm lý do.
+9. **Không xoá/sửa test để cho pass.** Test sai → ghi lý do trong `progress.md` rồi mới sửa.
+10. Làm trên nhánh `feature/` → Pull Request vào `main`. Không push thẳng `main`.
+11. Tiếng Việt cho giao diện và tài liệu; tên biến, hàm, API bằng tiếng Anh.
+12. **AI không được tự `git push`, tạo Pull Request hay merge lên repo này.** Chỉ sửa code và commit trên máy;
+ giao lại cho thành viên nhóm (patch / file zip / hướng dẫn lệnh) để người đó tự kiểm tra rồi tự push.
+
+13. **Khi sửa FE, đọc bắt buộc `docs/frontend-naming.md`, `SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md` và `FRONTEND-MAP.md` cùng thư mục.** Không tạo lại thư mục cũ; chạy `npm run check:structure` trước khi bàn giao.
+
+## 2. Dự án là gì
+
+Hệ thống quản lý và cho thuê kho tự phục vụ **SafeSpace** cho 5 nhóm người dùng
+(Khách hàng, Nhân viên cơ sở, Quản lý cơ sở, Quản lý vận hành kinh doanh, Quản trị hệ thống),
+27 use case (UC01–UC27), 7 luồng nghiệp vụ. Nguồn yêu cầu: `srs_content.txt` (SRS v2.0) và
+`dd_content.txt` (Data Dictionary, 25 bảng). Giao diện: Figma "SafeSpace - Modern UI"
+(https://www.figma.com/design/SX8EvOf1TJkxfMl90bZsGN/SafeSpace---Modern-UI).
+
+## 3. Bản đồ repo
+
+| Thư mục / file | Nội dung |
+|---|---|
+| `StorageProject.Api/` | .NET Minimal API: `Program.cs`, `Endpoints/*Endpoints.cs` |
+| `StorageProject.Core/` | Entities, DTOs, `Interfaces/IServices.cs` |
+| `StorageProject.Infrastructure/` | EF Core `AppDbContext`, `Migrations/`, `DbSeeder.cs`, `Services/*Service.cs` |
+| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/` | React 19 + Vite: khách hàng, nhân viên, quản lý cơ sở, quản trị |
+| `…/src/features/facility-operations/` | Khu Nhân viên `#/staff` + Quản lý cơ sở `#/manager` (gọi `/api/ops/*`, D15) |
+| `…/src/app/state/appReducer.js` | Nghiệp vụ phía giao diện (hàm thuần, có test) |
+| `…/src/app/state/AppProvider.jsx` | Phiên đăng nhập, 2 chế độ: API / lưu trình duyệt |
+| `…/src/shared/api/` | Gọi API + `mappers.js` chuyển dữ liệu backend → giao diện |
+| `…/BE-CONTRACT.md` | Endpoint giao diện cần backend bổ sung |
+| `…/BACKEND-TODO.md` | Việc backend còn thiếu, xếp ưu tiên A/B/C, mẫu JSON `GET /api/ops/board` |
+| `docs/facility-ops-api.md`, `docs/operations-api.md` | API khu Nhân viên / Quản lý cơ sở và khu Vận hành KD |
+| `…/CUSTOMER-FLOW-COVERAGE.md`, `ADMIN-FLOW-COVERAGE.md`, `OPS-FLOW-COVERAGE.md` | Đối chiếu màn Figma ↔ route ↔ component ↔ API |
+
+## 4. Đọc thêm khi cần (tiết lộ dần)
+
+| Khi làm việc này | Đọc |
+|---|---|
+| Hiểu kiến trúc, luồng request, chế độ API / trình duyệt | `docs/architecture.md` |
+| Sửa trạng thái, cách tính tiền, quy tắc nghiệp vụ | `docs/business-rules.md` + SRS mục 7–8 |
+| Viết code FE hoặc BE mới | `docs/conventions.md` |
+| Kiểm chứng, viết test, định nghĩa "xong" | `docs/verification.md` |
+| Thêm / sửa endpoint | `BE-CONTRACT.md` + `docs/conventions.md` mục Backend |
+| Dựng màn hình từ Figma | `CUSTOMER-FLOW-COVERAGE.md` / `ADMIN-FLOW-COVERAGE.md` + `docs/figma-review-2026-09-26.md` |
+| Tính năng lớn, nhiều file | Tạo sprint contract từ `docs/templates/sprint-contract.md` |
+
+## 5. Chạy dự án
+
+```bash
+./init.sh # Linux/macOS/Git Bash — kiểm tra môi trường + test + build
+./init.ps1 # Windows PowerShell — tương đương
+npm run dev # Khởi chạy đồng thời Backend (:5151), Frontend (:5173) và Ngrok tunnel
+dotnet run --project StorageProject.Api --launch-profile http # API riêng lẻ: http://localhost:5151
+cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm run dev # UI riêng lẻ: http://127.0.0.1:5173
+```
+
+Cần: .NET SDK 10 (project đặt `net10.0`), Node ≥ 22.12, SQL Server (mặc định `.\SQLEXPRESS`).
+Tài khoản seed: `customer01`…`customer06`/`Customer@123`, `staff01`, `staff02`/`Staff@123`, `manager01`/`Manager@123`
+(cả ba phụ trách SafeSpace Nguyễn Lương Bằng), `ops01`/`Ops@123` (Vận hành KD), `admin`/`Admin@123`.
+Không có backend: tạo `.env.local` với `VITE_USE_API=false`, hoặc `MOCK_OPS=1 npm run dev:mock` (máy chủ giả có cả `/api/ops/*`,
+thêm `manager01`/`Manager@123`).
+
+## 6. Vòng đời một phiên làm việc
+
+**Bắt đầu**
+1. Đọc `AGENTS.md` (file này).
+2. Chạy `./init.sh` (hoặc `./init.ps1`). Nếu fail → sửa môi trường trước, KHÔNG code tính năng.
+3. Đọc `progress.md` — phiên trước làm gì, dừng ở đâu.
+4. Đọc `feature_list.json` — chọn tính năng `active`; nếu không có, chọn `not_started` đầu tiên
+ có `depends_on` đã `passing`. Tính năng `blocked` chỉ làm khi đã gỡ được lý do chặn.
+5. `git log --oneline -10` để xem thay đổi gần đây.
+
+**Làm việc**
+6. Đổi `state` tính năng đó sang `active`.
+7. Chỉ sửa những file cần cho tính năng đó.
+8. Chạy lệnh `verification` của tính năng; fail → sửa → chạy lại.
+
+**Kết thúc**
+9. Chạy lại `./init.sh` — toàn bộ phải pass.
+10. Cập nhật `feature_list.json` (`state`, `evidence`) và thêm một mục vào `progress.md`.
+11. Có quyết định kỹ thuật mới → thêm vào `DECISIONS.md`.
+12. Commit rõ ràng (`feat(F05): …`). Chỉ commit khi repo ở trạng thái chạy được.
+
+## 7. Checklist trước khi nói "xong"
+
+- [ ] `npm test` pass (thư mục frontend)
+- [ ] `npm run test:render` pass
+- [ ] `npm run build` pass
+- [ ] `dotnet build StorageProject.slnx` pass (khi có sửa backend)
+- [ ] Lệnh `verification` riêng của tính năng pass
+- [ ] Không còn `console.log`, `debugger`, TODO tạm, dữ liệu cứng để thử
+- [ ] Không có chữ "demo"/"sample" mới trên giao diện
+- [ ] Đã cập nhật `feature_list.json`, `progress.md` (và `DECISIONS.md` nếu có)
+- [ ] Tài liệu liên quan (`BE-CONTRACT.md`, `*-FLOW-COVERAGE.md`) khớp với code
+
+## 8. Khi bị kẹt
+
+Ghi rõ vào `progress.md`: đang kẹt ở đâu, đã thử gì, cần ai quyết định. Đổi `state` thành `blocked`
+kèm `blocked_reason`. Không đoán nghiệp vụ — nếu SRS, Figma và code mâu thuẫn, hỏi nhóm và ghi vào `DECISIONS.md`.
+
+## 9. Nguồn tham khảo
+
+Bộ tài liệu harness này được soạn theo hướng dẫn từ hai trang do thầy Hoàng giới thiệu ngày 25/09/2026:
+- https://learnharness.org/#dinh-nghia — Harness Engineering: làm chủ AI coding agent
+- https://skills.learnharness.org/ — bộ skill cho AI coding agent
diff --git a/C07-QR-HUONG-DAN.md b/C07-QR-HUONG-DAN.md
new file mode 100644
index 0000000..465ba80
--- /dev/null
+++ b/C07-QR-HUONG-DAN.md
@@ -0,0 +1,36 @@
+# C07 — Xem và quét QR mở cửa (frontend)
+
+## Phạm vi
+Chỉ thêm frontend C07q, C07r1, C07r2 theo Figma; không triển khai backend QR. File code cũ `src/pages/Units.jsx` chỉ thêm 1 import và 1 lần render component. Không đổi đăng nhập, đặt kho, thanh toán, bàn giao, trả kho, giao diện KD, backend hay database.
+
+## Xem giao diện
+Vào `SafeSpace-Customer-UI/SafeSpace-Customer-UI`, tạo/cập nhật `.env.local`:
+```
+VITE_USE_API=false
+```
+Chạy `npm install`, `npm run dev`. Đăng nhập `mai.nguyen@example.com` / `SafeSpace@123`, chọn Kho của tôi → B-015 → Mở cửa kho → bấm trực tiếp hình QR để mô phỏng máy quét, giống prototype Figma. Nút Quay lại đưa về QR; Đóng, Escape hoặc bấm nền ngoài đóng hộp thoại.
+A-102 chưa được bàn giao (`handed_over: false`) nên QR bị khóa. Không đổi dữ liệu A-102 chỉ để mở khóa.
+Nếu đang đăng nhập tài khoản cục bộ khác không có hợp đồng, nó sẽ không có QR. Tính năng không kiểm tra email cố định; lấy hợp đồng và người dùng từ state.
+
+## Hành vi
+- Chỉ hiện mã khi hợp đồng đã bàn giao, trạng thái ACTIVE/EXPIRING và trong kỳ thuê.
+- QR thật được tạo bằng thư viện qrcode đã có; chứa mã tham chiếu ngẫu nhiên, không chứa thông tin cá nhân.
+- Mã dự phòng, ô kho và hạn hợp đồng lấy theo phiên mô phỏng và hợp đồng hiện tại.
+- Bấm QR kiểm tra lại quyền phiên mô phỏng, mã, ô kho, ngày cấp, ngày hiệu lực và trạng thái; hợp lệ hiện Mở cửa, không hợp lệ hiện Từ chối.
+- Nhật ký mô phỏng nằm riêng trong localStorage, tối đa 100 lần; không phải activity_logs database.
+- Mã cấp lại khi mở popup; mã mô phỏng hết hiệu lực sau ngày cấp.
+- Không có thao tác đóng cửa kho. Đóng chỉ đóng popup; cửa vật lý khách tự đóng.
+- Màn nhập mã dự phòng/camera không có trong khung Figma này nên không thêm.
+
+## Chế độ API
+Khi `VITE_USE_API=true`, các chức năng cũ vẫn dùng backend như trước. QR sẽ báo máy chủ chưa hỗ trợ; không giả lập thành công trên tài khoản thật. Đổi `src/state/useAccessQr.js` khi triển khai API cấp mã, kiểm mã và thu hồi mã; backend phải tự kiểm tra quyền sở hữu, đúng ô và thời hạn. Không dùng kiểm tra frontend làm kiểm soát cửa thật.
+
+## Các file thêm
+- src/components/AccessQr.jsx: giao diện và popup.
+- src/styles/access-qr.css: CSS riêng C07.
+- src/state/useAccessQr.js: ranh giới mô phỏng/tích hợp sau.
+- src/lib/access.js: kiểm tra mô phỏng.
+- src/assets/access/check.svg, close.svg: icon xuất từ Figma 601:9827/601:9837, kích thước 96×96.
+- tests/access.test.js: chạy `node --test tests/access.test.js`.
+
+Thiết kế tham chiếu: Figma SafeSpace - Modern UI, C07q 601:9806, C07r1 601:9826, C07r2 601:9836. Vùng giữ chỗ QR trong thiết kế được thay bằng QR có thể giải mã, thông tin minh họa được thay bằng dữ liệu hợp đồng.
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..beeb13e
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,5 @@
+# CLAUDE.md
+
+Hướng dẫn cho Claude Code. Toàn bộ quy tắc nằm trong `AGENTS.md` để dùng chung với Cursor, Copilot, Codex.
+
+@AGENTS.md
diff --git a/DECISIONS.md b/DECISIONS.md
new file mode 100644
index 0000000..1c9b590
--- /dev/null
+++ b/DECISIONS.md
@@ -0,0 +1,178 @@
+# Quyết định thiết kế (DECISIONS.md)
+
+> Ghi lại vì sao chọn A thay vì B, để phiên AI sau không tự đảo ngược.
+> Muốn đổi một quyết định → thêm quyết định mới ghi "Thay thế Dxx", không sửa mục cũ.
+> Trạng thái: **Đã chốt** · **Cần nhóm chốt** · **Đã thay thế**.
+
+## D01 — Figma là chuẩn cho giao diện khách hàng — Đã chốt
+- Giao diện code bám file Figma "SafeSpace - Modern UI". Backend được sửa cho khớp giao diện, không ngược lại.
+- Figma đã được rà và sửa hết mâu thuẫn về luồng ngày 26/09/2026 (D11, `docs/figma-review-2026-09-26.md`).
+- Những gì backend cần bổ sung: `BE-CONTRACT.md`.
+
+## D02 — Thời điểm thanh toán khi đặt chỗ — Đã chốt theo Figma (26/09/2026)
+- Theo D01: khách chuyển khoản QR ngay lúc đặt (C04), bấm "Tôi đã chuyển khoản" → đơn "Chờ đối soát";
+ nhân viên đối soát (S09) → quản lý phân bổ kho (M05) → nhận kho theo lịch (S02, S03). Hết giờ giữ chỗ → đơn tự huỷ (C04b).
+- SRS v2.0 mục A03 (thanh toán sau hợp đồng DRAFT) khác luồng này → nhóm cần sửa SRS cho khớp.
+- Backend còn thiếu API báo đã chuyển khoản và đối soát (F03).
+
+## D03 — Khách đăng ký dùng email làm username — Đã chốt
+- Backend chỉ đăng nhập bằng `username`; Figma không có ô username.
+- Khi khách đăng ký trên giao diện, `username = email`. Tài khoản seed vẫn dùng username (`customer01`…).
+
+## D04 — Luồng backend chưa hỗ trợ thì lưu trong trình duyệt theo tài khoản — Đã chốt
+- Áp dụng: báo đã chuyển khoản, trả kho, thông báo, đổi tên, ảnh đính kèm hỗ trợ.
+- Khi backend có API: chỉ sửa nhánh `ApiProvider` trong `src/state/store.jsx`; không rải lời gọi API vào page.
+
+## D05 — Tên vai trò lấy từ backend, không cứng trong giao diện — Đã chốt
+- Backend có `ADMIN`, `MANAGER`, `STAFF`, `CUSTOMER`; SRS/Figma có thêm Quản lý vận hành KD.
+- Giao diện quản trị đọc `GET /api/admin/roles`, nên thêm vai trò ở backend (F24) là giao diện tự hiện.
+
+## D06 — Ảnh cơ sở là file tĩnh của nhóm — Đã chốt
+- Dùng ảnh thật của nhóm trong `public/images/` (mặt tiền, bên trong, sơ đồ), không lấy ảnh từ Figma.
+- Cách gán ảnh cho cơ sở nằm ở `src/config/media.js`; khi có API ảnh chỉ đổi file này.
+
+## D07 — Giao diện trông như sản phẩm chính thức — Đã chốt
+- Không hiện chữ "demo", "bản thử", "dữ liệu mẫu", "sample" trên giao diện, kể cả khi chạy không có backend.
+
+## D08 — Quy trình Git — Đã chốt
+- Mỗi việc một nhánh `feature/` → Pull Request vào `main`. Giao diện khách hàng dùng `feature/customer-ui-figma`.
+- Commit theo tính năng: `feat(F05): …`, `fix(F02): …`, `docs: …`.
+
+## D09 — Tiền cọc và số tiền chuyển lúc đặt — Đã chốt (phía giao diện)
+- Cọc = 1 tháng tiền thuê. Số tiền chuyển lúc đặt = tiền thuê cả kỳ + cọc. Gói thuê 1 / 3 / 6 tháng.
+- Đi cùng luồng thanh toán lúc đặt (D02).
+
+## D10 — Thời gian từ backend coi là UTC — Đã chốt
+- Backend trả DateTime không kèm múi giờ; giao diện hiểu là UTC. Nên cấu hình JSON backend trả kèm `Z`.
+
+## D11 — Figma đã rà mâu thuẫn, mọi màn dùng chung một mốc dữ liệu — Đã chốt (26/09/2026)
+- Mốc chung 14/09/2026: A-102 chờ nhận kho 20/09; B-015 sắp hết hạn, chưa gửi gia hạn; HT-0082 thuộc B-015;
+ một tên cơ sở "SafeSpace Nguyễn Lương Bằng"; một nhân viên Trần Văn Long. Chi tiết: `docs/figma-review-2026-09-26.md`.
+- Quy tắc rút ra từ Figma: hợp đồng **chưa bàn giao** chỉ cho "Xem lịch nhận kho" / "Đổi lịch nhận kho" / hỗ trợ;
+ gia hạn và trả kho chỉ mở sau khi nhận kho. Gia hạn gửi chậm nhất 7 ngày trước ngày kết thúc; tiền cọc chuyển sang kỳ mới.
+- Ảnh, giá, số liệu trong Figma chỉ là minh hoạ — dữ liệu thật lấy từ backend.
+
+## D12 — Tìm kho: chế độ Bản đồ chỉ hiện bản đồ — Đã chốt (01/10/2026)
+- `#/find` (Danh sách) và `#/find/map` (Bản đồ) chuyển qua nút Danh sách / Bản đồ trên đầu trang.
+- Chế độ Bản đồ không hiện danh sách cơ sở bên cạnh; bấm điểm trên bản đồ → popup có "Xem chi tiết cơ sở".
+- Bản đồ dùng Leaflet + OpenStreetMap (ghi công trong `THIRD-PARTY-NOTICES.md`); toạ độ cơ sở ở `src/config/geo.js`.
+
+## D13 — Sơ đồ ô kho ở chi tiết cơ sở: chọn ô để xem giá, quản lý vẫn phân bổ — Cần nhóm chốt
+- Nút "Sơ đồ tình trạng kho" thay phần ảnh + tiện ích bằng sơ đồ 10 ô; ô trống màu xanh như nút bấm.
+ Chọn ô → tóm tắt đặt trước đổi theo loại kho / diện tích / giá của ô đó; ô không trống thì khoá nút đặt.
+- Ô khách chọn được gửi kèm đơn (`unit_code`) chỉ như **mong muốn**; quản lý vẫn phân bổ chính thức ở M05 (giữ D02).
+- Ảnh sơ đồ mặt bằng bỏ khỏi thư viện ảnh cơ sở (sơ đồ ô kho thay thế); D06 vẫn giữ cho ảnh mặt tiền / bên trong.
+- Số ô trống lấy từ `POST /api/availability/check`. Khi backend có `GET /api/facilities/{id}/units` thì sơ đồ dùng ô thật.
+- Nhóm cần chốt: có cho khách giữ đúng ô đã chọn hay không. Nếu có → đổi D02 và API đặt chỗ.
+
+## D14 — Công việc nhân viên dạng lưới 3×3 — Đã chốt (01/10/2026)
+- Mỗi trang danh sách việc của nhân viên hiện tối đa 9 thẻ (3×3), có phân trang.
+- Ô / mục không có việc hiện "Chưa có việc" — không để trống. Khách chưa thuê kho thì phần kho chỉ hiện một dòng thông báo.
+
+## D15 — Khu vận hành gọi `/api/ops/*`, chưa có thì lưu trong trình duyệt — Đã chốt (mở rộng D04)
+- Khu Nhân viên (`#/staff`) và Quản lý cơ sở (`#/manager`) dùng một hợp đồng API: `GET /api/ops/board` + các lệnh
+ `POST /api/ops/...` (chi tiết `BACKEND-TODO.md` mục A). Mọi lời gọi nằm trong `src/ops/api.js` + `src/ops/store.jsx`.
+- Backend trả 404 cho `/api/ops/board` → giao diện chuyển sang lưu trên trình duyệt (`safespace.ops.v1`) và hiện dòng
+ "Khu vận hành chưa kết nối được máy chủ. Thao tác đang được lưu trên trình duyệt này." (không dùng chữ "dữ liệu mẫu", theo D07).
+- Mock `npm run dev:mock` với `MOCK_OPS=1` có đủ endpoint này để thử; backend làm xong thì không cần sửa giao diện.
+
+## D16 — Vai trò Vận hành KD và quy ước báo cáo — Đã chốt (14/10/2026)
+- Tên role backend là `OPERATIONS` (khớp `src/lib/roles.js`). API riêng `/api/operations/*`, chỉ role này gọi được;
+ hợp đồng chi tiết ở `docs/operations-api.md`. Tài khoản seed `ops01` / `Ops@123`.
+- Chính sách `DEPOSIT`: `PERCENTAGE` = % tiền thuê cả kỳ; `FIXED ≥ 1.000` = số tiền VND; `FIXED < 1.000` = số tháng tiền thuê
+ (giữ nghĩa của chính sách seed `Value = 1` = 1 tháng, khớp D09). Chỉ chính sách `ACTIVE` còn hiệu lực mới được áp dụng.
+- Tra cứu giá thuê chỉ lấy `rental_rates.Status = ACTIVE`, để giá bị thay thế (`INACTIVE`) không còn được dùng.
+- Báo cáo: `payments` chưa có `original_payment_id`, và hoàn tiền hiện chỉ có hoàn cọc, nên mọi REFUND trừ vào
+ "Cọc còn giữ"; "Doanh thu thuê và phí" không trừ REFUND. Khi thêm hoàn tiền thuê/phí thì phải thêm liên kết khoản gốc.
+- Cơ sở `TEMPORARILY_CLOSED` chặn đặt chỗ mới; `INACTIVE` chỉ khi không còn hợp đồng / đơn đang xử lý. Không xoá cơ sở.
+
+## D17 — Mô hình kho theo Figma 14/10: 2 cỡ, mọi cơ sở có kho lạnh, gợi ý theo khu vực — Đã chốt (14/10/2026)
+- Chỉ còn 2 cỡ kho: **Cỡ M · 15 m²** và **Cỡ L · 30 m²** (bỏ cỡ S). Loại kho từ backend: diện tích ≤ 20 m² là M, lớn hơn là L.
+- Cả 12 cơ sở đều có kho thường và kho lạnh. Mỗi cơ sở 12 ô: 8 kho thường (4 M + 4 L) và 4 kho lạnh (2 M + 2 L).
+ Sơ đồ ô kho: dãy A cỡ M (K01–K04 thường, K05–K06 lạnh), dãy B cỡ L (K07–K10 thường, K11–K12 lạnh).
+- Gợi ý cơ sở theo **khu vực khách chọn**, không theo vị trí người dùng: bỏ "Gần bạn nhất" và "Cách bạn … km".
+- Tên loại kho hiển thị là "Kho lạnh" (thay "Kiểm soát nhiệt độ") cho khớp Figma.
+- Nhân viên / quản lý cơ sở thấy tên cơ sở phụ trách dưới vai trò trên header (SRS A06: mỗi người 1 cơ sở).
+- Trang chủ theo Figma mới: hero ảnh + tìm theo khu vực, số liệu, 4 loại kho, 3 bước, cơ sở theo khu vực, kêu gọi, footer.
+- Backend đổi seed cho khớp (4 loại kho, 12 cơ sở, 12 ô mỗi cơ sở) — đã làm ở D18.
+
+## D18 — Backend khu Nhân viên / Quản lý cơ sở (`/api/ops/*`) và seed theo D17 — Đã chốt (14/10/2026)
+- Làm đúng hợp đồng giao diện đã có (`src/ops/api.js`, mẫu JSON trong `BACKEND-TODO.md`); tài liệu `docs/facility-ops-api.md`.
+- Id trong API là **mã hiển thị** (`SS-…`, `XM-`/`BG-`, `TK-`, `HT-`, `GH-`, `HĐ-…`, `PC-`, `NV-`), backend đọc số cuối.
+- Phạm vi: chỉ cơ sở đang phân công trong `user_facilities` (A06); khác cơ sở trả 404, chưa phân công trả 403.
+- Không thêm bảng mới. Phần bảng chưa có cột (loại giấy tờ + 4 số cuối, biên bản trả kho 4 mục, phản hồi hỗ trợ,
+ lý do từ chối gia hạn, lần nhắc khách, thời điểm khách báo chuyển khoản, báo sai lệch) lưu và đọc lại từ `activity_logs`.
+- `handover_records.StaffId` và `return_inspections.StaffId` bắt buộc: việc **chưa giao** tạm ghi người tạo (quản lý);
+ bảng M06 coi người không có role STAFF là "chưa giao" (`OPEN`).
+- Trạng thái hỗ trợ: giao diện `WAITING_CUSTOMER` = DB `RESOLVED`, `DONE` = DB `CLOSED`.
+- Mở khoá: `CARD` → `ACCESS_CARD`; `PIN`, `FINGER` → `ACCESS_CODE` (mã tham chiếu ghi phương thức, **không lưu bí mật**).
+- Báo sai lệch thanh toán không đổi trạng thái đơn (vẫn `PENDING_VERIFICATION`); sau khi quản lý làm rõ, nhân viên xác nhận lại.
+- Phân bổ ô: ô phải trống và **đúng loại kho** của đơn; lúc này mới tạo hợp đồng `DRAFT` và ghi khoản cọc + tiền thuê `PAID`
+ (bảng `payments` bắt buộc có hợp đồng nên không ghi được lúc nhân viên đối soát).
+- Hoàn cọc: khoản còn nợ được trừ vào cọc (đánh dấu `PAID`, ghi chú "Trừ vào tiền cọc"), phần còn lại tạo khoản `REFUND`.
+- Thêm trạng thái đơn `PENDING_VERIFICATION` (migration viết tay `20261014150000_ReservationPendingVerification`).
+- Sửa lỗi cũ: `HandoverService` ghi `COMPLETED` và `RenewalService` ghi `PENDING_PAYMENT` — cả hai vi phạm CHECK trong DB;
+ nay ghi `HANDED_OVER` và `PENDING` (gia hạn chờ quản lý duyệt ở M03).
+- Seed D17: 4 loại kho, 12 cơ sở, 12 ô K01–K12 mỗi cơ sở, giá cùng công thức `src/lib/catalog.js`. Loại kho S/M/L/XL và
+ cơ sở "Quận 7" đời cũ chỉ chuyển ngừng dùng (không xoá). Muốn dữ liệu sạch: xoá database rồi chạy lại API.
+
+## D19 — Kết nối 100% dữ liệu vận hành & khách hàng trực tiếp từ SQL Server — Đã chốt (16/10/2026)
+- Xoá bỏ hoàn toàn mock store RAM `FacilityOpsStateStore.GetOrCreateState` và mock data fallback trong `OpsProvider`.
+- Mọi dữ liệu hiển thị trên bảng làm việc của Nhân viên (`GET /api/staff/board`) và Quản lý (`GET /api/manager/board`) đều được truy vấn trực tiếp từ các bảng SQL Server (`Reservations`, `StorageUnits`, `RentalContracts`, `UnitAssignments`, `HandoverRecords`, `ReturnInspections`, `SupportTickets`, `UserFacilities`, `Payments`).
+- Mọi thao tác ghi nhận (đối soát, phân bổ kho, bàn giao, kiểm tra trả kho, gia hạn, hoàn cọc) đều được lưu vĩnh viễn vào SQL Server qua `dbContext.SaveChangesAsync()`.
+- Các hành động của khách hàng (`REQUEST_RETURN`, `UPDATE_NAME`, `CHANGE_PASSWORD`) được kết nối trực tiếp đến các endpoint backend (`POST /api/contracts/{id}/move-out`, `PUT /api/auth/profile`, `POST /api/auth/change-password`).
+
+## D20 — Toạ độ cơ sở lưu trong database, Vận hành KD sửa ở B05a — Đã chốt (15/10/2026)
+- Bảng `facilities` thêm `Latitude`, `Longitude` (decimal(9,6), cùng có hoặc cùng trống). API cơ sở công khai và `/api/operations/facilities` trả / nhận hai trường này.
+- Màn B05 thêm nút "Sửa thông tin cơ sở" mở hộp thoại B05a (tên, địa chỉ, điện thoại, giờ ra vào, vĩ độ, kinh độ). Dán cặp toạ độ copy từ Google Maps vào một ô thì tự tách hai ô.
+- Bản đồ Tìm kho (C02m) đọc toạ độ từ API; `src/config/geo.js` chỉ còn là toạ độ dự phòng cho cơ sở chưa nhập.
+- Toạ độ khởi tạo của 12 cơ sở lấy giống `geo.js` (ước lượng); Vận hành KD nên kiểm tra lại trên Google Maps và sửa ở B05a.
+
+## D21 — Giao diện thanh toán theo Figma 16/10: PayOS + tại cửa hàng, QR mở cửa mô phỏng — Đã chốt (16/10/2026)
+- C04 có hai lựa chọn: **Thanh toán QR** (PayOS, tự xác nhận qua webhook PayOS, giao diện hỏi trạng thái 3 giây/lần rồi tự
+ sang C05) và **Tại cửa hàng** (C04c → C05c, nhân viên thu ở S09). Bỏ nút "Tôi đã chuyển khoản"; chữ "đối soát" đổi thành
+ "thanh toán" / "thu tiền" trên mọi màn (S09 "Thu tiền tại kho").
+- Giữ chỗ khi thanh toán QR: **10 phút** (Figma C04; `VITE_PAYMENT_TIMEOUT_SECONDS=600`, trước là 60 giây). Tại cửa hàng: 24 giờ.
+- Thanh toán tại cửa hàng dùng lại trạng thái `PENDING_VERIFICATION` (hàng chờ S09 sẵn có). Backend chưa có
+ `pay-at-facility` thì giao diện gọi `confirm-transfer` — luồng vẫn chạy với backend hiện tại.
+- Endpoint mới chưa có trên backend (404/405 không kèm nội dung) → giao diện hiện thông báo thay thế, không báo lỗi
+ (`src/api/payment-access.js` `isUnsupported`). Hợp đồng JSON: `SafeSpace-Customer-UI/BACKEND-TODO.md` mục "Mới 16/10".
+- QR mở cửa: **mô phỏng** máy quét ở `#/door` (không cần đăng nhập, như thiết bị tại cơ sở); mã QR chỉ là mã tham chiếu.
+- Huỷ đơn đã thanh toán (C14a) lấy số tiền hoàn từ `cancel-preview`; chế độ trình duyệt tạm tính phí 10% tiền thuê như Figma.
+- M02a đổi trạng thái ô chỉ cho Trống ↔ Bảo trì và Chờ kiểm tra → Trống / Bảo trì (SRS 8.1); ô đang có khách không đổi ở đây.
+
+## D22 — Cơ chế cấp mã QR mở cửa và máy quét mô phỏng cửa kho (C07q, C07r) — Đã chốt (16/10/2026)
+- Cấp mã mở cửa không trạng thái (stateless HMAC-SHA256) từ `ContractId + CredentialId + IssuedAt` với khoá bí mật `JwtSettings:Secret` hoặc `AccessQr:Secret`. Không cần tạo migration hay thêm bảng mới.
+- Định dạng mã QR: `SSQR--<8 ký tự hex>` (ví dụ `SSQR-1-1733D3D0`). Mã dự phòng: 8 chữ số (ví dụ `03502103`), hiển thị dạng `xxxx xxxx`.
+- `GET /api/contracts/{id}/access-qr` (cần đăng nhập) hỗ trợ cả ID số nguyên lẫn mã chuỗi `HĐ-...`. Kiểm tra điều kiện: kho đã bàn giao (`handover_records.Status == HANDED_OVER`), hợp đồng hiệu lực (`ACTIVE`/`EXPIRING`/`OVERDUE`), thẻ ra vào mới nhất `ACTIVE`.
+- `POST /api/access/scan` (công khai cho thiết bị máy quét ở cửa): nhận diện cả mã QR và mã dự phòng 8 số (hỗ trợ có hoặc không có dấu cách), kiểm tra quyền truy cập theo thứ tự và luôn trả về HTTP 200 kèm `result: "OPEN" | "DENIED"` và lý do từ chối.
+- Ghi nhận lịch sử quét mã vào bảng `activity_logs` với `Action = "ACCESS_SCANNED"`, `EntityType = "CONTRACT"`, `EntityId = ContractId`, `NewValue = { result, unit, reason }`, `IpAddress` của máy quét.
+- Frontend: kết nối `useAccessQr.js` và `endpoints.js` trực tiếp với API backend khi `VITE_USE_API=true`, giữ nguyên mock offline cho môi trường thử nghiệm khi `VITE_USE_API=false`.
+
+
+## D23 — Thu tiền đặt kho và dự phòng thanh toán tại cơ sở (20/10/2026)
+- Bổ sung cho D19/D21; không đổi số hoặc xoá nội dung quyết định cũ. Phạm vi được yêu cầu: kiểm tiền PayOS, ghi khoản thu, chống lặp, phân bổ, thanh toán tại kho và F12.
+- Giữ cách tính hiện tại: khách trả tiền thuê cả kỳ + tiền cọc; không triển khai bỏ cọc trong gói này.
+- PayOS: backend tính số tiền; SDK kiểm chữ ký; đối chiếu chính xác orderCode và số tiền. Không tìm đơn bằng cách tách số từ mô tả. Không dùng VietQR mặc định khi PayOS lỗi.
+- Khoản thu RENT và DEPOSIT ghi vào payments ngay khi xác nhận, gắn ReservationId; ContractId được phép trống trước khi quản lý phân bổ. Gắn lại đúng bản ghi vào hợp đồng DRAFT, không tạo khoản PAID mới.
+- Webhook chỉ xác nhận thanh toán; quản lý chọn ô ở M05. Đơn trả tại kho cũng được phân bổ trước, nhưng chưa thu đủ thì không được bàn giao.
+- Chọn trả tại kho phải còn hạn và chưa trả tiền. Nếu đã khởi tạo orderCode, cần PayOS xác nhận link đã huỷ/không tồn tại; không chuyển nếu không kiểm tra được hoặc PayOS đã nhận tiền (kể cả một phần).
+- Đơn trả tại kho có trạng thái PENDING_AT_FACILITY và PaymentMethod AT_FACILITY. Giữ chỗ đến hết ngày hẹn nhận kho theo giờ Việt Nam; worker xử lý hết hạn mỗi phút, huỷ phân bổ/hợp đồng nháp chưa thu và trả ô RESERVED về AVAILABLE. Thu tiền và worker dùng cùng khoá giao dịch.
+- S09 chỉ là đơn chờ thu tại kho; nhân viên bấm xác nhận khi đã thực nhận tiền mặt. Ghi CASH. API gọi lại không tạo khoản thu mới.
+- Tiền PayOS về sau khi đổi phương thức/đóng đơn: ghi PAYMENT_REVIEW_REQUIRED đúng một lần cho orderCode, không cộng vào khoản thu thuê lần nữa. Quản lý kiểm tra khoản tiền thực về và hoàn thủ công theo nhật ký; không tuyên bố đã tự chuyển tiền hoàn.
+- Khoá transaction ở SQL Server bằng sp_getapplock, cùng khoá reservation cho webhook/thu tiền/phân bổ; thêm unique index trên ReservationId + PaymentType cho RENT/DEPOSIT. API /api/ops chỉ đăng ký một lần.
+- Migration nối khoản RENT/DEPOSIT cũ vào đơn khi liên kết là duy nhất; không xoá hay tự bịa khoản tiền cho các đơn cũ chỉ có PaidAt. Các đơn cũ thiếu bằng chứng thu cần đối chiếu trước khi bàn giao.
+
+## D24 — Đổi trạng thái ô bằng tay phải có lý do và lịch sử (20/10/2026)
+- AVAILABLE, MAINTENANCE, OUT_OF_SERVICE được chuyển qua lại bằng thao tác quản lý vận hành nếu ô không có giữ chỗ/hợp đồng chưa đóng. Mỗi lần đổi phải có lý do 1–255 ký tự và ghi unit_status_history trong cùng transaction.
+- RESERVED/ASSIGNED/OCCUPIED/RETURN_PENDING/INSPECTION thuộc luồng phân bổ, bàn giao, trả kho. Không cho dùng form trạng thái để bỏ qua các bước này.
+- LOCKED từ giao diện được ánh xạ thành OUT_OF_SERVICE theo tập trạng thái SQL hiện có. Gọi lại cùng trạng thái với lý do hợp lệ không thêm lịch sử trùng.
+
+
+## D25 — 2026-10-20: Tổ chức FE theo vai trò và chức năng
+
+Theo yêu cầu nhóm, dùng src/app, src/features//, src/shared, src/assets. Tách từng Page từ các file tổng StaffPages/ManagerPages/Units/Auth/Checkout/Public; giữ code dùng chung Staff/Manager ở facility-operations. Giữ URL, API, localStorage và nghiệp vụ. Không đổi hai cấp thư mục gốc FE để không phá lệnh chạy/CI. docs/frontend-naming.md và FRONTEND-MAP.md là hướng dẫn bắt buộc; npm run check:structure kiểm tra quy ước cơ bản.
+
+## D26 — 2026-10-22: Kiểm thử tương tác C12/C13 bằng Playwright
+
+Thêm `@playwright/test` vào devDependencies để kiểm tra biểu mẫu React, đổi tài khoản, F5 và luồng nhân viên phản hồi → khách đọc. Test chạy Vite ở cổng 5273 và chặn request `/api/` bằng dữ liệu theo DTO backend; không gọi SQL Server hoặc API thanh toán. Không thêm thư viện giao diện. Chromium được cài riêng bằng `npx playwright install chromium`; có thể truyền `PLAYWRIGHT_EXECUTABLE_PATH` khi môi trường đã có trình duyệt. Không commit binary, ảnh kiểm tra hoặc test-results. Kết quả API giả lập không thay kiểm chứng trên SQL Server thật. Sau khi đọc được section 436:9217, đối chiếu thiết kế được ghi riêng tại docs/figma-auth-support-review.md.
diff --git a/README-QR-MO-CUA.md b/README-QR-MO-CUA.md
new file mode 100644
index 0000000..1cec7f1
--- /dev/null
+++ b/README-QR-MO-CUA.md
@@ -0,0 +1,172 @@
+# Backend QR mở cửa kho (C07q, C07r) — SafeSpace / SSFRMS
+
+Phần backend cho tính năng **QR mở cửa** và **máy quét mô phỏng ở cửa kho** (Figma C07q, C07r1, C07r2; quyết định D21).
+Giao diện đã gọi sẵn đúng 2 endpoint này, làm xong backend là giao diện chạy ngay, không phải sửa frontend.
+
+> **Trạng thái:** đã viết xong, kiểm tra cú pháp C# OK. **Chưa `dotnet build` và chưa chạy với SQL Server**
+> (máy viết code không có .NET). Người nhận cần build và chạy thử theo mục 6.
+
+---
+
+## 1. Tính năng làm gì
+
+| Bước | Ai | Việc |
+|---|---|---|
+| 1 | Nhân viên (S03) | Bàn giao kho → backend **đã có sẵn** đoạn tạo 1 thẻ ra vào trong bảng `access_credentials` (trạng thái `ACTIVE`) |
+| 2 | Khách (C07) | Bấm **"Mở cửa kho"** → giao diện gọi `GET /api/contracts/{id}/access-qr` → hiện QR + mã dự phòng 8 số |
+| 3 | Máy quét (`#/door`) | Khách bấm "Mô phỏng quét ở cửa kho" (hoặc gõ mã dự phòng) → gọi `POST /api/access/scan` |
+| 4 | Backend | Kiểm mã → trả **OPEN** ("Mở cửa", xanh) hoặc **DENIED** ("Từ chối", đỏ, kèm lý do); ghi `activity_logs` |
+| 5 | Nhân viên (S04) | Lập biên bản trả kho → backend **đã có sẵn** đoạn chuyển thẻ sang `RETURNED` → mã QR cũ tự hết hiệu lực |
+
+Nhóm không dùng thiết bị thật: "máy quét" là trang `#/door` trên chính web SafeSpace.
+
+---
+
+## 2. Cách tạo mã — không thêm bảng, không cần migration
+
+- Mã QR **không lưu trong database**. Mỗi lần cần, backend tính lại bằng **HMAC-SHA256** với khoá bí mật từ:
+ `mã hợp đồng + mã thẻ ra vào mới nhất của hợp đồng (access_credentials) + thời điểm cấp thẻ`.
+- Mã QR có dạng `SSQR--<8 ký tự hex>`, ví dụ `SSQR-12-9F3A61C0`.
+- Mã dự phòng có 8 chữ số, ví dụ `4821 9037`. Cũng tính từ cùng HMAC đó.
+- Khách không đoán được mã vì không có khoá bí mật. Mã chỉ là mã tham chiếu, không chứa mật khẩu hay bí mật nào.
+
+Hệ quả tự động, không phải viết thêm code:
+- **Chưa bàn giao** thì chưa có thẻ, nên chưa có mã.
+- **Trả kho** (S04) chuyển thẻ sang `RETURNED`, nên quét mã cũ sẽ bị từ chối: "đã trả kho".
+- **Bàn giao lại** thì thẻ cũ chuyển `REPLACED` và có thẻ mới, nên mã QR đổi theo và mã cũ hết dùng.
+
+---
+
+## 3. API
+
+### 3.1 `GET /api/contracts/{id}/access-qr` — lấy mã (cần đăng nhập khách)
+
+Chỉ chủ hợp đồng gọi được. Hợp đồng phải **đã bàn giao** (`handover_records.Status = HANDED_OVER`), thẻ mới nhất đang
+`ACTIVE`, hợp đồng ở `ACTIVE` / `EXPIRING` / `OVERDUE`.
+
+**200**
+```json
+{
+ "contractId": 12,
+ "code": "SSQR-12-9F3A61C0",
+ "backupCode": "4821 9037",
+ "unitNumber": "K01",
+ "unitType": "Kho thường",
+ "location": "Tầng trệt · Dãy A",
+ "validUntil": "2026-12-31"
+}
+```
+| Trường hợp | Mã | Body |
+|---|---|---|
+| Hợp đồng không tồn tại / không phải của khách | 404 | `{ "error": "Không tìm thấy hợp đồng." }` |
+| Chưa bàn giao | 400 | `{ "error": "QR mở cửa chỉ dùng được sau khi nhân viên bàn giao kho." }` |
+| Đã trả kho / hết hiệu lực | 400 | `{ "error": "Hợp đồng đã trả kho hoặc hết hiệu lực, mã mở cửa không còn dùng được." }` |
+
+### 3.2 `POST /api/access/scan` — máy quét kiểm mã (không cần đăng nhập)
+
+Request: `{ "code": "SSQR-12-9F3A61C0" }` hoặc mã dự phòng `{ "code": "4821 9037" }` (có hay không có khoảng trắng đều được).
+
+Luôn trả **200**. Kết quả nằm trong `result`:
+```json
+{ "result": "OPEN", "unitNumber": "K01", "customerName": "Nguyễn Văn An", "contractCode": "HĐ-2026-0012",
+ "scannedAt": "2026-10-16T08:32:00Z", "reason": null }
+```
+```json
+{ "result": "DENIED", "unitNumber": "K01", "customerName": "Nguyễn Văn An", "contractCode": "HĐ-2026-0012",
+ "scannedAt": "2026-10-16T08:35:00Z", "reason": "Mã đã hết hiệu lực — hợp đồng đã trả kho." }
+```
+
+Thứ tự kiểm và lý do từ chối:
+
+| # | Điều kiện | `reason` |
+|---|---|---|
+| 1 | Mã rỗng | Chưa nhận được mã. Đưa mã QR vào máy quét hoặc nhập mã dự phòng. |
+| 2 | Không khớp mã nào | Mã không đúng. Kiểm tra lại mã trên ứng dụng hoặc mã dự phòng. |
+| 3 | Thẻ `RETURNED` hoặc hợp đồng `RETURN_PENDING` / `COMPLETED` / `TERMINATED` / `CANCELLED` | Mã đã hết hiệu lực — hợp đồng đã trả kho. |
+| 4 | Thẻ `REVOKED` / `LOST` / `REPLACED` | Mã đã bị thu hồi. Liên hệ nhân viên cơ sở để được cấp lại. |
+| 5 | Chưa bàn giao | Kho chưa được bàn giao cho khách. |
+| 6 | Hợp đồng không ở `ACTIVE` / `EXPIRING` / `OVERDUE` | Hợp đồng không còn hiệu lực. |
+| 7 | Quá hạn (`OVERDUE` hoặc `EndDate` < hôm nay giờ VN) và `DenyOverdue = true` | Hợp đồng đã quá hạn. Vui lòng gia hạn hoặc liên hệ cơ sở. |
+| — | Qua hết | `result = "OPEN"`, `reason = null` |
+
+Mỗi lần quét ghi 1 dòng `activity_logs`: `Action = ACCESS_SCANNED`, `EntityType = CONTRACT`, `EntityId` = mã hợp đồng
+(null nếu mã sai), `NewValue` = `{ result, unit, reason }`, `IpAddress` của máy quét, `UserId = null`.
+
+---
+
+## 4. Các file trong gói
+
+Giữ đúng đường dẫn khi chép vào repo (thư mục gốc SSFRMS).
+
+| File | Mới / sửa | Nội dung |
+|---|---|---|
+| `StorageProject.Core/DTOs/Access/AccessDtos.cs` | **Mới** | `AccessQrDto`, `ScanAccessRequest`, `ScanResultDto`, `AccessQrOptions` |
+| `StorageProject.Infrastructure/Services/AccessService.cs` | **Mới** | Tính mã HMAC, lấy QR, kiểm mã khi quét, ghi log |
+| `StorageProject.Api/Endpoints/AccessEndpoints.cs` | **Mới** | 2 endpoint ở mục 3 |
+| `StorageProject.Core/Interfaces/IServices.cs` | Sửa | Thêm `using StorageProject.Core.DTOs.Access;` và interface `IAccessService` (đặt trước `IPaymentService`) |
+| `StorageProject.Api/Program.cs` | Sửa | Đăng ký `AccessQrOptions` + `IAccessService`, gọi `app.MapAccessEndpoints();` |
+| `StorageProject.Api/StorageProject.Api.http` | Sửa | Thêm biến `@customerToken` và 3 request mẫu ở cuối file |
+| `qr-mo-cua-backend.patch` | — | Toàn bộ thay đổi trên ở dạng patch, dùng thay cho chép tay |
+
+Chi tiết phần sửa trong `Program.cs`:
+```csharp
+using StorageProject.Core.DTOs.Access; // thêm cạnh các using khác
+...
+builder.Services.AddScoped();
+builder.Services.AddSingleton(new AccessQrOptions(
+ builder.Configuration["AccessQr:Secret"] ?? jwtSecret,
+ !bool.TryParse(builder.Configuration["AccessQr:DenyOverdue"], out var denyOverdue) || denyOverdue));
+builder.Services.AddScoped();
+...
+app.MapFacilityOpsEndpoints();
+app.MapAccessEndpoints();
+```
+
+---
+
+## 5. Cấu hình (không bắt buộc)
+
+Trong `appsettings.json` (không commit khoá thật):
+```json
+"AccessQr": {
+ "Secret": "",
+ "DenyOverdue": true
+}
+```
+- Không có `AccessQr:Secret` thì dùng `JwtSettings:Secret`. **Đổi khoá thì mọi mã QR đang có đổi theo.**
+- `DenyOverdue`: hợp đồng quá hạn có bị khoá QR không. Nhóm chưa chốt; mặc định là **có khoá**.
+
+---
+
+## 6. Cách đưa vào repo và chạy thử
+
+**Cách 1 — dùng patch (khuyên dùng):**
+```bash
+git checkout main && git pull
+git checkout -b feature/access-qr-backend
+git apply qr-mo-cua-backend.patch
+dotnet build StorageProject.slnx
+```
+Nếu `git apply` báo lệch ở `IServices.cs` / `Program.cs` / `.http` (do main đổi), chép 3 file mới vào, rồi sửa tay 3 file kia theo mục 4.
+
+**Chạy thử:**
+1. `dotnet run --project StorageProject.Api --launch-profile http`. Không cần migration mới.
+2. Swagger (`http://localhost:5151`): đăng nhập `customer01` / `Customer@123`, gọi `GET /api/contracts` lấy `contractId` của kho
+ **K01** (seed đã bàn giao sẵn), rồi gọi `GET /api/contracts/{id}/access-qr` → nhận `code`, `backupCode`.
+3. `POST /api/access/scan` với `code` vừa nhận → `result = OPEN`.
+4. `POST /api/access/scan` với `{ "code": "1234 5678" }` → `DENIED`, "Mã không đúng…".
+5. Trên giao diện (`npm run dev`, chế độ API): `customer01` → Kho của tôi → K01 → **Mở cửa kho** → **Mô phỏng quét ở cửa kho** → "Mở cửa".
+6. Thử thu hồi: `staff01` lập biên bản trả kho K01 (S04) → quét lại mã cũ → "Từ chối — đã trả kho"; gọi lại `access-qr` → 400.
+7. Xem `activity_logs` có các dòng `ACCESS_SCANNED`.
+
+Giao diện tương ứng (đã có trong bản FE): popup C07q ở `src/pages/Units.jsx` (`AccessQrModal`), máy quét `src/pages/Door.jsx`,
+gọi API ở `src/api/endpoints.js` (`accessQr`, `scanAccess`). Bản FE cũ khi chưa có BE chỉ hiện "Mã QR mở cửa đang được cơ sở kích hoạt".
+
+---
+
+## 7. Lưu ý
+
+- Endpoint quét **không cần đăng nhập** vì đóng vai thiết bị ở cửa. Mã dự phòng 8 số đủ cho đồ án; sản phẩm thật nên
+ giới hạn số lần quét sai theo IP.
+- Tìm theo mã dự phòng duyệt các hợp đồng đã có thẻ ra vào — với quy mô 12 cơ sở × 12 ô thì nhẹ.
+- Không đổi bảng, không đổi dữ liệu cũ; chỉ thêm dòng `activity_logs` khi quét.
diff --git a/README.md b/README.md
index a88e8e9..5f3969d 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,10 @@ Hệ thống quản lý và cho thuê kho tự quản thông minh (SafeSpace Sel
---
+> **Quy định cho công cụ AI (Claude, Cursor, Copilot, Codex…):** AI chỉ được sửa code và commit trên máy,
+> **không được tự `git push`, tạo Pull Request hay merge** lên repo này. Thành viên nhóm tự kiểm tra rồi tự push.
+> Quy tắc đầy đủ cho AI nằm trong [`AGENTS.md`](AGENTS.md).
+
## 📋 Yêu Cầu Môi Trường (Prerequisites)
Trước khi chạy dự án, hãy đảm bảo máy tính đã cài đặt các công cụ sau:
@@ -14,14 +18,23 @@ Trước khi chạy dự án, hãy đảm bảo máy tính đã cài đặt các
---
-## 🚀 Hướng Dẫn Cài Đặt & Khởi Chạy
+## ⚡ Khởi Chạy Nhanh Toàn Bộ Hệ Thống (1 Lệnh Duy Nhất)
+
+Sau khi cài đặt thư viện ở thư mục gốc (`npm install`), bạn có thể khởi chạy đồng thời **Backend (.NET)**, **Frontend (Vite React)** và **Ngrok tunnel** chỉ với một lệnh duy nhất:
-### 1. Clone Repository
```bash
-git clone https://github.com/ryocoding13/SSFRMS.git
-cd SSFRMS
+npm run dev
```
+* **[BACKEND]**: `http://localhost:5151`
+* **[FRONTEND]**: `http://127.0.0.1:5173`
+* **[NGROK]**: Tự động forward public domain tới `http://localhost:5151` (phục vụ webhook PayOS)
+* **Dừng toàn bộ**: Nhấn `Ctrl + C` trong terminal.
+
+---
+
+## 🚀 Hướng Dẫn Cài Đặt Chi Tiết
+
---
### 2. Thiết lập & Khởi động Backend (.NET Web API)
@@ -89,7 +102,10 @@ Hệ thống đã tạo sẵn các tài khoản để kiểm thử quy trình:
|-----------|--------------------------|---------------------|-------|
| **CUSTOMER** | `customer01` | `Customer@123` | Khách hàng mẫu (Nguyễn Văn An) |
| **CUSTOMER** | `customer02` | `Customer@123` | Khách hàng mẫu (Trần Thị Mai) |
-| **STAFF** | `staff01` | `Staff@123` | Nhân viên vận hành |
+| **CUSTOMER** | `customer03` … `customer06` | `Customer@123` | Khách đang thuê / chờ bàn giao / quá hạn tại cơ sở mẫu |
+| **STAFF** | `staff01`, `staff02` | `Staff@123` | Nhân viên cơ sở SafeSpace Nguyễn Lương Bằng (`#/staff`) |
+| **MANAGER** | `manager01` | `Manager@123` | Quản lý cơ sở SafeSpace Nguyễn Lương Bằng (`#/manager`) |
+| **OPERATIONS** | `ops01` | `Ops@123` | Quản lý vận hành kinh doanh |
| **ADMIN** | `admin` | `Admin@123` | Quản trị viên hệ thống |
*(Bạn cũng có thể bấm nút **"Đăng ký"** trực tiếp trên giao diện để tạo tài khoản mới)*.
@@ -102,7 +118,7 @@ Giao diện SafeSpace hỗ trợ cơ chế hoạt động linh hoạt (dual-mode
```
┌─────────────────────────────────────────────────────────────┐
-│ App Startup (CustomerApp.jsx) │
+│ App Startup (App.jsx) │
│ ────────────────────────────────────────────────────── │
│ 1. loadServerData() → GET /api/facilities, /unit-types │
│ ├── Success → isLiveApi = true, load real data │
@@ -125,7 +141,7 @@ Giao diện SafeSpace hỗ trợ cơ chế hoạt động linh hoạt (dual-mode
```text
SSFRMS/
├── StorageProject.Api/ # .NET 9 Minimal API, Middleware, Endpoints
-│ ├── Endpoints/ # Auth, Facility, Reservation, Contract, Payment, Support...
+│ ├── Endpoints/ # Auth, Facility, Reservation, Contract, Payment, SupportPage...
│ └── appsettings.json # Cấu hình DB, JWT
├── StorageProject.Core/ # Domain Entities, DTOs, Service Interfaces
├── StorageProject.Infrastructure/ # EF Core DbContext, Migrations, DbSeeder, Service Implementations
@@ -133,9 +149,9 @@ SSFRMS/
│ └── SafeSpace-Customer-UI/ # React + Vite Frontend
│ ├── src/
│ │ ├── components/ # UI Components (AuthModal, ActionModal, UI Elements)
-│ │ ├── pages/ # Pages: FindStorage, Overview, Records, Support
+│ │ ├── pages/ # Pages: FindStorage, CustomerDashboardPage, Records, SupportPage
│ │ ├── services/ # API Clients & Service Adapters
-│ │ ├── CustomerApp.jsx # App Root & State Management
+│ │ ├── App.jsx # App Root & State Management
│ │ └── customer.css # SafeSpace Modern Design System
│ └── .env # Environment Config (VITE_API_URL)
└── README.md # Hướng dẫn dự án
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example
index 1fe7d33..b1c3eaf 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example
@@ -5,8 +5,8 @@ VITE_API_URL=http://localhost:5151
# Đặt false để tắt API và dùng dữ liệu lưu trong trình duyệt (chỉ xem giao diện khách hàng)
VITE_USE_API=true
-# Thời gian giữ đơn chờ chuyển khoản (giây). Figma: 01:00 → 60. Dùng 900 cho 15 phút.
-VITE_PAYMENT_TIMEOUT_SECONDS=60
+# Thời gian giữ đơn chờ chuyển khoản (giây). 900 cho 15 phút.
+VITE_PAYMENT_TIMEOUT_SECONDS=900
# Tài khoản nhận chuyển khoản, dùng để tạo mã VietQR ở màn thanh toán (C04)
VITE_BANK_BIN=970422
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.gitignore b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.gitignore
index e5fb60a..c22197a 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.gitignore
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.gitignore
@@ -8,3 +8,5 @@ Thumbs.db
.env.local
.env.production
*.tsbuildinfo
+test-results/
+playwright-report/
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md
index f4ab795..0493a3e 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md
@@ -8,12 +8,12 @@ tài khoản khác mở `#/admin` sẽ thấy "Không có quyền truy cập". T
| Figma | Route | Component | API |
|---|---|---|---|
-| A01 Quản lý tài khoản | `#/admin` | `admin/AdminUsers.jsx` | `GET dashboard/stats`, `GET users?page&pageSize&searchTerm&status&roleId`, `GET roles`, `GET users/{id}/facilities` (cột Cơ sở phụ trách) |
-| (thêm) Chi tiết tài khoản | `#/admin/users/:id` | `admin/AdminUserDetail.jsx` | `GET/PUT users/{id}`, `POST users/{id}/reset-password`, `POST/DELETE users/{id}/roles`, `GET users/{id}/facilities`, `POST user-facilities`, `PUT user-facilities/{id}/status` |
-| A02 Thêm & phân quyền tài khoản | `#/admin/new` | `admin/AdminCreateUser.jsx` | `POST users` (+ `POST user-facilities` khi là Nhân viên / Quản lý) |
-| A03 Cấu hình quyền truy cập | `#/admin/permissions` | `admin/AdminPermissions.jsx` | `GET roles`, `GET permissions`, `POST/DELETE roles/{id}/permissions` |
-| A04 Nhật ký hoạt động | `#/admin/logs` | `admin/AdminLogs.jsx` | `GET logs/login-history`, `GET logs/activity-logs` |
-| Thông báo / admin | (chuông) | `admin/AdminShell.jsx` | `GET dashboard/stats`, `GET logs/login-history` |
+| A01 Quản lý tài khoản | `#/admin` | `src/features/admin/users/UserListPage.jsx` | `GET dashboard/stats`, `GET users?page&pageSize&searchTerm&status&roleId`, `GET roles`, `GET users/{id}/facilities` (cột Cơ sở phụ trách) |
+| (thêm) Chi tiết tài khoản | `#/admin/users/:id` | `src/features/admin/users/UserDetailPage.jsx` | `GET/PUT users/{id}`, `POST users/{id}/reset-password`, `POST/DELETE users/{id}/roles`, `GET users/{id}/facilities`, `POST user-facilities`, `PUT user-facilities/{id}/status` |
+| A02 Thêm & phân quyền tài khoản | `#/admin/new` | `src/features/admin/users/CreateUserPage.jsx` | `POST users` (+ `POST user-facilities` khi là Nhân viên / Quản lý) |
+| A03 Cấu hình quyền truy cập | `#/admin/permissions` | `src/features/admin/permissions/PermissionListPage.jsx` | `GET roles`, `GET permissions`, `POST/DELETE roles/{id}/permissions` |
+| A04 Nhật ký hoạt động | `#/admin/logs` | `src/features/admin/logs/AuditLogPage.jsx` | `GET logs/login-history`, `GET logs/activity-logs` |
+| Thông báo / admin | (chuông) | `src/features/admin/AdminLayout.jsx` | `GET dashboard/stats`, `GET logs/login-history` |
## Khác Figma vì backend
- **A02**: Figma "Gửi lời mời qua email" nhưng backend chưa gửi email → form có thêm **Tên đăng nhập** (gợi ý từ email)
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md
new file mode 100644
index 0000000..2ef4d0a
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md
@@ -0,0 +1,10 @@
+# Hướng dẫn AI khi sửa frontend
+
+1. Đọc `../../AGENTS.md` và `../../docs/frontend-naming.md` trước khi sửa.
+2. Tra `FRONTEND-MAP.md` để xác định đúng vai trò, chức năng, route, provider và API.
+3. Dùng `src/features///Page.jsx`; mỗi file một màn hình.
+4. Code chung Staff/Manager đặt ở `features/facility-operations`; code toàn app ở `app`, tiện ích chung ở `shared`.
+5. Không tái tạo các thư mục nguồn cũ. Không giữ file copy hoặc re-export ở đường dẫn cũ.
+6. Cập nhật import, test và bản đồ khi thêm/đổi tên màn hình. Giữ nguyên URL, API và localStorage trừ khi task yêu cầu.
+7. Chạy `npm run check:structure`, `npm test`, `npm run test:business`, `npm run test:render`, `npm run build` và init theo hướng dẫn gốc.
+8. Không tự push/PR/merge. Bàn giao patch chứa cả thao tác xóa file cũ và thêm file mới.
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
index 23b8bdc..31c7c47 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
@@ -7,6 +7,79 @@ API ngay khi backend có — không cần sửa giao diện nếu làm đúng h
Chạy thử hợp đồng không cần .NET: `MOCK_OPS=1 npm run dev:mock` (máy chủ giả lập `mock/mock-api.mjs` đã làm đủ các
endpoint mục A–B; `tests/ops-api.test.mjs` kiểm tra từng endpoint). Backend làm đúng như mock là giao diện chạy.
+## Mới 16/10/2026 — API cho các màn đồng bộ Figma (PayOS, thanh toán tại kho, QR mở cửa, F12)
+
+Giao diện **đã gọi sẵn** các endpoint dưới đây (`src/shared/api/customerApi.js`, `src/features/customer/access/accessApi.js`, `src/features/facility-operations/api/facilityOperationsApi.js`).
+Backend chưa có route → giao diện **không báo lỗi**: hiện thông báo thay thế (bảng cột "Khi chưa có") cho tới khi backend
+làm xong. Máy chủ giả lập đã làm đủ (`npm run dev:mock`), `tests/payment-api.test.mjs` kiểm tra từng endpoint. Làm đúng
+tên route + tên trường JSON là giao diện chạy ngay, không phải sửa giao diện. JSON camelCase như các endpoint đang có.
+
+| Mục | Endpoint | Người làm | Khi chưa có (404/405) |
+|---|---|---|---|
+| P1 | ~~`POST /api/reservations/{id}/payos`~~ — **đã nối** vào `POST /api/reservations/create-payos-qr` `{ reservationId }` có sẵn trên main (16/10) | Đạt | — |
+| P2 | `POST /api/reservations/{id}/pay-at-facility` → `ReservationDto` | Đạt | Giao diện gọi `confirm-transfer` (đã có) → đơn vẫn vào S09 chờ thu tiền |
+| P3 | `POST /api/payments/{id}/payos` → `PayosCheckoutDto`; `GET /api/payments/{id}` (đã có) để hỏi trạng thái | Đạt | Popup C11q báo "đang tạm gián đoạn, thanh toán tại quầy" |
+| P4 | Webhook PayOS — **đã có** `POST /api/payments/payos-webhook` (webhook đổi đơn sang `CONFIRMED`) | Đạt | — (giao diện hỏi trạng thái 3 giây/lần) |
+| Q1 | `GET /api/contracts/{id}/access-qr` → `AccessQrDto` | Tiến | Popup C07q báo "Mã QR đang được cơ sở kích hoạt" |
+| Q2 | `POST /api/access/scan` `{ code }` → `ScanResultDto` (cho phép không đăng nhập — máy quét ở cửa) | Tiến | Màn `#/door` báo "Máy quét chưa kết nối được hệ thống" |
+| R1 | `GET /api/tickets/{id}` trả thêm `responses[]` | Ngọc Mai | C12 không hiện dòng phản hồi |
+| H1 | `GET /api/reservations/{id}/cancel-preview` → `CancelPreviewDto`; `ReservationDto` thêm `refundAmount`, `refundStatus` | Ngọc Mai | C14a ghi "Theo chính sách hiện hành / Cơ sở xác nhận sau khi huỷ" |
+| U1 | **Đã nối** `PUT /api/staff/units/{mã}/status` `{ status, reason }` có sẵn trên main (nhân viên + quản lý). Còn thiếu: kiểm chuyển tiếp hợp lệ, bắt buộc lý do, trạng thái `INSPECTION` | Thắng | — |
+
+### P · PayOS (D19) và thanh toán tại cửa hàng
+```json
+// PayosCheckoutDto — P1, P3 (gọi lại khi đơn PayOS còn hạn thì trả lại đúng đơn cũ, không tạo mới)
+{ "orderCode": 100001, "amount": 4600000, "description": "SS0142", "status": "PENDING",
+ "qrCode": "000201010212385700...6304ABCD", "checkoutUrl": "https://pay.payos.vn/web/...", "expiredAt": "2026-10-16T08:10:00Z" }
+```
+- `qrCode`, `checkoutUrl` lấy nguyên từ PayOS SDK (`createPaymentLink`). Giao diện vẽ `qrCode` thành ảnh QR, kèm link `checkoutUrl`.
+- `amount` của P1 = `estimatedAmount + requiredDeposit` (thuê cả kỳ + cọc 1 tháng). P3 = số tiền khoản `RENEWAL`.
+- `expiredAt` = thời gian giữ chỗ. Giao diện đếm ngược theo giá trị nhỏ hơn giữa `expiredAt` và 10 phút (`VITE_PAYMENT_TIMEOUT_SECONDS=600`);
+ hết giờ giao diện gọi `POST /api/reservations/{id}/cancel` như cũ. **Backend đặt `expiredAt` 10 phút** cho khớp Figma C04.
+- Webhook (P4): kiểm chữ ký bằng SDK + Checksum Key, đúng `orderCode`, đúng `amount`, gửi trùng chỉ ghi một lần. Đặt chỗ: đơn
+ `PENDING_PAYMENT` → `CONFIRMED` (hoặc `PAID`; giao diện coi cả hai là "Đã thanh toán", `UNIT_ASSIGNED` cũng vậy) và ghi khoản
+ thuê + cọc `PAID`. Gia hạn: payment `RENEWAL` → `PAID`, renewal → `PAID`, `contracts.end_date` = `newEndDate`.
+- Giao diện hỏi trạng thái bằng `GET /api/reservations/{id}` (đặt chỗ) và `GET /api/payments/{id}` (gia hạn, `status: "PAID"`).
+- Lúc quản lý phân bổ ô (M05) với đơn đã trả qua PayOS: gắn các khoản đã thu vào hợp đồng, **không tạo khoản mới**.
+- P2 thanh toán tại cửa hàng: đơn `PENDING_PAYMENT` → trạng thái chờ thu (dùng `PENDING_VERIFICATION` sẵn có, hoặc trạng thái mới
+ `PENDING_AT_FACILITY` — giao diện hiểu cả hai), ghi `paymentMethod: "AT_FACILITY"` trong `ReservationDto`, giữ chỗ 24 giờ
+ (job nền tự huỷ khi quá hạn), huỷ link PayOS đang mở của đơn. `GET /api/ops/board` phải đưa đơn này vào `payments[]` để hiện
+ ở S09; nhân viên xác nhận bằng `POST /api/ops/payments/{id}/confirm` (đã có). Đơn trả PayOS **không** vào `payments[]`.
+- Board `payments[]` nên trả thêm `rent`, `deposit`, `months` (S09 dòng "Gồm"); chưa có thì giao diện tự tách từ `amount`.
+
+### Q · QR mở cửa (Tiến) — mô phỏng, không dùng thiết bị thật
+```json
+// AccessQrDto — Q1: chỉ chủ hợp đồng, hợp đồng đã bàn giao (HANDED_OVER) và còn hiệu lực; sai → 400 { "error": "..." }
+{ "contractId": 86, "code": "SSQR-86-4821", "backupCode": "4821 9037", "unitNumber": "B-015",
+ "unitType": "Kho lạnh", "location": "Tầng 1 · Dãy B", "validUntil": "2026-12-25" }
+// ScanResultDto — Q2: nhận code hoặc backupCode; luôn trả 200, kết quả nằm trong "result"; ghi activity_logs mỗi lần quét
+{ "result": "OPEN", "unitNumber": "B-015", "customerName": "Nguyễn Thị Mai", "contractCode": "HĐ-2026-0086",
+ "scannedAt": "2026-10-16T03:32:00Z", "reason": null }
+{ "result": "DENIED", "reason": "Mã đã hết hiệu lực — hợp đồng đã trả kho.", "unitNumber": "B-015", ... }
+```
+`code` chỉ là mã tham chiếu (không chứa bí mật). Hết hiệu lực khi biên bản trả kho được lập (S04) hoặc hợp đồng kết thúc.
+Hợp đồng quá hạn có khoá QR hay không: nhóm chốt (giao diện chỉ hiện `reason` backend trả về).
+
+### R · Phản hồi hỗ trợ (Ngọc Mai)
+`SupportTicketDetailDto` thêm `"responses": [{ "message": "Thẻ cũ bị lỗi từ…", "staffName": "Trần Văn Long", "createdAt": "2026-09-14T04:02:00" }]`
+(lấy từ phản hồi S05, hiện đang nằm trong `activity_logs`). Giao diện cũng đọc `note`/`content` nếu đặt tên khác.
+
+### H · Huỷ đơn đã thanh toán (Ngọc Mai)
+```json
+// CancelPreviewDto — theo chính sách CANCELLATION đang hiệu lực ở B02
+{ "paidAmount": 4600000, "cancellationFee": 345000, "refundAmount": 4255000, "policyName": "Huỷ trước ngày nhận kho: phí 10% tiền thuê" }
+```
+`POST /api/reservations/{id}/cancel` (đã có, nhận `PENDING_PAYMENT` / `CONFIRMED`) với đơn đã trả: ghi khoản `REFUND`, trả
+`refundAmount` + `refundStatus: "PENDING"` trong `ReservationDto` để C14b hiện "Đã huỷ · Đang hoàn tiền".
+
+### U · Đổi trạng thái ô kho — F12 (Thắng)
+`PUT /api/ops/units/{code}/status` `{ "status": "MAINTENANCE", "reason": "Hỏng khoá cửa" }` — chỉ `MANAGER`, đúng cơ sở.
+Trạng thái theo từ của board: `EMPTY` (DB `AVAILABLE`), `MAINTENANCE`, `INSPECTION`. Chỉ cho: `EMPTY ↔ MAINTENANCE`,
+`INSPECTION → EMPTY | MAINTENANCE`; ô đang có khách → 400. Thiếu lý do → 400. Ghi `unit_status_history` (dùng lại
+`FacilityOpsService.SetUnitStatus`). Board `units[]` nên trả thêm `history[]` `{ from, to, reason, by, at }` (không bắt buộc).
+
+---
+
## Đã nối API (không cần làm thêm)
`/api/auth/register · login · logout`, `/api/facilities`, `/api/unit-types`, `/api/rates`, `/api/availability/check`,
`/api/reservations` (tạo, xem, huỷ), `/api/contracts` (+ payments, renewals), `/api/handovers/{id}/confirm`,
@@ -17,13 +90,16 @@ loại kho từ `/api/availability/check`.
## A. Ưu tiên 1 — chặn luồng chính
+> **Đã làm (14/10/2026, nhánh `feature/ops-backend`, D18):** toàn bộ A1–A4 theo đúng bảng dưới. Tài liệu API:
+> `docs/facility-ops-api.md`. Còn lại: chạy thử với SQL Server rồi đổi F03, F11–F21 sang `passing`.
+
### A1. Dữ liệu seed & phân quyền
-- [ ] `DbSeeder`: thêm tài khoản **quản lý cơ sở** `manager01 / Manager@123` (role `MANAGER`); hiện chỉ có `staff01`.
-- [ ] Gán `UserFacility` cho `staff01` và `manager01` (ví dụ cơ sở SafeSpace Nguyễn Lương Bằng). Mọi endpoint mục A2–A3
+- [x] `DbSeeder`: thêm tài khoản **quản lý cơ sở** `manager01 / Manager@123` (role `MANAGER`); hiện chỉ có `staff01`.
+- [x] Gán `UserFacility` cho `staff01` và `manager01` (ví dụ cơ sở SafeSpace Nguyễn Lương Bằng). Mọi endpoint mục A2–A3
chỉ trả / cho sửa dữ liệu của cơ sở được gán.
-- [ ] Gán quyền cho role `STAFF` (`HANDOVER_MANAGE`, `RETURN_MANAGE`, `TICKET_MANAGE`, `PAYMENT_CONFIRM`) và `MANAGER`
+- [x] Gán quyền cho role `STAFF` (`HANDOVER_MANAGE`, `RETURN_MANAGE`, `TICKET_MANAGE`, `PAYMENT_CONFIRM`) và `MANAGER`
(thêm `UNIT_MANAGE`, `ASSIGNMENT_MANAGE`, `RENEWAL_MANAGE`, `REPORT_VIEW`). Hiện chỉ `ADMIN` có quyền.
-- [ ] Endpoint mục A2 cho role `STAFF` **và** `MANAGER`; mục A3 chỉ `MANAGER` (sai vai trò → **403**).
+- [x] Endpoint mục A2 cho role `STAFF` **và** `MANAGER`; mục A3 chỉ `MANAGER` (sai vai trò → **403**).
### A2. Khu Nhân viên cơ sở (Figma S01–S09) — chưa có endpoint nào
Bảng trong DB đã có sẵn (`HandoverRecord`, `ReturnInspection`, `UnitAssignment`, `MaintenanceRequest`, `Payment`,
@@ -49,14 +125,14 @@ Bảng trong DB đã có sẵn (`HandoverRecord`, `ReturnInspection`, `UnitAssig
| M03 | `POST /api/ops/renewals/{id}/reject` | `{ reason }` | `reason` rỗng → 400; gửi lý do cho khách |
| M07 | `POST /api/ops/contracts/{id}/reminders` | `{ note }` | Ghi lịch sử nhắc khách (`OverdueCase`) |
| M07 | `POST /api/ops/contracts/{id}/refund` | — | Chỉ sau biên bản trả kho. Hoàn cọc = cọc − khoản còn nợ; kho → `AVAILABLE`; hợp đồng đóng |
-| M01/M02/M04 | (trong `GET /api/ops/board`) | — | `units` (86 kho của cơ sở), `revenue` 6 tháng + cơ cấu theo loại kho, tỷ lệ lấp đầy tính từ `units` |
+| M01/M02/M04 | (trong `GET /api/ops/board`) | — | `units` (12 ô của cơ sở, D17), `revenue` 6 tháng + cơ cấu theo loại kho, tỷ lệ lấp đầy tính từ `units` |
-Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái) xem `src/ops/reducer.js` — có test `tests/ops.test.js`.
+Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái) xem `src/features/facility-operations/state/facilityOperationsReducer.js` — có test `tests/ops.test.js`.
### A4. Khách báo đã chuyển khoản (Figma C04)
-- [ ] `POST /api/reservations/{id}/confirm-transfer` → đơn `PENDING_PAYMENT` chuyển `PENDING_VERIFICATION` (để hiện ở
+- [x] `POST /api/reservations/{id}/confirm-transfer` → đơn `PENDING_PAYMENT` chuyển `PENDING_VERIFICATION` (để hiện ở
S09 của nhân viên). Hiện giao diện chỉ lưu trong trình duyệt nên **nhân viên không thấy khách đã chuyển**.
-- [ ] Thêm trạng thái `PENDING_VERIFICATION` cho `Reservation` (entity hiện liệt kê `PENDING_PAYMENT, CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW`).
+- [x] Thêm trạng thái `PENDING_VERIFICATION` cho `Reservation` (entity hiện liệt kê `PENDING_PAYMENT, CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW`).
---
@@ -64,8 +140,8 @@ Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái)
| Việc | Endpoint / thay đổi | Giao diện đang tạm làm gì |
|---|---|---|
-| Sơ đồ 10 ô kho (C03b-sđ) | `GET /api/facilities/{id}/units` → `unitId, unitNumber, floor, zone, unitTypeId, status` (công khai, không lộ khách thuê) | Tự xếp 10 ô theo loại kho, số ô trống lấy từ availability (`src/lib/units.js`) |
-| Bản đồ cơ sở (C02m) | Thêm `latitude, longitude` vào `Facility` + `FacilityDto` (cần migration) | Toạ độ gán cứng theo tên cơ sở (`src/config/geo.js`) |
+| Sơ đồ 10 ô kho (C03b-sđ) | `GET /api/facilities/{id}/units` → `unitId, unitNumber, floor, zone, unitTypeId, status` (công khai, không lộ khách thuê) | Tự xếp 10 ô theo loại kho, số ô trống lấy từ availability (`src/shared/utils/units.js`) |
+| Bản đồ cơ sở (C02m) | Thêm `latitude, longitude` vào `Facility` + `FacilityDto` (cần migration) | Toạ độ gán cứng theo tên cơ sở (`src/app/config/geo.js`) |
| Đăng ký trả kho (C09) | `POST /api/contracts/{id}/move-out` `{ date, slot, note }` → tạo lịch trả kho (hiện ở S04 của nhân viên) | Lưu trong trình duyệt |
| Thông báo (chuông) | `GET /api/notifications`, `POST /api/notifications/read` `{ ids? }` | Lưu trong trình duyệt |
| Hồ sơ (C13) | `PUT /api/auth/profile` `{ fullName }`, `POST /api/auth/change-password`, `POST /api/auth/forgot-password` | Đổi tên lưu cục bộ; đổi / quên mật khẩu đang khoá |
@@ -74,9 +150,9 @@ Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái)
## C. Ưu tiên 3 — chỉnh nhỏ
- [ ] JSON `DateTime` trả kèm `Z` (UTC); hiện đọc từ DB không có múi giờ, giao diện phải tự coi là UTC.
-- [ ] Giữ chỗ đơn chờ chuyển khoản: backend 24 giờ, Figma 1 phút → thống nhất một con số (giao diện đọc `VITE_PAYMENT_TIMEOUT_SECONDS`).
-- [ ] Khu quản trị: role `OPERATIONS` (Vận hành KD), ghi lịch sử đăng nhập thất bại, lọc nhật ký nhiều `action`.
-- [ ] Khu Vận hành KD (Figma B01–B05) chưa có giao diện lẫn API — để sau.
+- [ ] Giữ chỗ: thanh toán QR 10 phút (Figma C04, `VITE_PAYMENT_TIMEOUT_SECONDS=600`), thanh toán tại cửa hàng 24 giờ (C04c) — backend đặt `ExpiresAt` / `expiredAt` PayOS theo hai con số này.
+- [ ] Khu quản trị: ~~role `OPERATIONS` (Vận hành KD)~~ (đã có), ghi lịch sử đăng nhập thất bại, lọc nhật ký nhiều `action`.
+- [x] API khu Vận hành KD (Figma B01–B05): `/api/operations/*`, role `OPERATIONS`, tài khoản `ops01` / `Ops@123` — hợp đồng ở `docs/operations-api.md`. Giao diện B01–B05 chưa có.
---
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
index 7aa3662..14538bb 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
@@ -3,7 +3,7 @@
# BE-CONTRACT — những gì giao diện khách hàng cần từ backend
Giao diện bám Figma nên **khác luồng backend cũ (v3)** ở vài điểm. Tài liệu này là danh sách để sửa BE cho khớp.
-Toàn bộ nghiệp vụ hiện nằm ở `src/state/reducer.js`; mỗi lệnh (`CREATE_RESERVATION`, `CONFIRM_TRANSFER`, ...)
+Toàn bộ nghiệp vụ hiện nằm ở `src/app/state/appReducer.js`; mỗi lệnh (`CREATE_RESERVATION`, `CONFIRM_TRANSFER`, ...)
tương ứng một endpoint dưới đây, nên thay bằng lời gọi API là đủ.
## 0. Hiện trạng nối API
@@ -38,7 +38,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend:
Đã gọi toàn bộ `/api/admin/*` hiện có (xem `ADMIN-FLOW-COVERAGE.md`). Đề xuất bổ sung phía backend:
- Gửi email mời / đặt mật khẩu lần đầu khi tạo tài khoản (Figma A02 "Gửi lời mời").
-- Vai trò `OPERATIONS` (Vận hành KD) như Figma.
+- ~~Vai trò `OPERATIONS` (Vận hành KD) như Figma.~~ Đã có (14/10/2026): role `OPERATIONS`, tài khoản `ops01`, API `/api/operations/*` — xem `docs/operations-api.md`.
- Ghi lịch sử đăng nhập **thất bại** (hiện chỉ ghi khi thành công) và lưu IP vào nhật ký hoạt động.
- Cho lọc nhật ký theo nhiều `action` một lúc (để tab "Thay đổi dữ liệu" / "Phân quyền" phân trang ở máy chủ).
- Trả kèm cơ sở phụ trách trong `GET /api/admin/users` để khỏi gọi thêm từng người.
@@ -47,8 +47,8 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend:
| Điểm | Figma / giao diện hiện tại | Backend cũ (v3) |
|---|---|---|
-| Thanh toán đặt chỗ | Khách chuyển khoản QR **ngay lúc đặt** (C04), bấm "Tôi đã chuyển khoản" → đơn "Chờ đối soát" | Đặt chỗ trước, thanh toán sau khi có hợp đồng |
-| Giữ chỗ | Đơn chờ chuyển khoản **tự huỷ sau N giây** (Figma: 60 giây) → C04b | Không có |
+| Thanh toán đặt chỗ | **QR PayOS** ngay lúc đặt (C04), tự xác nhận qua webhook, trang tự chuyển (D19); hoặc **thanh toán tại cửa hàng** (C04c) → nhân viên thu ở S09 | Đặt chỗ trước, thanh toán sau khi có hợp đồng |
+| Giữ chỗ | QR: **10 phút** (Figma C04) rồi tự huỷ → C04b; tại cửa hàng: 24 giờ (C04c) | Không có |
| Số tiền chuyển | Tổng ban đầu = tiền thuê + cọc (cọc = 1 tháng) | — |
| Gói thuê | 1 / 3 / 6 tháng | 1–24 tháng tuỳ nhập |
| Đăng ký | Họ tên, email, SĐT, mật khẩu, xác nhận; **không có username** | Có `username` |
@@ -59,12 +59,12 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend:
## 2. Trạng thái UI dùng (khoá → nhãn)
-- **Reservation**: `PENDING_PAYMENT` Chờ chuyển khoản · `PENDING_VERIFICATION` Chờ đối soát · `CONFIRMED` Đã xác nhận · `CHECKED_IN` Đã nhận kho · `CANCELLED` Đã huỷ đặt chỗ (kèm `cancel_reason`)
+- **Reservation**: `PENDING_PAYMENT` Chờ thanh toán · `PENDING_VERIFICATION` Chờ thanh toán tại cửa hàng (BE `PENDING_VERIFICATION` hoặc `PENDING_AT_FACILITY`) · `CONFIRMED` Đã xác nhận (BE `CONFIRMED` / `PAID` / `UNIT_ASSIGNED`) · `CHECKED_IN` Đã nhận kho · `CANCELLED` Đã huỷ đặt chỗ (kèm `cancel_reason`)
- **Contract**: `ACTIVE`, `ENDED` lưu ở BE; `EXPIRING` (≤ 30 ngày) và `OVERDUE` UI tự suy ra từ `end_date`
-- **Ledger (khoản thu)**: `RECONCILED` Đã đối soát · `PENDING_VERIFICATION` Chờ đối soát · `DEPOSIT_HELD` Đang giữ cọc · `RENEWAL_PENDING` Chờ duyệt yêu cầu · `UNPAID` Chưa thanh toán · `REFUNDED`
+- **Ledger (khoản thu)**: `RECONCILED` Đã thanh toán · `PENDING_VERIFICATION` Chờ thanh toán tại cửa hàng · `DEPOSIT_HELD` Đang giữ cọc · `RENEWAL_PENDING` Chờ duyệt yêu cầu · `UNPAID` Chờ thanh toán (khoản `RENEWAL` chưa trả có nút "Thanh toán" → C11q) · `REFUNDED`
- **Appointment**: `kind` = `CHECK_IN` | `MOVE_OUT`; `status` = `CONFIRMED` | `PENDING` | `DONE` | `CANCELLED`
- **Ticket**: `OPEN` · `IN_PROGRESS` · `RESOLVED` · `CANCELLED`; `topic` = `ACCESS|LOCK|UNIT|PAYMENT|ITEMS|SCHEDULE|OTHER`
-- **Renewal**: `PENDING` | `APPROVED` | `REJECTED` — **Return**: `PENDING` | `SCHEDULED` | `COMPLETED`
+- **Renewal**: `PENDING` | `APPROVED` | `REJECTED` — **ReturnRequestPage**: `PENDING` | `SCHEDULED` | `COMPLETED`
## 3. Endpoint cần có
@@ -73,13 +73,13 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend:
| A01 | `POST /api/auth/login` `{identifier, password}` | Sai mật khẩu nên trả **400/422**, không phải 401 (UI coi 401 là hết phiên) |
| A02 | `POST /api/auth/register` `{fullName, email, phone, password}` | Tự gán role Customer; trả token + user |
| A01 | `POST /api/auth/forgot-password` `{email}` | Luôn trả 200 |
-| C13 | `GET/PUT /api/auth/profile` | PUT chỉ nhận `fullName` |
+| C13 | `GET/PUT /api/auth/profile` | PUT gửi `fullName` đã trim và giữ `phone` từ GET; chỉ tên được sửa trên màn hình. Kết quả API cập nhật phiên hiện tại, không dùng tên overlay thay dữ liệu máy chủ. |
| C13 | `POST /api/auth/change-password` `{currentPassword, newPassword}` | Sai mật khẩu hiện tại → 400 |
| C02, C03 | `GET /api/facilities?type=&band=&area=&camera=&sort=&page=` | Trả: `id, name, district, city, address, distanceKm, hours, camera, hasClimate, basePrice`. `distanceKm` cần vị trí khách hoặc tạm tính |
| C03b | `POST /api/quotes` `{facilityId, type, band, months, startDate}` | → `monthlyRate, rentTotal, deposit, initialTotal, endDate, available` |
| C03c | `GET /api/facilities/{id}/photos` | 4+ ảnh kèm chú thích (mặt tiền, sơ đồ, ...) |
| C04 | `POST /api/reservations` | Tạo đơn `PENDING_PAYMENT`, trả `reservationId, expiresAt, timeoutSeconds, transferAmount, transferContent` (UI tự tạo VietQR từ tài khoản nhận) |
-| C04 | `POST /api/reservations/{id}/confirm-transfer` | → `PENDING_VERIFICATION`; sau `expiresAt` trả lỗi mã `EXPIRED` |
+| C04 | `POST /api/reservations/{id}/payos`, `POST /api/reservations/{id}/pay-at-facility` | PayOS + thanh toán tại cửa hàng — hợp đồng JSON ở `BACKEND-TODO.md` mục "Mới 16/10". `confirm-transfer` (đã có) chỉ còn là dự phòng khi chưa có `pay-at-facility` |
| C04b | (job nền) | Tự chuyển `PENDING_PAYMENT` quá hạn sang `CANCELLED`, `cancelReason` kiểu "Quá 1 phút chưa xác nhận" |
| C14, C05 | `GET /api/reservations`, `GET /api/reservations/{id}` | |
| C06, C07 | `GET /api/contracts`, `GET /api/contracts/{id}` | Thêm `unitNumber, sizeM2, location, handedOver, depositAmount` |
@@ -87,24 +87,30 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend:
| C09 | `POST /api/contracts/{id}/move-out` `{date, slot, note}` | Tạo `Appointment MOVE_OUT` trạng thái `PENDING` |
| C11 | `GET /api/appointments`, `GET /api/ledger` | Sổ khoản thu: `ref, label, amount, status, contractId?, reservationId?` |
| C12 | `GET/POST /api/tickets`, `POST /api/tickets/{id}/cancel` | POST là multipart: `contractId?, topic, description, files[≤3, ≤5MB, image/*]`; chỉ huỷ được khi `OPEN` |
+| C12 | `GET /api/tickets/{id}` | Đã nối `responses: [{message, staffName, createdAt}]`; hiện phản hồi mới nhất và lịch sử, lỗi tải có thông báo và nút cập nhật. 401 kết thúc phiên. Tên ảnh đính kèm hiện lưu cục bộ; upload ảnh còn là đề xuất, không nằm trong gói C12/C13. |
| Popup | `GET /api/notifications`, `POST /api/notifications/read` `{ids?}` | `id, title, detail, to, createdAt, read` |
## 4. Việc còn lại phía backend
- Tài khoản nhận chuyển khoản đang cấu hình ở `.env` (`VITE_BANK_*`); nếu mỗi cơ sở nhận tiền riêng thì trả kèm theo đơn.
- Khoảng cách "Cách bạn X km" cần vị trí khách; hiện lấy từ dữ liệu cơ sở.
-- Ảnh cơ sở đang là file tĩnh trong `public/images/`; khi có API ảnh (`GET /api/facilities/{id}/photos`), thay các hàm trong `src/config/media.js`.
+- Ảnh cơ sở đang là file tĩnh trong `public/images/`; khi có API ảnh (`GET /api/facilities/{id}/photos`), thay các hàm trong `src/app/config/media.js`.
- Khu Nhân viên cơ sở (S01–S09) và Quản lý cơ sở (M01–M08) đã có giao diện, đang chạy trên dữ liệu trong trình duyệt
- (`src/ops/`). Endpoint cần có ở mục 5.
+ (`src/features/facility-operations/`). Endpoint cần có ở mục 5.
- Kho dữ liệu cục bộ lưu cả mật khẩu để đăng nhập được khi chưa có server; khi nối API, bỏ trường này.
## 5. Endpoint cho sơ đồ ô kho, bản đồ và khu vận hành (giao diện đã sẵn, đang dùng dữ liệu cục bộ)
| Màn | Endpoint đề xuất | Thay ở |
|---|---|---|
-| C03b-sđ | `GET /api/facilities/{id}/units` → `unitNumber, zone, floor, sizeM2, unitTypeId, status` (StorageUnit) | `unitsFor()` trong `src/lib/units.js`; `fromBackendStatus()` đã map trạng thái |
-| C02m | Thêm `latitude, longitude` vào `GET /api/facilities` | `coordsOf()` trong `src/config/geo.js` |
-| S01–S09, M01–M08 | `/api/ops/*` — **đã chốt hợp đồng ở `BACKEND-TODO.md` mục A2–A3**, giao diện gọi qua `src/ops/api.js` | `src/ops/store.jsx` |
+| C03b-sđ | **Đã có** `GET /api/facilities/{id}/units` → `unitId, facilityId, unitTypeId, unitNumber, floor, zone, locationDescription, sizeM2, climateControlled, status` | `customerApi.facilityUnits`, `AppProvider.getFacilityUnits`, `FacilityDetailPage.jsx`, `unitsFor()` trong `units.js` |
-Hình dạng dữ liệu giao diện đang dùng nằm ở `src/ops/data.js`; nghiệp vụ (điều kiện chặn, chuyển trạng thái) ở
-`src/ops/reducer.js` và có test (`tests/ops.test.js`) để backend đối chiếu.
+| C02m | **Đã có** `latitude, longitude` trong `GET /api/facilities` (nhập ở B05a) | `mapCatalog` gán `lat/lng`; `coordsOf()` trong `src/app/config/geo.js` chỉ dùng toạ độ dự phòng khi cơ sở chưa có toạ độ |
+| S01–S09, M01–M08 | `/api/ops/*` — **đã chốt hợp đồng ở `BACKEND-TODO.md` mục A2–A3**, giao diện gọi qua `src/features/facility-operations/api/facilityOperationsApi.js` | `src/features/facility-operations/state/FacilityOperationsProvider.jsx` |
+
+Hình dạng dữ liệu giao diện đang dùng nằm ở `src/features/facility-operations/data/facilityOperationsSeed.js`; nghiệp vụ (điều kiện chặn, chuyển trạng thái) ở
+`src/features/facility-operations/state/facilityOperationsReducer.js` và có test (`tests/ops.test.js`) để backend đối chiếu.
+
+## Bổ sung 20/10 — thu tiền trước phân bổ và trạng thái ô
+
+Đã triển khai API chọn trả tại kho, PaymentMethod, ghi khoản thu theo ReservationId rồi gắn ContractId, kiểm chuyển tiếp ô và lịch sử. Xem `docs/payment-integrity-2026-10-20.md` và D23–D24 để biết hợp đồng API, migration, phạm vi test và các ca cần chạy thật. FE không còn dùng confirm-transfer làm fallback cho chọn trả tại kho. Các API /api/ops tương thích được đăng ký duy nhất trong FacilityOpsEndpoints.
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md
new file mode 100644
index 0000000..510ac35
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md
@@ -0,0 +1,28 @@
+# Quản lý vận hành KD — frontend B01–B05
+
+Nguồn: Figma section 436:13803; operations-api(3).md do người dùng cung cấp.
+
+| Màn | Component | Route | API |
+|---|---|---|---|
+| B01 Tổng quan | business/CustomerDashboardPage.jsx | business | GET facilities, reports/facilities, reports/revenue-trend |
+| B02 Chính sách | business/Policies.jsx | business/policies | GET/POST policies; POST policies/{id}/activate; PUT cho DRAFT |
+| B03 Giá & phí | business/PublicPricingPage.jsx | business/pricing | GET unit-types, policies, facilities; POST policies và activate |
+| B04 Báo cáo | business/Reports.jsx | business/reports | GET reports/facilities, unit-types, revenue-trend, rental-status, export |
+| B05 Cơ sở | business/Facilities.jsx | business/facilities | GET facilities, rates; điều hướng sang reports với facilityId |
+| Header/session | business/BusinessLayout.jsx | các route KD | JWT và logout của store chung; notice tổng hợp từ API được tài liệu mô tả |
+
+Không thêm endpoint ngoài hợp đồng. Không sửa endpoint hay schema backend.
+Màn Figma không có nút CRUD cơ sở hoặc bảng giá từng cơ sở nên không thêm các nút này vào UI.
+Lớp businessApi vẫn cung cấp các phương thức tương ứng hợp đồng để backend/frontend mở rộng về sau.
+
+B02 gom các ô cùng type/phạm vi vào một chính sách; phần quy định bổ sung dùng ruleDescription.
+Khi tạo/thay chính sách gặp 409, frontend hỏi xác nhận trước khi replaceExisting=true.
+Đổi số tiền hoặc quy định không tự chỉnh hợp đồng/đơn đặt chỗ trên frontend.
+
+Xuất XLSX: ba chế độ đầu gọi CSV backend và đóng gói OOXML ở client;
+chế độ trạng thái xuất snapshot đã tải. Không giả định có endpoint xuất trạng thái.
+managerName là trường bổ sung tùy chọn, không tự suy từ assignedStaff.
+Chỉ tiêu quá hạn dùng đúng overdueContracts trong tài liệu và ghi nhãn Hợp đồng quá hạn.
+
+Các luồng thật sẽ gọi API theo VITE_API_URL; dev:business là mock HTTP opt-in cho phát triển frontend,
+không phải chế độ fallback tự động khi API thật gặp lỗi.
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md
index 68af081..2164717 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md
@@ -4,38 +4,41 @@ Nguồn: file Figma "SafeSpace - Modern UI" (section Khách hàng + Trang chủ
| Figma | Route | Component | Ghi chú |
|---|---|---|---|
-| START Trang chủ | `#/home` | `pages/Home.jsx` | Hero tối, 3 điểm nổi bật, 12 cơ sở phân trang 9/trang, CTA đăng ký / đăng nhập |
-| A01 Đăng nhập | `#/login` | `pages/Auth.jsx` | Trang riêng; "Quên mật khẩu?" mở hộp thoại; giữ `?next=` để quay lại |
-| A02 Đăng ký | `#/register` | `pages/Auth.jsx` | Họ tên, email, SĐT, mật khẩu, xác nhận mật khẩu; tự vào vai trò Khách hàng |
-| P01 Bảng giá | `#/pricing` | `pages/Public.jsx` | Giá "Từ" tính từ dữ liệu cơ sở |
-| P02 Hướng dẫn | `#/guide` | `pages/Public.jsx` | Accordion +/− |
-| C01 Dashboard | `#/overview` | `pages/Overview.jsx` | 3 số liệu, kho đang thuê, hành động nhanh, mốc sắp tới, hoạt động |
-| C02 Tìm & đặt kho | `#/find` | `pages/FindList.jsx` | Hiện tất cả cơ sở; lọc loại kho / diện tích / khu vực; chip; sắp xếp; phân trang |
-| C02a–f, C03 | `#/find?type=&band=&area=` | `pages/FindList.jsx` | Các trạng thái chọn + kết quả lọc + trail 01→04 |
-| Nút Danh sách · Bản đồ | `#/find` ↔ `#/find/map` | `components/Inline.jsx` (`ViewToggle`) | Góc trên phải của C02 và C02m, giữ bộ lọc khi chuyển |
-| C01/C06/C14-trống | `#/overview`, `#/units`, `#/reservations` | `components/Inline.jsx` (`EmptyInline`) | Khách chưa có kho / đơn: một dòng thông báo + nút "Tìm & đặt kho" |
-| C02m, C02m-1, C02m-2 | `#/find/map` | `pages/FindMap.jsx` | Chỉ có thanh tìm kho + bản đồ Leaflet/OSM (không có danh sách thẻ, Figma 01/10); bấm logo mở "Thông tin cơ sở" + "Xem chi tiết cơ sở" |
-| C03b, C03b-1..3 | `#/find/:id` | `pages/FacilityDetail.jsx` | Loại kho, diện tích, gói 1/3/6 tháng, lịch chọn ngày, chi phí |
-| C03b-sđ (13 cơ sở) | `#/find/:id?view=map&unit=K01` | `pages/FacilityDetail.jsx`, `components/UnitMap.jsx` | Nút "Xem sơ đồ & tình trạng kho" ↔ "← Xem ảnh & tiện ích"; 10 ô; tóm tắt đổi theo ô; ô không trống → nút xám "Ô này hiện không khả dụng" |
-| C03c-1..4 | (lightbox) | `components/Photo.jsx` | 5 ảnh: ảnh cơ sở + 4 ảnh bên trong kho (đã bỏ sơ đồ mặt bằng); ← → / Esc |
-| C04 Đặt chỗ & Thanh toán | `#/checkout/:id` | `pages/Checkout.jsx` | Mã VietQR thật, số tiền, nội dung CK, đếm ngược, "Tôi đã chuyển khoản" |
-| C04b Không thành công | `#/checkout/:id/failed` | `pages/Checkout.jsx` | Hết giờ → đơn tự huỷ, kể cả khi đã đóng tab |
-| C05 Xác nhận | `#/confirmation/:id` | `pages/Checkout.jsx` | "Chờ đối soát thanh toán" |
-| C06 Kho của tôi | `#/units` | `pages/Units.jsx` | |
-| C07 / C07b Hợp đồng | `#/units/:id` | `pages/Units.jsx` | Nút gia hạn / trả kho bị khoá khi đang có yêu cầu chờ |
-| C08 / C08b Gia hạn | `#/units/:id/renew` | `pages/Units.jsx` | Chọn 1/3/6 tháng |
-| C09 / C09b Trả kho | `#/units/:id/return` | `pages/Units.jsx` | Ngày (lịch), khung giờ, ghi chú, đối chiếu cọc |
-| C10 Yêu cầu đã gửi | `#/sent?type=&contract=` | `pages/Units.jsx` | |
-| C11 Thanh toán & lịch hẹn | `#/payments` | `pages/Payments.jsx` | Thẻ lịch hẹn + bảng khoản thu; "Cần đổi lịch?" mở form hỗ trợ đúng chủ đề |
-| C12 Hỗ trợ | `#/support` | `pages/Support.jsx` | Có ảnh đính kèm (tối đa 3, 5 MB); danh sách yêu cầu bên phải |
-| C13, C13a–d, toast | `#/profile` | `pages/Profile.jsx` | Chỉ sửa tên; email / SĐT chỉ đọc (SĐT che bớt); hộp thoại "Đã hiểu" |
-| C14 Đơn đặt chỗ | `#/reservations`, `#/reservations/:id` | `pages/Reservations.jsx`, `pages/Checkout.jsx` | |
-| Popup thông báo (public / customer, đã đọc) | (header) | `components/Header.jsx` | |
+| START Trang chủ | `#/home` | `src/features/customer/home/HomePage.jsx` | Hero tối, 3 điểm nổi bật, 12 cơ sở phân trang 9/trang, CTA đăng ký / đăng nhập |
+| A01 Đăng nhập | `#/login` | `src/features/auth/LoginPage.jsx`, `src/features/auth/RegisterPage.jsx` | Trang riêng; "Quên mật khẩu?" mở hộp thoại; giữ `?next=` để quay lại |
+| A02 Đăng ký | `#/register` | `src/features/auth/LoginPage.jsx`, `src/features/auth/RegisterPage.jsx` | Họ tên, email, SĐT, mật khẩu, xác nhận mật khẩu; tự vào vai trò Khách hàng |
+| P01 Bảng giá | `#/pricing` | `src/features/customer/pricing/PublicPricingPage.jsx`, `src/features/customer/help/HelpPage.jsx` | Giá "Từ" tính từ dữ liệu cơ sở |
+| P02 Hướng dẫn | `#/guide` | `src/features/customer/pricing/PublicPricingPage.jsx`, `src/features/customer/help/HelpPage.jsx` | Accordion +/− |
+| C01 Dashboard | `#/overview` | `src/features/customer/dashboard/CustomerDashboardPage.jsx` | 3 số liệu, kho đang thuê, hành động nhanh, mốc sắp tới, hoạt động |
+| C02 Tìm & đặt kho | `#/find` | `src/features/customer/facilities/FacilityListPage.jsx` | Hiện tất cả cơ sở; lọc loại kho / diện tích / khu vực; chip; sắp xếp; phân trang |
+| C02a–f, C03 | `#/find?type=&band=&area=` | `src/features/customer/facilities/FacilityListPage.jsx` | Các trạng thái chọn + kết quả lọc + trail 01→04 |
+| Nút Danh sách · Bản đồ | `#/find` ↔ `#/find/map` | `src/shared/components/Inline.jsx` (`ViewToggle`) | Góc trên phải của C02 và C02m, giữ bộ lọc khi chuyển |
+| C01/C06/C14-trống | `#/overview`, `#/units`, `#/reservations` | `src/shared/components/Inline.jsx` (`EmptyInline`) | Khách chưa có kho / đơn: một dòng thông báo + nút "Tìm & đặt kho" |
+| C02m, C02m-1, C02m-2 | `#/find/map` | `src/features/customer/facilities/FacilityMapPage.jsx` | Chỉ có thanh tìm kho + bản đồ Leaflet/OSM (không có danh sách thẻ, Figma 01/10); bấm logo mở "Thông tin cơ sở" + "Xem chi tiết cơ sở" + "Chỉ đường" |
+| C03b, C03b-1..3 | `#/find/:id` | `src/features/customer/facilities/FacilityDetailPage.jsx` | Loại kho, diện tích, gói 1/3/6 tháng, lịch chọn ngày, chi phí; khối "Chỉ đường đến cơ sở" mở Google Maps (toạ độ D20, chưa có thì theo địa chỉ) |
+| C03b-sđ (13 cơ sở) | `#/find/:id?view=map&unit=K01` | `src/features/customer/facilities/FacilityDetailPage.jsx`, `src/shared/components/UnitMap.jsx` | Nút "Xem sơ đồ & tình trạng kho" ↔ "← Xem ảnh & tiện ích"; 10 ô; tóm tắt đổi theo ô; ô không trống → nút xám "Ô này hiện không khả dụng" |
+| C03c-1..4 | (lightbox) | `src/shared/components/Photo.jsx` | 5 ảnh: ảnh cơ sở + 4 ảnh bên trong kho (đã bỏ sơ đồ mặt bằng); ← → / Esc |
+| C04 Đặt chỗ & Thanh toán | `#/checkout/:id` | `src/features/customer/payments/CheckoutPage.jsx` | Chọn "Thanh toán QR" / "Tại cửa hàng". QR PayOS từ `POST /api/reservations/{id}/payos`, tiền thuê + cọc, đếm ngược 10:00, hỏi trạng thái 3 giây/lần rồi tự sang C05 (D19). Đã bỏ "Tôi đã chuyển khoản" |
+| C04c Thanh toán tại cửa hàng | `#/checkout/:id` (chọn "Tại cửa hàng") | `src/features/customer/payments/CheckoutPage.jsx` | Giữ chỗ 24 giờ, "Xác nhận đặt chỗ" → `pay-at-facility` (chưa có thì `confirm-transfer`) → C05c |
+| C04b Không thành công | `#/checkout/:id/failed` | `src/features/customer/payments/CheckoutPage.jsx` | Hết giờ → đơn tự huỷ, kể cả khi đã đóng tab |
+| C05 / C05c Xác nhận | `#/confirmation/:id` | `src/features/customer/payments/CheckoutPage.jsx` | QR: "Đã thanh toán"; tại cửa hàng: "Đã giữ chỗ cho bạn", số tiền, hạn 24 giờ, "Chờ thanh toán tại cửa hàng" |
+| C06 Kho của tôi | `#/units` | `src/features/customer/contracts/RentedUnitListPage.jsx` | |
+| C07 / C07b Hợp đồng | `#/units/:id` | `src/features/customer/contracts/RentedUnitListPage.jsx` | Chưa bàn giao (F29): "Xem / Đổi lịch nhận kho", khoá gia hạn, trả kho, mở cửa. Đã bàn giao: "Mở cửa kho" mở C07q. Gia hạn / trả kho khoá khi đang có yêu cầu chờ |
+| C07q QR mở cửa | (popup ở `#/units/:id`) | `src/features/customer/contracts/RentedUnitListPage.jsx` (`AccessQrModal`) | `GET /api/contracts/{id}/access-qr`: QR, mã dự phòng, ô kho, hiệu lực; link "Mô phỏng quét ở cửa kho" |
+| C07r1 / C07r2 Máy quét | `#/door?unit=&code=` | `src/features/customer/access/DoorScannerPage.jsx` | Mô phỏng máy quét (không cần đăng nhập): `POST /api/access/scan` → "Mở cửa" / "Từ chối" kèm lý do |
+| C08 / C08b Gia hạn | `#/units/:id/renew` | `src/features/customer/contracts/RentedUnitListPage.jsx` | Chọn 1/3/6 tháng; chỉ trả tiền thuê kỳ mới, cọc chuyển sang kỳ mới |
+| C09 / C09b Trả kho | `#/units/:id/return` | `src/features/customer/contracts/RentedUnitListPage.jsx` | Ngày (lịch), khung giờ, ghi chú, đối chiếu cọc |
+| C10 Yêu cầu đã gửi | `#/sent?type=&contract=` | `src/features/customer/contracts/RentedUnitListPage.jsx` | |
+| C11 / C11b Thanh toán & lịch hẹn | `#/payments` | `src/features/customer/payments/PaymentListPage.jsx` | Thẻ lịch hẹn + bảng khoản thu; khoản gia hạn đã duyệt có nút "Thanh toán" → C11q (`src/shared/components/PayosModal.jsx`, `POST /api/payments/{id}/payos`); trả xong hiện thông báo C11b |
+| C12 Hỗ trợ | `#/support` | `src/features/customer/support/SupportPage.jsx` | C12 trích đoạn phản hồi; C12b `#/support/:id` có tiến trình/lịch sử từ `GET /api/tickets/{id}`, có tên nhân viên và giờ UTC được định dạng; giữ sau F5; nút cập nhật và báo lỗi chi tiết. Tên ảnh hiện chỉ lưu cục bộ. |
+| C13, C13a–d, toast | `#/profile` | `src/features/customer/profile/CustomerProfilePage.jsx` | GET/PUT hồ sơ theo phiên hiện tại, tên 2–100 ký tự; giữ SĐT chỉ đọc. POST đổi mật khẩu đúng payload, sai mật khẩu hiện tại báo dưới ô nhập; chặn gửi lặp, hộp thoại thành công và kiểm đăng nhập lại. |
+| C14 / C14a / C14b Đơn đặt chỗ | `#/reservations`, `#/reservations/:id` | `src/features/customer/reservations/ReservationListPage.jsx`, `src/features/customer/payments/CheckoutPage.jsx` | Nút "Huỷ đơn" (đơn chưa nhận kho) → hộp thoại C14a: đã trả, phí huỷ, số tiền hoàn (`cancel-preview`); huỷ xong "Đã huỷ · Đang hoàn tiền" |
+| Popup thông báo (public / customer, đã đọc) | (header) | `src/shared/components/Header.jsx` | |
## Chỗ Figma tự mâu thuẫn, code chọn như sau
- C04 ghi cần chuyển 3.450.000 đ nhưng C03b/C14 ghi "Tổng ban đầu" 4.600.000 đ → chuyển **4.600.000 đ** (tiền thuê + cọc).
- C03c ghi "x trên 4" → thư viện hiện **5 ảnh** (ảnh cơ sở + 4 ảnh bên trong).
- C03b-sđ: ô 5 m² / 10 m² dùng giá của nhóm diện tích "2 – 5 m²" / "10 – 20 m²" để khớp với giá đặt chỗ.
-- C01 nói đã gửi gia hạn B-015 nhưng vẫn có nút "Gửi yêu cầu gia hạn" → dữ liệu khởi tạo chưa có yêu cầu gia hạn.
+- C01 nói đã gửi gia hạn B-015 nhưng vẫn có nút "Gửi yêu cầu gia hạn" → **đã sửa trong Figma 26/09/2026**: B-015 chưa gửi gia hạn (xem `docs/figma-review-2026-09-26.md` ở thư mục gốc repo).
- Figma không có màn cho: chi tiết đơn, huỷ yêu cầu hỗ trợ, trạng thái rỗng → dựng theo cùng phong cách.
- Figma có 12 cơ sở nhưng chỉ vẽ 9 thẻ; 3 cơ sở trang 2 (Gò Vấp, Tân Bình, Bình Tân) dùng lại ảnh Bình Thạnh, Tân Thuận, Bình Chánh.
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md
new file mode 100644
index 0000000..475e8b9
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md
@@ -0,0 +1,181 @@
+# Bản đồ frontend SafeSpace
+
+Đường dẫn trong bảng tính từ thư mục này. Mở `src/features/` rồi chọn vai trò và chức năng. Quy tắc: `../../docs/frontend-naming.md`.
+
+## Điểm bắt đầu
+
+C12/C13 nối API: xem `../../docs/frontend-auth-support.md`. Kiểm tra tương tác bằng `npm run test:auth-support` (Playwright, API giả lập). Đã đối chiếu C12/C12b và C13a–d trong Figma, nguồn tại `../../docs/figma-auth-support-review.md`.
+
+| Việc cần tìm | File |
+|---|---|
+| Khởi động React | `src/main.jsx` |
+| Route tổng và phân quyền trang | `src/app/App.jsx` |
+| Đọc/chuyển URL hash | `src/app/router.js` |
+| Phiên đăng nhập, dữ liệu chung, lệnh khách hàng | `src/app/state/AppProvider.jsx` |
+| API khách hàng và HTTP/JWT | `src/shared/api/customerApi.js`, `src/shared/api/httpClient.js` |
+| Chuyển dữ liệu BE sang FE | `src/shared/api/apiMappers.js` |
+| Staff/Manager: route, dữ liệu và thao tác | `src/features/facility-operations/FacilityOperationsRoutes.jsx`, `state/FacilityOperationsProvider.jsx`, `api/facilityOperationsApi.js` |
+| Admin: route và API | `src/features/admin/AdminRoutes.jsx`, `api/adminApi.js` |
+| Business: route và API | `src/features/business/BusinessRoutes.jsx`, `api/businessApi.js` |
+
+## Tìm màn hình theo chức năng
+
+| Vai trò / chức năng | File màn hình |
+|---|---|
+| Quản trị / Nhật ký — AuditLogPage | `src/features/admin/logs/AuditLogPage.jsx` |
+| Quản trị / Phân quyền — PermissionListPage | `src/features/admin/permissions/PermissionListPage.jsx` |
+| Quản trị / Tài khoản — CreateUserPage | `src/features/admin/users/CreateUserPage.jsx` |
+| Quản trị / Tài khoản — UserDetailPage | `src/features/admin/users/UserDetailPage.jsx` |
+| Quản trị / Tài khoản — UserListPage | `src/features/admin/users/UserListPage.jsx` |
+| Đăng nhập / đăng ký — LoginPage | `src/features/auth/LoginPage.jsx` |
+| Đăng nhập / đăng ký — RegisterPage | `src/features/auth/RegisterPage.jsx` |
+| Vận hành kinh doanh / Tổng quan — BusinessDashboardPage | `src/features/business/dashboard/BusinessDashboardPage.jsx` |
+| Vận hành kinh doanh / Cơ sở kho — FacilityManagementPage | `src/features/business/facilities/FacilityManagementPage.jsx` |
+| Vận hành kinh doanh / Chính sách — PolicySettingsPage | `src/features/business/policies/PolicySettingsPage.jsx` |
+| Vận hành kinh doanh / Bảng giá — PricingPage | `src/features/business/pricing/PricingPage.jsx` |
+| Vận hành kinh doanh / Báo cáo — BusinessReportPage | `src/features/business/reports/BusinessReportPage.jsx` |
+| Khách hàng / Mở cửa kho — DoorScannerPage | `src/features/customer/access/DoorScannerPage.jsx` |
+| Khách hàng / Hợp đồng / kho đang thuê — RenewalRequestPage | `src/features/customer/contracts/RenewalRequestPage.jsx` |
+| Khách hàng / Hợp đồng / kho đang thuê — RentedUnitDetailPage | `src/features/customer/contracts/RentedUnitDetailPage.jsx` |
+| Khách hàng / Hợp đồng / kho đang thuê — RentedUnitListPage | `src/features/customer/contracts/RentedUnitListPage.jsx` |
+| Khách hàng / Hợp đồng / kho đang thuê — ReturnRequestPage | `src/features/customer/contracts/ReturnRequestPage.jsx` |
+| Khách hàng / Tổng quan — CustomerDashboardPage | `src/features/customer/dashboard/CustomerDashboardPage.jsx` |
+| Khách hàng / Cơ sở kho — FacilityDetailPage | `src/features/customer/facilities/FacilityDetailPage.jsx` |
+| Khách hàng / Cơ sở kho — FacilityListPage | `src/features/customer/facilities/FacilityListPage.jsx` |
+| Khách hàng / Cơ sở kho — FacilityMapPage | `src/features/customer/facilities/FacilityMapPage.jsx` |
+| Khách hàng / Hướng dẫn — HelpPage | `src/features/customer/help/HelpPage.jsx` |
+| Khách hàng / Trang chủ — HomePage | `src/features/customer/home/HomePage.jsx` |
+| Khách hàng / Thanh toán — CheckoutFailedPage | `src/features/customer/payments/CheckoutFailedPage.jsx` |
+| Khách hàng / Thanh toán — CheckoutPage | `src/features/customer/payments/CheckoutPage.jsx` |
+| Khách hàng / Thanh toán — PaymentListPage | `src/features/customer/payments/PaymentListPage.jsx` |
+| Khách hàng / Bảng giá — PublicPricingPage | `src/features/customer/pricing/PublicPricingPage.jsx` |
+| Khách hàng / Hồ sơ — CustomerProfilePage | `src/features/customer/profile/CustomerProfilePage.jsx` |
+| Khách hàng / Yêu cầu — RequestSentPage | `src/features/customer/requests/RequestSentPage.jsx` |
+| Khách hàng / Đặt chỗ — ReservationDetailPage | `src/features/customer/reservations/ReservationDetailPage.jsx` |
+| Khách hàng / Đặt chỗ — ReservationListPage | `src/features/customer/reservations/ReservationListPage.jsx` |
+| Khách hàng / Chi tiết hỗ trợ — SupportTicketDetailPage | `src/features/customer/support/SupportTicketDetailPage.jsx` |
+| Khách hàng / Hỗ trợ — SupportPage | `src/features/customer/support/SupportPage.jsx` |
+| Quản lý cơ sở / Phân bổ kho — UnitAllocationPage | `src/features/manager/allocations/UnitAllocationPage.jsx` |
+| Quản lý cơ sở / Phân công — StaffAssignmentPage | `src/features/manager/assignments/StaffAssignmentPage.jsx` |
+| Quản lý cơ sở / Hợp đồng / kho đang thuê — ContractListPage | `src/features/manager/contracts/ContractListPage.jsx` |
+| Quản lý cơ sở / Tổng quan — ManagerDashboardPage | `src/features/manager/dashboard/ManagerDashboardPage.jsx` |
+| Quản lý cơ sở / Gia hạn — RenewalApprovalPage | `src/features/manager/renewals/RenewalApprovalPage.jsx` |
+| Quản lý cơ sở / Báo cáo — FacilityReportPage | `src/features/manager/reports/FacilityReportPage.jsx` |
+| Quản lý cơ sở / Kết quả — ManagerResultPage | `src/features/manager/results/ManagerResultPage.jsx` |
+| Quản lý cơ sở / Quản lý ô kho — UnitManagementPage | `src/features/manager/units/UnitManagementPage.jsx` |
+| Nhân viên / Tổng quan — StaffDashboardPage | `src/features/staff/dashboard/StaffDashboardPage.jsx` |
+| Nhân viên / Xác minh / bàn giao — CustomerVerificationPage | `src/features/staff/handovers/CustomerVerificationPage.jsx` |
+| Nhân viên / Xác minh / bàn giao — HandoverPage | `src/features/staff/handovers/HandoverPage.jsx` |
+| Nhân viên / Thanh toán — PaymentConfirmationPage | `src/features/staff/payments/PaymentConfirmationPage.jsx` |
+| Nhân viên / Kết quả — StaffResultPage | `src/features/staff/results/StaffResultPage.jsx` |
+| Nhân viên / Trả kho — ReturnInspectionPage | `src/features/staff/returns/ReturnInspectionPage.jsx` |
+| Nhân viên / Hỗ trợ — StaffSupportPage | `src/features/staff/support/StaffSupportPage.jsx` |
+
+## Các URL thường dùng
+
+| Muốn mở | URL hash |
+|---|---|
+| Tìm cơ sở / bản đồ / chi tiết | `#/find`, `#/find/map`, `#/find/:id` |
+| Đặt chỗ / thanh toán / kết quả | `#/reservations`, `#/checkout/:id`, `#/confirmation/:id` |
+| Hỗ trợ / chi tiết yêu cầu | `#/support`, `#/support/:id` |
+| Kho thuê / gia hạn / trả kho | `#/units`, `#/units/:id/renew`, `#/units/:id/return` |
+| Nhân viên thu tiền / xác minh / bàn giao | `#/staff/reconcile`, `#/staff/verify`, `#/staff/handover` |
+| Quản lý ô / phân bổ / gia hạn | `#/manager/units`, `#/manager/allocate`, `#/manager/renewals` |
+| Vận hành kinh doanh / quản trị | `#/business`, `#/admin` |
+
+## Ví dụ lần theo code
+
+- Chỉ đường: `features/customer/facilities/FacilityDetailPage.jsx`; bản đồ tìm cơ sở: `FacilityMapPage.jsx`; toạ độ mặc định: `app/config/geo.js`.
+- Thanh toán khách: `features/customer/payments/CheckoutPage.jsx` → `app/state/AppProvider.jsx` → `shared/api/customerApi.js` → BE.
+- Thu tiền tại quầy: `features/staff/payments/PaymentConfirmationPage.jsx` → `features/facility-operations/state/FacilityOperationsProvider.jsx` → `api/facilityOperationsApi.js`.
+- Các đường dẫn rút gọn trong ví dụ tính theo thư mục feature được nêu; bảng màn hình phía trên có đường dẫn đầy đủ.
+
+## Chuyển từ đường dẫn cũ
+
+| File cũ | Vị trí mới |
+|---|---|
+| `src/CustomerApp.jsx` | `src/app/App.jsx` |
+| `src/admin/AdminApp.jsx` | `src/features/admin/AdminRoutes.jsx` |
+| `src/admin/AdminCreateUser.jsx` | `src/features/admin/users/CreateUserPage.jsx` |
+| `src/admin/AdminLogs.jsx` | `src/features/admin/logs/AuditLogPage.jsx` |
+| `src/admin/AdminPermissions.jsx` | `src/features/admin/permissions/PermissionListPage.jsx` |
+| `src/admin/AdminShell.jsx` | `src/features/admin/AdminLayout.jsx` |
+| `src/admin/AdminUserDetail.jsx` | `src/features/admin/users/UserDetailPage.jsx` |
+| `src/admin/AdminUsers.jsx` | `src/features/admin/users/UserListPage.jsx` |
+| `src/admin/util.js` | `src/features/admin/utils/adminUtils.js` |
+| `src/api/admin.js` | `src/features/admin/api/adminApi.js` |
+| `src/api/business.js` | `src/features/business/api/businessApi.js` |
+| `src/api/endpoints.js` | `src/shared/api/customerApi.js` |
+| `src/api/http.js` | `src/shared/api/httpClient.js` |
+| `src/api/mappers.js` | `src/shared/api/apiMappers.js` |
+| `src/api/payment-access.js` | `src/features/customer/access/accessApi.js` |
+| `src/business/BusinessApp.jsx` | `src/features/business/BusinessRoutes.jsx` |
+| `src/business/BusinessShell.jsx` | `src/features/business/BusinessLayout.jsx` |
+| `src/business/Facilities.jsx` | `src/features/business/facilities/FacilityManagementPage.jsx` |
+| `src/business/Overview.jsx` | `src/features/business/dashboard/BusinessDashboardPage.jsx` |
+| `src/business/Policies.jsx` | `src/features/business/policies/PolicySettingsPage.jsx` |
+| `src/business/Pricing.jsx` | `src/features/business/pricing/PricingPage.jsx` |
+| `src/business/Reports.jsx` | `src/features/business/reports/BusinessReportPage.jsx` |
+| `src/business/actions.js` | `src/features/business/policies/policyActions.js` |
+| `src/business/design.css` | `src/features/business/business.css` |
+| `src/business/export.js` | `src/features/business/reports/reportExport.js` |
+| `src/business/facility-form.js` | `src/features/business/facilities/facilityForm.js` |
+| `src/business/format.js` | `src/features/business/utils/businessFormat.js` |
+| `src/business/parts.jsx` | `src/features/business/components/BusinessComponents.jsx` |
+| `src/business/policy-fields.js` | `src/features/business/policies/policyFields.js` |
+| `src/components/AccessQr.jsx` | `src/shared/components/AccessQr.jsx` |
+| `src/components/Header.jsx` | `src/shared/components/Header.jsx` |
+| `src/components/Inline.jsx` | `src/shared/components/Inline.jsx` |
+| `src/components/PayOSEmbeddedModal.jsx` | `src/shared/components/PayOSEmbeddedModal.jsx` |
+| `src/components/PaymentQr.jsx` | `src/shared/components/PaymentQr.jsx` |
+| `src/components/PayosModal.jsx` | `src/shared/components/PayosModal.jsx` |
+| `src/components/Photo.jsx` | `src/shared/components/Photo.jsx` |
+| `src/components/Pickers.jsx` | `src/shared/components/Pickers.jsx` |
+| `src/components/QrCode.jsx` | `src/shared/components/QrCode.jsx` |
+| `src/components/SearchBar.jsx` | `src/shared/components/SearchBar.jsx` |
+| `src/components/UI.jsx` | `src/shared/components/UI.jsx` |
+| `src/components/UnitMap.jsx` | `src/shared/components/UnitMap.jsx` |
+| `src/config/api.js` | `src/app/config/api.js` |
+| `src/config/geo.js` | `src/app/config/geo.js` |
+| `src/config/media.js` | `src/app/config/media.js` |
+| `src/config/payment.js` | `src/app/config/payment.js` |
+| `src/data/seed.js` | `src/app/data/appSeed.js` |
+| `src/lib/access.js` | `src/shared/utils/access.js` |
+| `src/lib/catalog.js` | `src/shared/utils/catalog.js` |
+| `src/lib/format.js` | `src/shared/utils/format.js` |
+| `src/lib/hooks.js` | `src/shared/hooks/useBrowserEvents.js` |
+| `src/lib/roles.js` | `src/shared/utils/roles.js` |
+| `src/lib/router.js` | `src/app/router.js` |
+| `src/lib/status.js` | `src/shared/utils/status.js` |
+| `src/lib/units.js` | `src/shared/utils/units.js` |
+| `src/lib/vietqr.js` | `src/shared/utils/vietqr.js` |
+| `src/ops/OpsApp.jsx` | `src/features/facility-operations/FacilityOperationsRoutes.jsx` |
+| `src/ops/OpsShell.jsx` | `src/features/facility-operations/FacilityOperationsLayout.jsx` |
+| `src/ops/api.js` | `src/features/facility-operations/api/facilityOperationsApi.js` |
+| `src/ops/data.js` | `src/features/facility-operations/data/facilityOperationsSeed.js` |
+| `src/ops/reducer.js` | `src/features/facility-operations/state/facilityOperationsReducer.js` |
+| `src/ops/store.jsx` | `src/features/facility-operations/state/FacilityOperationsProvider.jsx` |
+| `src/ops/tasks.jsx` | `src/features/facility-operations/components/StaffTasks.jsx` |
+| `src/ops/util.jsx` | `src/features/facility-operations/components/FacilityOperationsComponents.jsx` |
+| `src/pages/Door.jsx` | `src/features/customer/access/DoorScannerPage.jsx` |
+| `src/pages/FacilityDetail.jsx` | `src/features/customer/facilities/FacilityDetailPage.jsx` |
+| `src/pages/FindList.jsx` | `src/features/customer/facilities/FacilityListPage.jsx` |
+| `src/pages/FindMap.jsx` | `src/features/customer/facilities/FacilityMapPage.jsx` |
+| `src/pages/Home.jsx` | `src/features/customer/home/HomePage.jsx` |
+| `src/pages/Overview.jsx` | `src/features/customer/dashboard/CustomerDashboardPage.jsx` |
+| `src/pages/Payments.jsx` | `src/features/customer/payments/PaymentListPage.jsx` |
+| `src/pages/Profile.jsx` | `src/features/customer/profile/CustomerProfilePage.jsx` |
+| `src/pages/Reservations.jsx` | `src/features/customer/reservations/ReservationListPage.jsx` |
+| `src/pages/Support.jsx` | `src/features/customer/support/SupportPage.jsx` |
+| `src/state/reducer.js` | `src/app/state/appReducer.js` |
+| `src/state/selectors.js` | `src/app/state/appSelectors.js` |
+| `src/state/store.jsx` | `src/app/state/AppProvider.jsx` |
+| `src/state/useAccessQr.js` | `src/features/customer/access/useAccessQr.js` |
+| `src/styles/access-qr.css` | `src/shared/styles/access-qr.css` |
+| `src/styles/ss.css` | `src/shared/styles/ss.css` |
+| `src/ops/StaffPages.jsx` | `src/features/staff/hooks/useStaffIdentity.js`, `src/features/staff/dashboard/StaffDashboardPage.jsx`, `src/features/staff/payments/PaymentConfirmationPage.jsx`, `src/features/staff/handovers/CustomerVerificationPage.jsx`, `src/features/staff/handovers/HandoverPage.jsx`, `src/features/staff/returns/ReturnInspectionPage.jsx`, `src/features/staff/support/StaffSupportPage.jsx`, `src/features/staff/results/StaffResultPage.jsx`, `src/features/facility-operations/utils/unitStateTag.js` |
+| `src/ops/ManagerPages.jsx` | `src/features/manager/dashboard/ManagerDashboardPage.jsx`, `src/features/manager/units/UnitManagementPage.jsx`, `src/features/manager/allocations/UnitAllocationPage.jsx`, `src/features/manager/components/PageHeaderBlock.jsx`, `src/features/manager/assignments/StaffAssignmentPage.jsx`, `src/features/manager/renewals/RenewalApprovalPage.jsx`, `src/features/manager/contracts/ContractListPage.jsx`, `src/features/manager/reports/FacilityReportPage.jsx`, `src/features/manager/results/ManagerResultPage.jsx` |
+| `src/pages/Units.jsx` | `src/features/customer/contracts/components/ContractNotFound.jsx`, `src/features/customer/contracts/RentedUnitListPage.jsx`, `src/features/customer/access/AccessQrModal.jsx`, `src/features/customer/contracts/RentedUnitDetailPage.jsx`, `src/features/customer/contracts/RenewalRequestPage.jsx`, `src/features/customer/contracts/ReturnRequestPage.jsx`, `src/features/customer/requests/RequestSentPage.jsx` |
+| `src/pages/Checkout.jsx` | `src/features/customer/reservations/components/ReservationNotFound.jsx`, `src/features/customer/payments/CheckoutPage.jsx`, `src/features/customer/payments/CheckoutFailedPage.jsx`, `src/features/customer/reservations/ReservationDetailPage.jsx` |
+| `src/pages/Auth.jsx` | `src/features/auth/utils/safeNext.js`, `src/features/auth/components/ForgotPasswordDialog.jsx`, `src/features/auth/LoginPage.jsx`, `src/features/auth/RegisterPage.jsx` |
+| `src/pages/Public.jsx` | `src/features/customer/pricing/PublicPricingPage.jsx`, `src/features/customer/help/HelpPage.jsx` |
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md
index b7a281b..620d1ad 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md
@@ -1,15 +1,15 @@
# Đối chiếu Figma ↔ code: Nhân viên cơ sở & Quản lý cơ sở
Nguồn: file Figma "SafeSpace - Modern UI", section *SafeSpace · Nhân viên cơ sở* và *SafeSpace · Quản lý cơ sở*.
-Dữ liệu: `src/ops/data.js` (khởi tạo) · nghiệp vụ: `src/ops/reducer.js` (có test) · lưu: `src/ops/store.jsx`.
+Dữ liệu: `src/features/facility-operations/data/facilityOperationsSeed.js` (khởi tạo) · nghiệp vụ: `src/features/facility-operations/state/facilityOperationsReducer.js` (có test) · lưu: `src/features/facility-operations/state/FacilityOperationsProvider.jsx`.
## Nhân viên cơ sở (`#/staff`)
| Figma | Route | Làm được gì |
|---|---|---|
-| S01 Công việc trong ngày | `#/staff` | 3 số liệu + thẻ việc dạng **lưới 3x3** (9 thẻ / trang, phân trang); không có việc → S01-trống |
+| S01 Công việc trong ngày | `#/staff` | 3 số liệu (có "Chờ thu tiền tại kho") + thẻ việc dạng **lưới 3x3** (9 thẻ / trang, phân trang); không có việc → S01-trống |
| S09a / S02a / S03a / S04a / S05a | `#/staff/reconcile` … `#/staff/support` (không có `?id`) | Mỗi tab là lưới 3x3 thẻ việc của tab đó; bấm thẻ mở màn xử lý; không có việc → thông báo trống (S09a-trống) |
-| S09 Đối soát thanh toán | `#/staff/reconcile?id=` (có `?id`) | Xác nhận đã thu / Báo sai lệch (bắt buộc ghi rõ) |
+| S09 Thu tiền tại kho | `#/staff/reconcile?id=` (có `?id`) | Đơn khách chọn "Thanh toán tại cửa hàng": số tiền, giữ chỗ đến, gồm thuê + cọc; "Xác nhận đã thu" (`POST /api/ops/payments/{id}/confirm`) / "Để sau". Đơn trả PayOS không vào đây |
| S02 Xác minh khách hàng | `#/staff/verify?id=` | Loại + số giấy tờ (chỉ giữ 4 số cuối), 2 ô đối chiếu; xong chuyển sang bàn giao |
| S03 Bàn giao kho | `#/staff/handover?id=` | Thẻ từ / Mã PIN / Vân tay; chặn khi chưa xác minh; kho → Đang hoạt động |
| S04 Kiểm tra trả kho | `#/staff/return?id=` | 4 mục biên bản, gửi quản lý; kho → Chờ kiểm tra |
@@ -21,7 +21,7 @@ Dữ liệu: `src/ops/data.js` (khởi tạo) · nghiệp vụ: `src/ops/reducer
| Figma | Route | Làm được gì |
|---|---|---|
| M01 Tổng quan | `#/manager` | 86 kho, tỷ lệ lấp đầy tính từ dữ liệu, doanh thu, "Cần xử lý" gom mọi việc tồn |
-| M02 Danh sách kho | `#/manager/units?tab=` | Lọc theo trạng thái, tìm mã kho / khách, phân trang 12 |
+| M02 / M02a Danh sách kho | `#/manager/units?tab=` | Lọc theo trạng thái (thêm "Bảo trì"), tìm mã kho / khách, phân trang 12; cột "Thao tác": "Đổi trạng thái" → hộp thoại M02a (Trống ↔ Bảo trì, Chờ kiểm tra → Trống / Bảo trì, bắt buộc lý do) — `PUT /api/ops/units/{code}/status` (F12) |
| M05 Phân bổ kho | `#/manager/allocate?id=` | Chỉ hiện kho trống đúng loại + diện tích; phân bổ xong tạo lịch xác minh & bàn giao cho nhân viên |
| M06 Phân công | `#/manager/assign` | Giao việc cho nhân viên (ca làm, số việc đang nhận) |
| M03 Gia hạn | `#/manager/renewals` | Duyệt (cập nhật ngày hết hạn) / Từ chối (bắt buộc lý do) |
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md
index ad53d3e..b32b31d 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md
@@ -1,3 +1,5 @@
+> **Tìm code:** đọc [FRONTEND-MAP.md](FRONTEND-MAP.md). Quy tắc đặt tên: [frontend-naming.md](../../docs/frontend-naming.md).
+
# SafeSpace — Giao diện khách hàng & quản trị hệ thống
React + Vite, bám theo file Figma **SafeSpace - Modern UI**: Trang chủ, Đăng nhập, Đăng ký, Bảng giá,
@@ -62,12 +64,13 @@ Muốn làm lại từ đầu: xoá `safespace.ops.v1` và `safespace.customer.v
| Hợp đồng, khoản thu, lịch nhận kho, xác nhận bàn giao | `/api/contracts`, `/api/handovers/{id}/confirm` |
| Gia hạn | `POST /api/contracts/{id}/renewals` |
| Yêu cầu hỗ trợ (gửi, xem, huỷ) | `/api/tickets` |
-| Báo "Tôi đã chuyển khoản", đăng ký trả kho, thông báo, đổi tên hiển thị, ảnh đính kèm hỗ trợ | Backend **chưa có API** → lưu trong trình duyệt theo từng tài khoản |
+| Thanh toán QR PayOS (C04, C11q), thanh toán tại cửa hàng (C04c), QR mở cửa + máy quét `#/door` (C07q/C07r), phản hồi hỗ trợ (C12), xem trước hoàn tiền (C14a), đổi trạng thái ô (M02a) | Giao diện **gọi sẵn** endpoint theo `BACKEND-TODO.md` mục "Mới 16/10"; backend chưa có (404/405) → hiện thông báo thay thế, thanh toán tại cửa hàng tự dùng `confirm-transfer`. Thử đủ luồng: `MOCK_OPS=1 npm run dev:mock`; thử như backend chưa cập nhật: thêm `MOCK_LEGACY=1` |
+| Đăng ký trả kho, thông báo, đổi tên hiển thị, ảnh đính kèm hỗ trợ | Backend **chưa có API** → lưu trong trình duyệt theo từng tài khoản |
| Đổi mật khẩu, quên mật khẩu | Backend chưa có API → giao diện hướng dẫn liên hệ quản trị viên |
-| Sơ đồ tình trạng 10 ô kho, toạ độ cơ sở trên bản đồ | Backend chưa có API → sinh cố định theo cơ sở (`src/lib/units.js`, `src/config/geo.js`) |
-| Toàn bộ khu Nhân viên / Quản lý cơ sở | Đăng nhập qua API (vai trò `STAFF` / `MANAGER` trong JWT); dữ liệu vận hành lưu trong trình duyệt (`src/ops/`) cho đến khi backend có API (xem mục 5 của `BE-CONTRACT.md`) |
+| Sơ đồ tình trạng 10 ô kho, toạ độ cơ sở trên bản đồ | Backend chưa có API → sinh cố định theo cơ sở (`src/shared/utils/units.js`, `src/app/config/geo.js`) |
+| Toàn bộ khu Nhân viên / Quản lý cơ sở | Đăng nhập qua API (vai trò `STAFF` / `MANAGER` trong JWT); dữ liệu vận hành lưu trong trình duyệt (`src/features/facility-operations/`) cho đến khi backend có API (xem mục 5 của `BE-CONTRACT.md`) |
-Khi backend bổ sung API cho các dòng cuối, chỉ cần sửa `src/state/store.jsx` (nhánh `ApiProvider`), xem `BE-CONTRACT.md`.
+Khi backend bổ sung API cho các dòng cuối, chỉ cần sửa `src/app/state/AppProvider.jsx` (nhánh `ApiProvider`), xem `BE-CONTRACT.md`.
## Kiểm tra
@@ -83,7 +86,7 @@ npm run build # xuất bản dist/ (đường dẫn tương đối, đặ
Toàn bộ ảnh nằm sẵn trong `public/images/` (đã nén JPG, tổng ~3,9 MB): ảnh hero trang chủ, ảnh mặt tiền
9 cơ sở, 4 ảnh bên trong kho và 3 sơ đồ mặt bằng. Khi bấm xem một cơ sở, thư viện ảnh gồm ảnh cơ sở và
4 ảnh bên trong kho (sơ đồ mặt bằng không còn trong thư viện theo Figma 30/09; file vẫn giữ trong `public/images/plans/`). Chi tiết ở
-`public/images/README.md`; đổi cách gán ảnh ở `src/config/media.js`.
+`public/images/README.md`; đổi cách gán ảnh ở `src/app/config/media.js`.
## Thanh toán
@@ -95,14 +98,14 @@ chuyển khoản; ứng dụng ngân hàng quét là điền sẵn cả ba. Đơ
```
src/
- CustomerApp.jsx router + chặn trang cần đăng nhập
+ App.jsx router + chặn trang cần đăng nhập
pages/ mỗi màn Figma một component (xem CUSTOMER-FLOW-COVERAGE.md)
components/ Header + thông báo, lịch chọn ngày, thư viện ảnh, mã QR, UI dùng chung
state/reducer.js nghiệp vụ (thuần, có test)
state/store.jsx phiên đăng nhập; 2 chế độ: dữ liệu trong trình duyệt / API backend
api/ gọi API (http.js, endpoints.js, admin.js) + chuyển dữ liệu backend → giao diện (mappers.js)
- admin/ khu quản trị: AdminShell, AdminUsers, AdminUserDetail, AdminCreateUser, AdminPermissions, AdminLogs
- ops/ khu nhân viên & quản lý cơ sở: OpsShell, StaffPages, ManagerPages, data (khởi tạo), reducer (nghiệp vụ), store
+ admin/ khu quản trị: AdminLayout, UserListPage, UserDetailPage, CreateUserPage, PermissionListPage, AuditLogPage
+ ops/ khu nhân viên & quản lý cơ sở: FacilityOperationsLayout, StaffPages, ManagerPages, data (khởi tạo), reducer (nghiệp vụ), store
data/seed.js dữ liệu khởi tạo: 12 cơ sở, khách hàng Nguyễn Thị Mai
config/ địa chỉ API, ảnh, tài khoản nhận chuyển khoản
```
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs
index 0e19256..a656a12 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs
@@ -2,8 +2,9 @@
// Dùng để chạy / kiểm thử giao diện khi máy chưa có .NET và SQL Server: npm run dev:mock
// Dữ liệu nằm trong bộ nhớ, tắt là mất. Không thay thế backend thật.
import http from "node:http";
-import { createOpsData } from "../src/ops/data.js";
-import { reduceOps } from "../src/ops/reducer.js";
+import { handleBusiness, seedBusiness } from "./mock-business.mjs";
+import { createOpsData } from "../src/features/facility-operations/data/facilityOperationsSeed.js";
+import { reduceOps } from "../src/features/facility-operations/state/facilityOperationsReducer.js";
const pad = (n) => String(n).padStart(2, "0");
const iso = (d) => d.toISOString(); // DateTime.UtcNow trả về khi vừa tạo: có "Z"
@@ -61,7 +62,8 @@ export function createState() {
const rates = rateRows.map(([facilityId, unitTypeId, monthlyRate], i) => ({ rateId: i + 1, facilityId, facilityName: facilities[facilityId - 1].name, unitTypeId, unitTypeName: unitTypes[unitTypeId - 1].typeName, monthlyRate, effectiveFrom: eff, effectiveTo: null }));
const units = [
[1, 1, 1, "TB-S-101", "AVAILABLE"], [2, 1, 1, "TB-S-102", "AVAILABLE"], [3, 1, 2, "TB-M-103", "OCCUPIED"], [4, 1, 2, "TB-M-104", "AVAILABLE"],
- [5, 1, 3, "TB-L-201", "AVAILABLE"], [6, 1, 3, "TB-L-202", "AVAILABLE"], [7, 2, 1, "Q7-S-101", "AVAILABLE"], [8, 2, 1, "Q7-S-102", "AVAILABLE"],
+ [5, 1, 3, "TB-L-201", "AVAILABLE"], [6, 1, 3, "TB-L-202", "AVAILABLE"],
+ [7, 2, 1, "Q7-S-101", "AVAILABLE"], [8, 2, 1, "Q7-S-102", "AVAILABLE"],
[9, 2, 2, "Q7-M-103", "AVAILABLE"], [10, 2, 2, "Q7-M-104", "AVAILABLE"], [11, 2, 3, "Q7-L-201", "AVAILABLE"], [12, 2, 4, "Q7-XL-301", "AVAILABLE"],
].map(([unitId, facilityId, unitTypeId, unitNumber, status]) => ({ unitId, facilityId, unitTypeId, unitNumber, status }));
NETWORK.forEach(([code, , , , , xl], i) => {
@@ -77,7 +79,7 @@ export function createState() {
{ reservationId: 2, customerId: 3, facilityId: 1, unitTypeId: 1, startDate: start2, expectedEndDate: addMonths(start2, 1), rentalPeriodMonths: 1, quotedMonthlyRate: 500000, estimatedAmount: 500000, requiredDeposit: 500000, status: "PENDING_PAYMENT", createdAt: new Date(), expiresAt: new Date(Date.now() + 24 * 3600000), cancelledAt: null, cancellationReason: null },
];
const contracts = [
- { contractId: 1, reservationId: 1, customerId: 3, unitId: 3, startDate: start1, endDate: addMonths(start1, 3), agreedMonthlyRate: 1500000, depositAmount: 1500000, status: "ACTIVE", createdAt: days(-15), activatedAt: days(-15) },
+ { contractId: 1, reservationId: 1, customerId: 3, unitId: 5, startDate: start1, endDate: addMonths(start1, 3), agreedMonthlyRate: 1500000, depositAmount: 1500000, status: "ACTIVE", createdAt: days(-15), activatedAt: days(-15) },
];
const handovers = [{ handoverId: 1, contractId: 1, status: "HANDED_OVER", scheduledAt: days(-15), handoverAt: days(-15), customerConfirmed: true, staffConfirmed: true }];
const payments = [
@@ -86,6 +88,10 @@ export function createState() {
];
const tickets = [
{ ticketId: 1, customerId: 3, contractId: 1, unitId: 3, issueType: "UNIT", title: "Kiểm tra nhiệt độ phòng kho", description: "Nhờ nhân viên kiểm tra lại nhiệt độ kho TB-M-103 vào buổi trưa", priority: "NORMAL", status: "OPEN", createdAt: days(-2), assignedAt: null, resolvedAt: null, closedAt: null },
+ {
+ ticketId: 2, customerId: 3, contractId: 1, unitId: 3, issueType: "ACCESS", title: "Lỗi thẻ ra vào", description: "Thẻ ra vào chưa mở được cổng cơ sở.", priority: "HIGH", status: "RESOLVED", createdAt: days(-6), assignedAt: days(-6), resolvedAt: days(-6), closedAt: null,
+ responses: [{ message: "Thẻ cũ bị lỗi từ. Bạn qua quầy lễ tân nhận thẻ mới, mang theo CCCD giúp mình nhé.", staffName: "Trần Nhân Viên", createdAt: days(-6) }],
+ },
];
const roles = [
{ roleId: 1, roleName: "ADMIN", description: "Quản trị viên toàn quyền hệ thống" },
@@ -101,11 +107,15 @@ export function createState() {
const rolePermissions = permissions.map((p) => ({ roleId: 1, permissionId: p.permissionId }));
const userRoles = [{ userId: 1, roleId: 1 }, { userId: 2, roleId: 3 }, { userId: 3, roleId: 4 }, { userId: 4, roleId: 4 }];
for (const u of users) Object.assign(u, { phone: null, createdAt: days(-30 + u.userId), updatedAt: days(-30 + u.userId) });
- return { users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals: [], tickets, tokens: new Map(), down: false, roles, permissions, rolePermissions, userRoles, userFacilities: [], loginHistory: [], activityLogs: [] };
+ // Gia hạn đã được quản lý duyệt (M03) → khoản RENEWAL chờ khách trả qua PayOS ở C11 (BACKEND-TODO.md mục P3)
+ const renewEnd = addMonths(contracts[0].endDate, 3);
+ const renewals = [{ renewalId: 1, contractId: 1, oldEndDate: contracts[0].endDate, newEndDate: renewEnd, renewalPeriodMonths: 3, oldMonthlyRate: 1500000, newMonthlyRate: 1500000, renewalAmount: 4500000, status: "APPROVED", requestedAt: days(-2) }];
+ payments.push({ paymentId: 3, contractId: 1, renewalId: 1, paymentType: "RENEWAL", amount: 4500000, currency: "VND", paymentMethod: "PAYOS", transactionReference: "SS-0001-REN", dueDate: contracts[0].endDate, paidAt: null, status: "PENDING", createdAt: days(-1) });
+ return { users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals, tickets, payos: new Map(), accessLogs: [], tokens: new Map(), down: false, roles, permissions, rolePermissions, userRoles, userFacilities: [], loginHistory: [], activityLogs: [] };
}
-// ---- Khu vận hành (Nhân viên / Quản lý cơ sở): backend thật CHƯA có, chỉ bật khi { ops: true } hoặc MOCK_OPS=1.
-// Đây là bản chạy được của hợp đồng đề xuất trong BE-CONTRACT.md mục 5, dùng lại nghiệp vụ src/ops/reducer.js.
+// ---- Khu vận hành (Nhân viên / Quản lý cơ sở): chỉ bật khi { ops: true } hoặc MOCK_OPS=1.
+// Cùng hợp đồng với backend thật (docs/facility-ops-api.md), dùng lại nghiệp vụ src/ops/reducer.js.
const camel = (k) => k.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
const snake = (k) => k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
const mapKeys = (v, fn) =>
@@ -113,25 +123,57 @@ const mapKeys = (v, fn) =>
const STAFF_PARTS = ["facility", "staff", "units", "payments", "verifications", "handovers", "returns", "tickets"];
const OPS_ROUTES = [
// [method, regex, role, action, payload(body, id)]
- ["POST", /^\/api\/ops\/payments\/([^/]+)\/confirm$/, "STAFF", "CONFIRM_PAYMENT", (b, id) => ({ id })],
- ["POST", /^\/api\/ops\/payments\/([^/]+)\/mismatch$/, "STAFF", "REPORT_MISMATCH", (b, id) => ({ id, note: b?.note })],
- ["POST", /^\/api\/ops\/verifications\/([^/]+)$/, "STAFF", "VERIFY_CUSTOMER", (b, id) => ({ id, doc_type: b?.docType, doc_no: b?.docNumber, photo_ok: b?.photoMatched, info_ok: b?.infoMatched })],
- ["POST", /^\/api\/ops\/handovers\/([^/]+)\/complete$/, "STAFF", "HANDOVER", (b, id) => ({ id, method: b?.unlockMethod })],
- ["POST", /^\/api\/ops\/returns\/([^/]+)\/inspection$/, "STAFF", "SUBMIT_RETURN", (b, id) => ({ id, report: mapKeys(b || {}, snake) })],
- ["POST", /^\/api\/ops\/tickets\/([^/]+)\/responses$/, "STAFF", "TICKET_RESPONSE", (b, id, me) => ({ id, note: b?.note, next: b?.nextStatus, staff: me })],
- ["POST", /^\/api\/ops\/renewals\/([^/]+)\/approve$/, "MANAGER", "DECIDE_RENEWAL", (b, id) => ({ id, approve: true })],
- ["POST", /^\/api\/ops\/renewals\/([^/]+)\/reject$/, "MANAGER", "DECIDE_RENEWAL", (b, id) => ({ id, approve: false, reason: b?.reason })],
- ["POST", /^\/api\/ops\/allocations\/([^/]+)$/, "MANAGER", "ALLOCATE", (b, id) => ({ id, unit: b?.unitCode })],
- ["PUT", /^\/api\/ops\/assignments\/([^/]+)$/, "MANAGER", "ASSIGN", (b, id) => ({ id, staff: b?.staffId })],
- ["POST", /^\/api\/ops\/contracts\/([^/]+)\/reminders$/, "MANAGER", "REMIND", (b, id) => ({ id, note: b?.note })],
- ["POST", /^\/api\/ops\/contracts\/([^/]+)\/refund$/, "MANAGER", "CONFIRM_REFUND", (b, id) => ({ id })],
+ ["POST", /^\/api\/(?:ops|staff)\/payments\/([^/]+)\/confirm$/, "STAFF", "CONFIRM_PAYMENT", (b, id) => ({ id })],
+ ["POST", /^\/api\/(?:ops|staff)\/payments\/([^/]+)\/mismatch$/, "STAFF", "REPORT_MISMATCH", (b, id) => ({ id, note: b?.note })],
+ ["POST", /^\/api\/(?:ops|staff)\/verifications\/([^/]+)$/, "STAFF", "VERIFY_CUSTOMER", (b, id) => ({ id, doc_type: b?.docType, doc_no: b?.docNumber, photo_ok: b?.photoMatched, info_ok: b?.infoMatched })],
+ ["POST", /^\/api\/(?:ops|staff)\/handovers\/([^/]+)\/complete$/, "STAFF", "HANDOVER", (b, id) => ({ id, method: b?.unlockMethod })],
+ ["POST", /^\/api\/(?:ops|staff)\/returns\/([^/]+)\/inspection$/, "STAFF", "SUBMIT_RETURN", (b, id) => ({ id, report: mapKeys(b || {}, snake) })],
+ ["POST", /^\/api\/(?:ops|staff)\/tickets\/([^/]+)\/responses$/, "STAFF", "TICKET_RESPONSE", (b, id, me) => ({ id, note: b?.note, next: b?.nextStatus, staff: me })],
+ ["PUT", /^\/api\/(?:ops|staff)\/units\/([^/]+)\/status$/, "STAFF", "UPDATE_UNIT_STATUS", (b, id) => ({ id, code: id, status: b?.status, reason: b?.reason })],
+ ["POST", /^\/api\/(?:ops|staff)\/credentials\/([^/]+)\/revoke$/, "STAFF", "REVOKE_CREDENTIAL", (b, id) => ({ id })],
+ ["POST", /^\/api\/(?:ops|staff)\/credentials\/reissue$/, "STAFF", "REISSUE_CREDENTIAL", (b) => ({ unit: b?.unitCode, type: b?.credentialType, reason: b?.reason })],
+ ["POST", /^\/api\/(?:ops|manager)\/renewals\/([^/]+)\/approve$/, "MANAGER", "DECIDE_RENEWAL", (b, id) => ({ id, approve: true })],
+ ["POST", /^\/api\/(?:ops|manager)\/renewals\/([^/]+)\/reject$/, "MANAGER", "DECIDE_RENEWAL", (b, id) => ({ id, approve: false, reason: b?.reason })],
+ ["POST", /^\/api\/(?:ops|manager)\/allocations\/([^/]+)$/, "MANAGER", "ALLOCATE", (b, id) => ({ id, unit: b?.unitCode })],
+ ["PUT", /^\/api\/(?:ops|manager)\/assignments\/([^/]+)$/, "MANAGER", "ASSIGN", (b, id) => ({ id, staff: b?.staffId })],
+ ["POST", /^\/api\/(?:ops|manager)\/contracts\/([^/]+)\/reminders$/, "MANAGER", "REMIND", (b, id) => ({ id, note: b?.note })],
+ ["POST", /^\/api\/(?:ops|manager)\/contracts\/([^/]+)\/refund$/, "MANAGER", "CONFIRM_REFUND", (b, id) => ({ id })],
+ ["POST", /^\/api\/(?:ops|manager)\/units$/, "MANAGER", "CREATE_UNIT", (b) => b],
+ ["PUT", /^\/api\/(?:ops|manager)\/units\/([^/]+)$/, "MANAGER", "UPDATE_UNIT", (b, id) => ({ id, ...b })],
+ ["POST", /^\/api\/(?:ops|manager)\/units\/([^/]+)\/lock$/, "MANAGER", "LOCK_UNIT", (b, id) => ({ id, reason: b?.reason })],
];
-export function startMockApi(port = 5199, { verbose = false, ops = process.env.MOCK_OPS === "1" } = {}) {
+// Endpoint mới (BACKEND-TODO.md mục "Mới 16/10") — tắt hết khi chạy legacy để thử giao diện với backend chưa cập nhật
+const LEGACY_MISSING = [
+ /^\/api\/reservations\/\d+\/(payos|pay-at-facility|cancel-preview)$/,
+ /^\/api\/payments\/\d+\/payos$/,
+ /^\/api\/contracts\/\d+\/access-qr$/,
+ /^\/api\/access\/scan$/,
+ /^\/api\/ops\/units\/[^/]+\/status$/,
+];
+
+export function startMockApi(
+ port = 5199,
+ {
+ verbose = false,
+ ops = process.env.MOCK_OPS === "1",
+ business = false,
+ payosAutoPaySeconds = Number(process.env.MOCK_PAYOS_AUTOPAY ?? 0),
+ // legacy: giống backend hiện tại trên main — chưa có các endpoint mới 16/10 (trả 404 rỗng như ASP.NET)
+ legacy = process.env.MOCK_LEGACY === "1",
+ } = {},
+) {
const S = createState();
+ if (business) {
+ S.roles.push({ roleId: 5, roleName: 'OPERATIONS', description: 'Quản lý vận hành kinh doanh' });
+ const userId = S.users.length + 1;
+ S.users.push({ userId, username: 'ops01', email: 'ops01@storage.vn', password: 'Ops@123', fullName: 'Vũ Đức Anh', status: 'ACTIVE', createdAt: days(-20), updatedAt: days(-20) });
+ S.userRoles.push({ userId, roleId: 5 });
+ seedBusiness(S);
+ }
let O = null;
if (ops) {
- // Tài khoản quản lý cơ sở (DbSeeder thật chưa có) + gán nhân viên staff01 vào cơ sở
+ // Tài khoản quản lý cơ sở manager01 (giống DbSeeder) + gán nhân viên staff01 vào cơ sở
S.users.push({ userId: S.users.length + 1, username: "manager01", email: "manager01@storage.vn", password: "Manager@123", fullName: "Phạm Thu Hà", status: "ACTIVE", phone: null, createdAt: days(-20), updatedAt: days(-20) });
S.userRoles.push({ userId: S.users.length, roleId: 2 });
O = createOpsData();
@@ -147,6 +189,7 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M
startDate: r.startDate, expectedEndDate: r.expectedEndDate, rentalPeriodMonths: r.rentalPeriodMonths, quotedMonthlyRate: r.quotedMonthlyRate,
estimatedAmount: r.estimatedAmount, requiredDeposit: r.requiredDeposit, status: r.status, expiresAt: r.expiresAt ? dbTime(r.expiresAt) : null,
cancelledAt: r.cancelledAt ? dbTime(r.cancelledAt) : null, cancellationReason: r.cancellationReason, createdAt: dbTime(r.createdAt),
+ paymentMethod: r.paymentMethod || null, refundAmount: r.refundAmount ?? null, refundStatus: r.refundStatus || null,
});
const payDto = (p) => ({ ...p, paidAt: p.paidAt ? dbTime(p.paidAt) : null, createdAt: dbTime(p.createdAt) });
const renDto = (r) => ({ ...r, requestedAt: dbTime(r.requestedAt), approvedAt: null });
@@ -154,12 +197,48 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M
const u = unit(c.unitId);
return { contractId: c.contractId, reservationId: c.reservationId, unitId: c.unitId, unitNumber: u.unitNumber, facilityName: fac(u.facilityId).name, unitTypeName: ut(u.unitTypeId).typeName, startDate: c.startDate, endDate: c.endDate, agreedMonthlyRate: c.agreedMonthlyRate, depositAmount: c.depositAmount, status: c.status, activatedAt: c.activatedAt ? dbTime(c.activatedAt) : null };
};
+ // ---- PayOS giả lập (D19): tạo đơn → QR → "webhook" (tự báo đã trả sau payosAutoPaySeconds hoặc gọi /__payos/paid?order=)
+ const payosPaid = (order) => {
+ const o = S.payos.get(order);
+ if (!o || o.status === "PAID") return;
+ o.status = "PAID";
+ if (o.kind === "reservation") {
+ const r = S.reservations.find((x) => x.reservationId === o.id);
+ if (r && r.status === "PENDING_PAYMENT") Object.assign(r, { status: "CONFIRMED", paymentMethod: "PAYOS" });
+ } else {
+ const p = S.payments.find((x) => x.paymentId === o.id);
+ if (p && p.status !== "PAID") {
+ Object.assign(p, { status: "PAID", paidAt: new Date(), transactionReference: p.transactionReference || `PAYOS-${order}` });
+ const ren = S.renewals.find((x) => x.renewalId === p.renewalId);
+ const c = S.contracts.find((x) => x.contractId === p.contractId);
+ if (ren && c && ren.status !== "PAID") {
+ ren.status = "PAID";
+ c.endDate = ren.newEndDate;
+ }
+ }
+ }
+ };
+ const payosOrder = (kind, id, amount, description) => {
+ const existing = [...S.payos.values()].find((o) => o.kind === kind && o.id === id && o.status === "PENDING" && o.expiredAt > new Date());
+ const o = existing || { orderCode: 100000 + S.payos.size + 1, kind, id, amount, description, status: "PENDING", expiredAt: new Date(Date.now() + 15 * 60000) };
+ if (!existing) {
+ S.payos.set(o.orderCode, o);
+ if (payosAutoPaySeconds > 0) setTimeout(() => payosPaid(o.orderCode), payosAutoPaySeconds * 1000).unref?.();
+ }
+ const qr = `00020101021238570010A000000727012700069704220113SAFESPACE${o.orderCode}0208QRIBFTTA530370454${String(o.amount).length.toString().padStart(2, "0")}${o.amount}5802VN62${String(o.description.length + 4).padStart(2, "0")}08${String(o.description.length).padStart(2, "0")}${o.description}6304ABCD`;
+ return { orderCode: o.orderCode, amount: o.amount, description: o.description, qrCode: qr, checkoutUrl: `https://pay.payos.vn/web/mock-${o.orderCode}`, expiredAt: iso(o.expiredAt), status: o.status };
+ };
+ const accessCode = (c) => {
+ const n = String((c.contractId * 7919 + 4821) % 100000000).padStart(8, "0");
+ return { code: `SSQR-${c.contractId}-${n.slice(0, 4)}`, backup: `${n.slice(0, 4)} ${n.slice(4)}` };
+ };
+
const ticketDto = (t) => ({ ticketId: t.ticketId, contractId: t.contractId, unitId: t.unitId, issueType: t.issueType, title: t.title, priority: t.priority, status: t.status, createdAt: dbTime(t.createdAt), resolvedAt: null, closedAt: null });
const availability = (facilityId, unitTypeId, startDate, months) => {
const end = addMonths(startDate, months);
const free = S.units.filter((u) => u.facilityId === facilityId && u.unitTypeId === unitTypeId && u.status === "AVAILABLE").length;
- const held = S.reservations.filter((r) => r.facilityId === facilityId && r.unitTypeId === unitTypeId && ["PENDING_PAYMENT", "CONFIRMED"].includes(r.status) && r.startDate < end && r.expectedEndDate > startDate).length;
+ const held = S.reservations.filter((r) => r.facilityId === facilityId && r.unitTypeId === unitTypeId && ["PENDING_PAYMENT", "PENDING_VERIFICATION", "CONFIRMED"].includes(r.status) && r.startDate < end && r.expectedEndDate > startDate).length;
return Math.max(0, free - held);
};
@@ -180,7 +259,14 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M
if (path === "/__down") { S.down = true; return send(200, {}); }
if (path === "/__up") { S.down = false; return send(200, {}); }
if (path === "/__revoke") { S.tokens.clear(); return send(200, {}); }
+ // Giả lập webhook PayOS: /__payos/paid?order= (bỏ trống order = trả mọi đơn đang chờ)
+ if (path === "/__payos/paid") {
+ const order = Number(url.searchParams.get("order"));
+ for (const o of S.payos.values()) if (!order || o.orderCode === order) payosPaid(o.orderCode);
+ return send(200, {});
+ }
if (S.down) { req.socket.destroy(); return; }
+ if (legacy && LEGACY_MISSING.some((re) => re.test(path))) return send(404);
let body = null;
if (req.method === "POST" || req.method === "PUT") {
const chunks = [];
@@ -224,21 +310,87 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M
if (h) h.logoutAt = new Date();
return send(200, { message: "Đăng xuất thành công." });
}
+ if (req.method === "GET" && path === "/api/auth/profile") {
+ const u = auth();
+ if (!u) return send(401);
+ const roleNames = S.userRoles.filter((r) => r.userId === u.userId).map((r) => S.roles.find((x) => x.roleId === r.roleId).roleName);
+ return send(200, { userId: u.userId, username: u.username, fullName: u.fullName, email: u.email, phone: u.phone || null, status: u.status, roles: roleNames });
+ }
+ if (req.method === "PUT" && path === "/api/auth/profile") {
+ const u = auth();
+ if (!u) return send(401);
+ if (body.fullName) u.fullName = body.fullName.trim();
+ if (body.phone !== undefined) u.phone = body.phone;
+ const roleNames = S.userRoles.filter((r) => r.userId === u.userId).map((r) => S.roles.find((x) => x.roleId === r.roleId).roleName);
+ return send(200, { userId: u.userId, username: u.username, fullName: u.fullName, email: u.email, phone: u.phone || null, status: u.status, roles: roleNames });
+ }
+ if (req.method === "POST" && path === "/api/auth/change-password") {
+ const u = auth();
+ if (!u) return send(401);
+ if (u.password !== body.currentPassword) return bad("Mật khẩu hiện tại không chính xác.");
+ if (!body.newPassword || body.newPassword.length < 6) return bad("Mật khẩu mới phải có ít nhất 6 ký tự.");
+ u.password = body.newPassword;
+ return send(200, { message: "Đổi mật khẩu thành công." });
+ }
// ---- Công khai
if (req.method === "GET" && path === "/api/facilities") return send(200, S.facilities);
if (req.method === "GET" && path === "/api/unit-types") return send(200, S.unitTypes);
if (req.method === "GET" && path === "/api/rates") return send(200, S.rates);
+ if (req.method === "GET" && (m = path.match(/^\/api\/facilities\/(\d+)\/units$/))) {
+ const fid = Number(m[1]);
+ const list = S.units.filter((u) => u.facilityId === fid && u.status !== "OUT_OF_SERVICE").map((u) => {
+ const t = S.unitTypes.find((x) => x.unitTypeId === u.unitTypeId);
+ return {
+ unitId: u.unitId,
+ facilityId: u.facilityId,
+ unitTypeId: u.unitTypeId,
+ unitNumber: u.unitNumber,
+ floor: u.floor || "Tầng trệt",
+ zone: u.zone || "Dãy A",
+ locationDescription: u.locationDescription || null,
+ sizeM2: t?.area || 15,
+ climateControlled: t?.climateControlled || false,
+ status: u.status,
+ };
+ });
+ return send(200, list);
+ }
if (req.method === "POST" && path === "/api/availability/check") {
+
const rate = S.rates.find((r) => r.facilityId === body.facilityId && r.unitTypeId === body.unitTypeId);
const t = ut(body.unitTypeId);
const count = availability(body.facilityId, body.unitTypeId, body.startDate, body.rentalPeriodMonths);
return send(200, { facilityId: body.facilityId, facilityName: fac(body.facilityId)?.name, unitTypeId: body.unitTypeId, unitTypeName: t?.typeName, area: t?.area, climateControlled: t?.climateControlled, monthlyRate: rate?.monthlyRate || 0, estimatedTotalRent: (rate?.monthlyRate || 0) * body.rentalPeriodMonths, requiredDeposit: rate?.monthlyRate || 0, startDate: body.startDate, expectedEndDate: addMonths(body.startDate, body.rentalPeriodMonths), availableUnitCount: count, isAvailable: count > 0 });
}
+ // C07r · máy quét cửa kho (thiết bị tại cơ sở, không cần đăng nhập khách)
+ if (req.method === "POST" && path === "/api/access/scan") {
+ const code = String(body?.code || "").trim();
+ const clean = code.replace(/\s/g, "");
+ const c = S.contracts.find((x) => { const a = accessCode(x); return a.code === code || a.backup.replace(/\s/g, "") === clean; });
+ const now = new Date();
+ const out = (result, reason, cc) => {
+ S.accessLogs.push({ code, result, at: now });
+ const u = cc && unit(cc.unitId);
+ const cust = cc && S.users.find((x) => x.userId === cc.customerId);
+ return send(200, { result, unitNumber: u?.unitNumber || null, customerName: cust?.fullName || null, contractCode: cc ? `HĐ-${cc.startDate.slice(0, 4)}-${String(cc.contractId).padStart(4, "0")}` : null, scannedAt: iso(now), reason });
+ };
+ if (!c) return out("DENIED", "Mã không đúng. Kiểm tra lại mã trên ứng dụng hoặc mã dự phòng.", null);
+ const h = S.handovers.find((x) => x.contractId === c.contractId);
+ if (c.status !== "ACTIVE") return out("DENIED", "Mã đã hết hiệu lực — hợp đồng đã trả kho.", c);
+ if (!h || h.status !== "HANDED_OVER") return out("DENIED", "Kho chưa được bàn giao cho khách.", c);
+ if (c.endDate < dateOnly(now)) return out("DENIED", "Hợp đồng đã quá hạn. Vui lòng gia hạn hoặc liên hệ cơ sở.", c);
+ return out("OPEN", null, c);
+ }
+
const user = auth();
if (path.startsWith("/api/") && !user) return send(401);
const me = user?.userId;
+ if (business && path.startsWith('/api/operations')) {
+ handleBusiness({ req, res, path, url, body, S, me, send });
+ return;
+ }
// ---- Quản trị (RequireRole ADMIN)
@@ -426,13 +578,74 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M
S.reservations.push(r);
return send(201, { ...resDto(r), createdAt: iso(r.createdAt), expiresAt: iso(r.expiresAt) });
}
+ if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/confirm-transfer$/))) {
+ // Giống ReservationService.ConfirmTransferAsync: PENDING_PAYMENT → PENDING_VERIFICATION; quá hạn giữ chỗ → 400 code EXPIRED
+ const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me);
+ if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." });
+ if (r.status === "PENDING_VERIFICATION") return send(200, resDto(r));
+ if (r.status !== "PENDING_PAYMENT") return bad("Đơn đặt chỗ này không còn chờ chuyển khoản.");
+ if (r.expiresAt && r.expiresAt <= new Date()) {
+ Object.assign(r, { status: "EXPIRED", cancelledAt: new Date(), cancellationReason: "Quá thời gian giữ chỗ chưa xác nhận chuyển khoản" });
+ return send(400, { error: "Đơn đặt chỗ đã hết thời gian giữ chỗ.", code: "EXPIRED" });
+ }
+ r.status = "PENDING_VERIFICATION";
+ return send(200, resDto(r));
+ }
+ if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/payos$/))) {
+ const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me);
+ if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." });
+ if (r.status !== "PENDING_PAYMENT") return bad("Đơn đặt chỗ này không còn chờ thanh toán.");
+ return send(200, payosOrder("reservation", r.reservationId, r.estimatedAmount + r.requiredDeposit, `SS${String(r.reservationId).padStart(4, "0")}`));
+ }
+ if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/pay-at-facility$/))) {
+ const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me);
+ if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." });
+ if (r.status === "PENDING_VERIFICATION") return send(200, resDto(r));
+ if (r.status !== "PENDING_PAYMENT") return bad("Đơn đặt chỗ này không còn chờ thanh toán.");
+ Object.assign(r, { status: "PENDING_VERIFICATION", paymentMethod: "AT_FACILITY", expiresAt: new Date(Date.now() + 24 * 3600000) });
+ for (const o of S.payos.values()) if (o.kind === "reservation" && o.id === r.reservationId && o.status === "PENDING") o.status = "CANCELLED";
+ return send(200, resDto(r));
+ }
+ if (req.method === "GET" && (m = path.match(/^\/api\/reservations\/(\d+)\/cancel-preview$/))) {
+ const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me);
+ if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." });
+ const paid = r.status === "CONFIRMED" ? r.estimatedAmount + r.requiredDeposit : 0;
+ const fee = paid ? Math.round(r.estimatedAmount * 0.1) : 0;
+ return send(200, { paidAmount: paid, cancellationFee: fee, refundAmount: paid - fee, policyName: "Huỷ trước ngày nhận kho: phí 10% tiền thuê" });
+ }
if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/cancel$/))) {
const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me);
if (!r) return bad("Không tìm thấy đơn đặt chỗ hợp lệ.");
if (!["PENDING_PAYMENT", "CONFIRMED"].includes(r.status)) return bad(`Không thể hủy đơn đặt chỗ ở trạng thái '${r.status}'.`);
- Object.assign(r, { status: "CANCELLED", cancelledAt: new Date(), cancellationReason: body?.reason });
+ const paid = r.status === "CONFIRMED" && r.paymentMethod === "PAYOS";
+ Object.assign(r, { status: "CANCELLED", cancelledAt: new Date(), cancellationReason: body?.reason, ...(paid ? { refundAmount: r.estimatedAmount + r.requiredDeposit - Math.round(r.estimatedAmount * 0.1), refundStatus: "PENDING" } : {}) });
return send(200, { message: "Đã hủy đơn đặt chỗ thành công." });
}
+ if (req.method === "POST" && (path === "/api/v1/reservations/create-payos-qr" || path === "/api/reservations/create-payos-qr")) {
+ const resId = body?.reservationId;
+ const r = S.reservations.find((x) => x.reservationId === resId);
+ // Đơn của khách đang chờ thanh toán → dùng chung PayOS giả lập (QR + webhook /__payos/paid) như /api/reservations/{id}/payos
+ if (r && r.customerId === me) {
+ if (r.status !== "PENDING_PAYMENT") return bad("Đơn đặt chỗ này không còn chờ thanh toán.");
+ return send(200, { reservationId: r.reservationId, ...payosOrder("reservation", r.reservationId, r.estimatedAmount + r.requiredDeposit, `SS${String(r.reservationId).padStart(4, "0")}`) });
+ }
+ const amount = body?.amount || (r ? (r.estimatedAmount + (r.requiredDeposit > 0 ? r.requiredDeposit : 0)) : 1000000);
+ const orderCode = Date.now() % 1000000000;
+ const checkoutUrl = `https://pay.payos.vn/web/mock-${resId || orderCode}`;
+ return send(200, {
+ reservationId: resId || 1,
+ orderCode,
+ checkoutUrl,
+ qrCode: checkoutUrl,
+ amount,
+ });
+ }
+ if (req.method === "GET" && (m = path.match(/^\/api(?:\/v1)?\/reservations\/(\d+)\/status$/))) {
+ const r = S.reservations.find((x) => x.reservationId === +m[1]);
+ if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." });
+ const isPaid = r.status === "CONFIRMED" || r.status === "PAID";
+ return send(200, { reservationId: r.reservationId, status: r.status, isPaid, paidAt: isPaid ? iso(new Date()) : null });
+ }
// ---- Hợp đồng
if (req.method === "GET" && path === "/api/contracts") return send(200, S.contracts.filter((c) => c.customerId === me).map(contractSummary));
@@ -453,19 +666,45 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M
return send(201, { ...r, requestedAt: iso(r.requestedAt), approvedAt: null });
}
if (req.method === "GET" && (m = path.match(/^\/api\/contracts\/(\d+)\/payments$/))) return send(200, S.payments.filter((p) => p.contractId === +m[1]).map(payDto));
+ const myPayment = (id) => S.payments.find((p) => p.paymentId === id && S.contracts.some((c) => c.contractId === p.contractId && c.customerId === me));
+ if (req.method === "GET" && (m = path.match(/^\/api\/payments\/(\d+)$/))) {
+ const p = myPayment(+m[1]);
+ return p ? send(200, payDto(p)) : send(404, { error: "Không tìm thấy khoản thanh toán." });
+ }
+ if (req.method === "POST" && (m = path.match(/^\/api\/payments\/(\d+)\/payos$/))) {
+ const p = myPayment(+m[1]);
+ if (!p) return send(404, { error: "Không tìm thấy khoản thanh toán." });
+ if (p.status === "PAID") return bad("Khoản này đã được thanh toán.");
+ return send(200, payosOrder("payment", p.paymentId, p.amount, (p.transactionReference || `TT${p.paymentId}`).replaceAll("-", "")));
+ }
+ if (req.method === "GET" && (m = path.match(/^\/api\/contracts\/(\d+)\/access-qr$/))) {
+ const c = S.contracts.find((x) => x.contractId === +m[1] && x.customerId === me);
+ if (!c) return send(404, { error: "Không tìm thấy hợp đồng." });
+ const h = S.handovers.find((x) => x.contractId === c.contractId);
+ if (c.status !== "ACTIVE" || !h || h.status !== "HANDED_OVER") return bad("QR mở cửa chỉ dùng được sau khi nhận kho và khi hợp đồng còn hiệu lực.");
+ const u = unit(c.unitId);
+ const a = accessCode(c);
+ return send(200, { contractId: c.contractId, code: a.code, backupCode: a.backup, unitNumber: u.unitNumber, unitType: ut(u.unitTypeId).climateControlled ? "Kho lạnh" : "Kho thường", location: null, validUntil: c.endDate });
+ }
if (req.method === "POST" && (m = path.match(/^\/api\/handovers\/(\d+)\/confirm$/))) {
const h = S.handovers.find((x) => x.handoverId === +m[1]);
if (!h) return bad("Không tìm thấy biên bản bàn giao phù hợp.");
h.customerConfirmed = true;
return send(200, { message: "Đã xác nhận bàn giao." });
}
+ if (req.method === "POST" && (m = path.match(/^\/api\/contracts\/(\d+)\/move-out$/))) {
+ const c = S.contracts.find((x) => x.contractId === +m[1] && x.customerId === me);
+ if (!c) return send(404, { error: "Không tìm thấy hợp đồng." });
+ c.status = "RETURN_PENDING";
+ return send(200, { inspectionId: 1, contractId: c.contractId, status: "SCHEDULED", message: "Đăng ký trả kho thành công." });
+ }
// ---- Hỗ trợ
if (req.method === "GET" && path === "/api/tickets") return send(200, S.tickets.filter((t) => t.customerId === me).map(ticketDto));
if (req.method === "GET" && (m = path.match(/^\/api\/tickets\/(\d+)$/))) {
const t = S.tickets.find((x) => x.ticketId === +m[1] && x.customerId === me);
if (!t) return send(404, { error: "Không tìm thấy yêu cầu hỗ trợ." });
- return send(200, { ...ticketDto(t), contractUnitNumber: unit(S.contracts.find((c) => c.contractId === t.contractId).unitId).unitNumber, description: t.description, assignedAt: null });
+ return send(200, { ...ticketDto(t), contractUnitNumber: unit(S.contracts.find((c) => c.contractId === t.contractId).unitId).unitNumber, description: t.description, assignedAt: null, responses: (t.responses || []).map((x) => ({ ...x, createdAt: dbTime(x.createdAt) })) });
}
if (req.method === "POST" && path === "/api/tickets") {
const c = S.contracts.find((x) => x.contractId === body.contractId && x.customerId === me);
@@ -482,14 +721,14 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M
return send(200, { message: "Đã hủy yêu cầu hỗ trợ." });
}
// ---- Khu vận hành (chỉ khi bật ops)
- if (O && path.startsWith("/api/ops/")) {
+ if (O && (path.startsWith("/api/ops/") || path.startsWith("/api/staff/") || path.startsWith("/api/manager/"))) {
const u = auth();
if (!u) return send(401);
const roleNames = S.userRoles.filter((r) => r.userId === u.userId).map((r) => S.roles.find((x) => x.roleId === r.roleId).roleName);
const isManager = roleNames.includes("MANAGER");
if (!isManager && !roleNames.includes("STAFF")) return send(403, { error: "Chỉ nhân viên hoặc quản lý cơ sở được truy cập." });
const me = O.staff.find((x) => x.full_name === u.fullName) || null;
- if (req.method === "GET" && path === "/api/ops/board") {
+ if (req.method === "GET" && (path === "/api/ops/board" || path === "/api/staff/board" || path === "/api/manager/board")) {
const { log: _log, version: _v, ...all } = O;
const board = isManager ? all : Object.fromEntries(STAFF_PARTS.map((k) => [k, O[k]]));
return send(200, mapKeys({ ...board, me }, camel));
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs
new file mode 100644
index 0000000..d0f7d1d
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs
@@ -0,0 +1,262 @@
+// Phần /api/operations/* (Quản lý vận hành KD, role OPERATIONS) của máy chủ giả lập — bật bằng { business: true }.
+// Theo hợp đồng docs/operations-api.md; số liệu tính đơn giản từ dữ liệu giả lập, không thay backend thật.
+
+const pad = (n) => String(n).padStart(2, "0");
+const dateOnly = (d) => `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
+const todayIso = () => dateOnly(new Date(Date.now() + 7 * 3600000));
+const dbTime = (d) => d.toISOString().replace("Z", "").replace(/\.\d+$/, "");
+const IN_USE = ["OCCUPIED", "RETURN_PENDING"];
+const UNAVAILABLE = ["MAINTENANCE", "OUT_OF_SERVICE", "INSPECTION"];
+
+export function seedBusiness(S) {
+ const now = new Date();
+ const from = dateOnly(new Date(Date.now() - 30 * 86400000));
+ const p = (policyId, policyName, policyType, calculationType, value, ruleDescription, extra = {}) => ({
+ policyId, policyName, policyType, calculationType, value, minValue: null, maxValue: null, ruleDescription,
+ facilityId: null, unitTypeId: null, effectiveFrom: from, effectiveTo: null, status: "ACTIVE", createdBy: 1, createdAt: now, updatedAt: now, ...extra,
+ });
+ S.policies = [
+ p(1, "Mức đặt cọc mặc định", "DEPOSIT", "FIXED", 1, "Đặt cọc tương đương 1 tháng tiền thuê khi đặt chỗ"),
+ p(2, "Thông báo trước khi hết hạn", "RENEWAL", "FIXED", 7, "Thông báo trước khi hết hạn: 7 ngày\nSố lần gia hạn tối đa: Không giới hạn"),
+ p(3, "Phí huỷ trước ngày nhận kho", "CANCELLATION", "RULE", null, "Miễn phí nếu huỷ trước 48 giờ"),
+ p(4, "Hoàn cọc sau khi trả kho", "RETURN", "RULE", null, "Hoàn cọc trong vòng: 5 ngày làm việc sau khi trả kho\nThời gian kiểm tra sau khi trả kho: 24 giờ"),
+ p(5, "Phí phạt quá hạn / ngày", "OVERDUE", "FIXED", 20000, "Số ngày ân hạn trước khi khoá quyền truy cập: 3 ngày"),
+ p(6, "Thuê từ 6 tháng trở lên", "DISCOUNT", "PERCENTAGE", 10, "Giảm 10% tổng phí thuê"),
+ p(7, "Giới thiệu bạn bè đăng ký mới", "FEE_WAIVER", "RULE", null, "Miễn phí dịch vụ tháng đầu", { status: "DRAFT" }),
+ ];
+ // Preview fixtures only; opt-in startMockApi({ business:true }) never writes to SQL Server.
+ for (const [i, type] of S.unitTypes.entries()) {
+ const min = [700000, 1200000, 1800000, 2500000][i] || 700000;
+ const max = [1400000, 2200000, 3500000, 5000000][i] || 1400000;
+ S.policies.push(p(S.policies.length + 1, `Khung giá ${type.typeName}`, 'PRICE_RANGE', 'RANGE', null, 'Khoảng giá thuê theo tháng', {unitTypeId:type.unitTypeId,minValue:min,maxValue:max}));
+ S.policies.push(p(S.policies.length + 1, `Phí dịch vụ ${type.typeName}`, 'EXTRA_FEE', 'FIXED', [50000,80000,100000,120000][i] || 50000, 'Phí dịch vụ theo tháng', {unitTypeId:type.unitTypeId}));
+ }
+}
+
+export function handleBusiness({ req, res, path, url, body, S, me, send }) {
+ if (!path.startsWith("/api/operations")) return false;
+ const roleNames = S.userRoles.filter((r) => r.userId === me).map((r) => S.roles.find((x) => x.roleId === r.roleId)?.roleName);
+ if (!roleNames.includes("OPERATIONS")) return send(403), true;
+ const bad = (error) => (send(400, { error }), true);
+ const notFound = (error) => (send(404, { error }), true);
+ const fac = (id) => S.facilities.find((f) => f.facilityId === id);
+ const ut = (id) => S.unitTypes.find((t) => t.unitTypeId === id);
+ const today = todayIso();
+ const num = (k) => (url.searchParams.get(k) ? Number(url.searchParams.get(k)) : null);
+ let m;
+
+ const metrics = (units, contracts, payments) => {
+ const inUse = units.filter((u) => IN_USE.includes(u.status)).length;
+ const unavailable = units.filter((u) => UNAVAILABLE.includes(u.status)).length;
+ const operable = units.length - unavailable;
+ const paid = payments.filter((x) => x.status === "PAID");
+ const sum = (list) => list.reduce((s, x) => s + Number(x.amount), 0);
+ const overdue = contracts.filter((c) => c.status === "OVERDUE").length;
+ return {
+ collected: sum(paid.filter((x) => x.paymentType !== "REFUND")),
+ refunded: sum(paid.filter((x) => x.paymentType === "REFUND")),
+ netCollected: sum(paid.filter((x) => x.paymentType !== "REFUND")) - sum(paid.filter((x) => x.paymentType === "REFUND")),
+ rentalAndFeeRevenue: sum(paid.filter((x) => !["DEPOSIT", "REFUND"].includes(x.paymentType))),
+ depositCollected: sum(paid.filter((x) => x.paymentType === "DEPOSIT")),
+ depositHeld: sum(paid.filter((x) => x.paymentType === "DEPOSIT")),
+ outstanding: sum(payments.filter((x) => ["PENDING", "FAILED"].includes(x.status))),
+ totalUnits: units.length,
+ unitsInUse: inUse,
+ unitsAvailable: units.filter((u) => u.status === "AVAILABLE").length,
+ unitsReserved: units.filter((u) => ["RESERVED", "ASSIGNED"].includes(u.status)).length,
+ unitsUnavailable: unavailable,
+ operableUnits: operable,
+ occupancyRate: operable ? Math.round((inUse / operable) * 1000) / 10 : null,
+ activeContracts: contracts.filter((c) => ["ACTIVE", "EXPIRING", "OVERDUE", "RETURN_PENDING"].includes(c.status)).length,
+ overdueCases: overdue,
+ overdueContracts: overdue,
+ overdueUnits: new Set(contracts.filter(c => c.status === "OVERDUE").map(c => c.unitId)).size,
+ };
+ };
+ const scoped = (facilityId, unitTypeId) => {
+ const units = S.units.filter((u) => (!facilityId || u.facilityId === facilityId) && (!unitTypeId || u.unitTypeId === unitTypeId));
+ const ids = new Set(units.map((u) => u.unitId));
+ const contracts = S.contracts.filter((c) => ids.has(c.unitId));
+ const cids = new Set(contracts.map((c) => c.contractId));
+ return { units, contracts, payments: S.payments.filter((x) => cids.has(x.contractId)) };
+ };
+ const filter = () => ({ from: url.searchParams.get("from") || `${today.slice(0, 7)}-01`, to: url.searchParams.get("to") || today, facilityId: num("facilityId"), unitTypeId: num("unitTypeId") });
+
+ // ---- Cơ sở
+ const facilityDto = (f) => {
+ const { units } = scoped(f.facilityId);
+ const mm = metrics(units, [], []);
+ return {
+ facilityId: f.facilityId, name: f.name, address: f.address, contactPhone: f.contactPhone, openingTime: f.openingTime, closingTime: f.closingTime,
+ status: f.status, totalUnits: units.length, unitsInUse: mm.unitsInUse, operableUnits: mm.operableUnits, occupancyRate: mm.occupancyRate,
+ pricedUnitTypes: new Set(S.rates.filter((r) => r.facilityId === f.facilityId && (r.status ?? "ACTIVE") === "ACTIVE").map((r) => r.unitTypeId)).size,
+ assignedStaff: f.facilityId === 1 ? 2 : 0, managerName: f.facilityId === 1 ? "Phạm Thu Hà" : null,
+ createdAt: "2026-09-15T12:40:41", updatedAt: "2026-09-15T12:40:41",
+ latitude: f.latitude ?? null, longitude: f.longitude ?? null,
+ };
+ };
+ if (req.method === "GET" && path === "/api/operations/facilities") return send(200, S.facilities.map(facilityDto)), true;
+ if (req.method === "POST" && path === "/api/operations/facilities") {
+ if (!body?.name?.trim() || !body?.address?.trim()) return bad("Tên và địa chỉ cơ sở là bắt buộc.");
+ const f = { facilityId: S.facilities.length + 1, name: body.name.trim(), address: body.address.trim(), contactPhone: body.contactPhone, openingTime: body.openingTime, closingTime: body.closingTime, status: "ACTIVE", latitude: body.latitude ?? null, longitude: body.longitude ?? null };
+ S.facilities.push(f);
+ return send(201, { facility: facilityDto(f), warnings: ["Cơ sở đang hoạt động nhưng chưa có bảng giá, ô kho hoặc nhân sự."] }), true;
+ }
+ if ((m = path.match(/^\/api\/operations\/facilities\/(\d+)(\/status)?$/))) {
+ const f = fac(+m[1]);
+ if (!f) return notFound("Không tìm thấy cơ sở.");
+ if (req.method === "PUT" && m[2]) {
+ if (body?.status === "INACTIVE" && S.contracts.some((c) => S.units.find((u) => u.unitId === c.unitId)?.facilityId === f.facilityId && c.status === "ACTIVE"))
+ return send(409, { error: "Cơ sở còn hợp đồng đang xử lý.", details: { openContracts: 1, openReservations: 0 } }), true;
+ f.status = body.status;
+ return send(200, { facility: facilityDto(f), warnings: [] }), true;
+ }
+ if (req.method === "PUT") {
+ if ((body.latitude == null) !== (body.longitude == null)) return bad("Cần nhập cả vĩ độ và kinh độ, hoặc để trống cả hai.");
+ Object.assign(f, { name: body.name, address: body.address, contactPhone: body.contactPhone, openingTime: body.openingTime, closingTime: body.closingTime, latitude: body.latitude ?? null, longitude: body.longitude ?? null });
+ return send(200, { facility: facilityDto(f), warnings: [] }), true;
+ }
+ if (req.method === "GET") return send(200, facilityDto(f)), true;
+ }
+
+ // ---- Chính sách
+ const policyDto = (x) => ({
+ ...x, scope: x.facilityId && x.unitTypeId ? "FACILITY_UNIT_TYPE" : x.facilityId ? "FACILITY" : x.unitTypeId ? "UNIT_TYPE" : "GLOBAL",
+ facilityName: x.facilityId ? fac(x.facilityId)?.name : null, unitTypeName: x.unitTypeId ? ut(x.unitTypeId)?.typeName : null,
+ createdByName: "Lê Vận Hành", createdAt: dbTime(x.createdAt), updatedAt: dbTime(x.updatedAt),
+ });
+ const validate = (b) => {
+ if (!b?.policyName?.trim() || !b?.ruleDescription?.trim()) return "Tên và mô tả chính sách là bắt buộc.";
+ if (b.calculationType === "RANGE" && !(b.minValue <= b.maxValue)) return "Khoảng giá không hợp lệ.";
+ if (b.calculationType === "PERCENTAGE" && !(b.value >= 0 && b.value <= 100)) return "Phần trăm từ 0 đến 100.";
+ if (b.value < 0) return "Giá trị không được âm.";
+ return null;
+ };
+ if (req.method === "GET" && path === "/api/operations/policies") {
+ const type = url.searchParams.get("type");
+ const status = url.searchParams.get("status");
+ return send(200, S.policies.filter((x) => (!type || x.policyType === type) && (!status || x.status === status)).map(policyDto)), true;
+ }
+ if (req.method === "POST" && path === "/api/operations/policies") {
+ const err = validate(body);
+ if (err) return bad(err);
+ const x = { ...body, policyId: S.policies.length + 1, status: "DRAFT", createdBy: me, createdAt: new Date(), updatedAt: new Date() };
+ S.policies.push(x);
+ return send(201, policyDto(x)), true;
+ }
+ if ((m = path.match(/^\/api\/operations\/policies\/(\d+)(\/activate|\/deactivate)?$/))) {
+ const x = S.policies.find((y) => y.policyId === +m[1]);
+ if (!x) return notFound("Không tìm thấy chính sách.");
+ if (m[2] === "/activate" && req.method === "POST") {
+ if (x.status === "ACTIVE") return bad("Chính sách đang được áp dụng.");
+ const conflicts = S.policies.filter(y => y !== x && y.status === 'ACTIVE' && y.policyType === x.policyType
+ && (y.facilityId ?? null) === (x.facilityId ?? null) && (y.unitTypeId ?? null) === (x.unitTypeId ?? null)
+ && (!y.effectiveTo || y.effectiveTo >= x.effectiveFrom) && (!x.effectiveTo || x.effectiveTo >= y.effectiveFrom));
+ if (conflicts.length && url.searchParams.get("replaceExisting") !== "true")
+ return send(409, { error: "Đã có chính sách cùng loại và cùng phạm vi đang áp dụng.", details: { conflictingPolicyIds: conflicts.map((c) => c.policyId) } }), true;
+ for (const c of conflicts) c.status = "INACTIVE";
+ x.status = "ACTIVE";
+ return send(200, { policy: policyDto(x), superseded: conflicts.map(policyDto) }), true;
+ }
+ if (m[2] === "/deactivate" && req.method === "POST") {
+ x.status = "INACTIVE";
+ return send(200, policyDto(x)), true;
+ }
+ if (req.method === "PUT") {
+ if (x.status !== "DRAFT") return bad("Chỉ sửa được chính sách ở trạng thái nháp.");
+ const err = validate(body);
+ if (err) return bad(err);
+ Object.assign(x, body, { updatedAt: new Date() });
+ return send(200, policyDto(x)), true;
+ }
+ if (req.method === "DELETE") {
+ if (x.status !== "DRAFT") return bad("Chỉ xoá được chính sách nháp.");
+ S.policies.splice(S.policies.indexOf(x), 1);
+ return send(204), true;
+ }
+ }
+
+ // ---- Bảng giá
+ if (req.method === "GET" && path === "/api/operations/rates") {
+ const fid = num("facilityId");
+ return send(200, S.rates.filter((r) => (!fid || r.facilityId === fid) && (r.status ?? "ACTIVE") === "ACTIVE").map((r) => ({ ...r, isCurrent: r.effectiveFrom <= today && (!r.effectiveTo || r.effectiveTo >= today) }))), true;
+ }
+ if (req.method === "POST" && path === "/api/operations/rates") {
+ if (!(body?.monthlyRate > 0) || body.monthlyRate % 1000) return bad("Giá thuê phải lớn hơn 0 và là bội số của 1.000 đ.");
+ const from = body.effectiveFrom || today;
+ if (from < today) return bad("Ngày áp dụng không được ở quá khứ.");
+ for (const r of S.rates.filter((x) => x.facilityId === body.facilityId && x.unitTypeId === body.unitTypeId && (x.status ?? "ACTIVE") === "ACTIVE")) {
+ if (r.effectiveFrom >= from) r.status = "INACTIVE";
+ else r.effectiveTo = dateOnly(new Date(new Date(`${from}T00:00:00Z`).getTime() - 86400000));
+ }
+ const r = { rateId: S.rates.length + 1, facilityId: body.facilityId, facilityName: fac(body.facilityId)?.name, unitTypeId: body.unitTypeId, unitTypeName: ut(body.unitTypeId)?.typeName, monthlyRate: body.monthlyRate, effectiveFrom: from, effectiveTo: null, status: "ACTIVE" };
+ S.rates.push(r);
+ return send(200, { ...r, isCurrent: from <= today }), true;
+ }
+
+ // ---- Báo cáo
+ const snapshotAt = dbTime(new Date());
+ if (req.method === "GET" && path === "/api/operations/reports/facilities") {
+ const fl = filter();
+ const rows = S.facilities.filter((f) => !fl.facilityId || f.facilityId === fl.facilityId).map((f) => {
+ const s = scoped(f.facilityId, fl.unitTypeId);
+ return { facilityId: f.facilityId, facilityName: f.name, facilityStatus: f.status, metrics: metrics(s.units, s.contracts, s.payments) };
+ });
+ const all = scoped(fl.facilityId, fl.unitTypeId);
+ return send(200, { filter: fl, snapshotAt, totals: metrics(all.units, all.contracts, all.payments), facilities: rows }), true;
+ }
+ if (req.method === "GET" && path === "/api/operations/reports/unit-types") {
+ const fl = filter();
+ const rows = S.unitTypes.map((t) => {
+ const s = scoped(fl.facilityId, t.unitTypeId);
+ return { unitTypeId: t.unitTypeId, unitTypeName: t.typeName, metrics: metrics(s.units, s.contracts, s.payments) };
+ });
+ const all = scoped(fl.facilityId, fl.unitTypeId);
+ return send(200, { filter: fl, snapshotAt, totals: metrics(all.units, all.contracts, all.payments), unitTypes: rows }), true;
+ }
+ if (req.method === "GET" && path === "/api/operations/reports/revenue-trend") {
+ const n = num("months") || 6;
+ const [y, mo] = today.split("-").map(Number);
+ const months = Array.from({ length: n }, (_, i) => {
+ const d = new Date(Date.UTC(y, mo - n + i, 1));
+ const base = i === n - 1 ? 3000000 : 0;
+ return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, label: `${pad(d.getUTCMonth() + 1)}/${d.getUTCFullYear()}`, collected: base * 1.5, refunded: 0, rentalAndFeeRevenue: base, depositCollected: base / 2 };
+ });
+ return send(200, { facilityId: num("facilityId"), unitTypeId: null, snapshotAt, months }), true;
+ }
+ if (req.method === "GET" && path === "/api/operations/reports/rental-status") {
+ const s = scoped(num("facilityId"));
+ const count = (list) => Object.entries(list.reduce((a, x) => ({ ...a, [x.status]: (a[x.status] || 0) + 1 }), {})).map(([status, n]) => ({ status, count: n }));
+ const rids = new Set(s.units.map((u) => u.facilityId));
+ return send(200, { facilityId: num("facilityId"), unitTypeId: null, snapshotAt, contracts: count(s.contracts), reservations: count(S.reservations.filter((r) => rids.has(r.facilityId))), units: count(s.units) }), true;
+ }
+ if (req.method === "GET" && path === "/api/operations/reports/export") {
+ const view = url.searchParams.get("view") || "facilities";
+ const fl = filter();
+ const rows = [[`Báo cáo ${view}`], ['Từ', fl.from, 'Đến', fl.to]];
+ if (view === 'facilities') {
+ rows.push(['Cơ sở', 'Doanh thu', 'Tỷ lệ lấp đầy', 'Kho quá hạn']);
+ for (const f of S.facilities.filter(f => !fl.facilityId || f.facilityId === fl.facilityId)) {
+ const s = scoped(f.facilityId, fl.unitTypeId), m = metrics(s.units, s.contracts, s.payments);
+ rows.push([f.name, m.rentalAndFeeRevenue, m.occupancyRate, m.overdueUnits]);
+ }
+ } else if (view === 'unit-types') {
+ rows.push(['Loại kho', 'Doanh thu', 'Tỷ lệ lấp đầy', 'Kho quá hạn']);
+ for (const t of S.unitTypes.filter(t => !fl.unitTypeId || t.unitTypeId === fl.unitTypeId)) {
+ const s = scoped(fl.facilityId, t.unitTypeId), m = metrics(s.units, s.contracts, s.payments);
+ rows.push([t.typeName, m.rentalAndFeeRevenue, m.occupancyRate, m.overdueUnits]);
+ }
+ } else if (view === 'revenue-trend') {
+ rows.push(['Tháng', 'Đã thu', 'Hoàn', 'Thuê và phí', 'Tiền cọc']);
+ for (let d = new Date(fl.from.slice(0, 7) + '-01T00:00:00Z'); d.toISOString().slice(0, 10) <= fl.to; d.setUTCMonth(d.getUTCMonth() + 1)) {
+ const current = d.toISOString().slice(0, 7) === today.slice(0, 7), revenue = current ? 3000000 : 0;
+ rows.push([`${d.getUTCMonth() + 1}/${d.getUTCFullYear()}`, revenue * 1.5, 0, revenue, revenue / 2]);
+ }
+ } else return bad('view không hợp lệ.');
+ const csv = '\ufeff' + rows.map(row => row.map(v => '"' + String(v ?? '').replaceAll('"', '""') + '"').join(',')).join('\r\n');
+ res.writeHead(200, { "Access-Control-Allow-Origin": "*", "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="bao-cao-${view}.csv"` });
+ res.end(csv);
+ return true;
+ }
+ return send(404, { error: "Not found" }), true;
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package-lock.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package-lock.json
index 124f8cc..815f6da 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package-lock.json
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package-lock.json
@@ -15,6 +15,7 @@
"react-dom": "^19.3.0"
},
"devDependencies": {
+ "@playwright/test": "^1.64.1",
"vite": "^8.3.0"
},
"engines": {
@@ -40,6 +41,22 @@
"url": "https://github.com/sponsors/oxc-project"
}
},
+ "node_modules/@playwright/test": {
+ "version": "1.64.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz",
+ "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright": "1.64.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz",
@@ -822,6 +839,35 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/playwright": {
+ "version": "1.64.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",
+ "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.64.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.64.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
+ "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/pngjs": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json
index 47e7587..e231c0f 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json
@@ -4,12 +4,16 @@
"private": true,
"type": "module",
"scripts": {
+ "test:auth-support": "playwright test",
+ "dev:business": "node scripts/dev-business.mjs",
+ "test:business": "node --test tests/business-frontend.test.mjs",
"dev": "vite --host 127.0.0.1",
"build": "vite build --base=./",
"preview": "vite preview --host 127.0.0.1",
- "test": "node --test tests/reducer.test.js tests/api-mappers.test.js tests/admin.test.js tests/ops.test.js tests/units.test.js tests/ops-api.test.mjs",
+ "test": "node --test tests/reducer.test.js tests/api-mappers.test.js tests/admin.test.js tests/ops.test.js tests/units.test.js tests/ops-api.test.mjs tests/payment-access.test.js tests/payment-api.test.mjs tests/access.test.js",
"test:render": "node tests/render.test.mjs",
- "dev:mock": "node scripts/dev-mock.mjs"
+ "dev:mock": "node scripts/dev-mock.mjs",
+ "check:structure": "node scripts/check-structure.mjs"
},
"dependencies": {
"@fontsource/inter": "^5.3.0",
@@ -19,6 +23,7 @@
"react-dom": "^19.3.0"
},
"devDependencies": {
+ "@playwright/test": "^1.64.1",
"vite": "^8.3.0"
},
"engines": {
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/playwright.config.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/playwright.config.js
new file mode 100644
index 0000000..b8b85e6
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/playwright.config.js
@@ -0,0 +1,23 @@
+import { defineConfig } from "@playwright/test";
+
+export default defineConfig({
+ testDir: "./tests",
+ testMatch: "auth-support.spec.js",
+ fullyParallel: false,
+ workers: 1,
+ reporter: "list",
+ use: {
+ baseURL: "http://127.0.0.1:5273",
+ browserName: "chromium",
+ viewport: { width: 1440, height: 922 },
+ launchOptions: process.env.PLAYWRIGHT_EXECUTABLE_PATH
+ ? { executablePath: process.env.PLAYWRIGHT_EXECUTABLE_PATH, args: ["--no-sandbox", "--disable-dev-shm-usage"] }
+ : {},
+ },
+ webServer: {
+ command: "npm run dev -- --port 5273 --strictPort",
+ url: "http://127.0.0.1:5273",
+ reuseExistingServer: false,
+ env: { VITE_USE_API: "true", VITE_API_URL: "http://127.0.0.1:5273" },
+ },
+});
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/LICENSE b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/LICENSE
new file mode 100644
index 0000000..462280f
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/LICENSE
@@ -0,0 +1,93 @@
+Copyright 2019 The Manrope Project Authors (https://github.com/sharanda/manrope)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-latin-700-normal.woff2 b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-latin-700-normal.woff2
new file mode 100644
index 0000000..84f7af5
Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-latin-700-normal.woff2 differ
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-vietnamese-700-normal.woff2 b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-vietnamese-700-normal.woff2
new file mode 100644
index 0000000..0d36914
Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-vietnamese-700-normal.woff2 differ
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/bell.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/bell.svg
new file mode 100644
index 0000000..82bdbf4
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/bell.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/brand.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/brand.svg
new file mode 100644
index 0000000..c0d7d5e
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/brand.svg
@@ -0,0 +1,12 @@
+
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-structure.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-structure.mjs
new file mode 100644
index 0000000..0bf92f3
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-structure.mjs
@@ -0,0 +1,36 @@
+import { readdirSync, readFileSync } from 'node:fs';
+import { dirname, join, basename, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..', 'src');
+const allowed = new Set(['main.jsx', 'app', 'features', 'shared', 'assets']);
+const errors = [];
+for (const entry of readdirSync(root)) {
+ if (!allowed.has(entry)) errors.push(`Unexpected src entry: ${entry}`);
+}
+function inspect(directory) {
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
+ const file = join(directory, entry.name);
+ const name = relative(root, file);
+ if (entry.isDirectory()) {
+ if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(entry.name)) errors.push(`Use kebab-case directory: ${name}`);
+ inspect(file);
+ } else if (entry.name.endsWith('.jsx')) {
+ if (entry.name !== 'main.jsx' && !/^[A-Z][A-Za-z0-9]*\.jsx$/.test(entry.name)) errors.push(`Use PascalCase JSX filename: ${name}`);
+ if (entry.name.endsWith('Page.jsx')) {
+ const source = readFileSync(file, 'utf8');
+ const component = basename(file, '.jsx');
+ if (!new RegExp(`export (?:default )?function ${component}\\b`).test(source)) errors.push(`Export a page component named ${component}: ${name}`);
+ const pages = [...source.matchAll(/export (?:default )?function (\w+Page)\b/g)];
+ if (pages.length !== 1) errors.push(`Keep one page per file: ${name}`);
+ }
+ } else if (entry.name.endsWith('.js') && !/^[a-z][A-Za-z0-9]*\.js$/.test(entry.name)) {
+ errors.push(`Use camelCase JS filename: ${name}`);
+ }
+ }
+}
+inspect(root);
+if (errors.length) {
+ console.error(errors.join('\n'));
+ process.exitCode = 1;
+} else console.log('Frontend structure and page naming: PASS');
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-business.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-business.mjs
new file mode 100644
index 0000000..c3dc592
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-business.mjs
@@ -0,0 +1,12 @@
+// Frontend-only preview: mock requests follow operations-api(3).md; no .NET/SQL Server needed.
+import { createServer } from 'vite';
+import { startMockApi } from '../mock/mock-api.mjs';
+const apiPort = Number(process.env.MOCK_API_PORT) || 5199;
+process.env.VITE_USE_API = 'true';
+process.env.VITE_API_URL = `http://localhost:${apiPort}`;
+const {server} = await startMockApi(apiPort, {business:true,ops:true});
+const vite = await createServer({server:{host:'127.0.0.1',port:5173}});
+await vite.listen();vite.printUrls();
+console.log('Đăng nhập ops01 / Ops@123 để mở #/business. Chế độ này chỉ dùng API giả lập trong bộ nhớ để kiểm tra frontend.');
+const close = async () => { await vite.close();server.close();process.exit(0); };
+process.on('SIGINT',close);process.on('SIGTERM',close);
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs
index 5e26292..2a0abfa 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs
@@ -5,13 +5,15 @@ import { createServer } from "vite";
import { startMockApi } from "../mock/mock-api.mjs";
const API_PORT = Number(process.env.MOCK_API_PORT) || 5151;
+const AUTOPAY = Number(process.env.MOCK_PAYOS_AUTOPAY ?? 10);
// Biến VITE_* có sẵn trong môi trường được Vite ưu tiên hơn file .env
process.env.VITE_USE_API = "true";
process.env.VITE_API_URL = `http://localhost:${API_PORT}`;
try {
- await startMockApi(API_PORT, { verbose: true, ops: process.env.MOCK_OPS === "1" });
+ // PayOS giả lập tự báo "đã thanh toán" sau 10 giây (đổi bằng MOCK_PAYOS_AUTOPAY, 0 = chỉ khi gọi /__payos/paid)
+ await startMockApi(API_PORT, { verbose: true, ops: process.env.MOCK_OPS === "1", payosAutoPaySeconds: AUTOPAY });
} catch (e) {
console.error(`Không mở được cổng ${API_PORT} (có thể backend thật đang chạy). Đặt MOCK_API_PORT=5199 rồi chạy lại.`);
process.exit(1);
@@ -26,7 +28,9 @@ console.log(`
customer01 / Customer@123 → Khách hàng
staff01 / Staff@123 → Nhân viên cơ sở (#/staff)
manager01 / Manager@123 → Quản lý cơ sở (#/manager) — chỉ khi chạy với MOCK_OPS=1
- MOCK_OPS=1 bật các endpoint /api/ops/* (backend thật CHƯA có, xem BE-CONTRACT.md mục 5).
- Không bật: khu vận hành báo "backend chưa có API" và dùng dữ liệu mẫu trong trình duyệt.
+ MOCK_OPS=1 bật các endpoint /api/ops/* (giống backend thật, xem docs/facility-ops-api.md).
+ Không bật: khu vận hành dùng dữ liệu cục bộ trong trình duyệt.
+ PayOS giả lập: mã QR tự được "thanh toán" sau ${AUTOPAY} giây (MOCK_PAYOS_AUTOPAY=0 để tắt; gọi
+ http://localhost:${API_PORT}/__payos/paid để báo đã trả ngay). Máy quét cửa kho: #/door.
Mỗi lời gọi API sẽ hiện bên dưới (xanh = thành công, đỏ = lỗi từ máy chủ).
`);
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx
deleted file mode 100644
index bfc7018..0000000
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx
+++ /dev/null
@@ -1,184 +0,0 @@
-import "@fontsource/inter/latin-400.css";
-import "@fontsource/inter/vietnamese-400.css";
-import "@fontsource/inter/latin-500.css";
-import "@fontsource/inter/vietnamese-500.css";
-import "@fontsource/inter/latin-600.css";
-import "@fontsource/inter/vietnamese-600.css";
-import "@fontsource/inter/latin-700.css";
-import "@fontsource/inter/vietnamese-700.css";
-import "@fontsource/inter/latin-800.css";
-import "@fontsource/inter/vietnamese-800.css";
-import "./styles/ss.css";
-import React, { useEffect } from "react";
-import Header from "./components/Header";
-import { Button, Empty, Icon, LinkButton } from "./components/UI";
-import { go, parseRoute, useRoute } from "./lib/router";
-import { Login, Register } from "./pages/Auth";
-import { Checkout, CheckoutFailed, ReservationSummary } from "./pages/Checkout";
-import FacilityDetail from "./pages/FacilityDetail";
-import FindList from "./pages/FindList";
-import FindMap from "./pages/FindMap";
-import Home from "./pages/Home";
-import Overview from "./pages/Overview";
-import Payments from "./pages/Payments";
-import Profile from "./pages/Profile";
-import { Guide, Pricing } from "./pages/Public";
-import AdminApp from "./admin/AdminApp";
-import { homeFor, isManagerRoles, isOpsRoles, isStaffRoles } from "./lib/roles";
-import OpsApp from "./ops/OpsApp";
-import { OpsProvider } from "./ops/store";
-import Reservations from "./pages/Reservations";
-import Support from "./pages/Support";
-import { Renew, Return, Sent, UnitDetail, Units } from "./pages/Units";
-import { AppProvider, useApp } from "./state/store";
-
-const TITLES = {
- home: "Trang chủ",
- login: "Đăng nhập",
- register: "Đăng ký",
- pricing: "Bảng giá",
- guide: "Hướng dẫn & hỗ trợ",
- find: "Tìm & đặt kho",
- checkout: "Đặt chỗ & thanh toán",
- confirmation: "Xác nhận đặt chỗ",
- overview: "Tổng quan",
- units: "Kho của tôi",
- reservations: "Đơn đặt chỗ",
- payments: "Thanh toán & lịch hẹn",
- sent: "Đã gửi yêu cầu",
- admin: "Quản trị hệ thống",
- staff: "Nhân viên cơ sở",
- manager: "Quản lý cơ sở",
- support: "Hỗ trợ",
- profile: "Tài khoản",
-};
-
-// Trang cần đăng nhập. Các trang công khai: home, login, register, pricing, guide, find (xem cơ sở).
-const PRIVATE = ["overview", "units", "reservations", "payments", "support", "profile", "checkout", "confirmation", "sent"];
-
-function renderPage({ page, parts, query }) {
- const [a, b] = parts;
- switch (page) {
- case "home": return ;
- case "login": return ;
- case "register": return ;
- case "pricing": return ;
- case "guide": return ;
- case "find": return a === "map" ? : a ? : ;
- case "checkout": return b === "failed" ? : ;
- case "confirmation": return ;
- case "overview": return ;
- case "reservations": return a ? : ;
- case "units":
- if (a && b === "renew") return ;
- if (a && b === "return") return ;
- return a ? : ;
- case "sent": return ;
- case "payments": return ;
- case "support": return ;
- case "profile": return ;
- default:
- return (
-
-
- Về trang chủ
-
-
- );
- }
-}
-
-function Shell() {
- const route = useRoute();
- const { authed, toast, dismissToast, storageError, ready, loadError, retry, isAdmin, mode, roles, notify, onApiError } = useApp();
- const isAdminPage = route.page === "admin";
- const isOpsPage = route.page === "staff" || route.page === "manager";
- const opsRole = route.page === "staff" ? "STAFF" : "MANAGER";
- const isOps = isOpsRoles(roles);
- const opsAllowed = route.page === "staff" ? isStaffRoles(roles) || isManagerRoles(roles) : isManagerRoles(roles);
- const needsLogin = (PRIVATE.includes(route.page) || isOpsPage || (isAdminPage && mode === "api")) && !authed;
-
- useEffect(() => {
- document.title = `${TITLES[route.page] || "SafeSpace"} · SafeSpace`;
- }, [route.page]);
- useEffect(() => {
- if (!needsLogin) return;
- // Đăng xuất rồi chuyển trang: hash có thể đã đổi sang trang công khai, khi đó không ép quay lại đăng nhập
- const current = parseRoute(window.location.hash);
- if (!PRIVATE.includes(current.page) && !["admin", "staff", "manager"].includes(current.page)) return;
- go(`login?next=${encodeURIComponent(current.raw)}`, { replace: true });
- }, [needsLogin, route.raw]);
-
- // Tài khoản quản trị / nhân viên / quản lý không dùng các trang khách hàng
- useEffect(() => {
- if ((isAdmin || isOps) && (PRIVATE.includes(route.page) || route.page === "login" || route.page === "register")) go(homeFor(roles), { replace: true });
- }, [isAdmin, isOps, roles, route.page]);
-
- const adminBody =
- mode !== "api" ? (
-
-
- Về trang chủ
-
-
- ) : authed && !isAdmin ? (
-
-
- Về trang của tôi
-
-
- ) : null;
-
- return (
-
- {active ? (
- <>Đang phụ trách {active.facilityName} từ {dateOnlyLabel(active.assignedFrom)}.>
- ) : (
- "Chưa được phân công cơ sở."
- )}{" "}
- Mỗi nhân viên / quản lý chỉ phụ trách một cơ sở tại một thời điểm; phân công mới sẽ tự kết thúc phân công cũ.
-
-
-
-
-
-
- {error && {error}}
- {rows.length > 0 && (
-
-
-
-
Cơ sở
Thời gian
Trạng thái
-
-
- {rows.map((r) => (
-
-
{r.facilityName}Phân công bởi {r.assignerName || "—"}
Trình duyệt không cho lưu dữ liệu, thao tác chỉ giữ trong phiên này.
}
+ {toast && (
+
+
+ {toast.message}
+
+
+ )}
+
+ );
+}
+
+export default function App() {
+ return (
+
+
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/api.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/api.js
similarity index 100%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/api.js
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/api.js
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/geo.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/geo.js
similarity index 100%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/geo.js
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/geo.js
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/media.js
similarity index 91%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/media.js
index 0c27dfb..c635a21 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/media.js
@@ -57,5 +57,6 @@ export function galleryImage(facility, index) {
return { ...item, src };
}
-// Thời gian giữ đơn chờ chuyển khoản (Figma: 01:00). Đổi bằng VITE_PAYMENT_TIMEOUT_SECONDS.
-export const paymentTimeoutSeconds = Number(import.meta.env?.VITE_PAYMENT_TIMEOUT_SECONDS) || 60;
+// Thời gian giữ chỗ khi thanh toán QR PayOS (15 phút). Đổi bằng VITE_PAYMENT_TIMEOUT_SECONDS.
+// Backend nên đặt hạn link PayOS (expiredAt) bằng đúng con số này; giao diện ưu tiên expiredAt backend trả về.
+export const paymentTimeoutSeconds = Number(import.meta.env?.VITE_PAYMENT_TIMEOUT_SECONDS) || 900;
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/payment.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/payment.js
similarity index 100%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/payment.js
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/payment.js
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js
similarity index 64%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js
index 9fadd1c..8d8593b 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js
@@ -1,35 +1,35 @@
-import { localOffers } from "../lib/catalog.js";
-import { addDays, addMonths, today } from "../lib/format.js";
+import { localOffers } from "../../shared/utils/catalog.js";
+import { addDays, addMonths, today } from "../../shared/utils/format.js";
export const SEED_EMAIL = "mai.nguyen@example.com";
export const SEED_PASSWORD = "SafeSpace@123";
-// Danh sách 12 cơ sở SafeSpace (tên, giá, khoảng cách theo Figma C02).
+// Danh sách 12 cơ sở SafeSpace (Figma 14/10). Cơ sở nào cũng có kho thường và kho lạnh, cỡ M và L.
+// Gợi ý theo khu vực khách chọn, không theo vị trí người dùng → không có khoảng cách.
const FACILITIES = [
- [1, "SafeSpace Nguyễn Lương Bằng", "Quận 7", 1.2, 1150000, true, "Số 12 Nguyễn Lương Bằng, Tân Phú"],
- [2, "SafeSpace Him Lam", "Quận 7", 2.8, 1050000, true, "Khu dân cư Him Lam, Tân Hưng"],
- [3, "SafeSpace Phú Xuân", "Quận 7", 5.4, 890000, true, "Đường Nguyễn Hữu Thọ, Phú Xuân"],
- [4, "SafeSpace Tân Thuận", "Quận 4", 6.1, 1100000, true, "Đường Huỳnh Tấn Phát, Tân Thuận"],
- [5, "SafeSpace Phú Mỹ Hưng", "Huyện Nhà Bè", 6.8, 1250000, true, "Đường Nguyễn Lương Bằng, Phú Mỹ"],
- [6, "SafeSpace Bình Thạnh", "Quận Bình Thạnh", 8.7, 980000, true, "Đường Nguyễn Xí, Phường 26"],
- [7, "SafeSpace Nhà Bè", "Huyện Nhà Bè", 9.3, 850000, true, "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè"],
- [8, "SafeSpace Bình Chánh", "Huyện Bình Chánh", 12.4, 790000, false, "Quốc lộ 50, Bình Chánh"],
- [9, "SafeSpace Thủ Đức", "TP. Thủ Đức", 15.2, 920000, false, "Đường Võ Văn Ngân, Linh Chiểu"],
- [10, "SafeSpace Gò Vấp", "Quận Gò Vấp", 16.8, 930000, true, "Đường Quang Trung, Phường 10"],
- [11, "SafeSpace Tân Bình", "Quận Tân Bình", 18.1, 1020000, true, "Đường Cộng Hòa, Phường 13"],
- [12, "SafeSpace Bình Tân", "Quận Bình Tân", 19.5, 820000, false, "Đường Kinh Dương Vương, An Lạc"],
+ [1, "SafeSpace Nguyễn Lương Bằng", "Quận 7", 1150000, "Số 12 Nguyễn Lương Bằng, Tân Phú"],
+ [2, "SafeSpace Him Lam", "Quận 7", 1050000, "Khu dân cư Him Lam, Tân Hưng"],
+ [3, "SafeSpace Phú Xuân", "Quận 7", 890000, "Đường Nguyễn Hữu Thọ, Phú Xuân"],
+ [4, "SafeSpace Tân Thuận", "Quận 7", 1100000, "Đường Huỳnh Tấn Phát, Tân Thuận"],
+ [5, "SafeSpace Phú Mỹ Hưng", "Quận 7", 1250000, "Đường Nguyễn Lương Bằng, Tân Phong"],
+ [6, "SafeSpace Bình Thạnh", "Quận Bình Thạnh", 980000, "Đường Nguyễn Xí, Phường 26"],
+ [7, "SafeSpace Nhà Bè", "Huyện Nhà Bè", 850000, "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè"],
+ [8, "SafeSpace Bình Chánh", "Huyện Bình Chánh", 790000, "Quốc lộ 50, Bình Hưng"],
+ [9, "SafeSpace Thủ Đức", "TP. Thủ Đức", 920000, "Đường Võ Văn Ngân, Linh Chiểu"],
+ [10, "SafeSpace Gò Vấp", "Quận Gò Vấp", 930000, "Đường Quang Trung, Phường 10"],
+ [11, "SafeSpace Tân Bình", "Quận Tân Bình", 1020000, "Đường Cộng Hòa, Phường 13"],
+ [12, "SafeSpace Bình Tân", "Quận Bình Tân", 820000, "Đường Kinh Dương Vương, An Lạc"],
];
export function createFacilities() {
- return FACILITIES.map(([facility_id, name, district, distance_km, base_price, has_climate, street]) => withOffers({
+ return FACILITIES.map(([facility_id, name, district, base_price, street]) => withOffers({
facility_id,
name,
district,
city: "TP. Hồ Chí Minh",
address: `${street}, ${district}, TP. Hồ Chí Minh`,
- distance_km,
base_price,
- has_climate,
+ has_climate: true,
camera: true,
hours: "06:00–22:00",
}));
@@ -59,7 +59,7 @@ export function createSeedData(t = today()) {
type: "normal",
band: "M",
offer_key: "normal-M",
- size_label: "10 – 20 m²",
+ size_label: "Cỡ M · 15 m²",
months: 3,
start_date: t,
end_date: a102End,
@@ -67,23 +67,23 @@ export function createSeedData(t = today()) {
deposit: 1150000,
rent_total: 3450000,
initial_total: 4600000,
- status: "PENDING_VERIFICATION",
+ status: "CONFIRMED", // đã thanh toán qua QR PayOS, chờ nhận kho (Figma C14)
created_at: at(addDays(t, -6), "09:12"),
},
{
reservation_id: "SS-20260615-0086",
facility_id: 1,
type: "climate",
- band: "S",
- offer_key: "climate-S",
- size_label: "2 – 5 m²",
+ band: "M",
+ offer_key: "climate-M",
+ size_label: "Cỡ M · 15 m²",
months: 3,
start_date: b015Start,
end_date: b015End,
- monthly_rate: 500000,
- deposit: 500000,
- rent_total: 1500000,
- initial_total: 2000000,
+ monthly_rate: 1380000,
+ deposit: 1380000,
+ rent_total: 4140000,
+ initial_total: 5520000,
status: "CHECKED_IN",
created_at: at(addDays(b015Start, -2), "14:30"),
},
@@ -96,7 +96,7 @@ export function createSeedData(t = today()) {
unit_number: "A-102",
type: "normal",
band: "M",
- size_m2: 12,
+ size_m2: 15,
location: "Tầng 1 · Dãy A",
months: 3,
start_date: t,
@@ -112,14 +112,14 @@ export function createSeedData(t = today()) {
facility_id: 1,
unit_number: "B-015",
type: "climate",
- band: "S",
- size_m2: 5,
+ band: "M",
+ size_m2: 15,
location: "Tầng 1 · Dãy B",
months: 3,
start_date: b015Start,
end_date: b015End,
- monthly_rate: 500000,
- deposit: 500000,
+ monthly_rate: 1380000,
+ deposit: 1380000,
status: "EXPIRING",
handed_over: true,
},
@@ -146,7 +146,7 @@ export function createSeedData(t = today()) {
label: "Thuê kho B-015 · 3 tháng",
contract_id: "HĐ-2026-0086",
reservation_id: "SS-20260615-0086",
- amount: 1500000,
+ amount: 4140000,
status: "RECONCILED",
},
{
@@ -154,9 +154,21 @@ export function createSeedData(t = today()) {
label: "Cọc hợp đồng B-015",
contract_id: "HĐ-2026-0086",
reservation_id: "SS-20260615-0086",
- amount: 500000,
+ amount: 1380000,
status: "DEPOSIT_HELD",
},
+ {
+ // C11: gia hạn đã được cơ sở duyệt, chờ khách thanh toán qua QR PayOS (C11q)
+ ref: "SS-0086-REN",
+ kind: "RENEWAL",
+ label: "Gia hạn B-015 · 3 tháng",
+ contract_id: "HĐ-2026-0086",
+ unit_number: "B-015",
+ amount: 4140000,
+ status: "UNPAID",
+ payable: true,
+ period: { from: b015End, to: addMonths(b015End, 3), months: 3 },
+ },
],
appointments: [
{
@@ -172,7 +184,18 @@ export function createSeedData(t = today()) {
note: "Mang giấy đăng ký và mã đặt chỗ. Nhân viên xác minh, hướng dẫn và bàn giao kho.",
},
],
- renewals: [],
+ renewals: [
+ {
+ renewal_id: "GH-0012",
+ contract_id: "HĐ-2026-0086",
+ months: 3,
+ old_end: b015End,
+ new_end: addMonths(b015End, 3),
+ amount: 4140000,
+ status: "APPROVED",
+ requested_at: at(addDays(t, -2), "10:20"),
+ },
+ ],
returns: [],
tickets: [
{
@@ -182,7 +205,14 @@ export function createSeedData(t = today()) {
description: "Thẻ ra vào chưa mở được cổng cơ sở.",
attachments: [],
status: "IN_PROGRESS",
- staff_note: "Nhân viên Trần Minh đang kiểm tra.",
+ staff_note: "Nhân viên Trần Văn Long đang kiểm tra.",
+ responses: [
+ {
+ text: "Thẻ cũ bị lỗi từ. Bạn qua quầy lễ tân nhận thẻ mới, mang theo CCCD giúp mình nhé.",
+ by: "Trần Văn Long",
+ at: at(addDays(t, -6), "11:02"),
+ },
+ ],
created_at: at(addDays(t, -6), "09:40"),
updated_at: at(addDays(t, -6), "10:15"),
},
@@ -222,7 +252,7 @@ export function createSeedData(t = today()) {
},
{
id: "A-2",
- text: "Thanh toán thuê kho 3 tháng đã đối soát",
+ text: "Thanh toán thuê kho 3 tháng qua QR thành công",
tone: "green",
at: addDays(t, -6),
},
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/router.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/router.js
similarity index 100%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/router.js
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/router.js
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx
similarity index 65%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx
index 9f07dae..94ea8d9 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx
@@ -1,17 +1,20 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
-import { api } from "../api/endpoints";
-import { ApiError, setToken } from "../api/http";
-import { composeData, emptyOverlay, mapCatalog, reservationCode, reservationsToExpire, ticketCode, usernameFromEmail } from "../api/mappers";
-import { API_URL, USE_API } from "../config/api";
-import { paymentTimeoutSeconds } from "../config/media";
-import { createEmptyData, createSeedData } from "../data/seed";
-import { RENTAL_PLANS, offerByKey } from "../lib/catalog";
-import { isEmail, localDate, shortCode, timeoutLabel } from "../lib/format";
-import { TICKET_TOPICS } from "../lib/status";
-import { isAdminRoles, isCustomerRoles, isOpsRoles, rolesFromToken } from "../lib/roles";
-import { OPS_ACCOUNTS, OPS_PASSWORD } from "../ops/data";
-import { reduce, sweepExpired, validateRegister } from "./reducer";
-import { pendingRenewal, pendingReturn } from "./selectors";
+import { api } from "../../shared/api/customerApi.js";
+import { ApiError, setToken } from "../../shared/api/httpClient.js";
+import { isUnsupported, localAccessCode, normAccess, normCancelPreview, normPayos, normScan } from "../../features/customer/access/accessApi.js";
+import { bankAccount } from "../config/payment.js";
+import { vietQrPayload } from "../../shared/utils/vietqr.js";
+import { composeData, emptyOverlay, mapCatalog, reservationCode, reservationsToExpire, ticketCode, usernameFromEmail } from "../../shared/api/apiMappers.js";
+import { API_URL, USE_API } from "../config/api.js";
+import { paymentTimeoutSeconds } from "../config/media.js";
+import { createEmptyData, createSeedData } from "../data/appSeed.js";
+import { RENTAL_PLANS, offerByKey } from "../../shared/utils/catalog.js";
+import { isEmail, localDate, shortCode, timeoutLabel } from "../../shared/utils/format.js";
+import { TICKET_TOPICS } from "../../shared/utils/status.js";
+import { isAdminRoles, isCustomerRoles, isOpsRoles, isBusinessRoles, rolesFromToken } from "../../shared/utils/roles.js";
+import { OPS_ACCOUNTS, OPS_PASSWORD } from "../../features/facility-operations/data/facilityOperationsSeed.js";
+import { cancelPreviewOf, reduce, sweepExpired, validateRegister } from "./appReducer.js";
+import { pendingRenewal, pendingReturn } from "./appSelectors.js";
const AppContext = createContext(null);
export const useApp = () => useContext(AppContext);
@@ -145,6 +148,59 @@ function LocalProvider({ children }) {
const logout = useCallback(async () => commit({ ...ref.current, authed: false, opsUser: null }), [commit]);
+ // Thanh toán QR / QR mở cửa khi chạy không có backend: mô phỏng phía trình duyệt.
+ // Mã QR là VietQR tới tài khoản cấu hình trong config/payment.js; sau vài giây tự ghi nhận "đã thanh toán"
+ // giống webhook PayOS để đi hết luồng C04 → C05 và C11q → C11b.
+ const simulated = useRef(new Set());
+ const services = useMemo(
+ () => ({
+ async startPayos({ kind, item }) {
+ const content = kind === "payment" ? item.ref.replaceAll("-", "") : item.reservation_id.replaceAll("-", "");
+ const key = kind === "payment" ? `p:${item.ref}` : `r:${item.reservation_id}`;
+ if (!simulated.current.has(key)) {
+ simulated.current.add(key);
+ setTimeout(() => {
+ simulated.current.delete(key);
+ const out = reduce(ref.current.data, { type: "PAYOS_PAID", payload: kind === "payment" ? { ref: item.ref } : { reservation_id: item.reservation_id } }, { now: new Date(), timeoutSeconds: paymentTimeoutSeconds });
+ if (!out.error && out.state !== ref.current.data) commit({ ...ref.current, data: out.state });
+ }, 8000);
+ }
+ return {
+ ok: true,
+ checkout: { order_code: content, amount: item.amount ?? item.initial_total, qr: vietQrPayload({ bin: bankAccount.bin, accountNo: bankAccount.accountNo, amount: item.amount ?? item.initial_total, content }), url: null, expires_at: null, description: content, paid: false },
+ };
+ },
+ async checkPaid({ kind, item }) {
+ const d = ref.current.data;
+ if (kind === "payment") return { ok: true, paid: d.ledger.find((l) => l.ref === item.ref)?.status === "RECONCILED" };
+ const r = d.reservations.find((x) => x.reservation_id === item.reservation_id);
+ return { ok: true, paid: Boolean(r && ["CONFIRMED", "CHECKED_IN"].includes(r.status)), cancelled: r?.status === "CANCELLED" };
+ },
+ async accessQr(contract) {
+ if (!contract.handed_over || contract.status === "ENDED") return { ok: false, error: "QR mở cửa chỉ dùng được sau khi nhận kho và khi hợp đồng còn hiệu lực." };
+ return { ok: true, access: localAccessCode(contract) };
+ },
+ async scan(code) {
+ const d = ref.current.data;
+ const clean = String(code || "").replace(/\s/g, "");
+ const c = d.contracts.find((x) => {
+ const a = localAccessCode(x);
+ return a.code === code || a.backup.replace(/\s/g, "") === clean;
+ });
+ const now = new Date().toISOString();
+ if (!c) return { ok: true, scan: { result: "DENIED", unit: null, customer: null, contract: null, at: now, reason: "Mã không đúng. Kiểm tra lại mã trên ứng dụng hoặc mã dự phòng." } };
+ if (c.status === "ENDED") return { ok: true, scan: { result: "DENIED", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: "Mã đã hết hiệu lực — hợp đồng đã trả kho." } };
+ if (!c.handed_over) return { ok: true, scan: { result: "DENIED", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: "Kho chưa được bàn giao cho khách." } };
+ if (c.end_date < localDate(new Date())) return { ok: true, scan: { result: "DENIED", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: "Hợp đồng đã quá hạn. Vui lòng gia hạn hoặc liên hệ cơ sở." } };
+ return { ok: true, scan: { result: "OPEN", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: null } };
+ },
+ async cancelPreview(r) {
+ return { ok: true, preview: r.status === "CONFIRMED" ? cancelPreviewOf(r) : { paid: 0, fee: 0, refund: 0, policy: null } };
+ },
+ }),
+ [commit],
+ );
+
const value = useMemo(
() => ({
mode: "local",
@@ -159,17 +215,19 @@ function LocalProvider({ children }) {
register,
logout,
checkAvailability: null,
+ getFacilityUnits: null,
onApiError: () => {},
roles: store.authed ? (store.opsUser ? [store.opsUser.role] : ["CUSTOMER"]) : [],
isAdmin: false,
supports: { changePassword: true, forgotPassword: true },
+ services,
toast,
notify,
dismissToast,
storageError,
timeoutSeconds: paymentTimeoutSeconds,
}),
- [store, dispatch, login, register, logout, toast, notify, dismissToast, storageError],
+ [store, dispatch, login, register, logout, services, toast, notify, dismissToast, storageError],
);
return {children};
@@ -177,7 +235,7 @@ function LocalProvider({ children }) {
// =====================================================================
// Chế độ API (VITE_USE_API=true)
-// Luồng backend đã có → gọi API. Luồng backend chưa có (báo chuyển khoản, trả kho, lịch trả kho,
+// Luồng backend đã có → gọi API. Luồng backend chưa có (trả kho, lịch trả kho,
// thông báo, đổi tên hiển thị) → lưu trong trình duyệt theo từng tài khoản ("overlay").
// =====================================================================
function readSession() {
@@ -245,13 +303,17 @@ function ApiProvider({ children }) {
}, []);
const loadCustomer = useCallback(async () => {
+ const activeSession = refs.current.session;
const [reservations, contracts, tickets] = await Promise.all([api.reservations(), api.contracts(), api.tickets()]);
const [reservationDetails, contractDetails, ticketDetails] = await Promise.all([
Promise.all(reservations.filter((r) => r.status !== "CANCELLED").map((r) => api.reservation(r.reservationId).catch(() => null))),
Promise.all(contracts.map((c) => api.contract(c.contractId).catch(() => ({ ...c, payments: [], renewals: [] })))),
- Promise.all(tickets.map((t) => api.ticket(t.ticketId).catch(() => t))),
+ Promise.all(tickets.map((t) => api.ticket(t.ticketId).catch((e) => {
+ if (e.status === 401) throw e;
+ return { ...t, responsesError: true };
+ }))),
]);
- if (!refs.current.session) return;
+ if (!activeSession || refs.current.session?.token !== activeSession.token) return;
const next = {
reservations,
reservationDetails: Object.fromEntries(reservationDetails.filter(Boolean).map((d) => [d.reservationId, d])),
@@ -263,6 +325,25 @@ function ApiProvider({ children }) {
setNow(new Date());
}, []);
+ // Hồ sơ do API xác nhận; không dùng tên lưu cục bộ để che dữ liệu trên máy chủ.
+ const applyProfile = useCallback((profile, activeSession) => {
+ if (!activeSession || refs.current.session?.token !== activeSession.token) return false;
+ if (String(profile.userId) !== String(activeSession.user.userId)) return false;
+ const next = { ...refs.current.session, user: { ...refs.current.session.user, ...profile } };
+ refs.current.session = next;
+ setSession(next);
+ setStorageError(!writeJson(SESSION_KEY, next));
+ updateOverlay((o) => ({ ...o, name: null }));
+ return true;
+ }, [updateOverlay]);
+
+ const loadProfile = useCallback(async () => {
+ const activeSession = refs.current.session;
+ if (!activeSession) return;
+ const profile = await api.getProfile();
+ applyProfile(profile, activeSession);
+ }, [applyProfile]);
+
const handleError = useCallback(
(e) => {
if (e instanceof ApiError && e.status === 401 && refs.current.session) endSession("expired");
@@ -283,15 +364,16 @@ function ApiProvider({ children }) {
setLoadError(null);
try {
await loadCatalog();
+ await loadProfile();
if (refs.current.session) {
- if (isAdminRoles(refs.current.session.roles) || isOpsRoles(refs.current.session.roles)) setRemote(EMPTY_REMOTE);
+ if (isAdminRoles(refs.current.session.roles) || isOpsRoles(refs.current.session.roles) || isBusinessRoles(refs.current.session.roles)) setRemote(EMPTY_REMOTE);
else await loadCustomer();
}
} catch (e) {
if (e instanceof ApiError && e.status === 401) endSession("expired");
else setLoadError(e?.message || "Không tải được dữ liệu.");
}
- }, [loadCatalog, loadCustomer, endSession]);
+ }, [loadCatalog, loadProfile, loadCustomer, endSession]);
useEffect(() => {
loadAll();
@@ -309,7 +391,7 @@ function ApiProvider({ children }) {
cancelling.current.add(r.reservationId);
const seconds = refs.current.overlay.holds[r.reservationId] ? paymentTimeoutSeconds : 24 * 3600;
api
- .cancelReservation(r.reservationId, `Quá ${timeoutLabel(seconds)} chưa xác nhận chuyển khoản`)
+ .cancelReservation(r.reservationId, `Quá ${timeoutLabel(seconds)} chưa thanh toán`)
.catch(() => {})
.then(() => loadCustomer().catch(() => {}));
}
@@ -329,12 +411,13 @@ function ApiProvider({ children }) {
refs.current.overlay = saved;
setOverlay(saved);
setSession(next);
- if (isAdminRoles(next.roles) || isOpsRoles(next.roles)) {
+ await loadProfile();
+ if (isAdminRoles(next.roles) || isOpsRoles(next.roles) || isBusinessRoles(next.roles)) {
refs.current.remote = EMPTY_REMOTE;
setRemote(EMPTY_REMOTE);
} else await loadCustomer();
},
- [loadCustomer],
+ [loadCustomer, loadProfile],
);
const login = useCallback(
@@ -344,7 +427,7 @@ function ApiProvider({ children }) {
try {
const res = await api.login(id.includes("@") ? id.toLowerCase() : id, password);
const roles = rolesFromToken(res.token);
- if (!isAdminRoles(roles) && !isCustomerRoles(roles) && !isOpsRoles(roles)) {
+ if (!isAdminRoles(roles) && !isCustomerRoles(roles) && !isOpsRoles(roles) && !isBusinessRoles(roles)) {
return fail("Tài khoản này chưa được gán vai trò trên giao diện SafeSpace. Vui lòng liên hệ quản trị viên.");
}
await startSession(res);
@@ -436,13 +519,29 @@ function ApiProvider({ children }) {
await loadCustomer();
return { ok: true, reservation_id: reservationCode(dto) };
}
+ case "PAY_AT_FACILITY":
case "CONFIRM_TRANSFER": {
const r = d.reservations.find((x) => x.reservation_id === p.reservation_id);
if (!r) return fail("Không tìm thấy đơn đặt chỗ.", "NOT_FOUND");
if (r.status === "CANCELLED") return fail("Đơn đặt chỗ đã hết thời gian giữ chỗ.", "EXPIRED");
if (r.status !== "PENDING_PAYMENT") return { ok: true, reservation_id: r.reservation_id };
- updateOverlay((o) => ({ ...o, transfers: { ...o.transfers, [r.api_id]: Date.now() } }));
- remember("Đã nhận thông tin đặt chỗ", `${shortCode(r.reservation_id)} · Chờ nhân viên đối soát chuyển khoản.`, "reservations", `Đơn ${shortCode(r.reservation_id)} đã gửi — chờ đối soát thanh toán`);
+ const expired = async (e) => {
+ if (e instanceof ApiError && e.data?.code === "EXPIRED") {
+ await loadCustomer().catch(() => {});
+ return fail(e.message, "EXPIRED");
+ }
+ return null;
+ };
+ try { await api.payAtFacility(r.api_id); }
+ catch (e) { const exp = await expired(e); if (exp) return exp; throw e; }
+ const done = true;
+ updateOverlay((o) => ({
+ ...o,
+ atFacility: { ...o.atFacility, [r.api_id]: Date.now() },
+ transfers: done ? o.transfers : { ...o.transfers, [r.api_id]: Date.now() },
+ }));
+ await loadCustomer().catch(() => {});
+ remember("Đã giữ chỗ cho bạn", `${shortCode(r.reservation_id)} · Thanh toán tại cửa hàng khi nhận kho.`, `reservations/${r.reservation_id}`, `Đơn ${shortCode(r.reservation_id)} chờ thanh toán tại cửa hàng`);
return { ok: true, reservation_id: r.reservation_id };
}
case "EXPIRE_RESERVATION": {
@@ -453,7 +552,7 @@ function ApiProvider({ children }) {
if (!cancelling.current.has(r.api_id)) {
cancelling.current.add(r.api_id);
api
- .cancelReservation(r.api_id, `Quá ${timeoutLabel(r.timeout_seconds || paymentTimeoutSeconds)} chưa xác nhận chuyển khoản`)
+ .cancelReservation(r.api_id, `Quá ${timeoutLabel(r.timeout_seconds || paymentTimeoutSeconds)} chưa thanh toán`)
.catch(() => {})
.then(() => loadCustomer().catch(() => {}));
}
@@ -515,10 +614,32 @@ function ApiProvider({ children }) {
await loadCustomer();
return { ok: true };
}
- case "CHANGE_PASSWORD":
- return fail("Máy chủ chưa hỗ trợ đổi mật khẩu. Vui lòng liên hệ quản trị viên SafeSpace.", "UNSUPPORTED");
- case "REQUEST_RETURN":
- case "UPDATE_NAME":
+ case "CHANGE_PASSWORD": {
+ try {
+ await api.changePassword({ currentPassword: p.current, newPassword: p.next });
+ } catch (e) {
+ if (e.status === 400 && /mật khẩu hiện tại/i.test(e.message)) return fail(e.message, "BAD_PASSWORD");
+ throw e;
+ }
+ return { ok: true };
+ }
+ case "UPDATE_NAME": {
+ const activeSession = refs.current.session;
+ if (!activeSession) return fail("Vui lòng đăng nhập lại.");
+ const profile = await api.updateProfile({ fullName: String(p.name || "").trim(), phone: activeSession.user.phone ?? null });
+ if (!applyProfile(profile, activeSession)) return fail("Phiên đăng nhập đã thay đổi. Vui lòng thử lại.");
+ return { ok: true, name: profile.fullName };
+ }
+ case "REQUEST_RETURN": {
+ const c = d.contracts.find((x) => x.contract_id === p.contract_id);
+ if (!c) return fail("Không tìm thấy hợp đồng.");
+ if (pendingRenewal(d, c.contract_id)) return fail("Hợp đồng đang có yêu cầu gia hạn.");
+ if (p.date < localDate(new Date())) return fail("Ngày hẹn không được ở quá khứ.");
+ await api.requestMoveOut(c.api_id, { date: p.date, slot: p.slot, note: p.notes });
+ remember("Đã đặt lịch trả kho", `Kho ${c.unit_number} · ${p.date} (${p.slot || "giờ hành chính"})`, `units/${c.contract_id}`, `Lịch trả kho ${c.unit_number} đã được ghi nhận`);
+ await loadCustomer();
+ return { ok: true, return_id: `TK-${c.api_id}` };
+ }
case "MARK_READ": {
const out = runLocal(type, p);
return out.error ? fail(out.error.message, out.error.code) : { ok: true, ...out.result };
@@ -530,7 +651,7 @@ function ApiProvider({ children }) {
return handleError(e);
}
},
- [loadCustomer, updateOverlay, remember, runLocal, handleError],
+ [loadCustomer, updateOverlay, remember, runLocal, handleError, applyProfile],
);
const checkAvailability = useCallback(async ({ facility_id, offer, start_date, months }) => {
@@ -543,6 +664,64 @@ function ApiProvider({ children }) {
}
}, []);
+ const getFacilityUnits = useCallback(async (facilityId) => {
+ try {
+ return await api.facilityUnits(facilityId);
+ } catch {
+ return null;
+ }
+ }, []);
+
+
+ // Màn mới gọi API trực tiếp: PayOS (C04, C11q), QR mở cửa (C07q), máy quét (C07r), xem trước hoàn tiền (C14a).
+ // Backend chưa có endpoint (404/405) → trả { unsupported: true } để màn hiện thông báo phù hợp, không báo lỗi.
+ const services = useMemo(() => {
+ const guard = async (fn) => {
+ try {
+ return await fn();
+ } catch (e) {
+ if (isUnsupported(e)) return { ok: false, unsupported: true };
+ return handleError(e);
+ }
+ };
+ return {
+ startPayos: ({ kind, item }) =>
+ guard(async () => {
+ const dto = kind === "payment" ? await api.paymentPayos(item.api_id) : await api.reservationPayos(item.api_id);
+ const checkout = normPayos(dto);
+ if (!checkout) return fail("Máy chủ chưa trả mã QR thanh toán. Vui lòng thử lại.");
+ if (checkout.paid) await loadCustomer().catch(() => {});
+ return { ok: true, checkout };
+ }),
+ checkPaid: ({ kind, item }) =>
+ guard(async () => {
+ if (kind === "payment") {
+ const p = await api.payment(item.api_id);
+ const paid = p?.status === "PAID";
+ if (paid) await loadCustomer().catch(() => {});
+ return { ok: true, paid };
+ }
+ const r = await api.reservation(item.api_id);
+ const status = String(r?.status || "");
+ const paid = ["PAID", "CONFIRMED", "UNIT_ASSIGNED", "CHECKED_IN", "COMPLETED"].includes(status);
+ const cancelled = ["CANCELLED", "EXPIRED"].includes(status);
+ if (paid || cancelled) await loadCustomer().catch(() => {});
+ return { ok: true, paid, cancelled };
+ }),
+ accessQr: (contract) =>
+ guard(async () => {
+ const access = normAccess(await api.accessQr(contract.api_id));
+ return access ? { ok: true, access } : fail("Máy chủ chưa trả mã mở cửa.");
+ }),
+ scan: (code) => guard(async () => ({ ok: true, scan: normScan(await api.scanAccess({ code: String(code || "").trim() })) })),
+ cancelPreview: (r) =>
+ guard(async () => {
+ const preview = normCancelPreview(await api.cancelPreview(r.api_id));
+ return preview ? { ok: true, preview } : { ok: false, unsupported: true };
+ }),
+ };
+ }, [handleError, loadCustomer]);
+
const ready = Boolean(catalog) && (!session || Boolean(remote));
const value = useMemo(
@@ -560,19 +739,22 @@ function ApiProvider({ children }) {
register,
logout,
checkAvailability,
+ getFacilityUnits,
onApiError,
roles: session?.roles || [],
isAdmin: isAdminRoles(session?.roles),
session,
- supports: { changePassword: false, forgotPassword: false },
+ supports: { changePassword: true, forgotPassword: false },
+ services,
toast,
notify,
dismissToast,
storageError,
timeoutSeconds: paymentTimeoutSeconds,
}),
- [ready, loadError, loadAll, session, data, dispatch, login, register, logout, checkAvailability, onApiError, toast, notify, dismissToast, storageError],
+ [ready, loadError, loadAll, session, data, dispatch, login, register, logout, checkAvailability, getFacilityUnits, onApiError, services, toast, notify, dismissToast, storageError],
);
+
return {children};
}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/reducer.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js
similarity index 71%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/reducer.js
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js
index 1f0a5ba..0383e8f 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/reducer.js
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js
@@ -1,4 +1,4 @@
-import { RENTAL_PLANS, SIZE_BANDS, offerByKey, quote } from "../lib/catalog.js";
+import { RENTAL_PLANS, SIZE_BANDS, offerByKey, quote } from "../../shared/utils/catalog.js";
import {
addDays,
addMonths,
@@ -7,8 +7,8 @@ import {
localDate,
shortCode,
timeoutLabel,
-} from "../lib/format.js";
-import { TICKET_TOPICS } from "../lib/status.js";
+} from "../../shared/utils/format.js";
+import { TICKET_TOPICS } from "../../shared/utils/status.js";
export class DomainError extends Error {
constructor(message, code = "INVALID") {
@@ -69,6 +69,15 @@ const hasPending = (state, contract_id) => ({
ret: state.returns.some((r) => r.contract_id === contract_id && ["PENDING", "SCHEDULED"].includes(r.status)),
});
+// C14a · Ước tính hoàn tiền khi huỷ đơn đã thanh toán (chế độ trình duyệt). Chế độ API lấy từ
+// GET /api/reservations/{id}/cancel-preview theo chính sách CANCELLATION ở B02.
+export const CANCEL_FEE_RATE = 0.1; // 10% tiền thuê, hoàn đủ tiền cọc (Figma C14a)
+export function cancelPreviewOf(r) {
+ const paid = r.initial_total || 0;
+ const fee = Math.round((r.rent_total || 0) * CANCEL_FEE_RATE);
+ return { paid, fee, refund: Math.max(0, paid - fee), policy: null };
+}
+
const handlers = {
CREATE_RESERVATION(state, p, ctx) {
const facility = state.facilities.find((f) => f.facility_id === Number(p.facility_id));
@@ -152,8 +161,62 @@ const handlers = {
},
],
};
- next = notify(next, "Đã nhận thông tin đặt chỗ", `${shortCode(r.reservation_id)} · Chờ nhân viên đối soát chuyển khoản.`, "reservations", ctx.now);
- next = log(next, `Đơn ${shortCode(r.reservation_id)} đã gửi — chờ đối soát thanh toán`, "amber", ctx.now);
+ next = notify(next, "Đã nhận thông tin đặt chỗ", `${shortCode(r.reservation_id)} · Chờ cơ sở xác nhận thanh toán.`, "reservations", ctx.now);
+ next = log(next, `Đơn ${shortCode(r.reservation_id)} đã gửi — chờ xác nhận thanh toán`, "amber", ctx.now);
+ return { state: next, result: { reservation_id: r.reservation_id } };
+ },
+
+ // C04c → C05c: khách chọn thanh toán tại cửa hàng. Đơn giữ chỗ chờ nhân viên thu tiền ở S09.
+ PAY_AT_FACILITY(state, p, ctx) {
+ const out = handlers.CONFIRM_TRANSFER(state, p, ctx);
+ const r = out.state.reservations.find((x) => x.reservation_id === p.reservation_id);
+ if (!r || r.pay_at_facility) return out;
+ let next = {
+ ...out.state,
+ // Bỏ thông báo / hoạt động kiểu "chờ đối soát" của bước chuyển khoản cũ
+ notifications: out.state.notifications.slice(1),
+ activities: out.state.activities.slice(1),
+ reservations: out.state.reservations.map((x) => (x.reservation_id === r.reservation_id ? { ...x, pay_at_facility: true } : x)),
+ };
+ next = notify(next, "Đã giữ chỗ cho bạn", `${shortCode(r.reservation_id)} · Thanh toán tại cửa hàng khi nhận kho.`, `reservations/${r.reservation_id}`, ctx.now);
+ next = log(next, `Đơn ${shortCode(r.reservation_id)} chờ thanh toán tại cửa hàng`, "amber", ctx.now);
+ return { state: next, result: out.result };
+ },
+
+ // PayOS báo đã thanh toán (webhook ở backend; chế độ trình duyệt tự gọi để mô phỏng).
+ // reservation_id → đơn đặt chỗ đã trả tiền thuê + cọc; ref → khoản gia hạn ở C11.
+ PAYOS_PAID(state, p, ctx) {
+ if (p.ref) {
+ const l = state.ledger.find((x) => x.ref === p.ref);
+ if (!l) fail("Không tìm thấy khoản thanh toán.", "NOT_FOUND");
+ if (l.status === "RECONCILED") return { state, result: { ref: l.ref } };
+ const c = contractOf(state, l.contract_id);
+ let next = {
+ ...state,
+ ledger: state.ledger.map((x) => (x.ref === l.ref ? { ...x, status: "RECONCILED", payable: false } : x)),
+ contracts: state.contracts.map((x) => (c && x.contract_id === c.contract_id && l.period?.to ? { ...x, end_date: l.period.to, status: "ACTIVE" } : x)),
+ };
+ next = notify(next, "Đã thanh toán gia hạn", `Kho ${l.unit_number || c?.unit_number || ""} · gia hạn đến ${l.period?.to ? dateLabel(l.period.to) : "kỳ mới"}.`, "payments", ctx.now);
+ next = log(next, `Đã thanh toán gia hạn ${l.unit_number || ""} qua QR`, "green", ctx.now);
+ return { state: next, result: { ref: l.ref } };
+ }
+ const r = state.reservations.find((x) => x.reservation_id === p.reservation_id);
+ if (!r) fail("Không tìm thấy đơn đặt chỗ.", "NOT_FOUND");
+ if (r.status !== "PENDING_PAYMENT") return { state, result: { reservation_id: r.reservation_id } };
+ const base = refBase(r.reservation_id);
+ let next = {
+ ...state,
+ reservations: state.reservations.map((x) =>
+ x.reservation_id === r.reservation_id ? { ...x, status: "CONFIRMED", paid_at: iso(ctx.now), expires_at: null } : x,
+ ),
+ ledger: [
+ ...state.ledger,
+ { ref: `${base}-RENT`, kind: "RENT", label: `Thuê kho · ${r.months} tháng`, reservation_id: r.reservation_id, amount: r.rent_total, status: "RECONCILED" },
+ { ref: `${base}-DEP`, kind: "DEPOSIT", label: "Cọc hợp đồng", reservation_id: r.reservation_id, amount: r.deposit, status: "DEPOSIT_HELD" },
+ ],
+ };
+ next = notify(next, "Đã thanh toán đặt chỗ", `${shortCode(r.reservation_id)} · Cơ sở sẽ phân bổ kho và xác nhận lịch nhận kho.`, `reservations/${r.reservation_id}`, ctx.now);
+ next = log(next, `Đơn ${shortCode(r.reservation_id)} đã thanh toán qua QR`, "green", ctx.now);
return { state: next, result: { reservation_id: r.reservation_id } };
},
@@ -166,18 +229,33 @@ const handlers = {
CANCEL_RESERVATION(state, p, ctx) {
const r = state.reservations.find((x) => x.reservation_id === p.reservation_id);
if (!r) fail("Không tìm thấy đơn đặt chỗ.", "NOT_FOUND");
- if (r.status !== "PENDING_PAYMENT") fail("Đơn này đã gửi thông tin thanh toán, vui lòng liên hệ cơ sở để huỷ.");
- return {
- state: {
- ...state,
- reservations: state.reservations.map((x) =>
- x.reservation_id === r.reservation_id
- ? { ...x, status: "CANCELLED", cancel_reason: p.reason || "Khách hàng huỷ đặt chỗ", cancelled_at: iso(ctx.now) }
- : x,
- ),
- },
- result: { reservation_id: r.reservation_id },
+ const contract = state.contracts.find((c) => c.reservation_id === r.reservation_id);
+ // Giống backend: huỷ được đơn chờ thanh toán hoặc đã thanh toán nhưng chưa nhận kho (C14a)
+ if (r.status !== "PENDING_PAYMENT" && !(r.status === "CONFIRMED" && !contract?.handed_over))
+ fail(r.status === "PENDING_VERIFICATION" ? "Đơn chờ thanh toán tại cửa hàng, vui lòng liên hệ cơ sở để huỷ." : "Đơn đã nhận kho, không huỷ được.");
+ const preview = r.status === "CONFIRMED" ? cancelPreviewOf(r) : null;
+ let next = {
+ ...state,
+ reservations: state.reservations.map((x) =>
+ x.reservation_id === r.reservation_id
+ ? {
+ ...x,
+ status: "CANCELLED",
+ cancel_reason: p.reason || "Khách hàng huỷ đặt chỗ",
+ cancelled_at: iso(ctx.now),
+ refund_amount: preview?.refund ?? null,
+ refund_status: preview?.refund ? "PENDING" : null,
+ }
+ : x,
+ ),
+ contracts: contract ? state.contracts.map((c) => (c === contract ? { ...c, status: "ENDED" } : c)) : state.contracts,
+ appointments: state.appointments.map((a) => (a.reservation_id === r.reservation_id && a.status !== "DONE" ? { ...a, status: "CANCELLED" } : a)),
};
+ if (preview?.refund) {
+ next = notify(next, "Đã huỷ đơn đặt chỗ", `${shortCode(r.reservation_id)} · Đang hoàn ${preview.refund.toLocaleString("vi-VN")} đ.`, "reservations", ctx.now);
+ next = log(next, `Đã huỷ đơn ${shortCode(r.reservation_id)} — đang hoàn tiền`, "gray", ctx.now);
+ }
+ return { state: next, result: { reservation_id: r.reservation_id, refund: preview?.refund ?? 0 } };
},
REQUEST_RENEWAL(state, p, ctx) {
@@ -322,11 +400,11 @@ const handlers = {
};
},
- // Nghiệp vụ phía nhân viên (Figma S09 Đối soát thanh toán): xác nhận chuyển khoản, tạo hợp đồng + lịch nhận kho.
+ // Nghiệp vụ phía nhân viên (Figma S09 Thu tiền tại kho): xác nhận chuyển khoản, tạo hợp đồng + lịch nhận kho.
// Giao diện khách hàng không gọi lệnh này.
STAFF_CONFIRM_PAYMENT(state, p, ctx) {
const r = state.reservations.find((x) => x.reservation_id === p.reservation_id);
- if (!r || r.status !== "PENDING_VERIFICATION") fail("Chỉ đối soát được đơn đang chờ đối soát.");
+ if (!r || r.status !== "PENDING_VERIFICATION") fail("Chỉ xác nhận thu được đơn đang chờ thanh toán tại cửa hàng.");
const facility = state.facilities.find((f) => f.facility_id === r.facility_id);
const n = state.contracts.length + 1;
const prefix = r.type === "climate" ? "B" : "A";
@@ -376,7 +454,7 @@ const handlers = {
),
};
next = notify(next, "Lịch nhận kho đã xác nhận", `${dateLabel(appointment.date)} · 09:00 tại ${facility.name.replace("SafeSpace ", "")}.`, "payments", ctx.now);
- next = log(next, `Thanh toán ${shortCode(r.reservation_id)} đã đối soát`, "green", ctx.now);
+ next = log(next, `Đã thu tiền đơn ${shortCode(r.reservation_id)} tại cửa hàng`, "green", ctx.now);
return { state: next, result: { contract_id: contract.contract_id } };
},
};
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/selectors.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js
similarity index 98%
rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/selectors.js
rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js
index 3cca7eb..4f3af27 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/selectors.js
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js
@@ -1,4 +1,4 @@
-import { daysBetween, localDate } from "../lib/format.js";
+import { daysBetween, localDate } from "../../shared/utils/format.js";
// Luôn trả về một cơ sở (dự phòng khi dữ liệu máy chủ chỉ có tên cơ sở)
export const facilityOf = (data, id, name) =>
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/access/check.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/access/check.svg
new file mode 100644
index 0000000..2b3dd43
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/access/check.svg
@@ -0,0 +1,4 @@
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/access/close.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/access/close.svg
new file mode 100644
index 0000000..98f1d35
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/access/close.svg
@@ -0,0 +1,4 @@
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/brand.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/brand.svg
new file mode 100644
index 0000000..52ecefe
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/brand.svg
@@ -0,0 +1,11 @@
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/notification.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/notification.svg
new file mode 100644
index 0000000..22246d8
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/notification.svg
@@ -0,0 +1,6 @@
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-blue.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-blue.svg
new file mode 100644
index 0000000..90afc78
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-blue.svg
@@ -0,0 +1,3 @@
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-green.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-green.svg
new file mode 100644
index 0000000..9ccd061
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-green.svg
@@ -0,0 +1,3 @@
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-pending.svg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-pending.svg
new file mode 100644
index 0000000..7e2bd0b
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/assets/customer/auth-support/timeline-pending.svg
@@ -0,0 +1,3 @@
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/PaymentQr.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/PaymentQr.jsx
deleted file mode 100644
index b9e4631..0000000
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/PaymentQr.jsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import React, { useEffect, useState } from "react";
-import QRCode from "qrcode";
-import { bankAccount } from "../config/payment";
-import { vietQrPayload } from "../lib/vietqr";
-import { Icon } from "./UI";
-
-export default function PaymentQr({ amount, content }) {
- const [svg, setSvg] = useState("");
- const payload = vietQrPayload({ bin: bankAccount.bin, accountNo: bankAccount.accountNo, amount, content });
- useEffect(() => {
- let alive = true;
- QRCode.toString(payload, { type: "svg", margin: 1, errorCorrectionLevel: "M", color: { dark: "#10152a", light: "#ffffff" } })
- .then((s) => alive && setSvg(s))
- .catch(() => alive && setSvg(""));
- return () => {
- alive = false;
- };
- }, [payload]);
- return (
-
- {svg ? (
-
- ) : (
-
- )}
-
- {bankAccount.bankName} · {bankAccount.accountNo}
-
- {bankAccount.holder}
-
-
- );
-}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx
new file mode 100644
index 0000000..f51f2b6
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx
@@ -0,0 +1,301 @@
+/*
+ * ADMIN LAYOUT - KHUNG GIAO DIỆN CHUNG KHU VỰC QUẢN TRỊ (ADMIN)
+ *
+ * Chức năng chính:
+ * - Cung cấp Header chung cho khu quản trị: Logo thương hiệu, menu tài khoản Admin, chuông thông báo.
+ * - Thanh điều hướng phụ (Subnav tabs): Chuyển đổi giữa các phân hệ:
+ * 1. Quản lý tài khoản (admin)
+ * 2. Thêm tài khoản mới (admin/new)
+ * 3. Cấu hình phân quyền (admin/permissions)
+ * 4. Nhật ký hoạt động & đăng nhập (admin/logs)
+ * - Tích hợp hệ thống thông báo nhanh (Bell): Cảnh báo tài khoản bị khóa, cập nhật quyền, lượt đăng nhập mới.
+ * - Menu quản trị (UserMenu): Xem thông tin tài khoản đăng nhập hiện tại và nút đăng xuất.
+ */
+
+import React, { useEffect, useRef, useState } from "react";
+import { Icon } from "../../shared/components/UI.jsx";
+import { go, href } from "../../app/router.js";
+import { useApp } from "../../app/state/AppProvider.jsx";
+import { adminApi } from "./api/adminApi.js";
+import { dateTime } from "./utils/adminUtils.js";
+
+// Danh sách các tab điều hướng trên thanh Subnav của khu vực Admin: [đường dẫn con, tên hiển thị]
+const TABS = [
+ ["", "Tài khoản"],
+ ["new", "Thêm tài khoản"],
+ ["permissions", "Quyền truy cập"],
+ ["logs", "Nhật ký hoạt động"],
+];
+
+// Khóa lưu danh sách ID thông báo đã đọc trong LocalStorage của trình duyệt
+const READ_KEY = "safespace.admin.notices.read";
+
+/*
+ * useNotices - Custom Hook quản lý thông báo hệ thống cho Admin
+ *
+ * Luồng hoạt động:
+ * 1. Gọi song song API thống kê (adminApi.stats) và lịch sử đăng nhập mới nhất (adminApi.loginHistory).
+ * 2. Tổng hợp thành danh sách các thông báo cảnh báo:
+ * - Cảnh báo có tài khoản đang bị khóa hoặc ngừng hoạt động.
+ * - Thông báo khi có thay đổi cấu hình quyền/vai trò gần đây.
+ * - Thông báo lượt đăng nhập mới nhất vào hệ thống.
+ * 3. Quản lý trạng thái đọc thông báo thông qua LocalStorage.
+ */
+function useNotices(onApiError) {
+ // Danh sách các mục thông báo được tạo tự động từ dữ liệu hệ thống
+ const [items, setItems] = useState([]);
+
+ // Danh sách ID các thông báo mà Admin đã đọc (khởi tạo từ LocalStorage)
+ const [read, setRead] = useState(() => {
+ try {
+ return JSON.parse(localStorage.getItem(READ_KEY)) || [];
+ } catch {
+ return [];
+ }
+ });
+
+ // Tải dữ liệu để tạo thông báo khi component được gắn kết (mount)
+ useEffect(() => {
+ let alive = true;
+ (async () => {
+ try {
+ // Tải đồng thời thống kê và lần đăng nhập gần nhất
+ const [stats, logins] = await Promise.all([adminApi.stats(), adminApi.loginHistory({ page: 1, pageSize: 1 })]);
+ if (!alive) return;
+ const list = [];
+
+ // 1. Thông báo về tài khoản bị khóa / ngưng hoạt động
+ const locked = stats.inactiveUsersCount || 0;
+ list.push({
+ id: `locked-${locked}`,
+ title: "Tài khoản cần kiểm tra",
+ detail: locked ? `${locked} tài khoản đang khoá hoặc ngưng hoạt động.` : "Rà soát vai trò và cơ sở phụ trách.",
+ to: "admin",
+ });
+
+ // 2. Thông báo khi có hoạt động phân quyền mới nhất
+ const access = (stats.recentActivities || []).find((a) => /^(ROLE|PERMISSION)_/.test(a.action));
+ if (access) {
+ list.push({
+ id: `access-${access.logId}`,
+ title: "Quyền truy cập được cập nhật",
+ detail: `Lúc ${dateTime(access.loggedAt)}. Xem cấu hình quyền theo vai trò.`,
+ to: "admin/permissions",
+ });
+ }
+
+ // 3. Thông báo về lượt đăng nhập gần nhất
+ const last = logins.items?.[0];
+ if (last) {
+ list.push({
+ id: `login-${last.loginHistoryId}`,
+ title: "Nhật ký hoạt động mới",
+ detail: `${last.fullName} đăng nhập lúc ${dateTime(last.loginAt)}.`,
+ to: "admin/logs",
+ });
+ }
+
+ setItems(list);
+ } catch (e) {
+ onApiError?.(e);
+ }
+ })();
+ return () => {
+ alive = false;
+ };
+ }, [onApiError]);
+
+ // Đánh dấu các thông báo đã đọc và lưu vào LocalStorage (giữ tối đa 100 ID gần nhất)
+ const mark = (ids) => {
+ const next = [...new Set([...read, ...ids])].slice(-100);
+ setRead(next);
+ try {
+ localStorage.setItem(READ_KEY, JSON.stringify(next));
+ } catch {
+ /* bỏ qua lỗi nếu không lưu được vào localStorage */
+ }
+ };
+
+ return { items: items.map((n) => ({ ...n, read: read.includes(n.id) })), mark };
+}
+
+/*
+ * Bell - Component Chuông Thông Báo
+ *
+ * Hiển thị biểu tượng chuông và chấm đỏ khi có thông báo chưa đọc.
+ * Nhấn chuông để mở popup danh sách thông báo, bấm vào thông báo sẽ dẫn đến trang tương ứng.
+ */
+function Bell() {
+ const { onApiError } = useApp();
+ const { items, mark } = useNotices(onApiError);
+ const [open, setOpen] = useState(false); // Trạng thái mở/đóng popup thông báo
+ const ref = useRef(null);
+
+ // Đếm số lượng thông báo chưa đọc
+ const unread = items.filter((n) => !n.read).length;
+
+ // Lắng nghe sự kiện click bên ngoài hoặc phím Escape để tự động đóng popup
+ useEffect(() => {
+ if (!open) return undefined;
+ const onDown = (e) => !ref.current?.contains(e.target) && setOpen(false);
+ const onKey = (e) => e.key === "Escape" && setOpen(false);
+ document.addEventListener("pointerdown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("pointerdown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ return (
+
+ {/* Bấm vào thông báo: Đánh dấu đã đọc, đóng popup và chuyển hướng đến trang tương ứng */}
+
+
+ ))}
+
+ {/* Nút đánh dấu tất cả thông báo là đã đọc */}
+ {unread > 0 && (
+
+ )}
+
+ )}
+
+ );
+}
+
+/*
+ * UserMenu - Component Menu Người Dùng Quản Trị
+ *
+ * Hiển thị họ tên Admin hiện tại và nút mở menu tùy chọn (xem email, username, đăng xuất).
+ */
+function UserMenu() {
+ const { user, logout } = useApp();
+ const [open, setOpen] = useState(false); // Trạng thái mở/đóng dropdown menu
+ const ref = useRef(null);
+
+ // Đóng menu khi bấm ra ngoài
+ useEffect(() => {
+ if (!open) return undefined;
+ const onDown = (e) => !ref.current?.contains(e.target) && setOpen(false);
+ document.addEventListener("pointerdown", onDown);
+ return () => document.removeEventListener("pointerdown", onDown);
+ }, [open]);
+
+ return (
+
+ {/* Nút hiển thị tên Admin */}
+
+
+ {/* Menu thả xuống */}
+ {open && (
+
+
+ {user?.username}
+
+ {user?.email}
+
+ {/* Nút Đăng xuất: gọi logout từ context và điều hướng về trang đăng nhập */}
+
+
+ )}
+
+ );
+}
+
+/*
+ * AdminLayout - Layout bao bọc chính cho các trang quản trị
+ *
+ * Tham số:
+ * - tab: tên tab con đang kích hoạt ("" | "new" | "permissions" | "logs")
+ * - children: nội dung component của trang tương ứng được hiển thị bên dưới thanh điều hướng
+ */
+export default function AdminLayout({ tab, children }) {
+ return (
+ <>
+ {/* Header cấp cao nhất: Logo SafeSpace, Menu người dùng và Chuông thông báo */}
+
+
+
+
+ {/* Thanh điều hướng các tab phân hệ quản trị */}
+
+
+ {/* Nội dung chính của trang quản trị */}
+ {children}
+ >
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminRoutes.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminRoutes.jsx
new file mode 100644
index 0000000..a5f94a7
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminRoutes.jsx
@@ -0,0 +1,86 @@
+/*
+ * ADMIN APP - ĐIỀU HƯỚNG TRANG QUẢN TRỊ
+ *
+ * Chức năng chính:
+ * - Nhận thông tin đường dẫn (URL) từ component cha.
+ * - Xác định Admin đang truy cập chức năng nào.
+ * - Hiển thị component tương ứng với đường dẫn.
+ * - Sử dụng AdminShell làm layout chung cho các trang Admin.
+ *
+ * File này KHÔNG trực tiếp xử lý dữ liệu người dùng
+ * hoặc gọi API. Nó chỉ quyết định component nào được hiển thị.
+ */
+
+import React from "react";
+import { Empty, LinkButton } from "../../shared/components/UI.jsx";
+import CreateUserPage from "./users/CreateUserPage.jsx";
+import AuditLogPage from "./logs/AuditLogPage.jsx";
+import PermissionListPage from "./permissions/PermissionListPage.jsx";
+import AdminLayout from "./AdminLayout.jsx";
+import UserDetailPage from "./users/UserDetailPage.jsx";
+import UserListPage from "./users/UserListPage.jsx";
+
+// Định tuyến khu quản trị: #/admin, #/admin/users/:id, #/admin/new, #/admin/permissions, #/admin/logs
+export default function AdminRoutes({ parts }) {
+
+ // Lấy hai phần đầu tiên của đường dẫn.
+ // a: tên chức năng đang truy cập (users, new, logs,...).
+ // b: tham số bổ sung, thường là ID người dùng.
+ const [a, b] = parts;
+
+ // tab xác định mục menu đang được chọn trong AdminShell.
+ // Mặc định là chuỗi rỗng.
+ let tab = "";
+
+ // body lưu component sẽ được hiển thị
+ // bên trong layout AdminShell.
+ let body;
+
+ // TRƯỜNG HỢP 1: Admin truy cập #/admin
+ // Không có phần đường dẫn bổ sung (!a).
+ // Hiển thị trang danh sách người dùng mặc định.
+ if (!a) body = ;
+
+ // TRƯỜNG HỢP 2: Admin truy cập #/admin/users/:id
+ // a phải là "users" và b phải có giá trị.
+ // Hiển thị trang chi tiết của người dùng có ID tương ứng.
+ // key={b} giúp React tạo lại component khi ID thay đổi.
+ else if (a === "users" && b)
+ body = ;
+
+ // TRƯỜNG HỢP 3: Admin truy cập #/admin/new
+ // Chọn tab "new" và hiển thị form tạo tài khoản mới.
+ else if (a === "new") {
+ tab = "new";
+ body = ;
+
+ // TRƯỜNG HỢP 4: Admin truy cập #/admin/permissions
+ // Chọn tab "permissions" và hiển thị trang quản lý phân quyền.
+ } else if (a === "permissions") {
+ tab = "permissions";
+ body = ;
+
+ // TRƯỜNG HỢP 5: Admin truy cập #/admin/logs
+ // Chọn tab "logs" và hiển thị nhật ký hệ thống.
+ } else if (a === "logs") {
+ tab = "logs";
+ body = ;
+
+ // TRƯỜNG HỢP 6: URL không khớp với chức năng nào.
+ // Hiển thị thông báo không tìm thấy trang.
+ // Cung cấp nút quay lại trang quản lý tài khoản.
+ } else
+ body = (
+
+
+ Về quản lý tài khoản
+
+
+ );
+
+ // Render layout chung của Admin.
+ // tab: truyền mục menu hiện tại cho AdminShell.
+ // body: nội dung trang được chọn ở các điều kiện phía trên.
+ // {body} được truyền vào AdminShell thông qua children.
+ return {body};
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/api/adminApi.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/api/adminApi.js
new file mode 100644
index 0000000..676c64c
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/api/adminApi.js
@@ -0,0 +1,111 @@
+/*
+ * ADMIN API - CÁC HÀM GỌI API BACKEND CHO KHU VỰC QUẢN TRỊ
+ *
+ * Định nghĩa các endpoint quản trị tương ứng trên backend (StorageProject.Api/Endpoints/AdminEndpoints.cs).
+ * Tất cả các endpoint đều yêu cầu xác thực JWT với vai trò ADMIN (trừ facilities() là danh mục cơ sở công khai).
+ *
+ * Các nhóm chức năng API:
+ * 1. Thống kê Dashboard (dashboard stats)
+ * 2. Quản lý người dùng (danh sách, chi tiết, tạo mới, sửa thông tin, đặt lại mật khẩu)
+ * 3. Phân quyền và vai trò (danh sách vai trò/quyền, gán/thu hồi vai trò của user, gán/thu hồi quyền của vai trò)
+ * 4. Phân công cơ sở (lịch sử phân công của user, phân công cơ sở mới, cập nhật trạng thái phân công)
+ * 5. Nhật ký kiểm toán (lịch sử đăng nhập, nhật ký hoạt động thay đổi dữ liệu)
+ * 6. Danh mục cơ sở (lấy danh sách các cơ sở SafeSpace để phục vụ gán cơ sở)
+ */
+
+import { request } from "../../../shared/api/httpClient.js";
+
+/*
+ * q - Chuyển đổi đối tượng tham số (params) thành chuỗi Query String cho URL
+ *
+ * Tự động lọc bỏ các giá trị undefined, null, hoặc chuỗi rỗng "".
+ * Ví dụ: { page: 1, search: "admin", status: "" } -> "?page=1&search=admin"
+ */
+const q = (params = {}) => {
+ const s = new URLSearchParams();
+ for (const [k, v] of Object.entries(params)) {
+ if (v !== undefined && v !== null && v !== "") s.set(k, v);
+ }
+ const str = s.toString();
+ return str ? `?${str}` : "";
+};
+
+export const adminApi = {
+ /*
+ * 1. THỐNG KÊ DASHBOARD QUẢN TRỊ
+ * GET /api/admin/dashboard/stats
+ * Trả về: tổng số tài khoản, số lượng theo vai trò, số tài khoản bị khóa/ngưng hoạt động, hoạt động gần đây.
+ */
+ stats: () => request("/api/admin/dashboard/stats"),
+
+ /*
+ * 2. QUẢN LÝ TÀI KHOẢN NGƯỜI DÙNG
+ */
+ // Lấy danh sách người dùng có phân trang và bộ lọc: page, pageSize, searchTerm, status, roleId
+ users: (filter) => request(`/api/admin/users${q(filter)}`),
+
+ // Lấy thông tin chi tiết một tài khoản theo userId (kèm danh sách roles, số hợp đồng, tickets)
+ user: (id) => request(`/api/admin/users/${id}`),
+
+ // Tạo tài khoản mới (POST /api/admin/users)
+ // Body gồm: username, password, fullName, email, phone, initialRoleId, status
+ createUser: (body) => request("/api/admin/users", { method: "POST", body }),
+
+ // Cập nhật thông tin tài khoản (PUT /api/admin/users/{id})
+ // Body gồm: fullName, email, phone, status
+ updateUser: (id, body) => request(`/api/admin/users/${id}`, { method: "PUT", body }),
+
+ // Đặt lại mật khẩu cho tài khoản (POST /api/admin/users/{id}/reset-password)
+ // Body gồm: { newPassword }
+ resetPassword: (id, newPassword) => request(`/api/admin/users/${id}/reset-password`, { method: "POST", body: { newPassword } }),
+
+ /*
+ * 3. QUẢN LÝ VAI TRÒ VÀ PHÂN QUYỀN TRUY CẬP
+ */
+ // Lấy danh sách tất cả vai trò trong hệ thống kèm quyền được gán
+ roles: () => request("/api/admin/roles"),
+
+ // Lấy danh sách tất cả các quyền hạn (permissions) được định nghĩa trong hệ thống
+ permissions: () => request("/api/admin/permissions"),
+
+ // Gán một vai trò cho người dùng (POST /api/admin/users/{userId}/roles)
+ assignRole: (userId, roleId) => request(`/api/admin/users/${userId}/roles`, { method: "POST", body: { roleId } }),
+
+ // Thu hồi một vai trò khỏi người dùng (DELETE /api/admin/users/{userId}/roles/{roleId})
+ revokeRole: (userId, roleId) => request(`/api/admin/users/${userId}/roles/${roleId}`, { method: "DELETE" }),
+
+ // Gán một quyền cho vai trò (POST /api/admin/roles/{roleId}/permissions)
+ assignPermission: (roleId, permissionId) => request(`/api/admin/roles/${roleId}/permissions`, { method: "POST", body: { permissionId } }),
+
+ // Thu hồi một quyền khỏi vai trò (DELETE /api/admin/roles/{roleId}/permissions/{permissionId})
+ revokePermission: (roleId, permissionId) => request(`/api/admin/roles/${roleId}/permissions/${permissionId}`, { method: "DELETE" }),
+
+ /*
+ * 4. PHÂN CÔNG CƠ SỞ (FACILITY ASSIGNMENT)
+ */
+ // Lấy lịch sử phân công cơ sở của người dùng (nhân viên hoặc quản lý cơ sở)
+ userFacilities: (userId) => request(`/api/admin/users/${userId}/facilities`),
+
+ // Tạo mới phân công cơ sở cho người dùng (POST /api/admin/user-facilities)
+ // Body gồm: userId, facilityId, assignedFrom, assignedTo
+ assignFacility: (body) => request("/api/admin/user-facilities", { method: "POST", body }),
+
+ // Đổi trạng thái phân công cơ sở (PUT /api/admin/user-facilities/{id}/status)
+ // Trạng thái: ACTIVE, SUSPENDED, ENDED
+ setAssignmentStatus: (id, status) => request(`/api/admin/user-facilities/${id}/status`, { method: "PUT", body: { status } }),
+
+ /*
+ * 5. NHẬT KÝ KIỂM TOÁN (AUDIT LOGS)
+ */
+ // Lấy lịch sử đăng nhập hệ thống: có phân trang, lọc theo khoảng ngày (fromDate, toDate)
+ loginHistory: (filter) => request(`/api/admin/logs/login-history${q(filter)}`),
+
+ // Lấy nhật ký thay đổi dữ liệu và phân quyền: có phân trang, lọc theo khoảng ngày (fromDate, toDate)
+ activityLogs: (filter) => request(`/api/admin/logs/activity-logs${q(filter)}`),
+
+ /*
+ * 6. DANH MỤC CƠ SỞ CHUNG
+ * Lấy danh sách tất cả cơ sở để Admin chọn khi phân công người dùng phụ trách (không yêu cầu quyền Admin)
+ */
+ facilities: () => request("/api/facilities", { auth: false }),
+};
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/logs/AuditLogPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/logs/AuditLogPage.jsx
new file mode 100644
index 0000000..a357438
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/logs/AuditLogPage.jsx
@@ -0,0 +1,247 @@
+/*
+ * AUDIT LOG PAGE - NHẬT KÝ HOẠT ĐỘNG & LỊCH SỬ ĐĂNG NHẬP
+ *
+ * Chức năng chính:
+ * 1. Cho phép Quản trị viên (Admin) theo dõi toàn bộ hoạt động kiểm toán trong hệ thống:
+ * - Lịch sử đăng nhập: Thời gian, người dùng, IP, thiết bị, trạng thái (thành công / thất bại), giờ đăng xuất.
+ * - Thay đổi dữ liệu: Tạo, sửa, khóa, mở khóa tài khoản, phân công cơ sở.
+ * - Phân quyền: Gán hoặc thu hồi vai trò của người dùng, cấp hoặc gỡ quyền hạn của vai trò.
+ * 2. Phân loại theo Tab:
+ * - "Tất cả" (all): Gộp cả lịch sử đăng nhập và nhật ký hành động, sắp xếp mới nhất lên đầu.
+ * - "Đăng nhập" (login): Chỉ xem lịch sử đăng nhập (phân trang phía server).
+ * - "Thay đổi dữ liệu" (data): Nhật ký thay đổi người dùng, cơ sở.
+ * - "Phân quyền" (access): Nhật ký thay đổi vai trò và quyền hạn.
+ * 3. Bộ lọc thời gian: Lọc nhật ký từ ngày đến ngày (DatePicker).
+ * 4. Phân trang: Hiển thị 10 bản ghi mỗi trang.
+ */
+
+import React, { useMemo, useState } from "react";
+import { adminApi } from "../api/adminApi.js";
+import { parseUtc } from "../../../shared/api/apiMappers.js";
+import { DatePicker, Pagination } from "../../../shared/components/Pickers.jsx";
+import { Notice } from "../../../shared/components/UI.jsx";
+import { ACTION_GROUPS, roleLabel, sortRoles } from "../../../shared/utils/roles.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { dateTime, describeActivity, useLoad } from "../utils/adminUtils.js";
+
+// Danh sách các tab phân loại nhật ký: [mã tab, tên hiển thị]
+const TABS = [
+ ["all", "Tất cả"],
+ ["login", "Đăng nhập"],
+ ["data", "Thay đổi dữ liệu"],
+ ["access", "Phân quyền"],
+];
+
+// Số bản ghi hiển thị trên mỗi trang bảng
+const PAGE_SIZE = 10;
+
+// Số lượng bản ghi mới nhất tải về để gộp và lọc ở phía giao diện cho các tab tổng hợp
+const FETCH = 100;
+
+/*
+ * Các hàm tiện ích chuyển ngày địa phương thành mốc giờ UTC:
+ * - startOf(d): chuyển ngày d thành đầu ngày UTC (00:00:00)
+ * - endOf(d): chuyển ngày d thành cuối ngày UTC (23:59:59)
+ */
+const startOf = (d) => (d ? new Date(`${d}T00:00:00`).toISOString() : undefined);
+const endOf = (d) => (d ? new Date(`${d}T23:59:59`).toISOString() : undefined);
+
+export default function AuditLogPage() {
+ const { onApiError } = useApp();
+
+ /*
+ * STATE BỘ LỌC VÀ PHÂN TRANG
+ */
+ const [tab, setTab] = useState("all"); // Tab đang chọn (all, login, data, access)
+ const [from, setFrom] = useState(""); // Lọc từ ngày (chuỗi YYYY-MM-DD)
+ const [to, setTo] = useState(""); // Lọc đến ngày (chuỗi YYYY-MM-DD)
+ const [page, setPage] = useState(1); // Số trang hiện tại
+
+ /*
+ * TẢI DANH SÁCH NGƯỜI DÙNG ĐỂ MAP TÊN VÀ VAI TRÒ
+ * Tải map người dùng (tối đa 500) để tra cứu họ tên và vai trò theo userId nhanh chóng khi hiển thị log.
+ */
+ const users = useLoad(async () => {
+ const res = await adminApi.users({ page: 1, pageSize: 500 });
+ return new Map(res.items.map((u) => [u.userId, u]));
+ }, [], onApiError);
+
+ /*
+ * TẢI NHẬT KÝ TỪ BACKEND
+ * - Nếu tab là "login": Chỉ gọi API loginHistory với phân trang từ server.
+ * - Nếu tab khác: Gọi đồng thời cả loginHistory (nếu tab all) và activityLogs theo khoảng ngày lọc.
+ */
+ const logs = useLoad(async () => {
+ const range = { fromDate: startOf(from), toDate: endOf(to) };
+ if (tab === "login") return { login: await adminApi.loginHistory({ page, pageSize: PAGE_SIZE, ...range }) };
+ const [login, activity] = await Promise.all([
+ tab === "all" ? adminApi.loginHistory({ page: 1, pageSize: FETCH, ...range }) : null,
+ adminApi.activityLogs({ page: 1, pageSize: FETCH, ...range }),
+ ]);
+ return { login, activity };
+ }, [tab, from, to, tab === "login" ? page : 0], onApiError);
+
+ const userMap = users.data || new Map();
+ // Hàm lấy tên người dùng từ map
+ const nameOf = (id) => userMap.get(id)?.fullName;
+ // Hàm lấy chuỗi các vai trò của người dùng từ map
+ const rolesOf = (id) => sortRoles(userMap.get(id)?.roles || []).map(roleLabel).join(", ") || "—";
+
+ /*
+ * rows - Chuẩn hóa và gộp danh sách bản ghi hiển thị
+ * - Chuyển login logs và activity logs thành định dạng bảng thống nhất.
+ * - Tab "login": chỉ hiển thị danh sách đăng nhập.
+ * - Tab khác: lọc theo nhóm hành động (ACTION_GROUPS) và sắp xếp theo mốc thời gian giảm dần (mới nhất lên trước).
+ */
+ const rows = useMemo(() => {
+ const d = logs.data;
+ if (!d) return [];
+
+ // Chuẩn hóa danh sách lịch sử đăng nhập
+ const loginRows = (d.login?.items || []).map((h) => ({
+ id: `L${h.loginHistoryId}`,
+ at: h.loginAt,
+ userId: h.userId,
+ user: h.fullName || h.username,
+ action: `${h.loginStatus === "SUCCESS" ? "Đăng nhập thành công" : `Đăng nhập ${h.loginStatus === "FAILED" ? "thất bại" : h.loginStatus.toLowerCase()}`}${h.logoutAt ? ` · đăng xuất ${dateTime(h.logoutAt).slice(11)}` : ""}`,
+ ip: h.ipAddress || "—",
+ device: h.deviceInfo,
+ }));
+
+ if (tab === "login") return loginRows;
+
+ // Chuẩn hóa danh sách nhật ký hành động (activity logs)
+ const group = ACTION_GROUPS[tab];
+ const actRows = (d.activity?.items || [])
+ .filter((a) => !group || group.includes(a.action))
+ .map((a) => ({
+ id: `A${a.logId}`,
+ at: a.loggedAt,
+ userId: a.userId,
+ user: a.userId ? nameOf(a.userId) || a.username || `#${a.userId}` : "Hệ thống",
+ action: describeActivity(a, nameOf),
+ ip: a.ipAddress || "—",
+ }));
+
+ // Gộp và sắp xếp theo thời gian mới nhất
+ return [...loginRows, ...actRows].sort((x, y) => (parseUtc(y.at)?.getTime() || 0) - (parseUtc(x.at)?.getTime() || 0));
+ }, [logs.data, tab, userMap]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ /*
+ * TÍNH TOÁN PHÂN TRANG
+ * - tab === "login": Phân trang phía server (serverPaged = true).
+ * - các tab khác: Phân trang phía client trên mảng `rows`.
+ */
+ const serverPaged = tab === "login";
+ const total = serverPaged ? logs.data?.login?.totalItems || 0 : rows.length;
+ const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
+ const current = Math.min(page, pages);
+ const shown = serverPaged ? rows : rows.slice((current - 1) * PAGE_SIZE, current * PAGE_SIZE);
+ const first = (current - 1) * PAGE_SIZE + 1;
+
+ // Hàm chọn giá trị bộ lọc: cập nhật state tương ứng và tự động quay về trang 1
+ const pick = (fn) => (v) => {
+ fn(v);
+ setPage(1);
+ };
+
+ return (
+
+ {/* Tiêu đề trang và phần mô tả */}
+
+
+
Lịch sử đăng nhập & nhật ký hoạt động
+
Theo dõi đăng nhập, thay đổi dữ liệu tài khoản và phân quyền trong hệ thống.
+
+
+
+ {/* Thanh công cụ: Chọn tab loại nhật ký và bộ lọc ngày */}
+
+ {/* Nhóm các nút chuyển đổi Tab */}
+
+ {TABS.map(([k, label]) => (
+
+ ))}
+
+
+ {/* Bộ lọc chọn khoảng ngày (Từ ngày - Đến ngày) */}
+
+
+
+ {/* Nút xóa bộ lọc ngày nếu đang lọc */}
+ {(from || to) && (
+
+ )}
+
+
+
+ {/* Thông báo nếu có lỗi tải log */}
+ {logs.error && {logs.error}}
+
+ {/* Bảng danh sách nhật ký */}
+
+
+
+
+
Thời gian
+
Người dùng
+
Vai trò
+
Hành động
+
Địa chỉ IP
+
+
+
+ {shown.map((r) => (
+
+
{dateTime(r.at)}
+
{r.user}
+
{r.userId ? rolesOf(r.userId) : "—"}
+
{r.action}
+
{r.ip}
+
+ ))}
+ {/* Trường hợp không có dữ liệu */}
+ {!logs.loading && shown.length === 0 && (
+
+
Chưa có hoạt động trong khoảng thời gian này.
+
+ )}
+ {/* Trường hợp đang tải lần đầu */}
+ {logs.loading && !logs.data && (
+
+
Đang tải nhật ký…
+
+ )}
+
+
+
+
+ {/* Thanh điều hướng phân trang */}
+
+
+ {/* Gợi ý khi số bản ghi đạt mốc FETCH ở phía client */}
+ {!serverPaged && total >= FETCH && (
+
Hiển thị {FETCH} bản ghi mới nhất mỗi loại. Dùng bộ lọc ngày để xem các mốc cũ hơn.
+ )}
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx
new file mode 100644
index 0000000..a4fa3f2
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx
@@ -0,0 +1,284 @@
+/*
+ * PERMISSION LIST PAGE - CẤU HÌNH PHÂN QUYỀN TRUY CẬP HỆ THỐNG
+ *
+ * Chức năng chính:
+ * 1. Hiển thị bảng tổng quan các vai trò (Roles) trong hệ thống:
+ * - Tên vai trò (Admin, Quản lý cơ sở, Nhân viên cơ sở, Quản lý vận hành kinh doanh, Khách hàng).
+ * - Phạm vi dữ liệu (Toàn hệ thống, Theo cơ sở phụ trách, Dữ liệu cá nhân).
+ * - Mô tả và tổng số quyền được gán trên tổng số quyền của hệ thống.
+ * 2. Ma trận phân quyền chi tiết (Role-Permission Matrix):
+ * - Hàng là từng quyền thao tác cụ thể (USER_MANAGE, ROLE_MANAGE, CONTRACT_VIEW, UNIT_UPDATE, v.v.).
+ * - Cột là các vai trò trong hệ thống.
+ * - Mỗi ô là một checkbox cho phép bật/tắt quyền.
+ * 3. Quản lý trạng thái thay đổi chưa lưu (changes):
+ * - Đánh dấu ô thay đổi bằng màu khác biệt (.is-changed).
+ * - Đếm số thay đổi chưa lưu.
+ * - Hỗ trợ nút "Hoàn tác" để khôi phục về trạng thái ban đầu.
+ * 4. Xác nhận an toàn trước khi lưu:
+ * - Mở Modal liệt kê chi tiết các quyền sẽ gán hoặc thu hồi.
+ * - Cảnh báo nguy hiểm nếu Quản trị viên vô tình gỡ bỏ quyền quản trị của chính vai trò ADMIN.
+ * - Gọi API assignPermission / revokePermission cho từng thay đổi.
+ */
+
+import React, { useMemo, useState } from "react";
+import { adminApi } from "../api/adminApi.js";
+import { Button, Modal, Notice } from "../../../shared/components/UI.jsx";
+import { ROLE_SCOPE, roleLabel, sortRoles } from "../../../shared/utils/roles.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { useLoad } from "../utils/adminUtils.js";
+
+// Tạo chuỗi khóa duy nhất đại diện cho cặp vai trò và quyền (ví dụ: "1:5")
+const key = (roleId, permissionId) => `${roleId}:${permissionId}`;
+
+export default function PermissionListPage() {
+ const { onApiError, notify } = useApp();
+
+ /*
+ * TẢI DANH SÁCH VAI TRÒ VÀ QUYỀN TỪ BACKEND
+ * Gọi đồng thời:
+ * 1. adminApi.roles(): danh sách vai trò kèm các quyền hiện tại của mỗi vai trò
+ * 2. adminApi.permissions(): danh sách toàn bộ quyền hạn được hỗ trợ trong hệ thống
+ */
+ const res = useLoad(async () => {
+ const [roles, permissions] = await Promise.all([adminApi.roles(), adminApi.permissions()]);
+ return { roles: sortRoles(roles, (r) => r.roleName), permissions };
+ }, [], onApiError);
+
+ /*
+ * STATE QUẢN LÝ THAY ĐỔI VÀ TIẾN TRÌNH LƯU
+ */
+ // Lưu các thay đổi cục bộ chưa lưu lên server: { "roleId:permissionId": true (gán) | false (thu hồi) }
+ const [changes, setChanges] = useState({});
+ // Trạng thái hiển thị modal xác nhận lưu thay đổi
+ const [confirm, setConfirm] = useState(false);
+ // Trạng thái đang gửi request lưu lên backend
+ const [saving, setSaving] = useState(false);
+ // Danh sách các lỗi nếu có request gán/thu hồi quyền thất bại
+ const [errors, setErrors] = useState([]);
+
+ /*
+ * granted - Tập hợp (Set) các quyền ban đầu hiện có từ backend
+ * Duyệt qua từng vai trò và lưu các key "roleId:permissionId" vào Set để tra cứu nhanh O(1).
+ */
+ const granted = useMemo(() => {
+ const s = new Set();
+ for (const r of res.data?.roles || []) {
+ for (const p of r.permissions) {
+ s.add(key(r.roleId, p.permissionId));
+ }
+ }
+ return s;
+ }, [res.data]);
+
+ /*
+ * isOn - Kiểm tra một quyền có đang được tích chọn cho vai trò hay không
+ * Ưu tiên kiểm tra trong `changes` (thay đổi tạm thời của người dùng),
+ * nếu người dùng chưa can thiệp thì lấy theo dữ liệu gốc trong `granted`.
+ */
+ const isOn = (roleId, pid) => {
+ const k = key(roleId, pid);
+ return k in changes ? changes[k] : granted.has(k);
+ };
+
+ /*
+ * toggle - Đảo ngược trạng thái checkbox khi click
+ * Nếu trạng thái mới trùng với dữ liệu gốc ban đầu trong `granted`, xóa khỏi `changes`.
+ */
+ const toggle = (roleId, pid) => {
+ const k = key(roleId, pid);
+ const next = !isOn(roleId, pid);
+ setChanges((c) => {
+ const copy = { ...c };
+ if (next === granted.has(k)) delete copy[k];
+ else copy[k] = next;
+ return copy;
+ });
+ };
+
+ // Mảng các thay đổi đang chờ lưu: [ ["roleId:permissionId", true/false], ... ]
+ const pending = Object.entries(changes);
+ const roles = res.data?.roles || [];
+ const permissions = res.data?.permissions || [];
+
+ // Hàm tra cứu vai trò theo ID
+ const roleOf = (id) => roles.find((r) => String(r.roleId) === String(id));
+ // Hàm tra cứu quyền theo ID
+ const permOf = (id) => permissions.find((p) => String(p.permissionId) === String(id));
+
+ /*
+ * adminLosesAccess - Kiểm tra an toàn:
+ * Phát hiện trường hợp người dùng đang thu hồi các quyền sống còn (USER_MANAGE, ROLE_MANAGE)
+ * của chính vai trò ADMIN, tránh trường hợp tự khóa quyền của chính mình dẫn đến không thể khôi phục.
+ */
+ const adminLosesAccess = pending.some(([k, on]) => {
+ const [rid, pid] = k.split(":");
+ return !on && roleOf(rid)?.roleName === "ADMIN" && ["USER_MANAGE", "ROLE_MANAGE"].includes(permOf(pid)?.permissionCode);
+ });
+
+ /*
+ * save - Thực thi lưu toàn bộ thay đổi lên Backend
+ * 1. Duyệt qua mảng pending.
+ * 2. Nếu on = true: gọi adminApi.assignPermission(roleId, permissionId).
+ * 3. Nếu on = false: gọi adminApi.revokePermission(roleId, permissionId).
+ * 4. Thu thập các lỗi (nếu có) để hiển thị cho Admin.
+ * 5. Tải lại dữ liệu mới từ backend và thông báo qua toast.
+ */
+ const save = async () => {
+ setConfirm(false);
+ setSaving(true);
+ const failed = [];
+
+ for (const [k, on] of pending) {
+ const [rid, pid] = k.split(":").map(Number);
+ try {
+ if (on) await adminApi.assignPermission(rid, pid);
+ else await adminApi.revokePermission(rid, pid);
+ } catch (e) {
+ onApiError(e);
+ failed.push(`${roleLabel(roleOf(rid)?.roleName)} · ${permOf(pid)?.permissionName}: ${e.message}`);
+ }
+ }
+
+ setSaving(false);
+ setErrors(failed);
+ setChanges({});
+ await res.reload();
+ notify(failed.length ? `Đã lưu, ${failed.length} thay đổi không thành công.` : "Đã lưu cấu hình quyền.", failed.length ? "error" : "success");
+ };
+
+ return (
+
+ {/* Tiêu đề trang */}
+
+
+
Cấu hình quyền truy cập dữ liệu
+
Thiết lập phạm vi dữ liệu và quyền thao tác mà mỗi vai trò được phép.
+
+
+
+ {/* Thông báo lỗi khi tải dữ liệu vai trò/quyền */}
+ {res.error && {res.error}}
+
+ {/* BẢNG 1: TỔNG QUAN VAI TRÒ VÀ PHẠM VI DỮ LIỆU */}
+
+
+ {/* Cảnh báo nếu Quản trị viên tự thu hồi quyền quản lý của Admin */}
+ {adminLosesAccess && (
+ Bạn đang thu hồi quyền quản lý tài khoản / vai trò của Quản trị. Hãy chắc chắn vẫn còn cách khôi phục.
+ )}
+
+ {/* Các nút hành động trong Modal */}
+
+
+
+
+
+ )}
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx
new file mode 100644
index 0000000..ba0271b
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx
@@ -0,0 +1,522 @@
+
+/*
+ * ADMIN CREATE USER - TẠO TÀI KHOẢN NGƯỜI DÙNG
+ *
+ * Chức năng:
+ * - Admin nhập thông tin tài khoản mới.
+ * - Tự tạo username từ email nếu Admin chưa tự sửa.
+ * - Tự sinh mật khẩu tạm thời.
+ * - Chọn vai trò cho tài khoản.
+ * - Phân công cơ sở nếu là Staff hoặc Manager.
+ * - Kiểm tra dữ liệu trước khi gửi.
+ * - Gọi API tạo tài khoản trên backend.
+ * - Hiển thị thông tin đăng nhập sau khi tạo thành công.
+ */
+
+
+import React, { useState } from "react";
+import { adminApi } from "../api/adminApi.js";
+import { Select } from "../../../shared/components/Pickers.jsx";
+import { Button, Field, Modal, Notice } from "../../../shared/components/UI.jsx";
+import { isEmail, isPhone, today } from "../../../shared/utils/format.js";
+import { FACILITY_ROLES, roleLabel, sortRoles } from "../../../shared/utils/roles.js";
+import { go } from "../../../app/router.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { tempPassword, useLoad, usernameFrom } from "../utils/adminUtils.js";
+
+/*
+ * EMPTY - DỮ LIỆU FORM MẶC ĐỊNH
+ *
+ * Tất cả trường được khởi tạo là chuỗi rỗng.
+ * Được dùng khi mở form và khi tạo tài khoản tiếp theo.
+ */
+const EMPTY = { fullName: "", email: "", phone: "", username: "", password: "", roleId: "", facilityId: "" };
+
+
+export default function CreateUserPage() {
+
+ // onApiError: xử lý lỗi liên quan đến API, đặc biệt HTTP 401.
+ // notify: hiển thị thông báo toast trên giao diện.
+ const { onApiError, notify } = useApp();
+
+
+ /*
+ * LẤY DANH SÁCH VAI TRÒ VÀ CƠ SỞ TỪ BACKEND
+ *
+ * Promise.all gọi đồng thời hai API:
+ * 1. adminApi.roles(): lấy các vai trò trong hệ thống.
+ * 2. adminApi.facilities(): lấy danh sách cơ sở.
+ *
+ * Sau khi nhận dữ liệu:
+ * - Sắp xếp các vai trò bằng sortRoles.
+ * - Chỉ giữ những cơ sở có trạng thái ACTIVE.
+ *
+ * useLoad quản lý:
+ * - meta.data: dữ liệu API trả về.
+ * - meta.loading: đang tải dữ liệu.
+ * - meta.error: lỗi khi gọi API.
+ */
+
+ const meta = useLoad(async () => {
+ const [roles, facilities] = await Promise.all([adminApi.roles(), adminApi.facilities()]);
+ return { roles: sortRoles(roles, (r) => r.roleName), facilities: facilities.filter((f) => f.status === "ACTIVE") };
+ }, [], onApiError);
+
+
+ /*
+ * STATE CỦA COMPONENT
+ */
+
+ // Lưu toàn bộ thông tin người dùng đang nhập.
+ // Mật khẩu mặc định được tạo bằng tempPassword().
+ const [form, setForm] = useState(() => ({ ...EMPTY, password: tempPassword() }));
+
+ // Kiểm tra Admin đã tự chỉnh username hay chưa.
+ // false: username được tự động tạo theo email.
+ // true: giữ username do Admin tự nhập.
+ const [userTouched, setUserTouched] = useState(false);
+
+ // Lưu các lỗi validation theo từng trường.
+ // Ví dụ: { email: "Email không hợp lệ" }.
+ const [errors, setErrors] = useState({});
+
+ // Trạng thái đang gửi request tạo tài khoản.
+ // Dùng để disable nút và tránh gửi lặp.
+ const [busy, setBusy] = useState(false);
+
+ // Lưu kết quả sau khi tạo tài khoản thành công.
+ // null: chưa tạo thành công, chưa hiện Modal.
+ // Có dữ liệu: hiện Modal thông tin đăng nhập.
+ const [done, setDone] = useState(null);
+
+
+ /*
+ * XÁC ĐỊNH VAI TRÒ ĐANG CHỌN
+ */
+
+ // Lấy danh sách vai trò từ API.
+ // Nếu chưa tải xong thì sử dụng mảng rỗng.
+ const roles = meta.data?.roles || [];
+
+ // Tìm object vai trò dựa trên roleId trong form.
+ // Chuyển sang String để so sánh được cả ID số và chuỗi.
+ const role = roles.find((r) => String(r.roleId) === String(form.roleId));
+
+ // scoped = true nếu vai trò bắt buộc gắn với một cơ sở.
+ // Ví dụ: STAFF hoặc MANAGER.
+ // Vai trò toàn hệ thống không cần chọn cơ sở.
+ const scoped = role && FACILITY_ROLES.includes(role.roleName);
+
+
+ /*
+ * HÀM SET - CẬP NHẬT DỮ LIỆU FORM
+ *
+ * k: tên trường cần cập nhật.
+ * v: giá trị mới của trường.
+ *
+ * Ví dụ:
+ * set("fullName", "Nguyen Van A")
+ * set("email", "abc@gmail.com")
+ */
+
+ const set = (k, v) => {
+
+ // Cập nhật trường tương ứng nhưng giữ nguyên
+ // các trường khác bằng spread operator (...f).
+ setForm((f) => {
+ const next = { ...f, [k]: v };
+
+ // Nếu đang nhập email và Admin chưa tự sửa username,
+ // tự tạo username từ email mới.
+ if (k === "email" && !userTouched) next.username = usernameFrom(v);
+
+ return next;
+ });
+
+ // Xóa lỗi của trường vừa được sửa.
+ // Đồng thời xóa lỗi chung của form để người dùng thử lại.
+ setErrors((e) => ({ ...e, [k]: undefined, form: undefined }));
+ };
+
+
+ /*
+ * VALIDATE - KIỂM TRA FORM TRƯỚC KHI TẠO TÀI KHOẢN
+ *
+ * Hàm chỉ kiểm tra và trả về object chứa các lỗi.
+ * Không gọi API và không lưu dữ liệu.
+ *
+ * Nếu object trả về rỗng {} => form hợp lệ.
+ */
+
+ const validate = () => {
+
+ // Object dùng để lưu các lỗi tìm được.
+ const e = {};
+
+ // Họ tên bắt buộc nhập, không được chỉ chứa khoảng trắng.
+ if (!form.fullName.trim()) e.fullName = "Vui lòng nhập họ và tên.";
+
+ // Kiểm tra định dạng địa chỉ email.
+ if (!isEmail(form.email)) e.email = "Nhập email hợp lệ, ví dụ ten@safespace.vn.";
+
+ // Số điện thoại không bắt buộc.
+ // Nhưng nếu đã nhập thì phải đúng định dạng.
+ if (form.phone && !isPhone(form.phone)) e.phone = "Số điện thoại chưa đúng định dạng.";
+
+ // Username phải dài 3-50 ký tự.
+ // Chỉ được chứa chữ cái, số, dấu chấm, _, @ và -.
+ if (!/^[a-zA-Z0-9._@-]{3,50}$/.test(form.username)) e.username = "Tên đăng nhập 3–50 ký tự: chữ, số, dấu . _ - @";
+
+ // Mật khẩu tạm thời tối thiểu 8 ký tự.
+ if (form.password.length < 8) e.password = "Mật khẩu tạm thời cần ít nhất 8 ký tự.";
+
+ // Bắt buộc lựa chọn một vai trò.
+ if (!form.roleId) e.roleId = "Chọn vai trò cho tài khoản.";
+
+ // Nhân viên và quản lý cơ sở phải được phân công cơ sở.
+ // Các vai trò không thuộc nhóm scoped được bỏ qua điều kiện.
+ if (scoped && !form.facilityId) e.facilityId = "Nhân viên và Quản lý cơ sở cần có cơ sở phụ trách.";
+
+ // Trả về danh sách lỗi để hàm submit xử lý.
+ return e;
+ };
+
+
+ /*
+ * SUBMIT - XỬ LÝ KHI ADMIN NHẤN "TẠO TÀI KHOẢN"
+ *
+ * Luồng xử lý:
+ * 1. Ngăn form reload.
+ * 2. Validate dữ liệu.
+ * 3. Gọi API tạo tài khoản.
+ * 4. Nếu có cơ sở phụ trách => gọi API phân công.
+ * 5. Lưu kết quả để hiển thị Modal.
+ */
+
+ const submit = async (ev) => {
+
+ // Ngăn hành vi submit mặc định của trình duyệt.
+ ev.preventDefault();
+
+ // Kiểm tra toàn bộ dữ liệu trước khi gọi API.
+ const e = validate();
+
+ // Nếu có ít nhất một lỗi, hiển thị lỗi và dừng.
+ if (Object.keys(e).length) return setErrors(e);
+
+ // Bật trạng thái xử lý để vô hiệu hóa nút submit.
+ setBusy(true);
+
+ // Biến lưu thông tin tài khoản được backend tạo.
+ let created;
+
+ try {
+
+ /*
+ * GỌI API TẠO TÀI KHOẢN
+ *
+ * Dữ liệu gửi đi:
+ * - username: tên đăng nhập.
+ * - password: mật khẩu tạm thời.
+ * - fullName: họ tên.
+ * - email: chuyển chữ thường.
+ * - phone: loại bỏ khoảng trắng, dấu . và -.
+ * - initialRoleId: ID vai trò được chọn.
+ * - status: tài khoản được tạo ở trạng thái ACTIVE.
+ */
+
+ created = await adminApi.createUser({
+ username: form.username.trim(),
+ password: form.password,
+ fullName: form.fullName.trim(),
+ email: form.email.trim().toLowerCase(),
+ phone: form.phone.replace(/[\s.-]/g, "") || null,
+ initialRoleId: Number(form.roleId),
+ status: "ACTIVE",
+ });
+
+ } catch (err) {
+
+ // Xử lý lỗi API, ví dụ phiên đăng nhập hết hạn.
+ onApiError(err);
+
+ // Tắt trạng thái đang xử lý.
+ setBusy(false);
+
+ // Lấy thông báo lỗi từ backend.
+ // Nếu không có thì sử dụng thông báo mặc định.
+ const msg = err.message || "Không tạo được tài khoản.";
+
+ // Nếu lỗi liên quan đến username,
+ // hiển thị ngay tại trường Tên đăng nhập.
+ if (/Tên đăng nhập/i.test(msg)) return setErrors({ username: msg });
+
+ // Nếu lỗi liên quan đến email,
+ // hiển thị ngay tại trường Email.
+ if (/Email/i.test(msg)) return setErrors({ email: msg });
+
+ // Các lỗi khác hiển thị phía trên form.
+ return setErrors({ form: msg });
+ }
+
+
+ /*
+ * PHÂN CÔNG CƠ SỞ SAU KHI TẠO TÀI KHOẢN
+ *
+ * Đây là request riêng, chạy sau createUser.
+ * Nếu phân công lỗi, tài khoản vẫn đã được tạo.
+ */
+
+ // Biến lưu lỗi phân công cơ sở (nếu có).
+ let facilityError = null;
+
+ // Chỉ phân công khi vai trò cần cơ sở
+ // và Admin đã chọn một cơ sở.
+ if (scoped && form.facilityId) {
+ try {
+
+ // Gọi API gán cơ sở cho tài khoản vừa tạo.
+ // userId: ID tài khoản mới.
+ // facilityId: cơ sở Admin chọn.
+ // assignedFrom: ngày bắt đầu phân công.
+ // assignedTo: null nghĩa là chưa xác định ngày kết thúc.
+ await adminApi.assignFacility({ userId: created.userId, facilityId: Number(form.facilityId), assignedFrom: today(), assignedTo: null });
+
+ } catch (err) {
+
+ // Lưu lỗi để cảnh báo trong Modal.
+ // Không hủy kết quả tạo tài khoản trước đó.
+ facilityError = err.message;
+ }
+ }
+
+ // Hoàn tất quá trình gửi API.
+ setBusy(false);
+
+ // Lưu kết quả thành công.
+ // State done có giá trị sẽ làm Modal xuất hiện.
+ // Lưu password để Admin xem và sao chép một lần.
+ setDone({ user: created, password: form.password, facilityError });
+ };
+
+
+ /*
+ * COPY - SAO CHÉP THÔNG TIN ĐĂNG NHẬP
+ *
+ * Dùng Clipboard API của trình duyệt.
+ * Sao chép username hoặc mật khẩu tạm thời.
+ */
+
+ const copy = async (text) => {
+ try {
+
+ // Ghi chuỗi được truyền vào clipboard.
+ await navigator.clipboard.writeText(text);
+
+ // Hiển thị toast sao chép thành công.
+ notify("Đã sao chép.");
+
+ } catch {
+
+ // Thông báo nếu trình duyệt không cho phép sao chép.
+ notify("Không sao chép được, vui lòng chép thủ công.", "error");
+ }
+ };
+
+
+ /*
+ * RENDER GIAO DIỆN TẠO TÀI KHOẢN
+ */
+
+ return (
+
+
+ {/* FORM CHÍNH
+ onSubmit gọi hàm submit khi Admin nhấn Tạo tài khoản.
+ noValidate tắt validation mặc định của HTML,
+ để sử dụng hàm validate tự viết phía trên. */}
+
+
+
+ {/* MODAL SAU KHI TẠO TÀI KHOẢN THÀNH CÔNG
+ Chỉ xuất hiện khi done khác null.
+ Khi đóng Modal sẽ chuyển sang trang chi tiết User. */}
+ {done && (
+ go(`admin/users/${done.user.userId}`)}>
+
+ {/* Thông báo Admin cần gửi thông tin đăng nhập
+ cho người dùng mới và mật khẩu chỉ hiển thị một lần. */}
+
Gửi thông tin đăng nhập dưới đây cho {done.user.fullName}. Mật khẩu chỉ hiển thị một lần.
+
+ {/* HIỂN THỊ USERNAME VÀ PASSWORD */}
+
+
+ {/* Username của tài khoản vừa được tạo.
+ Nút Chép gọi hàm copy(username). */}
+
+
+ {/* Nếu tạo User thành công nhưng phân công cơ sở lỗi,
+ hiển thị thông báo để Admin phân công lại sau. */}
+ {done.facilityError && Chưa phân công được cơ sở: {done.facilityError}. Bạn có thể phân công lại trong trang chi tiết.}
+
+
+
+ {/* Chuyển đến trang chi tiết User vừa tạo. */}
+
+
+ {/* RESET FORM ĐỂ TẠO THÊM TÀI KHOẢN
+ - Đóng Modal.
+ - Đưa các trường về giá trị mặc định.
+ - Tạo mật khẩu tạm thời mới.
+ - Cho phép username tự sinh lại theo email. */}
+
+
+
+ )}
+
+ );
+}
\ No newline at end of file
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx
new file mode 100644
index 0000000..8501d51
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx
@@ -0,0 +1,524 @@
+/*
+ * USER DETAIL PAGE - XEM VÀ CHỈNH SỬA CHI TIẾT TÀI KHOẢN NGƯỜI DÙNG
+ *
+ * Chức năng chính:
+ * 1. Hiển thị tổng quan tài khoản:
+ * - Tên, username, vai trò, ngày tạo, trạng thái hiện tại (Đang hoạt động, Đang khoá, Ngưng hoạt động).
+ * - 4 ô thống kê: Số hợp đồng đang thuê, yêu cầu hỗ trợ đang mở, đăng nhập gần nhất, cập nhật gần nhất.
+ * 2. Thẻ 1: Thông tin tài khoản (InfoCard):
+ * - Sửa họ tên, email, số điện thoại, trạng thái tài khoản.
+ * - Kiểm tra hợp lệ dữ liệu (họ tên không rỗng, định dạng email, số điện thoại).
+ * - Nút "Lưu thay đổi" chỉ bật khi có dữ liệu thay đổi (dirty) và không trong trạng thái đang gửi request.
+ * 3. Thẻ 2: Đặt lại mật khẩu (PasswordCard):
+ * - Cho phép Admin nhập mật khẩu mới hoặc bấm "Tạo ngẫu nhiên" mật khẩu mạnh 12 ký tự.
+ * - Gọi API resetPassword và mở Modal hiển thị mật khẩu mới để Admin sao chép gửi cho người dùng.
+ * 4. Thẻ 3: Quản lý vai trò (RolesCard):
+ * - Danh sách các vai trò tài khoản đang sở hữu dưới dạng pill.
+ * - Nút xoá (x) trên từng pill để thu hồi vai trò kèm Modal cảnh báo xác nhận.
+ * - Dropdown chọn vai trò để gán thêm vai trò mới (chỉ hiển thị những vai trò tài khoản chưa có).
+ * 5. Thẻ 4: Phân công cơ sở phụ trách (FacilityCard):
+ * - Hiển thị cơ sở đang phụ trách hiện tại (ACTIVE).
+ * - Bảng lịch sử phân công cơ sở: Tên cơ sở, người phân công, thời gian từ ngày - đến ngày, trạng thái.
+ * - Các thao tác trạng thái: Tạm ngưng (SUSPENDED), Kết thúc (ENDED), Kích hoạt lại (ACTIVE).
+ * - Form gán cơ sở mới kèm ngày bắt đầu phân công.
+ */
+
+import React, { useEffect, useState } from "react";
+import { adminApi } from "../api/adminApi.js";
+import { DatePicker, Select } from "../../../shared/components/Pickers.jsx";
+import { Button, Empty, Field, LinkButton, Modal, Notice, StatusTag } from "../../../shared/components/UI.jsx";
+import { isEmail, isPhone, today } from "../../../shared/utils/format.js";
+import { ASSIGNMENT_STATUS, USER_STATUS, needsFacility, roleLabel, sortRoles } from "../../../shared/utils/roles.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { dateOnlyLabel, dateTime, tempPassword, useLoad } from "../utils/adminUtils.js";
+
+/*
+ * InfoCard - Thẻ Cập Nhật Thông Tin Cá Nhân & Trạng Thái Tài Khoản
+ *
+ * Tham số:
+ * - user: đối tượng người dùng hiện tại
+ * - onSaved: callback làm mới lại dữ liệu từ server sau khi cập nhật thành công
+ */
+function InfoCard({ user, onSaved }) {
+ const { onApiError, notify } = useApp();
+
+ // State lưu dữ liệu form chỉnh sửa
+ const [form, setForm] = useState({ fullName: user.fullName, email: user.email, phone: user.phone || "", status: user.status });
+ // State lưu lỗi validation từng trường
+ const [errors, setErrors] = useState({});
+ // Trạng thái đang gửi API
+ const [busy, setBusy] = useState(false);
+
+ // Đồng bộ lại form khi thông tin user thay đổi
+ useEffect(() => {
+ setForm({ fullName: user.fullName, email: user.email, phone: user.phone || "", status: user.status });
+ }, [user]);
+
+ // Kiểm tra dữ liệu form có thay đổi so với dữ liệu gốc không
+ const dirty = form.fullName !== user.fullName || form.email !== user.email || form.phone !== (user.phone || "") || form.status !== user.status;
+
+ // Cập nhật giá trị một trường trong form
+ const set = (k, v) => {
+ setForm({ ...form, [k]: v });
+ setErrors({});
+ };
+
+ // Xử lý gửi form cập nhật thông tin
+ const save = async (e) => {
+ e.preventDefault();
+ const err = {};
+ if (!form.fullName.trim()) err.fullName = "Vui lòng nhập họ và tên.";
+ if (!isEmail(form.email)) err.email = "Email chưa hợp lệ.";
+ if (form.phone && !isPhone(form.phone)) err.phone = "Số điện thoại chưa đúng định dạng.";
+ if (Object.keys(err).length) return setErrors(err);
+
+ setBusy(true);
+ try {
+ await adminApi.updateUser(user.userId, {
+ fullName: form.fullName.trim(),
+ email: form.email.trim().toLowerCase(),
+ phone: form.phone.replace(/[\s.-]/g, "") || null,
+ status: form.status,
+ });
+ notify("Đã cập nhật tài khoản.");
+ onSaved();
+ } catch (ex) {
+ onApiError(ex);
+ setErrors({ form: ex.message });
+ }
+ setBusy(false);
+ };
+
+ return (
+
+ );
+}
+
+/*
+ * PasswordCard - Thẻ Đặt Lại Mật Khẩu Cho Người Dùng
+ *
+ * Cho phép Admin cấp lại mật khẩu mới cho người dùng.
+ * Sau khi đổi xong sẽ bật Modal hiển thị mật khẩu để sao chép.
+ */
+function PasswordCard({ user }) {
+ const { onApiError } = useApp();
+ const [pw, setPw] = useState(""); // Mật khẩu mới đang nhập
+ const [error, setError] = useState(""); // Lỗi độ dài mật khẩu
+ const [busy, setBusy] = useState(false);
+ const [done, setDone] = useState(null); // Lưu mật khẩu vừa đặt thành công để hiển thị modal
+
+ const submit = async (e) => {
+ e.preventDefault();
+ if (pw.length < 8) return setError("Mật khẩu mới cần ít nhất 8 ký tự.");
+
+ setBusy(true);
+ try {
+ await adminApi.resetPassword(user.userId, pw);
+ setDone(pw);
+ setPw("");
+ } catch (ex) {
+ onApiError(ex);
+ setError(ex.message);
+ }
+ setBusy(false);
+ };
+
+ return (
+
+ );
+}
+
+/*
+ * RolesCard - Thẻ Quản Lý Vai Trò Của Người Dùng
+ *
+ * Tham số:
+ * - user: thông tin người dùng kèm danh sách roles hiện có
+ * - allRoles: danh mục tất cả vai trò trong hệ thống
+ * - onSaved: callback làm mới dữ liệu
+ */
+function RolesCard({ user, allRoles, onSaved }) {
+ const { onApiError, notify } = useApp();
+ const [adding, setAdding] = useState(""); // roleId được chọn trong dropdown để gán thêm
+ const [confirm, setConfirm] = useState(null); // Role đang chờ xác nhận thu hồi
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+
+ // Tập hợp các roleId mà user đang sở hữu
+ const owned = new Set(user.roles.map((r) => r.roleId));
+ // Danh sách các vai trò còn lại mà user chưa có
+ const available = allRoles.filter((r) => !owned.has(r.roleId));
+
+ // Hàm thực thi gọi API kèm xử lý loading/lỗi
+ const run = async (fn, msg) => {
+ setBusy(true);
+ setError("");
+ try {
+ await fn();
+ notify(msg);
+ onSaved();
+ } catch (ex) {
+ onApiError(ex);
+ setError(ex.message);
+ }
+ setBusy(false);
+ };
+
+ return (
+
+
Vai trò
+
+ {/* Danh sách các vai trò hiện tại của người dùng */}
+
+ {user.fullName} sẽ mất vai trò {roleLabel(confirm.roleName)} và các quyền đi kèm.
+
+
+
+
+
+
+ )}
+
+ );
+}
+
+/*
+ * FacilityCard - Thẻ Quản Lý Phân Công Cơ Sở Phụ Trách
+ *
+ * Dành riêng cho vai trò Nhân viên cơ sở (STAFF) và Quản lý cơ sở (MANAGER).
+ * Quy tắc nghiệp vụ: Mỗi người chỉ phụ trách 1 cơ sở tại một thời điểm.
+ */
+function FacilityCard({ user, facilities, rows, onSaved }) {
+ const { onApiError, notify } = useApp();
+ const [facilityId, setFacilityId] = useState(""); // Cơ sở chọn trong dropdown để phân công
+ const [from, setFrom] = useState(today()); // Ngày bắt đầu phân công
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+
+ // Tìm phân công đang có hiệu lực (ACTIVE)
+ const active = rows.find((r) => r.status === "ACTIVE");
+
+ // Hàm chạy API đổi trạng thái hoặc phân công
+ const run = async (fn, msg) => {
+ setBusy(true);
+ setError("");
+ try {
+ await fn();
+ notify(msg);
+ onSaved();
+ } catch (ex) {
+ onApiError(ex);
+ setError(ex.message);
+ }
+ setBusy(false);
+ };
+
+ return (
+
+
Cơ sở phụ trách
+
+ {active ? (
+ <>Đang phụ trách {active.facilityName} từ {dateOnlyLabel(active.assignedFrom)}.>
+ ) : (
+ "Chưa được phân công cơ sở."
+ )}{" "}
+ Mỗi nhân viên / quản lý chỉ phụ trách một cơ sở tại một thời điểm; phân công mới sẽ tự kết thúc phân công cũ.
+
+
+ {/* Form phân công cơ sở mới */}
+
+
+
+
+
+
+ {error && {error}}
+
+ {/* Bảng lịch sử các đợt phân công cơ sở */}
+ {rows.length > 0 && (
+
+
+
+
+
Cơ sở
+
Thời gian
+
Trạng thái
+
+
+
+
+ {rows.map((r) => (
+
+
+ {r.facilityName}
+ Phân công bởi {r.assignerName || "—"}
+
+ {/* Các nút hành động khi phân công đang ACTIVE */}
+ {r.status === "ACTIVE" && (
+ <>
+
+
+ >
+ )}
+ {/* Nút kích hoạt lại khi phân công đang SUSPENDED */}
+ {r.status === "SUSPENDED" && (
+
+ )}
+
+
+ ))}
+
+
+
+ )}
+
+ );
+}
+
+/*
+ * UserDetailPage - Component Trang Chi Tiết Tài Khoản
+ *
+ * Tham số:
+ * - id: userId của tài khoản cần xem/chỉnh sửa
+ */
+export default function UserDetailPage({ id }) {
+ const { onApiError } = useApp();
+
+ /*
+ * TẢI ĐỒNG THỜI DỮ LIỆU TỪ 4 API:
+ * 1. adminApi.user(id): thông tin chi tiết người dùng
+ * 2. adminApi.roles(): toàn bộ danh sách vai trò
+ * 3. adminApi.facilities(): toàn bộ danh sách cơ sở
+ * 4. adminApi.userFacilities(id): lịch sử phân công cơ sở của người dùng này
+ */
+ const res = useLoad(async () => {
+ const [user, roles, facilities, assignments] = await Promise.all([
+ adminApi.user(id),
+ adminApi.roles(),
+ adminApi.facilities(),
+ adminApi.userFacilities(id),
+ ]);
+ return {
+ user,
+ roles: sortRoles(roles, (r) => r.roleName),
+ facilities: facilities.filter((f) => f.status === "ACTIVE"),
+ assignments,
+ };
+ }, [id], onApiError);
+
+ // Trường hợp tải thất bại hoàn toàn
+ if (res.error && !res.data)
+ return (
+
+
+ Về danh sách tài khoản
+
+
+ );
+
+ // Màn hình loading khi đang tải dữ liệu ban đầu
+ if (!res.data)
+ return (
+
+
+
+
+ {/* Header trang chi tiết: Họ tên, username, vai trò, ngày tạo và Tag trạng thái */}
+
+
+
{user.fullName}
+
+ @{user.username} · {sortRoles(roleNames).map(roleLabel).join(", ") || "Chưa có vai trò"} · Tạo ngày {dateTime(user.createdAt).slice(0, 10)}
+
+
+
+
+
+
+
+ {/* 4 Thẻ thống kê nhanh của tài khoản */}
+
+
{user.activeContractsCount}Hợp đồng đang thuê
+
{user.openTicketsCount}Yêu cầu hỗ trợ đang mở
+
{user.lastLoginAt ? dateTime(user.lastLoginAt) : "Chưa đăng nhập"}Đăng nhập gần nhất
+
{dateTime(user.updatedAt)}Cập nhật gần nhất
+
+
+ {/* Lưới 2 cột chứa 4 thẻ chức năng quản lý tài khoản */}
+
+ {/* Cột trái: Thông tin cá nhân & Đặt lại mật khẩu */}
+
+
+
+
+
+ {/* Cột phải: Quản lý vai trò & Phân công cơ sở phụ trách */}
+
+
+ {/* Chỉ hiển thị thẻ cơ sở nếu user có vai trò cần cơ sở (Staff/Manager) hoặc đã từng có lịch sử phân công */}
+ {(needsFacility(roleNames) || assignments.length > 0) && (
+
+ )}
+
+
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserListPage.jsx
new file mode 100644
index 0000000..c633994
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserListPage.jsx
@@ -0,0 +1,461 @@
+
+/*
+ * ADMIN USERS - TRANG QUẢN LÝ DANH SÁCH TÀI KHOẢN
+ *
+ * Chức năng chính:
+ * - Hiển thị thống kê số lượng tài khoản trong hệ thống.
+ * - Lấy danh sách người dùng từ Backend API.
+ * - Tìm kiếm người dùng theo từ khóa.
+ * - Lọc người dùng theo vai trò và trạng thái.
+ * - Hiển thị cơ sở mà nhân viên hoặc quản lý phụ trách.
+ * - Phân trang danh sách (10 tài khoản/trang).
+ * - Chuyển đến trang chi tiết hoặc tạo tài khoản mới.
+ */
+
+import React, { useEffect, useMemo, useState } from "react";
+import { adminApi } from "../api/adminApi.js";
+import { Pagination, Select } from "../../../shared/components/Pickers.jsx";
+import { Empty, LinkButton, Notice, StatusTag } from "../../../shared/components/UI.jsx";
+import { USER_STATUS, needsFacility, roleLabel, sortRoles } from "../../../shared/utils/roles.js";
+import { go, href } from "../../../app/router.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { useLoad } from "../utils/adminUtils.js";
+
+const PAGE_SIZE = 10;
+
+export default function UserListPage() {
+
+ // Lấy hàm xử lý lỗi API từ Context.
+ // Ví dụ: kết thúc phiên khi token hết hạn (HTTP 401).
+ const { onApiError } = useApp();
+
+
+ /*
+ * STATE - LƯU TRẠNG THÁI BỘ LỌC VÀ PHÂN TRANG
+ */
+
+ // ID vai trò đang được chọn để lọc.
+ // "" nghĩa là hiển thị tất cả vai trò.
+ const [roleId, setRoleId] = useState("");
+
+ // Trạng thái tài khoản đang lọc.
+ // "" nghĩa là không giới hạn trạng thái.
+ const [status, setStatus] = useState("");
+
+ // Nội dung người dùng đang nhập vào ô tìm kiếm.
+ const [search, setSearch] = useState("");
+
+ // Từ khóa thực sự dùng để gọi API tìm kiếm.
+ // Được cập nhật sau khi người dùng ngừng gõ 300ms.
+ const [term, setTerm] = useState("");
+
+ // Trang hiện tại của bảng danh sách.
+ // Mặc định bắt đầu từ trang 1.
+ const [page, setPage] = useState(1);
+
+ // Lưu tên cơ sở phụ trách theo ID người dùng.
+ // Ví dụ: { 5: "SafeSpace Quận 1" }.
+ const [scopes, setScopes] = useState({});
+
+
+ /*
+ * DEBOUNCE TÌM KIẾM
+ *
+ * Mục đích:
+ * - Không gọi API liên tục mỗi khi người dùng gõ một ký tự.
+ * - Chờ 300ms sau lần nhập cuối mới cập nhật từ khóa.
+ * - Khi tìm kiếm mới, quay về trang 1.
+ */
+
+ useEffect(() => {
+ const t = setTimeout(() => {
+ setTerm(search.trim());
+ setPage(1);
+ }, 300);
+
+ // Hủy timer cũ nếu người dùng tiếp tục nhập,
+ // tránh thực hiện tìm kiếm với từ khóa cũ.
+ return () => clearTimeout(t);
+ }, [search]);
+
+
+ /*
+ * API 1 - LẤY THỐNG KÊ VÀ DANH SÁCH VAI TRÒ
+ *
+ * adminApi.stats(): lấy số lượng tài khoản, trạng thái,...
+ * adminApi.roles(): lấy danh sách vai trò trong hệ thống.
+ *
+ * Promise.all giúp gọi hai API đồng thời.
+ * sortRoles sắp xếp vai trò trước khi sử dụng.
+ *
+ * [] nghĩa là không cần tải lại theo bộ lọc.
+ */
+
+ const meta = useLoad(async () => {
+ const [stats, roles] = await Promise.all([adminApi.stats(), adminApi.roles()]);
+ return { stats, roles: sortRoles(roles, (r) => r.roleName) };
+ }, [], onApiError);
+
+
+ /*
+ * API 2 - LẤY DANH SÁCH NGƯỜI DÙNG
+ *
+ * Gửi các tham số:
+ * - page: trang hiện tại.
+ * - pageSize: số tài khoản mỗi trang (10).
+ * - searchTerm: từ khóa tìm kiếm.
+ * - status: trạng thái cần lọc.
+ * - roleId: vai trò cần lọc.
+ *
+ * Khi page, term, status hoặc roleId thay đổi,
+ * useLoad sẽ tải lại danh sách từ backend.
+ */
+
+ const list = useLoad(() => adminApi.users({ page, pageSize: PAGE_SIZE, searchTerm: term, status, roleId }), [page, term, status, roleId], onApiError);
+
+
+ /*
+ * LẤY CƠ SỞ PHỤ TRÁCH CỦA NHÂN VIÊN / QUẢN LÝ
+ *
+ * Mỗi tài khoản có vai trò cần gán cơ sở sẽ được
+ * gọi API để tìm cơ sở đang được phân công.
+ *
+ * Khách hàng thông thường không cần xử lý phần này.
+ */
+
+ // Cơ sở phụ trách của nhân viên / quản lý trong trang hiện tại
+ useEffect(() => {
+
+ // Lấy danh sách tài khoản đang hiển thị.
+ // Nếu chưa có dữ liệu thì dùng mảng rỗng.
+ const items = list.data?.items || [];
+
+ // Cờ đánh dấu effect còn hiệu lực.
+ // Tránh setState từ request cũ sau khi cleanup.
+ let alive = true;
+
+ items
+
+ // Chỉ lấy những người cần phân công cơ sở
+ // và chưa có dữ liệu cơ sở trong scopes.
+ .filter((u) => needsFacility(u.roles) && scopes[u.userId] === undefined)
+
+ // Gọi API riêng cho từng tài khoản phù hợp.
+ .forEach(async (u) => {
+ try {
+
+ // Lấy danh sách cơ sở được phân công cho User.
+ const rows = await adminApi.userFacilities(u.userId);
+
+ // Tìm cơ sở có trạng thái phân công ACTIVE.
+ const active = rows.find((r) => r.status === "ACTIVE");
+
+ // Nếu có cơ sở đang hoạt động thì lưu tên cơ sở.
+ // Nếu không có thì hiển thị "Chưa phân công".
+ if (alive) setScopes((s) => ({ ...s, [u.userId]: active ? active.facilityName : "Chưa phân công" }));
+
+ } catch {
+
+ // Nếu API lỗi, hiển thị dấu "—" cho tài khoản đó.
+ if (alive) setScopes((s) => ({ ...s, [u.userId]: "—" }));
+ }
+ });
+
+ // Cleanup khi effect kết thúc hoặc dữ liệu thay đổi.
+ // Request cũ sẽ không cập nhật scopes nữa.
+ return () => {
+ alive = false;
+ };
+
+ }, [list.data]); // eslint-disable-line react-hooks/exhaustive-deps
+
+
+ /*
+ * XỬ LÝ DỮ LIỆU THỐNG KÊ
+ */
+
+ // Lấy dữ liệu thống kê đã tải từ API.
+ const stats = meta.data?.stats;
+
+ // Đối tượng chứa số lượng tài khoản theo từng vai trò.
+ // Nếu chưa có dữ liệu thì dùng object rỗng.
+ const byRole = stats?.usersByRole || {};
+
+ // Tính tổng số tài khoản thuộc nhóm nhân viên / quản lý.
+ // Loại trừ CUSTOMER và ADMIN khỏi phép tính.
+ const staffCount = Object.entries(byRole)
+ .filter(([k]) => k !== "CUSTOMER" && k !== "ADMIN")
+ .reduce((a, [, v]) => a + v, 0);
+
+ // Dữ liệu cho bốn thẻ thống kê ở đầu trang.
+ // Mỗi phần tử gồm: [số lượng, nhãn, màu].
+ const cards = [
+ [stats?.totalUsers, "Tổng tài khoản", ""],
+ [byRole.CUSTOMER || 0, "Khách hàng", "blue"],
+ [staffCount, "Nhân viên & Quản lý", "green"],
+ [stats?.inactiveUsersCount || 0, "Đang khoá / ngưng", "red"],
+ ];
+
+
+ /*
+ * XÁC ĐỊNH PHẠM VI PHỤ TRÁCH CỦA USER
+ *
+ * ADMIN: hiển thị "Toàn hệ thống".
+ * Nhân viên / quản lý cơ sở: hiển thị tên cơ sở.
+ * Các vai trò hệ thống khác CUSTOMER:
+ * hiển thị "Toàn hệ thống".
+ * CUSTOMER: hiển thị "—".
+ */
+
+ const scopeOf = (u) => {
+
+ // Admin có phạm vi toàn hệ thống.
+ if (u.roles.includes("ADMIN")) return "Toàn hệ thống";
+
+ // Nhân viên hoặc quản lý cần gán cơ sở.
+ // "…" nghĩa là dữ liệu cơ sở chưa tải xong.
+ if (needsFacility(u.roles)) return scopes[u.userId] ?? "…";
+
+ // Vai trò khác CUSTOMER được hiển thị toàn hệ thống.
+ if (u.roles.some((r) => r !== "CUSTOMER")) return "Toàn hệ thống";
+
+ // Khách hàng không có cơ sở phụ trách.
+ return "—";
+ };
+
+
+ /*
+ * XỬ LÝ THÔNG TIN PHÂN TRANG
+ */
+
+ // Dữ liệu danh sách người dùng trả về từ API.
+ const data = list.data;
+
+ // Tính vị trí bắt đầu của bản ghi trên trang hiện tại.
+ // Ví dụ: trang 2, 10 tài khoản/trang => bắt đầu từ 11.
+ const from = data ? (data.page - 1) * data.pageSize + 1 : 0;
+
+ // Tính tổng số trang dựa trên tổng số tài khoản.
+ // Math.ceil làm tròn lên để tính cả trang cuối.
+ // Math.max đảm bảo số trang không nhỏ hơn 1.
+ const totalPages = data ? Math.max(1, Math.ceil(data.totalItems / data.pageSize)) : 1;
+
+ // Danh sách vai trò lấy từ API.
+ const roles = meta.data?.roles || [];
+
+ // Thêm lựa chọn "Tất cả" (roleId rỗng)
+ // vào đầu danh sách vai trò để tạo bộ lọc.
+ // useMemo chỉ tính lại khi roles thay đổi.
+ const chips = useMemo(() => [{ roleId: "", roleName: "" }, ...roles], [roles]);
+
+
+ /*
+ * RENDER GIAO DIỆN QUẢN LÝ TÀI KHOẢN
+ */
+
+ return (
+
+
+ {/* HEADER - TIÊU ĐỀ VÀ NÚT THÊM TÀI KHOẢN */}
+
+
+
Quản lý tài khoản người dùng
+
+ {/* Hiển thị tổng số tài khoản từ API.
+ Nếu chưa tải xong thì hiển thị "Đang tải…". */}
+
{stats ? `${stats.totalUsers} tài khoản trong hệ thống` : "Đang tải…"}
+
+
+
+
+ {/* Điều hướng đến form tạo tài khoản mới. */}
+ + Thêm tài khoản mới
+
+
+
+
+ {/* HIỂN THỊ LỖI KHI KHÔNG TẢI ĐƯỢC THỐNG KÊ / VAI TRÒ */}
+ {meta.error && {meta.error}}
+
+
+ {/* BỐN THẺ THỐNG KÊ TÀI KHOẢN */}
+
+
+ {/* Duyệt mảng cards và tạo từng thẻ thống kê.
+ tone dùng để xác định màu chữ cho số lượng. */}
+ {cards.map(([n, label, tone]) => (
+
+ {n ?? "—"}
+ {label}
+
+ ))}
+
+
+
+ {/* THANH CÔNG CỤ - LỌC VAI TRÒ, TÌM KIẾM, TRẠNG THÁI */}
+
+
+ {/* BỘ LỌC THEO VAI TRÒ */}
+
+
+ {/* Render nút cho từng vai trò trong chips. */}
+ {chips.map((r) => (
+
+ ))}
+
+
+
+ {/* KHU VỰC TÌM KIẾM VÀ LỌC TRẠNG THÁI */}
+
+
+ {/* Ô tìm kiếm theo tên, email hoặc số điện thoại.
+ onChange cập nhật search mỗi khi người dùng nhập.
+ useEffect phía trên sẽ đợi 300ms trước khi tìm. */}
+ setSearch(e.target.value)} />
+
+ {/* Dropdown lọc tài khoản theo trạng thái.
+ Khi thay đổi trạng thái sẽ quay lại trang 1. */}
+
+
+
+
+
+ {/* HIỂN THỊ THÔNG BÁO NẾU API DANH SÁCH BỊ LỖI */}
+ {list.error && {list.error}}
+
+
+ {/* BẢNG DANH SÁCH TÀI KHOẢN */}
+
+
+
+ {/* PHẦN TIÊU ĐỀ CÁC CỘT */}
+
+
+
Họ tên
+
Email
+
Vai trò
+
Cơ sở phụ trách
+
Trạng thái
+
+
+
+
+
+ {/* Lặp qua danh sách tài khoản do API trả về.
+ Mỗi phần tử u tương ứng với một User.
+ Nếu data chưa có thì dùng mảng rỗng. */}
+ {(data?.items || []).map((u) => (
+
+ // Mỗi hàng là một tài khoản.
+ // Nhấn vào hàng sẽ chuyển đến trang chi tiết User.
+
go(`admin/users/${u.userId}`)}>
+
+ {/* CỘT 1: HỌ TÊN VÀ USERNAME */}
+
+
+ {/* Link mở trang chi tiết tài khoản.
+ stopPropagation ngăn sự kiện click
+ lan lên hàng
+
+ {/* CỘT 4: PHẠM VI / CƠ SỞ PHỤ TRÁCH.
+ Sử dụng hàm scopeOf đã định nghĩa phía trên. */}
+
{scopeOf(u)}
+
+ {/* CỘT 5: TRẠNG THÁI TÀI KHOẢN.
+ StatusTag hiển thị nhãn và màu tương ứng. */}
+
+
+
+
+ ))}
+
+
+ {/* TRƯỜNG HỢP KHÔNG CÓ USER PHÙ HỢP BỘ LỌC.
+ Chỉ hiển thị sau khi tải xong.
+ colSpan={5} gộp cả 5 cột thành một ô. */}
+ {!list.loading && data && data.items.length === 0 && (
+
+
Không có tài khoản phù hợp bộ lọc.
+
+ )}
+
+
+ {/* TRƯỜNG HỢP ĐANG TẢI DANH SÁCH LẦN ĐẦU.
+ Hiển thị khi loading và chưa có data. */}
+ {list.loading && !data && (
+
+
Đang tải danh sách…
+
+ )}
+
+
+
+
+
+ {/* PHÂN TRANG DANH SÁCH NGƯỜI DÙNG.
+ Chỉ hiển thị khi đã có data.
+ onPage={setPage}: khi chọn trang mới,
+ cập nhật state page để useLoad gọi lại API. */}
+ {data && }
+
+
+ {/* CÁC NÚT ĐIỀU HƯỚNG ĐẾN CHỨC NĂNG ADMIN KHÁC */}
+
+
+ {/* Mở trang quản lý và cấu hình phân quyền. */}
+ Cấu hình quyền truy cập
+
+ {/* Mở trang xem nhật ký hoạt động hệ thống. */}
+ Xem nhật ký hoạt động
+
+
+
+ {/* Nếu API metadata đã tải nhưng không có vai trò nào,
+ hiển thị thông báo hệ thống chưa có vai trò. */}
+ {meta.data && roles.length === 0 && }
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/utils/adminUtils.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/utils/adminUtils.js
new file mode 100644
index 0000000..d001e17
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/utils/adminUtils.js
@@ -0,0 +1,213 @@
+/*
+ * ADMIN UTILS - CÁC HÀM TIỆN ÍCH DÀNH RIÊNG CHO KHU VỰC QUẢN TRỊ
+ *
+ * Chức năng chính:
+ * 1. dateTime(v): Định dạng ngày giờ UTC từ backend thành chuỗi tiếng Việt dễ đọc (DD/MM/YYYY HH:mm).
+ * 2. dateOnlyLabel(v): Định dạng chuỗi ngày YYYY-MM-DD thành DD/MM/YYYY.
+ * 3. useLoad(fn, deps, onApiError): Custom React Hook tải dữ liệu bất đồng bộ với cơ chế chống race-condition (seq ref).
+ * 4. describeActivity(log, nameOf): Diễn giải mã hành động kỹ thuật (JSON PascalCase) thành mô tả tiếng Việt chi tiết cho nhật ký.
+ * 5. tempPassword(): Tạo mật khẩu tạm thời ngẫu nhiên 12 ký tự mạnh (chữ hoa, chữ thường, số, ký tự đặc biệt).
+ * 6. usernameFrom(email): Tạo gợi ý tên đăng nhập chuẩn hóa từ địa chỉ email (loại bỏ dấu tiếng Việt và ký tự đặc biệt).
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { parseUtc } from "../../../shared/api/apiMappers.js";
+import { ASSIGNMENT_STATUS, USER_STATUS, actionLabel, roleLabel } from "../../../shared/utils/roles.js";
+
+// Hàm đệm số có 2 chữ số (ví dụ: 5 -> "05")
+const pad = (n) => String(n).padStart(2, "0");
+
+/*
+ * dateTime - Định dạng ngày giờ
+ * Nhận giá trị ngày giờ (chuỗi ISO UTC hoặc Date) và chuyển thành định dạng "DD/MM/YYYY HH:mm" theo giờ địa phương.
+ * Trả về "—" nếu giá trị không hợp lệ hoặc rỗng.
+ */
+export function dateTime(v) {
+ const d = parseUtc(v);
+ if (!d) return "—";
+ return `${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+/*
+ * dateOnlyLabel - Định dạng chỉ ngày
+ * Nhận chuỗi ngày có dạng "YYYY-MM-DD..." và chuyển thành "DD/MM/YYYY".
+ * Trả về "—" nếu không có dữ liệu.
+ */
+export function dateOnlyLabel(v) {
+ if (!v) return "—";
+ const [y, m, d] = String(v).slice(0, 10).split("-");
+ return `${d}/${m}/${y}`;
+}
+
+/*
+ * useLoad - Custom Hook tải dữ liệu bất đồng bộ từ API
+ *
+ * Tham số:
+ * - fn: hàm async gọi API và trả về kết quả
+ * - deps: mảng dependencies kích hoạt tải lại dữ liệu khi giá trị thay đổi
+ * - onApiError: callback xử lý lỗi API (đặc biệt khi gặp lỗi 401 Unauthorized để đăng xuất)
+ *
+ * Trả về:
+ * - loading: boolean cho biết request đang chạy
+ * - error: thông điệp lỗi (hoặc null)
+ * - data: dữ liệu trả về từ API
+ * - reload: hàm thủ công kích hoạt tải lại dữ liệu
+ */
+export function useLoad(fn, deps, onApiError) {
+ const [state, setState] = useState({ loading: true, error: null, data: null });
+
+ // seq ref dùng để đếm số thứ tự request, tránh race-condition khi response cũ đến sau response mới
+ const seq = useRef(0);
+
+ const run = useCallback(async () => {
+ const id = ++seq.current;
+ setState((s) => ({ ...s, loading: true, error: null }));
+ try {
+ const data = await fn();
+ // Chỉ cập nhật state nếu đây là request mới nhất
+ if (id === seq.current) setState({ loading: false, error: null, data });
+ } catch (e) {
+ onApiError?.(e);
+ if (id === seq.current) setState((s) => ({ loading: false, error: e?.message || "Không tải được dữ liệu.", data: s.data }));
+ }
+ }, deps); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // Tự động gọi run khi các giá trị trong deps thay đổi
+ useEffect(() => {
+ run();
+ }, [run]);
+
+ return { ...state, reload: run };
+}
+
+/*
+ * parse - Chuyển chuỗi JSON sang object an toàn
+ * Nếu parse lỗi hoặc giá trị rỗng thì trả về object rỗng {} thay vì làm văng lỗi ứng dụng.
+ */
+const parse = (v) => {
+ if (!v) return {};
+ try {
+ const o = JSON.parse(v);
+ return o && typeof o === "object" ? o : {};
+ } catch {
+ return {};
+ }
+};
+
+/*
+ * get - Lấy thuộc tính của object bất kể backend dùng PascalCase hay camelCase
+ * Ví dụ: get(obj, "FullName") sẽ thử lấy obj["FullName"], nếu không có thì lấy obj["fullName"].
+ */
+const get = (o, key) => o[key] ?? o[key[0].toLowerCase() + key.slice(1)];
+
+/*
+ * describeActivity - Diễn giải nhật ký hoạt động sang tiếng Việt
+ *
+ * Backend AdminService ghi log oldValue và newValue dạng JSON PascalCase.
+ * Hàm này đọc log.action và các giá trị trước/sau để tạo câu mô tả tự nhiên bằng tiếng Việt cho Admin đọc.
+ *
+ * Tham số:
+ * - log: bản ghi log chứa action, entityId, oldValue, newValue
+ * - nameOf: hàm tra cứu tên người dùng theo userId
+ */
+export function describeActivity(log, nameOf) {
+ const nv = parse(log.newValue);
+ const ov = parse(log.oldValue);
+ const who = (id) => nameOf(id) || (id ? `#${id}` : "");
+ const status = (s) => USER_STATUS[s]?.[0] || s;
+ const scope = (s) => ASSIGNMENT_STATUS[s]?.[0] || s;
+
+ switch (log.action) {
+ // 1. Tạo tài khoản người dùng mới
+ case "USER_CREATE":
+ return `Tạo tài khoản mới — ${get(nv, "FullName") || who(log.entityId)}`;
+
+ // 2. Cập nhật thông tin hoặc trạng thái tài khoản
+ case "USER_UPDATE": {
+ const from = get(ov, "Status");
+ const to = get(nv, "Status");
+ const change = from && to && from !== to ? ` · ${status(from)} → ${status(to)}` : "";
+ return `Cập nhật tài khoản — ${get(nv, "FullName") || who(log.entityId)}${change}`;
+ }
+
+ // 3. Đặt lại mật khẩu
+ case "USER_RESET_PASSWORD":
+ return `Đặt lại mật khẩu — ${who(log.entityId)}`;
+
+ // 4. Gán vai trò cho người dùng
+ case "ROLE_ASSIGN":
+ return `Gán vai trò ${roleLabel(get(nv, "RoleName") || "")} — ${who(get(nv, "UserId") || log.entityId)}`;
+
+ // 5. Thu hồi vai trò khỏi người dùng
+ case "ROLE_REVOKE":
+ return `Thu hồi vai trò ${roleLabel(get(ov, "RoleName") || "")} — ${who(get(ov, "UserId") || log.entityId)}`;
+
+ // 6. Gán quyền cho vai trò
+ case "PERMISSION_ASSIGN":
+ return `Gán quyền ${get(nv, "PermissionCode") || ""} cho ${roleLabel(get(nv, "RoleName") || "")}`;
+
+ // 7. Thu hồi quyền khỏi vai trò
+ case "PERMISSION_REVOKE":
+ return `Thu hồi quyền ${get(ov, "PermissionCode") || ""} của ${roleLabel(get(ov, "RoleName") || "")}`;
+
+ // 8. Phân công cơ sở cho nhân viên/quản lý
+ case "FACILITY_SCOPE_ASSIGN":
+ return `Phân công ${get(nv, "FacilityName") || "cơ sở"} — ${who(get(nv, "UserId") || log.entityId)}`;
+
+ // 9. Thay đổi trạng thái phân công cơ sở (ví dụ: đang phụ trách -> kết thúc)
+ case "FACILITY_SCOPE_STATUS_CHANGE":
+ return `Đổi trạng thái phân công cơ sở · ${scope(get(ov, "Status"))} → ${scope(get(nv, "Status"))}`;
+
+ // Mặc định: hiển thị nhãn hành động và mã đối tượng
+ default:
+ return `${actionLabel(log.action)}${log.entityType ? ` (${log.entityType}${log.entityId ? ` #${log.entityId}` : ""})` : ""}`;
+ }
+}
+
+/*
+ * tempPassword - Sinh mật khẩu tạm thời ngẫu nhiên
+ *
+ * Tiêu chuẩn mật khẩu:
+ * - Độ dài: 12 ký tự.
+ * - Đảm bảo có ít nhất: 1 chữ cái in hoa, 1 chữ cái in thường, 1 chữ số, 1 ký tự đặc biệt.
+ * - Sử dụng crypto.getRandomValues để sinh số ngẫu nhiên an toàn mật mã (cryptographically secure).
+ * - Xáo trộn ngẫu nhiên (Fisher-Yates shuffle) trước khi trả về.
+ */
+export function tempPassword() {
+ const sets = ["ABCDEFGHJKLMNPQRSTUVWXYZ", "abcdefghijkmnpqrstuvwxyz", "23456789", "@#$%&*"];
+ const rand = (n) => {
+ const a = new Uint32Array(1);
+ (globalThis.crypto || window.crypto).getRandomValues(a);
+ return a[0] % n;
+ };
+ // Chọn ít nhất một ký tự từ mỗi tập hợp ký tự
+ const chars = sets.map((s) => s[rand(s.length)]);
+ const all = sets.join("");
+ // Bổ sung các ký tự còn lại cho đủ độ dài 12
+ while (chars.length < 12) chars.push(all[rand(all.length)]);
+ // Xáo trộn ngẫu nhiên mảng ký tự
+ for (let i = chars.length - 1; i > 0; i--) {
+ const j = rand(i + 1);
+ [chars[i], chars[j]] = [chars[j], chars[i]];
+ }
+ return chars.join("");
+}
+
+/*
+ * usernameFrom - Tạo gợi ý tên đăng nhập từ địa chỉ email
+ *
+ * Quy trình xử lý:
+ * 1. Lấy phần trước dấu '@' của email.
+ * 2. Chuyển sang chữ thường.
+ * 3. Chuẩn hóa NFD và loại bỏ toàn bộ dấu tiếng Việt (ví dụ: "đặng" -> "dang").
+ * 4. Loại bỏ các ký tự không phải chữ cái thường, số, dấu chấm, gạch dưới, gạch ngang.
+ * 5. Cắt ngắn tối đa 50 ký tự theo giới hạn của cơ sở dữ liệu.
+ */
+export const usernameFrom = (email) =>
+ String(email || "")
+ .split("@")[0]
+ .toLowerCase()
+ .normalize("NFD")
+ .replace(/[\u0300-\u036f]/g, "")
+ .replace(/[^a-z0-9._-]/g, "")
+ .slice(0, 50);
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/LoginPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/LoginPage.jsx
new file mode 100644
index 0000000..3f92b03
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/LoginPage.jsx
@@ -0,0 +1,63 @@
+import React, { useEffect, useState } from "react";
+import { Button, Field } from "../../shared/components/UI.jsx";
+import { go, href } from "../../app/router.js";
+import { homeFor, isOpsRoles, isBusinessRoles } from "../../shared/utils/roles.js";
+import { useApp } from "../../app/state/AppProvider.jsx";
+import { safeNext } from "./utils/safeNext.js";
+import { ForgotPassword } from "./components/ForgotPasswordDialog.jsx";
+
+export function LoginPage({ query }) {
+ const { login, authed, isAdmin, roles } = useApp();
+ const next = safeNext(query.get("next"));
+ const [form, setForm] = useState({ identifier: "", password: "" });
+ const [errors, setErrors] = useState({});
+ const [forgot, setForgot] = useState(false);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ if (authed) go(isAdmin || isOpsRoles(roles) || isBusinessRoles(roles) ? homeFor(roles) : next, { replace: true });
+ }, [authed, isAdmin, roles, next]);
+
+ const set = (k, v) => {
+ setForm({ ...form, [k]: v });
+ setErrors({});
+ };
+ const submit = async (e) => {
+ e.preventDefault();
+ const err = {};
+ if (!form.identifier.trim()) err.identifier = "Vui lòng nhập tên đăng nhập hoặc email.";
+ if (!form.password) err.password = "Vui lòng nhập mật khẩu.";
+ if (Object.keys(err).length) return setErrors(err);
+ setBusy(true);
+ const res = await login(form);
+ setBusy(false);
+ if (!res.ok) return setErrors({ form: res.error });
+ const home = homeFor(res.roles || []);
+ go(home === "overview" ? next : next.startsWith(home) ? next : home);
+ };
+
+ return (
+
+
+ {forgot && setForgot(false)} />}
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/RegisterPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/RegisterPage.jsx
new file mode 100644
index 0000000..f7c9daa
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/RegisterPage.jsx
@@ -0,0 +1,62 @@
+import React, { useEffect, useState } from "react";
+import { Button, Field, Icon } from "../../shared/components/UI.jsx";
+import { go, href } from "../../app/router.js";
+import { useApp } from "../../app/state/AppProvider.jsx";
+import { safeNext } from "./utils/safeNext.js";
+
+export function RegisterPage({ query }) {
+ const { register, authed } = useApp();
+ const next = safeNext(query.get("next"));
+ const [form, setForm] = useState({ name: "", email: "", phone: "", password: "", confirm: "" });
+ const [errors, setErrors] = useState({});
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ if (authed) go(next, { replace: true });
+ }, [authed, next]);
+
+ const set = (k, v) => {
+ setForm({ ...form, [k]: v });
+ setErrors((p) => ({ ...p, [k]: undefined, form: undefined }));
+ };
+ const submit = async (e) => {
+ e.preventDefault();
+ setBusy(true);
+ const res = await register(form);
+ setBusy(false);
+ if (!res.ok) return setErrors(res.errors);
+ go(next);
+ };
+
+ return (
+
+
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/components/ForgotPasswordDialog.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/components/ForgotPasswordDialog.jsx
new file mode 100644
index 0000000..1430a8e
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/components/ForgotPasswordDialog.jsx
@@ -0,0 +1,42 @@
+import React, { useState } from "react";
+import { Button, Field, Modal } from "../../../shared/components/UI.jsx";
+import { isEmail } from "../../../shared/utils/format.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+
+export function ForgotPassword({ onClose }) {
+ const { supports } = useApp();
+ const [email, setEmail] = useState("");
+ const [error, setError] = useState("");
+ const [sent, setSent] = useState(false);
+ const submit = (e) => {
+ e.preventDefault();
+ if (!isEmail(email)) return setError("Nhập email hợp lệ để nhận hướng dẫn.");
+ setSent(true);
+ };
+ return (
+
+ {!supports.forgotPassword ? (
+ <>
+
Vui lòng liên hệ quản trị viên hoặc nhân viên cơ sở SafeSpace để được đặt lại mật khẩu.
+
+ >
+ ) : sent ? (
+ <>
+
Nếu email đã đăng ký, SafeSpace sẽ gửi hướng dẫn đặt lại mật khẩu trong ít phút.
{f.managerName || ('managerName' in f ? 'Chưa phân công' : 'Chưa có thông tin')}
{f.totalUnits} kho · {rateLabel(f.occupancyRate)}
{FACILITY_STATUS[f.status]?.[0] || f.status}
+
)}{!facilities.length &&
Chưa có cơ sở nào.
}
+
+ {current &&
+
{current.name}
+
{[areaOf(current.address).district, areaOf(current.address).city].filter(Boolean).join(', ')}{current.openingTime && ` · Giờ ra vào ${current.openingTime}–${current.closingTime}`}
+
{typeNames.length ? `${typeNames.join(' & ')} · ` : ''}Quản lý: {current.managerName || ('managerName' in current ? 'Chưa phân công' : 'Chưa có thông tin')}
+
Vị trí bản đồ: {coordinateLabel(current)}
+
+
+
+
+ }
+ {editing && setEditing(null)} onSaved={() => { setEditing(null); load.reload(); }} />}
+ >;
+ }}
+ ;
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/facilityForm.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/facilityForm.js
new file mode 100644
index 0000000..5f72a50
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/facilityForm.js
@@ -0,0 +1,75 @@
+// B05a · Sửa thông tin cơ sở — chuyển giữa dữ liệu API và form, kiểm tra trước khi gửi
+// (backend kiểm tra lại y hệt trong OperationsService.ValidateFacility).
+
+const VN = { latMin: 8, latMax: 24, lngMin: 102, lngMax: 110 };
+
+const text = (v) => (v == null ? "" : String(v));
+const num = (v) => Number(String(v).trim().replace(",", "."));
+
+export function facilityToForm(f) {
+ return {
+ name: text(f?.name),
+ address: text(f?.address),
+ contactPhone: text(f?.contactPhone),
+ openingTime: text(f?.openingTime),
+ closingTime: text(f?.closingTime),
+ latitude: f?.latitude == null ? "" : String(f.latitude),
+ longitude: f?.longitude == null ? "" : String(f.longitude),
+ };
+}
+
+// Dán "10.6935, 106.7222" (copy từ Google Maps) → tách thành vĩ độ / kinh độ. Không phải cặp số thì trả null.
+export function splitCoordinates(value) {
+ const m = String(value || "").trim().match(/^(-?\d+(?:\.\d+)?)\s*[,;\s]\s*(-?\d+(?:\.\d+)?)$/);
+ return m ? { latitude: m[1], longitude: m[2] } : null;
+}
+
+// Trả { errors } nếu sai, hoặc { body } đúng hợp đồng PUT /api/operations/facilities/{id}
+export function formToRequest(form) {
+ const errors = {};
+ const name = form.name.trim();
+ const address = form.address.trim();
+ if (!name) errors.name = "Tên cơ sở không được để trống.";
+ else if (name.length > 150) errors.name = "Tên cơ sở tối đa 150 ký tự.";
+ if (!address) errors.address = "Địa chỉ không được để trống.";
+ else if (address.length > 255) errors.address = "Địa chỉ tối đa 255 ký tự.";
+
+ const open = form.openingTime.trim();
+ const close = form.closingTime.trim();
+ if (Boolean(open) !== Boolean(close)) errors.hours = "Nhập cả giờ mở cửa và giờ đóng cửa, hoặc để trống cả hai.";
+ else if (open && close && open >= close) errors.hours = "Giờ mở cửa phải trước giờ đóng cửa.";
+
+ const latText = form.latitude.trim();
+ const lngText = form.longitude.trim();
+ let latitude = null;
+ let longitude = null;
+ if (latText || lngText) {
+ latitude = num(latText);
+ longitude = num(lngText);
+ if (!latText || !lngText) errors.coords = "Cần nhập cả vĩ độ và kinh độ, hoặc để trống cả hai.";
+ else if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) errors.coords = "Vĩ độ và kinh độ phải là số, ví dụ 10.6935 và 106.7222.";
+ else if (latitude < VN.latMin || latitude > VN.latMax || longitude < VN.lngMin || longitude > VN.lngMax)
+ errors.coords = "Toạ độ phải nằm trong Việt Nam (vĩ độ 8–24, kinh độ 102–110). Kiểm tra có nhập ngược hai ô không.";
+ else {
+ latitude = Math.round(latitude * 1e6) / 1e6;
+ longitude = Math.round(longitude * 1e6) / 1e6;
+ }
+ }
+ if (Object.keys(errors).length) return { errors };
+
+ return {
+ body: {
+ name,
+ address,
+ contactPhone: form.contactPhone.trim() || null,
+ openingTime: open || null,
+ closingTime: close || null,
+ status: null, // đổi trạng thái dùng endpoint /status riêng
+ latitude,
+ longitude,
+ },
+ };
+}
+
+export const coordinateLabel = (f) =>
+ f?.latitude != null && f?.longitude != null ? `${Number(f.latitude).toFixed(6)}, ${Number(f.longitude).toFixed(6)}` : "Chưa có";
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx
new file mode 100644
index 0000000..16f7c6e
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx
@@ -0,0 +1,48 @@
+import React, { useState } from 'react';
+import { businessApi } from "../api/businessApi.js";
+import { Button, Field } from "../../../shared/components/UI.jsx";
+import { useLoad } from "../../admin/utils/adminUtils.js";
+import { today } from "../../../shared/utils/format.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { createPolicy, replacePolicy } from "./policyActions.js";
+import { LoadState, useConfirm } from "../components/BusinessComponents.jsx";
+import { POLICY_SECTIONS, fieldPolicy, fieldValue, policyJobs } from "./policyFields.js";
+
+export default function PolicySettingsPage() {
+ const { notify, onApiError } = useApp();
+ const load = useLoad(() => businessApi.policies({}), [], onApiError);
+ const [drafts, setDrafts] = useState({});
+ const [busy, setBusy] = useState(false);
+ const [confirmEl, ask] = useConfirm();
+ const save = async policies => {
+ let jobs;
+ try {
+ // Validate every edited field before the first network mutation.
+ jobs = policyJobs(policies, drafts, today());
+ } catch (e) { return notify(e.message, 'error'); }
+ if (!jobs.length) return notify('Chưa có thay đổi nào.');
+ setBusy(true);
+ try {
+ for (const { keys, p, body } of jobs) {
+ const applied = p ? await replacePolicy(p, body, ask) : (await createPolicy(body, true, ask)).active;
+ if (!applied) { notify('Đã giữ bản nháp; các ô chưa áp dụng vẫn được giữ lại.'); return; }
+ setDrafts(d => { const next = { ...d }; for (const key of keys) delete next[key]; return next; });
+ }
+ notify('Đã lưu thay đổi chính sách.');
+ } catch (e) { onApiError(e); notify(e.message, 'error'); }
+ finally { setBusy(false); load.reload(); }
+ };
+ return
+
Chính sách cho thuê chung
Áp dụng cho toàn bộ cơ sở trong hệ thống, trừ khi có quy định riêng cho từng cơ sở.
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/reports/reportExport.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/reports/reportExport.js
new file mode 100644
index 0000000..ca655e8
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/reports/reportExport.js
@@ -0,0 +1,60 @@
+// A minimal OOXML workbook (ZIP STORE) without a runtime dependency.
+// All text is inlineStr, so user-controlled cells cannot become Excel formulas.
+const encode = s => new TextEncoder().encode(s);
+const xml = v => String(v ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
+function crc32(bytes) {
+ let crc = -1;
+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }
+ return (crc ^ -1) >>> 0;
+}
+const header = (size, fields) => {
+ const out = new Uint8Array(size), view = new DataView(out.buffer);
+ for (const [offset, value, width] of fields) width === 4 ? view.setUint32(offset, value, true) : view.setUint16(offset, value, true);
+ return out;
+};
+export function workbookBytes(rows) {
+ const cell = (v, i) => {
+ let col = '', n = i + 1;
+ while (n) { col = String.fromCharCode(65 + (n - 1) % 26) + col; n = Math.floor((n - 1) / 26); }
+ return typeof v === 'number' && Number.isFinite(v) ? `${v}` : `${xml(v)}`;
+ };
+ const files = {
+ '[Content_Types].xml': '',
+ '_rels/.rels': '',
+ 'xl/workbook.xml': '',
+ 'xl/_rels/workbook.xml.rels': '',
+ 'xl/worksheets/sheet1.xml': '' + rows.map((row, r) => `${row.map((v, i) => cell(v, i).replace('ROW', String(r + 1))).join('')}`).join('') + '',
+ };
+ const local = [], central = []; let offset = 0, centralSize = 0;
+ for (const [path, content] of Object.entries(files)) {
+ const name = encode(path), data = encode(content), crc = crc32(data);
+ const entry = header(30, [[0, 0x04034b50, 4], [4, 20, 2], [10, 0, 2], [12, 33, 2], [14, crc, 4], [18, data.length, 4], [22, data.length, 4], [26, name.length, 2]]);
+ const dir = header(46, [[0, 0x02014b50, 4], [4, 20, 2], [6, 20, 2], [14, 33, 2], [16, crc, 4], [20, data.length, 4], [24, data.length, 4], [28, name.length, 2], [42, offset, 4]]);
+ local.push(entry, name, data); central.push(dir, name); offset += entry.length + name.length + data.length; centralSize += dir.length + name.length;
+ }
+ const count = Object.keys(files).length;
+ const end = header(22, [[0, 0x06054b50, 4], [8, count, 2], [10, count, 2], [12, centralSize, 4], [16, offset, 4]]);
+ const out = new Uint8Array(offset + centralSize + end.length); let pos = 0;
+ for (const part of [...local, ...central, end]) { out.set(part, pos); pos += part.length; }
+ return out;
+}
+export function parseCsv(text) {
+ const rows = []; let row = [], field = '', quoted = false;
+ text = text.replace(/^\ufeff/, '');
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i];
+ if (c === '"') { if (quoted && text[i + 1] === '"') { field += '"'; i++; } else quoted = !quoted; }
+ else if (c === ',' && !quoted) { row.push(field); field = ''; }
+ else if ((c === '\n' || c === '\r') && !quoted) { if (c === '\r' && text[i + 1] === '\n') i++; row.push(field); rows.push(row); row = []; field = ''; }
+ else field += c;
+ }
+ if (quoted) throw new Error('Tệp báo cáo từ máy chủ không hợp lệ.');
+ if (field || row.length) { row.push(field); rows.push(row); }
+ return rows;
+}
+export function downloadWorkbook(rows, fileName) {
+ const blob = new Blob([workbookBytes(rows)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
+ const url = URL.createObjectURL(blob), a = document.createElement('a');
+ a.href = url; a.download = fileName; document.body.append(a); a.click(); a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/utils/businessFormat.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/utils/businessFormat.js
new file mode 100644
index 0000000..b626b4f
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/utils/businessFormat.js
@@ -0,0 +1,181 @@
+// Hàm thuần cho khu Quản lý vận hành KD (B01–B05) — có test ở tests/business.test.js.
+import { money, today } from "../../../shared/utils/format.js";
+
+const comma = (n, digits = 1) => Number(n).toFixed(digits).replace(".", ",");
+
+/** Tiền rút gọn cho thẻ số liệu / bảng: 1.080.000.000 → "1,08 tỷ đ", 92.400.000 → "92,4 triệu đ". */
+export function shortMoney(n) {
+ const v = Number(n) || 0;
+ if (Math.abs(v) >= 1e9) return `${comma(v / 1e9, 2)} tỷ đ`;
+ if (Math.abs(v) >= 1e6) return `${comma(v / 1e6, 1)} triệu đ`;
+ return money(v);
+}
+
+/** Tỷ lệ sử dụng: null = "Không áp dụng" (cơ sở không có kho khai thác được — docs/operations-api.md). */
+export const rateLabel = (rate) => (rate === null || rate === undefined ? "Không áp dụng" : `${Number.isInteger(+rate) ? rate : comma(rate)}%`);
+
+/** Tăng trưởng so với kỳ trước: "+4,8%" / "−2,0%"; kỳ trước bằng 0 thì không so được. */
+export function growthLabel(prev, cur) {
+ if (!prev) return null;
+ const g = ((cur - prev) / prev) * 100;
+ return `${g >= 0 ? "+" : "−"}${comma(Math.abs(g))}%`;
+}
+
+/** Địa chỉ "…, Quận 7, TP. Hồ Chí Minh" → { district: "Quận 7", city: "TP. Hồ Chí Minh" } (cùng cách với giao diện khách). */
+export function areaOf(address = "") {
+ const parts = String(address).split(",").map((s) => s.trim()).filter(Boolean);
+ return { district: parts.length >= 2 ? parts[parts.length - 2] : "", city: parts[parts.length - 1] || "" };
+}
+
+export const shortFacility = (name = "") => name.replace(/^SafeSpace\s+/, "");
+
+export const FACILITY_STATUS = {
+ ACTIVE: ["Đang hoạt động", "green"],
+ TEMPORARILY_CLOSED: ["Tạm đóng", "amber"],
+ INACTIVE: ["Ngừng hoạt động", "gray"],
+};
+
+export const POLICY_STATUS = {
+ ACTIVE: ["Đang áp dụng", "green"],
+ DRAFT: ["Bản nháp", "amber"],
+ INACTIVE: ["Đã ngừng", "gray"],
+ EXPIRED: ["Hết hiệu lực", "gray"],
+};
+
+export const POLICY_TYPES = {
+ DEPOSIT: "Đặt cọc",
+ RENEWAL: "Gia hạn",
+ CANCELLATION: "Huỷ đặt chỗ",
+ RETURN: "Trả kho",
+ OVERDUE: "Quá hạn",
+ EXTRA_FEE: "Phí dịch vụ",
+ DISCOUNT: "Giảm giá",
+ FEE_WAIVER: "Miễn phí",
+ PRICE_RANGE: "Khung giá",
+};
+
+// Loại chính sách mà giá trị FIXED là số tiền (đ). Loại khác (gia hạn, trả kho…) là số ngày / giờ ghi trong mô tả.
+export const MONEY_TYPES = ["DEPOSIT", "OVERDUE", "EXTRA_FEE", "CANCELLATION", "FEE_WAIVER", "DISCOUNT"];
+export const isMoneyFixed = (p) =>
+ p?.calculationType === "FIXED" && MONEY_TYPES.includes(p.policyType) && !(p.policyType === "DEPOSIT" && Number(p.value) < 1000);
+
+export const CALC_TYPES = {
+ FIXED: "Số tiền cố định",
+ PERCENTAGE: "Phần trăm",
+ RANGE: "Khoảng giá",
+ RULE: "Quy định (mô tả)",
+};
+
+/**
+ * Giá trị chính sách dạng chữ. Cọc FIXED < 1.000 là số tháng tiền thuê (cách ghi của chính sách seed, D16).
+ * @param {object} p PolicyDto
+ * @param {string} [unit] đuôi cho số tiền cố định, vd "/ ngày"
+ */
+export function policyValueLabel(p, unit = "") {
+ if (!p) return "—";
+ const v = p.value === null || p.value === undefined ? null : Number(p.value);
+ const tail = unit ? ` ${unit}` : "";
+ switch (p.calculationType) {
+ case "PERCENTAGE":
+ return v === null ? "—" : `${comma(v, Number.isInteger(v) ? 0 : 1)}%`;
+ case "RANGE":
+ return `${money(p.minValue ?? 0)} – ${money(p.maxValue ?? 0)}`;
+ case "RULE":
+ return p.ruleDescription || "—";
+ case "FIXED":
+ if (v === null) return "—";
+ if (p.policyType === "DEPOSIT" && v < 1000) return `${comma(v, Number.isInteger(v) ? 0 : 1)} tháng tiền thuê`;
+ if (!MONEY_TYPES.includes(p.policyType)) return comma(v, Number.isInteger(v) ? 0 : 1);
+ return `${money(v)}${tail}`;
+ default:
+ return v === null ? p.ruleDescription || "—" : String(v);
+ }
+}
+
+/**
+ * Chính sách đang có hiệu lực cho một phạm vi: ưu tiên đúng loại kho rồi mới đến toàn hệ thống (BR20, phần dùng ở B03).
+ * Chỉ xét chính sách toàn hệ thống về cơ sở (facilityId = null).
+ */
+export function policyFor(policies, type, unitTypeId = null) {
+ const pool = policies.filter((p) => p.policyType === type && p.status === "ACTIVE" && p.facilityId == null
+ && (!p.effectiveFrom || p.effectiveFrom <= today()) && (!p.effectiveTo || p.effectiveTo >= today())
+ && !(type === "OVERDUE" && p.calculationType === "RULE"));
+ return pool.find((p) => p.unitTypeId === unitTypeId) || (unitTypeId != null ? pool.find((p) => p.unitTypeId == null) : null) || null;
+}
+
+/** Thân request tạo bản thay thế của một chính sách (giữ phạm vi, đổi giá trị, hiệu lực từ hôm nay). */
+export function replacementOf(p, changes, today) {
+ return {
+ policyName: p.policyName,
+ policyType: p.policyType,
+ calculationType: p.calculationType,
+ value: p.value,
+ minValue: p.minValue,
+ maxValue: p.maxValue,
+ ruleDescription: p.ruleDescription,
+ facilityId: p.facilityId ?? null,
+ unitTypeId: p.unitTypeId ?? null,
+ effectiveFrom: today,
+ effectiveTo: null,
+ ...changes,
+ };
+}
+
+/** Kỳ báo cáo của một tháng "yyyy-MM": từ ngày 1 đến cuối tháng (tháng hiện tại thì đến hôm nay). */
+export function monthPeriod(month, today) {
+ const [y, m] = month.split("-").map(Number);
+ const last = new Date(Date.UTC(y, m, 0)).getUTCDate();
+ const end = `${month}-${String(last).padStart(2, "0")}`;
+ return { from: `${month}-01`, to: end > today ? today : end };
+}
+
+/** 12 tháng gần nhất, mới nhất trước: [{ value: "2026-10", label: "Tháng 10/2026" }]. */
+export function recentMonths(today, count = 12) {
+ const [y, m] = today.split("-").map(Number);
+ return Array.from({ length: count }, (_, i) => {
+ const d = new Date(Date.UTC(y, m - 1 - i, 1));
+ const mm = d.getUTCMonth() + 1;
+ return { value: `${d.getUTCFullYear()}-${String(mm).padStart(2, "0")}`, label: `Tháng ${mm}/${d.getUTCFullYear()}` };
+ });
+}
+
+/** Giá thuê hợp lệ: số nguyên dương, bội số 1.000 đ (docs/operations-api.md mục 3). */
+export function rateError(value) {
+ const n = Number(String(value).replace(/[.\sđ₫]/g, ""));
+ if (!String(value).trim()) return "Nhập giá mới.";
+ if (!Number.isFinite(n) || n <= 0) return "Giá phải lớn hơn 0.";
+ if (n % 1000 !== 0) return "Giá là bội số của 1.000 đ.";
+ return null;
+}
+export const parseMoney = (value) => Number(String(value).replace(/[.\sđ₫]/g, ""));
+
+export const CONTRACT_STATUS_LABELS = {
+ DRAFT: "Chờ bàn giao",
+ ACTIVE: "Đang thuê",
+ EXPIRING: "Sắp hết hạn",
+ OVERDUE: "Quá hạn",
+ RETURN_PENDING: "Chờ trả kho",
+ COMPLETED: "Đã kết thúc",
+ TERMINATED: "Chấm dứt",
+ CANCELLED: "Đã huỷ",
+};
+export const RESERVATION_STATUS_LABELS = {
+ PENDING_PAYMENT: "Chờ thanh toán",
+ PENDING_VERIFICATION: "Chờ thu tại kho",
+ CONFIRMED: "Đã xác nhận, chờ phân bổ",
+ UNIT_ASSIGNED: "Đã phân bổ ô",
+ CHECKED_IN: "Đã nhận kho",
+ CANCELLED: "Đã huỷ",
+ EXPIRED: "Hết hạn giữ chỗ",
+ NO_SHOW: "Không đến nhận",
+};
+export const UNIT_STATUS_LABELS = {
+ AVAILABLE: "Trống",
+ RESERVED: "Đã giữ cho khách",
+ ASSIGNED: "Đã phân bổ",
+ OCCUPIED: "Đang thuê",
+ RETURN_PENDING: "Chờ trả kho",
+ INSPECTION: "Chờ kiểm tra",
+ MAINTENANCE: "Bảo trì",
+ OUT_OF_SERVICE: "Ngừng sử dụng",
+};
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/AccessQrModal.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/AccessQrModal.jsx
new file mode 100644
index 0000000..a103167
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/AccessQrModal.jsx
@@ -0,0 +1,51 @@
+import React, { useEffect, useState } from "react";
+import QrCode from "../../../shared/components/QrCode.jsx";
+import { Button, Modal, Notice } from "../../../shared/components/UI.jsx";
+import { typeLabel } from "../../../shared/utils/catalog.js";
+import { dateLabel } from "../../../shared/utils/format.js";
+import { href, qs } from "../../../app/router.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+
+export function AccessQrModal({ c, facility, onClose }) {
+ const { services } = useApp();
+ const [state, setState] = useState({ status: "loading" });
+ useEffect(() => {
+ let alive = true;
+ services.accessQr(c).then((res) => {
+ if (!alive) return;
+ if (res.ok) setState({ status: "ready", access: res.access });
+ else setState({ status: res.unsupported ? "unsupported" : "error", error: res.error });
+ });
+ return () => {
+ alive = false;
+ };
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+ const a = state.access;
+ const where = [facility.name, c.location].filter(Boolean).join(" · ");
+ return (
+
+
{where}
+ {state.status === "unsupported" ? (
+ Mã QR mở cửa đang được cơ sở kích hoạt. Trong lúc chờ, dùng thẻ ra vào đã nhận khi bàn giao hoặc liên hệ nhân viên trực.
+ ) : state.status === "error" ? (
+ {state.error}
+ ) : (
+
+ )}
+ {a && (
+
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorScannerPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorScannerPage.jsx
new file mode 100644
index 0000000..011e73a
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorScannerPage.jsx
@@ -0,0 +1,83 @@
+import React, { useEffect, useState } from "react";
+import { Button, Field, Icon, Notice } from "../../../shared/components/UI.jsx";
+import { dateTimeLabel } from "../../../shared/utils/format.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+
+// C07r1 / C07r2 — Mô phỏng máy quét QR ở cửa kho (D21: mô phỏng, không dùng thiết bị thật).
+// Nhận mã từ QR mở cửa (C07q) hoặc mã dự phòng, gọi POST /api/access/scan, hiện "Mở cửa" / "Từ chối".
+export default function DoorScannerPage({ query }) {
+ const { services } = useApp();
+ const unit = query.get("unit") || "";
+ const [code, setCode] = useState(query.get("code") || "");
+ const [result, setResult] = useState(null);
+ const [state, setState] = useState("idle"); // idle | busy | unsupported | error
+ const [error, setError] = useState("");
+
+ const scan = async (value = code) => {
+ if (!String(value).trim()) return setError("Đưa mã QR vào máy quét hoặc nhập mã dự phòng.");
+ setState("busy");
+ setError("");
+ const res = await services.scan(value);
+ if (res.ok) {
+ setResult(res.scan);
+ setState("idle");
+ } else if (res.unsupported) setState("unsupported");
+ else {
+ setState("error");
+ setError(res.error);
+ }
+ };
+
+ // Mở từ "Mô phỏng quét ở cửa kho" (C07q) có sẵn mã → quét ngay; đổi đường dẫn thì về màn chờ quét
+ const incoming = query.get("code") || "";
+ useEffect(() => {
+ setResult(null);
+ setCode(incoming);
+ setState("idle");
+ setError("");
+ if (incoming) scan(incoming);
+ }, [incoming, unit]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const head = `Cửa kho ${result?.unit || unit || ""} · Máy quét`.replace(/\s+·/, " ·");
+ if (result) {
+ const open = result.result === "OPEN";
+ return (
+
+
+
+
{head}
+
{open ? "Mở cửa" : "Từ chối"}
+ {open ? (
+
+ {[result.customer, result.contract].filter(Boolean).join(" · ")}
+
+ {dateTimeLabel(result.at)} · Đã ghi nhật ký ra vào
+
+ ) : (
+
+ {result.reason}
+
+ Liên hệ nhân viên cơ sở nếu cần hỗ trợ.
+
+ )}
+
+
+
+ );
+ }
+ return (
+
+
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/accessApi.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/accessApi.js
new file mode 100644
index 0000000..7ed96be
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/accessApi.js
@@ -0,0 +1,88 @@
+// Chuẩn hoá dữ liệu backend cho các màn mới: PayOS (C04, C11q), QR mở cửa (C07q), máy quét cửa kho (C07r),
+// xem trước hoàn tiền khi huỷ (C14a). Hàm thuần, có test (tests/payment-access.test.js).
+// Hợp đồng JSON đầy đủ ở BACKEND-TODO.md mục P (PayOS), Q (QR mở cửa), H (huỷ đơn).
+import { ApiError } from "../../../shared/api/httpClient.js";
+import { parseUtc } from "../../../shared/api/apiMappers.js";
+
+// Backend chưa có endpoint (bản cũ) → giao diện hiện thông báo thay vì báo lỗi
+export const isUnsupported = (e) => e instanceof ApiError && (e.status === 404 || e.status === 405 || e.status === 501);
+
+const num = (v) => (v === null || v === undefined || v === "" ? null : Number(v));
+const iso = (v) => parseUtc(v)?.toISOString() ?? null;
+
+// PayosCheckoutDto: { orderCode, amount, qrCode, checkoutUrl, expiredAt, description, status }
+// qrCode là chuỗi VietQR PayOS trả về (vẽ thành ảnh QR ở giao diện), checkoutUrl là trang thanh toán của PayOS.
+export function normPayos(dto) {
+ if (!dto || typeof dto !== "object") return null;
+ const qr = dto.qrCode ?? dto.qr_code ?? null;
+ const url = dto.checkoutUrl ?? dto.checkout_url ?? null;
+ if (!qr && !url) return null;
+ const status = String(dto.status || "PENDING").toUpperCase();
+ return {
+ order_code: dto.orderCode ?? dto.order_code ?? null,
+ amount: num(dto.amount),
+ qr,
+ url,
+ expires_at: iso(dto.expiredAt ?? dto.expiresAt ?? null),
+ description: dto.description || null,
+ paid: status === "PAID",
+ status,
+ };
+}
+
+// AccessQrDto: { code, backupCode, unitNumber, unitType, location, validUntil, contractId }
+export function normAccess(dto) {
+ if (!dto?.code) return null;
+ return {
+ code: String(dto.code),
+ backup: dto.backupCode ? String(dto.backupCode) : null,
+ unit: dto.unitNumber || null,
+ unit_type: dto.unitType || null,
+ location: dto.location || null,
+ valid_until: dto.validUntil ? String(dto.validUntil).slice(0, 10) : null,
+ };
+}
+
+// ScanResultDto: { result: "OPEN" | "DENIED", unitNumber, customerName, contractCode, scannedAt, reason }
+export function normScan(dto) {
+ const result = String(dto?.result || "").toUpperCase() === "OPEN" ? "OPEN" : "DENIED";
+ return {
+ result,
+ unit: dto?.unitNumber || null,
+ customer: dto?.customerName || null,
+ contract: dto?.contractCode || null,
+ at: iso(dto?.scannedAt) || new Date().toISOString(),
+ reason: dto?.reason || (result === "OPEN" ? null : "Mã không hợp lệ hoặc đã hết hiệu lực."),
+ };
+}
+
+// CancelPreviewDto: { paidAmount, cancellationFee, refundAmount, policyName }
+export function normCancelPreview(dto) {
+ if (!dto) return null;
+ const paid = num(dto.paidAmount);
+ const fee = num(dto.cancellationFee);
+ const refund = num(dto.refundAmount);
+ if (paid === null && refund === null) return null;
+ return { paid: paid ?? 0, fee: fee ?? Math.max(0, (paid ?? 0) - (refund ?? 0)), refund: refund ?? Math.max(0, (paid ?? 0) - (fee ?? 0)), policy: dto.policyName || null };
+}
+
+// Link chỉ đường Google Maps theo toạ độ (ưu tiên) hoặc địa chỉ
+export function directionsUrl({ lat, lng, address, name } = {}) {
+ const hasCoords = lat != null && lng != null && lat !== "" && lng !== "" && Number.isFinite(Number(lat)) && Number.isFinite(Number(lng));
+ const dest = hasCoords ? `${Number(lat)},${Number(lng)}` : [name, address].filter(Boolean).join(", ");
+ return `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(dest)}`;
+}
+
+// Mã QR mở cửa khi chạy không có backend (chế độ trình duyệt): mã tham chiếu cố định theo hợp đồng, không chứa bí mật
+export function localAccessCode(contract) {
+ const digits = [...String(contract.contract_id)].reduce((h, ch) => (h * 31 + ch.charCodeAt(0)) % 100000000, 7);
+ const backup = String(digits).padStart(8, "0");
+ return {
+ code: `SSQR-${String(contract.contract_id).replace(/[^A-Za-z0-9]/g, "")}-${backup.slice(0, 4)}`,
+ backup: `${backup.slice(0, 4)} ${backup.slice(4)}`,
+ unit: contract.unit_number,
+ unit_type: null,
+ location: contract.location || null,
+ valid_until: contract.end_date,
+ };
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/useAccessQr.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/useAccessQr.js
new file mode 100644
index 0000000..3949888
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/useAccessQr.js
@@ -0,0 +1,72 @@
+import { useCallback } from "react";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { USE_API } from "../../../app/config/api.js";
+import { api } from "../../../shared/api/customerApi.js";
+import { today } from "../../../shared/utils/format.js";
+import { accessError, validateAccess } from "../../../shared/utils/access.js";
+
+export function useAccessQr(id) {
+ const { data } = useApp();
+ const getCredential = useCallback(async () => {
+ if (USE_API) {
+ const contract = data.contracts.find(c => c.contract_id === id);
+ const targetId = contract?.api_id || id;
+ const res = await api.accessQr(targetId);
+ return {
+ owner: data.user.user_id,
+ contractId: id,
+ unit: res.unitNumber,
+ date: today(),
+ code: res.code,
+ backupCode: res.backupCode,
+ };
+ }
+ const contract = data.contracts.find(c => c.contract_id === id);
+ const error = accessError(contract, today());
+ if (error) throw new Error(error);
+ const credential = {
+ owner: data.user.user_id,
+ contractId: id,
+ unit: contract.unit_number,
+ date: today(),
+ code: crypto.randomUUID(),
+ backupCode: String(crypto.getRandomValues(new Uint32Array(1))[0] % 100000000).padStart(8, "0"),
+ };
+ return credential;
+ }, [data, id]);
+
+ const scan = useCallback(async (credential, code, unit) => {
+ if (USE_API) {
+ const res = await api.scanAccess(code);
+ const allowed = res.result === "OPEN";
+ const at = res.scannedAt || new Date().toISOString();
+ const key = `safespace.access.scans.${data.user.user_id}`;
+ let journal;
+ try { journal = JSON.parse(localStorage.getItem(key) || "[]"); } catch { journal = []; }
+ if (!Array.isArray(journal)) journal = [];
+ localStorage.setItem(key, JSON.stringify([...journal.slice(-99), { contractId: id, unit, allowed, message: res.reason || "", at }]));
+ return {
+ allowed,
+ message: res.reason || (allowed ? "Mở cửa thành công" : "Mã không hợp lệ"),
+ at,
+ };
+ }
+ const result = validateAccess({
+ contract: data.contracts.find(c => c.contract_id === id),
+ credential,
+ code,
+ unit,
+ owner: data.user.user_id,
+ date: today(),
+ });
+ const at = new Date().toISOString();
+ const key = `safespace.access.scans.${data.user.user_id}`;
+ let journal;
+ try { journal = JSON.parse(localStorage.getItem(key) || "[]"); } catch { journal = []; }
+ if (!Array.isArray(journal)) journal = [];
+ localStorage.setItem(key, JSON.stringify([...journal.slice(-99), { contractId: id, unit, allowed: result.allowed, message: result.message, at }]));
+ return { ...result, at };
+ }, [data, id]);
+
+ return { getCredential, scan };
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RenewalRequestPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RenewalRequestPage.jsx
new file mode 100644
index 0000000..1b419f6
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RenewalRequestPage.jsx
@@ -0,0 +1,54 @@
+import React, { useState } from "react";
+import { Select } from "../../../shared/components/Pickers.jsx";
+import { Button, Field, LinkButton, Notice, PageHeader } from "../../../shared/components/UI.jsx";
+import { RENTAL_PLANS } from "../../../shared/utils/catalog.js";
+import { addMonths, dateLabel, money } from "../../../shared/utils/format.js";
+import { go } from "../../../app/router.js";
+import { contractOf } from "../../../app/state/appSelectors.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { NotFound } from "./components/ContractNotFound.jsx";
+
+export function RenewalRequestPage({ id }) {
+ const { data, dispatch } = useApp();
+ const c = contractOf(data, id);
+ const [months, setMonths] = useState(3);
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+ if (!c) return ;
+ const newEnd = addMonths(c.end_date, months);
+ const submit = async (e) => {
+ e.preventDefault();
+ setBusy(true);
+ const res = await dispatch("REQUEST_RENEWAL", { contract_id: id, months });
+ setBusy(false);
+ if (!res.ok) return setError(res.error);
+ go(`sent?type=renew&contract=${encodeURIComponent(id)}`);
+ };
+ return (
+
+
+
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx
new file mode 100644
index 0000000..ddfe777
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx
@@ -0,0 +1,137 @@
+import React, { useState } from "react";
+import { Button, LinkButton, Notice, PageHeader, StatusTag, Tag } from "../../../shared/components/UI.jsx";
+import { typeLabel } from "../../../shared/utils/catalog.js";
+import { dateLabel, money, rangeLabel } from "../../../shared/utils/format.js";
+import { CONTRACT_STATUS, LEDGER_STATUS } from "../../../shared/utils/status.js";
+import { contractOf, contractStatus, facilityOf, pendingRenewal, pendingReturn } from "../../../app/state/appSelectors.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+import { NotFound } from "./components/ContractNotFound.jsx";
+import { AccessQrModal } from "../access/AccessQrModal.jsx";
+
+export function RentedUnitDetailPage({ id }) {
+ const { data, dispatch, notify } = useApp();
+ const [confirming, setConfirming] = useState(false);
+ const [qrOpen, setQrOpen] = useState(false);
+ const c = contractOf(data, id);
+ if (!c) return ;
+ const f = facilityOf(data, c.facility_id, c.facility_name);
+ const renewal = pendingRenewal(data, id);
+ const ret = pendingReturn(data, id);
+ const rent = [...data.ledger].reverse().find((l) => l.contract_id === id && (l.kind === "RENT" || /-RENT$/.test(l.ref)));
+ const pickup = data.appointments.find((a) => a.kind === "CHECK_IN" && (a.contract_id === id || (c.reservation_id && a.reservation_id === c.reservation_id)) && a.status !== "CANCELLED");
+ const confirmHandover = async () => {
+ setConfirming(true);
+ const res = await dispatch("CONFIRM_HANDOVER", { contract_id: id });
+ setConfirming(false);
+ notify(res.ok ? "Đã xác nhận nhận bàn giao kho." : res.error, res.ok ? "success" : "error");
+ };
+ const status = contractStatus(c);
+ const ended = status === "ENDED";
+ const handed = c.handed_over;
+ const busy = Boolean(renewal || ret);
+ const pickupText = pickup ? `${dateLabel(pickup.date)} · ${pickup.slot}` : null;
+ return (
+
+
+ {!handed && !ended && (
+
+
+
+ Chưa nhận kho{pickupText ? ` · Lịch nhận ${pickupText}` : ""}
+
+ Mang giấy tờ đã đăng ký{c.reservation_id ? ` và mã đặt chỗ ${c.reservation_id}` : ""} đến {f.name}. Gia hạn, trả kho và mở cửa kho dùng được sau khi nhân viên bàn giao.
+
+
+
+ {c.handover_pending_customer && (
+
+ Cơ sở đã bàn giao kho. Vui lòng kiểm tra và xác nhận đã nhận kho.{" "}
+
+
+ )}
+
Thông tin ra vào
+
+ {ended
+ ? "Hợp đồng đã kết thúc, mã mở cửa không còn hiệu lực."
+ : handed
+ ? "Mở cửa bằng QR: bấm \"Mở cửa kho\" rồi đưa mã vào máy quét ở cửa. QR chỉ dùng được khi hợp đồng còn hiệu lực và hết hiệu lực khi trả kho."
+ : `Khóa và mã truy cập được bàn giao khi nhận kho${pickupText ? ` ngày ${pickupText}` : " theo lịch hẹn"}.`}
+
+
+
+
+ {qrOpen && setQrOpen(false)} />}
+
+ );
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx
new file mode 100644
index 0000000..829ac94
--- /dev/null
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx
@@ -0,0 +1,42 @@
+import React from "react";
+import { EmptyInline } from "../../../shared/components/Inline.jsx";
+import { PageHeader, StatusTag } from "../../../shared/components/UI.jsx";
+import { typeLabel } from "../../../shared/utils/catalog.js";
+import { dateLabel } from "../../../shared/utils/format.js";
+import { siteLabel } from "../../../shared/hooks/useBrowserEvents.js";
+import { href } from "../../../app/router.js";
+import { CONTRACT_STATUS } from "../../../shared/utils/status.js";
+import { contractStatus, facilityOf } from "../../../app/state/appSelectors.js";
+import { useApp } from "../../../app/state/AppProvider.jsx";
+
+export function RentedUnitListPage() {
+ const { data } = useApp();
+ return (
+
+
+ {data.contracts.length === 0 ? (
+
+ ) : (
+