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 ( -
- { e.preventDefault(); document.getElementById("main")?.focus(); }}>Chuyển đến nội dung - {!(isAdminPage && !adminBody && authed) && !(isOpsPage && authed && opsAllowed) &&
} -
- {needsLogin ? null : loadError && !ready ? ( -
- - - -
- ) : !ready ? ( -
-
- ) : isAdminPage ? ( - adminBody || - ) : isOpsPage ? ( - opsAllowed ? ( - - - - ) : ( -
- - Về trang của tôi - -
- ) - ) : ( - renderPage(route) - )} -
- {storageError &&

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 CustomerApp() { - return ( - - - - ); -} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx deleted file mode 100644 index 0906752..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx +++ /dev/null @@ -1,35 +0,0 @@ -import React from "react"; -import { Empty, LinkButton } from "../components/UI"; -import AdminCreateUser from "./AdminCreateUser"; -import AdminLogs from "./AdminLogs"; -import AdminPermissions from "./AdminPermissions"; -import AdminShell from "./AdminShell"; -import AdminUserDetail from "./AdminUserDetail"; -import AdminUsers from "./AdminUsers"; - -// Định tuyến khu quản trị: #/admin, #/admin/users/:id, #/admin/new, #/admin/permissions, #/admin/logs -export default function AdminApp({ parts }) { - const [a, b] = parts; - let tab = ""; - let body; - if (!a) body = ; - else if (a === "users" && b) body = ; - else if (a === "new") { - tab = "new"; - body = ; - } else if (a === "permissions") { - tab = "permissions"; - body = ; - } else if (a === "logs") { - tab = "logs"; - body = ; - } else - body = ( -
- - Về quản lý tài khoản - -
- ); - return {body}; -} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx deleted file mode 100644 index e2a5655..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx +++ /dev/null @@ -1,183 +0,0 @@ -import React, { useState } from "react"; -import { adminApi } from "../api/admin"; -import { Select } from "../components/Pickers"; -import { Button, Field, Modal, Notice } from "../components/UI"; -import { isEmail, isPhone, today } from "../lib/format"; -import { FACILITY_ROLES, roleLabel, sortRoles } from "../lib/roles"; -import { go } from "../lib/router"; -import { useApp } from "../state/store"; -import { tempPassword, useLoad, usernameFrom } from "./util"; - -const EMPTY = { fullName: "", email: "", phone: "", username: "", password: "", roleId: "", facilityId: "" }; - -export default function AdminCreateUser() { - const { onApiError, notify } = useApp(); - 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); - const [form, setForm] = useState(() => ({ ...EMPTY, password: tempPassword() })); - const [userTouched, setUserTouched] = useState(false); - const [errors, setErrors] = useState({}); - const [busy, setBusy] = useState(false); - const [done, setDone] = useState(null); - - const roles = meta.data?.roles || []; - const role = roles.find((r) => String(r.roleId) === String(form.roleId)); - const scoped = role && FACILITY_ROLES.includes(role.roleName); - - const set = (k, v) => { - setForm((f) => { - const next = { ...f, [k]: v }; - if (k === "email" && !userTouched) next.username = usernameFrom(v); - return next; - }); - setErrors((e) => ({ ...e, [k]: undefined, form: undefined })); - }; - - const validate = () => { - const e = {}; - if (!form.fullName.trim()) e.fullName = "Vui lòng nhập họ và tên."; - if (!isEmail(form.email)) e.email = "Nhập email hợp lệ, ví dụ ten@safespace.vn."; - if (form.phone && !isPhone(form.phone)) e.phone = "Số điện thoại chưa đúng định dạng."; - 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 . _ - @"; - if (form.password.length < 8) e.password = "Mật khẩu tạm thời cần ít nhất 8 ký tự."; - if (!form.roleId) e.roleId = "Chọn vai trò cho tài khoả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."; - return e; - }; - - const submit = async (ev) => { - ev.preventDefault(); - const e = validate(); - if (Object.keys(e).length) return setErrors(e); - setBusy(true); - let created; - try { - 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) { - onApiError(err); - setBusy(false); - const msg = err.message || "Không tạo được tài khoản."; - if (/Tên đăng nhập/i.test(msg)) return setErrors({ username: msg }); - if (/Email/i.test(msg)) return setErrors({ email: msg }); - return setErrors({ form: msg }); - } - let facilityError = null; - if (scoped && form.facilityId) { - try { - await adminApi.assignFacility({ userId: created.userId, facilityId: Number(form.facilityId), assignedFrom: today(), assignedTo: null }); - } catch (err) { - facilityError = err.message; - } - } - setBusy(false); - setDone({ user: created, password: form.password, facilityError }); - }; - - const copy = async (text) => { - try { - await navigator.clipboard.writeText(text); - notify("Đã sao chép."); - } catch { - notify("Không sao chép được, vui lòng chép thủ công.", "error"); - } - }; - - return ( -
-
-

Thêm tài khoản mới

-

Tạo tài khoản và gán vai trò phù hợp. Gửi tên đăng nhập và mật khẩu tạm thời cho người dùng để đăng nhập lần đầu.

- {meta.error && {meta.error}} - {errors.form &&

{errors.form}

} - - set("fullName", e.target.value)} /> - - - set("email", e.target.value)} /> - - - set("phone", e.target.value)} /> - -
- - { setUserTouched(true); set("username", e.target.value.trim()); }} /> - - - - set("password", e.target.value)} /> - - - -
-
- Vai trò -
- {roles.map((r) => ( - - ))} - {meta.loading && Đang tải vai trò…} -
- {errors.roleId &&

{errors.roleId}

} -
- - - -

- "Cơ sở phụ trách" chỉ áp dụng cho vai trò gắn với một cơ sở cụ thể (Nhân viên, Quản lý cơ sở). Vận hành KD và Quản trị có quyền trên toàn hệ thống. -

- -

- ← Về danh sách tài khoản -

-
- - {done && ( - go(`admin/users/${done.user.userId}`)}> -

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.

-
-
Tên đăng nhập
{done.user.username}
-
Mật khẩu tạm thời
{done.password}
-
- {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.} -
- - -
-
- )} -
- ); -} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx deleted file mode 100644 index 9dc0387..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx +++ /dev/null @@ -1,143 +0,0 @@ -import React, { useMemo, useState } from "react"; -import { adminApi } from "../api/admin"; -import { parseUtc } from "../api/mappers"; -import { DatePicker, Pagination } from "../components/Pickers"; -import { Notice } from "../components/UI"; -import { ACTION_GROUPS, roleLabel, sortRoles } from "../lib/roles"; -import { useApp } from "../state/store"; -import { dateTime, describeActivity, useLoad } from "./util"; - -const TABS = [ - ["all", "Tất cả"], - ["login", "Đăng nhập"], - ["data", "Thay đổi dữ liệu"], - ["access", "Phân quyền"], -]; -const PAGE_SIZE = 10; -const FETCH = 100; // số bản ghi mới nhất lấy mỗi loại để gộp / lọc ở trình duyệt - -// Ngày địa phương → mốc UTC để gửi backend -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 AdminLogs() { - const { onApiError } = useApp(); - const [tab, setTab] = useState("all"); - const [from, setFrom] = useState(""); - const [to, setTo] = useState(""); - const [page, setPage] = useState(1); - - const users = useLoad(async () => { - const res = await adminApi.users({ page: 1, pageSize: 500 }); - return new Map(res.items.map((u) => [u.userId, u])); - }, [], onApiError); - - 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(); - const nameOf = (id) => userMap.get(id)?.fullName; - const rolesOf = (id) => sortRoles(userMap.get(id)?.roles || []).map(roleLabel).join(", ") || "—"; - - const rows = useMemo(() => { - const d = logs.data; - if (!d) return []; - 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; - 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 || "—", - })); - 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 - - 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; - - const pick = (fn) => (v) => { - fn(v); - setPage(1); - }; - - return ( -
-
-
-

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.

-
-
- -
-
- {TABS.map(([k, label]) => ( - - ))} -
-
- - - {(from || to) && ( - - )} -
-
- - {logs.error && {logs.error}} -
- - - - - - {shown.map((r) => ( - - - - - - - - ))} - {!logs.loading && shown.length === 0 && ( - - )} - {logs.loading && !logs.data && ( - - )} - -
Thời gianNgười dùngVai tròHành độngĐịa chỉ IP
{dateTime(r.at)}{r.user}{r.userId ? rolesOf(r.userId) : "—"}{r.action}{r.ip}
Chưa có hoạt động trong khoảng thời gian này.
Đang tải nhật ký…
-
- - {!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/admin/AdminPermissions.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx deleted file mode 100644 index a340c21..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx +++ /dev/null @@ -1,173 +0,0 @@ -import React, { useMemo, useState } from "react"; -import { adminApi } from "../api/admin"; -import { Button, Modal, Notice } from "../components/UI"; -import { ROLE_SCOPE, roleLabel, sortRoles } from "../lib/roles"; -import { useApp } from "../state/store"; -import { useLoad } from "./util"; - -const key = (roleId, permissionId) => `${roleId}:${permissionId}`; - -export default function AdminPermissions() { - const { onApiError, notify } = useApp(); - const res = useLoad(async () => { - const [roles, permissions] = await Promise.all([adminApi.roles(), adminApi.permissions()]); - return { roles: sortRoles(roles, (r) => r.roleName), permissions }; - }, [], onApiError); - const [changes, setChanges] = useState({}); // key → true (gán) | false (thu hồi) - const [confirm, setConfirm] = useState(false); - const [saving, setSaving] = useState(false); - const [errors, setErrors] = useState([]); - - 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]); - const isOn = (roleId, pid) => { - const k = key(roleId, pid); - return k in changes ? changes[k] : granted.has(k); - }; - 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; - }); - }; - const pending = Object.entries(changes); - const roles = res.data?.roles || []; - const permissions = res.data?.permissions || []; - const roleOf = (id) => roles.find((r) => String(r.roleId) === String(id)); - const permOf = (id) => permissions.find((p) => String(p.permissionId) === String(id)); - 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); - }); - - 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 ( -
-
-
-

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.

-
-
- {res.error && {res.error}} - -
- - - - - - {roles.map((r) => ( - - - - - - - ))} - {res.loading && !res.data && } - -
Vai tròPhạm vi dữ liệuMô tảSố quyền
{roleLabel(r.roleName)}{ROLE_SCOPE[r.roleName] || "Theo quyền được gán"}{r.description || "—"}{permissions.filter((p) => isOn(r.roleId, p.permissionId)).length} / {permissions.length}
Đang tải…
-
- -

Quyền thao tác theo vai trò

-
- - - - - {roles.map((r) => ( - - ))} - - - - {permissions.map((p) => ( - - - {roles.map((r) => { - const k = key(r.roleId, p.permissionId); - const on = isOn(r.roleId, p.permissionId); - return ( - - ); - })} - - ))} - -
Quyền{roleLabel(r.roleName)}
- {p.permissionName} - {p.permissionCode}{p.description ? ` · ${p.description}` : ""} - - -
-
- - {errors.length > 0 && ( - - {errors.map((e) => ( -
{e}
- ))} -
- )} -
- - {pending.length > 0 && !saving && ( - - )} -
- - {confirm && ( - setConfirm(false)} size="md"> -
    - {pending.map(([k, on]) => { - const [rid, pid] = k.split(":"); - return ( -
  • - {on ? "Gán" : "Thu hồi"} {permOf(pid)?.permissionName} {on ? "cho" : "của"} {roleLabel(roleOf(rid)?.roleName)} -
  • - ); - })} -
- {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.} -
- - -
-
- )} -
- ); -} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx deleted file mode 100644 index f598204..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx +++ /dev/null @@ -1,183 +0,0 @@ -import React, { useEffect, useRef, useState } from "react"; -import { Icon } from "../components/UI"; -import { go, href } from "../lib/router"; -import { useApp } from "../state/store"; -import { adminApi } from "../api/admin"; -import { dateTime } from "./util"; - -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"], -]; -const READ_KEY = "safespace.admin.notices.read"; - -function useNotices(onApiError) { - const [items, setItems] = useState([]); - const [read, setRead] = useState(() => { - try { - return JSON.parse(localStorage.getItem(READ_KEY)) || []; - } catch { - return []; - } - }); - useEffect(() => { - let alive = true; - (async () => { - try { - const [stats, logins] = await Promise.all([adminApi.stats(), adminApi.loginHistory({ page: 1, pageSize: 1 })]); - if (!alive) return; - const list = []; - 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", - }); - 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" }); - 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]); - const mark = (ids) => { - const next = [...new Set([...read, ...ids])].slice(-100); - setRead(next); - try { - localStorage.setItem(READ_KEY, JSON.stringify(next)); - } catch { - /* bỏ qua */ - } - }; - return { items: items.map((n) => ({ ...n, read: read.includes(n.id) })), mark }; -} - -function Bell() { - const { onApiError } = useApp(); - const { items, mark } = useNotices(onApiError); - const [open, setOpen] = useState(false); - const ref = useRef(null); - const unread = items.filter((n) => !n.read).length; - 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 ( -
-