From 6b583da5052ee1c3aac820bcfe9ee700b714c2d8 Mon Sep 17 00:00:00 2001 From: Vector Date: Sat, 26 Sep 2026 21:23:15 +0700 Subject: [PATCH 01/24] =?UTF-8?q?docs:=20th=C3=AAm=20b=E1=BB=99=20harness?= =?UTF-8?q?=20cho=20AI=20coding=20agent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tham khảo: https://learnharness.org/#dinh-nghia và https://skills.learnharness.org/ (thầy Hoàng giới thiệu). Kèm rà soát và chốt Figma ngày 26/09/2026. --- AGENTS.md | 110 ++++++++++ CLAUDE.md | 5 + DECISIONS.md | 53 +++++ .../CUSTOMER-FLOW-COVERAGE.md | 2 +- docs/architecture.md | 58 +++++ docs/business-rules.md | 58 +++++ docs/conventions.md | 40 ++++ docs/figma-review-2026-09-26.md | 52 +++++ docs/templates/sprint-contract.md | 33 +++ docs/verification.md | 38 ++++ feature_list.json | 200 ++++++++++++++++++ init.ps1 | 46 ++++ init.sh | 60 ++++++ progress.md | 55 +++++ 14 files changed, 809 insertions(+), 1 deletion(-) create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 DECISIONS.md create mode 100644 docs/architecture.md create mode 100644 docs/business-rules.md create mode 100644 docs/conventions.md create mode 100644 docs/figma-review-2026-09-26.md create mode 100644 docs/templates/sprint-contract.md create mode 100644 docs/verification.md create mode 100644 feature_list.json create mode 100644 init.ps1 create mode 100644 init.sh create mode 100644 progress.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..92ec72e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,110 @@ +# 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. + +## 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 + quản trị | +| `…/src/state/reducer.js` | Nghiệp vụ phía giao diện (hàm thuần, có test) | +| `…/src/state/store.jsx` | Phiên đăng nhập, 2 chế độ: API / lưu trình duyệt | +| `…/src/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 | +| `…/CUSTOMER-FLOW-COVERAGE.md`, `ADMIN-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 +dotnet run --project StorageProject.Api --launch-profile http # API: http://localhost:5151 +cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm run dev # UI: 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`/`Customer@123`, `staff01`/`Staff@123`, `admin`/`Admin@123`. +Không có backend: tạo `.env.local` với `VITE_USE_API=false`. + +## 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/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..0e50ff4 --- /dev/null +++ b/DECISIONS.md @@ -0,0 +1,53 @@ +# 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. 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 6f2e8d8..b3d900f 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md @@ -31,6 +31,6 @@ Nguồn: file Figma "SafeSpace - Modern UI" (section Khách hàng + Trang chủ ## 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 **6 ảnh** (ảnh cơ sở + 4 ảnh bên trong + sơ đồ). -- 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/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..4133533 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,58 @@ +# Kiến trúc SSFRMS / SafeSpace + +## Tổng quan + +``` +Trình duyệt (React 19 + Vite, hash router) + ├── Khu khách hàng #/home, #/find, #/overview, #/units, #/payments, #/support, #/profile … + └── Khu quản trị #/admin/* (chỉ vai trò ADMIN, chỉ chế độ API) + │ fetch + Bearer JWT (VITE_API_URL, mặc định http://localhost:5151) + ▼ +StorageProject.Api .NET Minimal API — Endpoints/*Endpoints.cs, JWT, Swagger (/index.html), /health + │ gọi interface trong Core + ▼ +StorageProject.Infrastructure Services/*Service.cs (nghiệp vụ), AppDbContext (EF Core), DbSeeder, Migrations + │ + ▼ +SQL Server (mặc định .\SQLEXPRESS, database SSFRMS) + +StorageProject.Core Entities (25 bảng theo Data Dictionary), DTOs, Interfaces/IServices.cs +``` + +## Backend — một request đi qua đâu + +1. `Endpoints/XxxEndpoints.cs`: nhận request, lấy `userId` từ JWT (`ClaimsPrincipal.GetUserId()`), gọi service. +2. `Core/Interfaces/IServices.cs`: khai báo `IXxxService`. +3. `Infrastructure/Services/XxxService.cs`: kiểm tra quyền sở hữu, nghiệp vụ, truy vấn EF Core, trả DTO. +4. Lỗi nghiệp vụ: service ném `ArgumentException` / `InvalidOperationException` → endpoint trả `400 { error }`. +5. Đăng ký service trong `Program.cs`; map endpoint bằng `app.MapXxxEndpoints()`. + +Khi khởi động, `DbSeeder` tạo vai trò, quyền, 12 cơ sở, loại kho, bảng giá, tài khoản seed. Chạy lại được (chỉ thêm phần thiếu). + +## Frontend — hai chế độ dữ liệu + +`src/state/store.jsx` chọn provider theo `VITE_USE_API`: + +| Chế độ | Khi nào | Dữ liệu | +|---|---|---| +| `ApiProvider` | `VITE_USE_API=true` (mặc định) | Gọi backend qua `src/api/*`; luồng backend chưa có → lưu trình duyệt theo tài khoản (D04) | +| Provider trình duyệt | `VITE_USE_API=false` | `src/data/seed.js` + `reducer.js`, lưu localStorage; chỉ để xem giao diện | + +Nghiệp vụ phía giao diện nằm trong `src/state/reducer.js` dưới dạng lệnh (`CREATE_RESERVATION`, `CONFIRM_TRANSFER`, …). +Mỗi lệnh tương ứng một endpoint trong `BE-CONTRACT.md`. Page chỉ gọi lệnh, không gọi `fetch` trực tiếp. + +| Thư mục | Vai trò | +|---|---| +| `src/pages/` | Mỗi màn Figma một component | +| `src/components/` | Header + thông báo, lịch, thư viện ảnh, mã QR, UI dùng chung (`UI.jsx`) | +| `src/admin/` | Khu quản trị A01–A04 | +| `src/api/` | `http.js` (fetch + token), `endpoints.js`, `admin.js`, `mappers.js` (backend → giao diện) | +| `src/lib/` | router, định dạng tiền/ngày, trạng thái → nhãn (`status.js`), vai trò, VietQR | +| `src/config/` | địa chỉ API, ảnh, tài khoản nhận chuyển khoản | +| `src/styles/ss.css` | Token màu / chữ / bo góc theo Figma | +| `tests/` | `node --test`: reducer, mappers, admin; `render.test.mjs` render mọi route | + +## Chưa có (theo SRS) + +Giao diện và phần lớn API cho Nhân viên cơ sở, Quản lý cơ sở, Quản lý vận hành KD (UC07–UC23), +vai trò Quản lý vận hành KD ở backend, project test backend. Xem `feature_list.json`. diff --git a/docs/business-rules.md b/docs/business-rules.md new file mode 100644 index 0000000..230364c --- /dev/null +++ b/docs/business-rules.md @@ -0,0 +1,58 @@ +# Quy tắc nghiệp vụ — bản tóm tắt cho AI + +> Nguồn đầy đủ: `srs_content.txt` mục 2 (A01–A10), 7 (BR01–BR30), 8 (trạng thái), 10 (thanh toán, báo cáo). +> File này chỉ là chỉ mục nhanh. Khi sửa nghiệp vụ, đọc đúng mục SRS được dẫn và ghi mã quy tắc vào commit/test. + +## Quy ước chung + +- Tiếng Việt, tiền VND, `DECIMAL(15,2)`. Khoá chính BIGINT tự tăng. Tên bảng/trường snake_case (Data Dictionary). +- Thuê theo số tháng nguyên. Khoảng thuê là **[start_date, end_date)**; cộng tháng theo lịch, chặn về cuối tháng (A02). +- Hai khoảng trùng khi `s1 < e2 && s2 < e1` (BR16). Không bao giờ gán một unit cho hai quyền sử dụng chồng nhau (BR01). +- Mọi thay đổi vai trò, phạm vi, giá, chính sách, phân bổ, hợp đồng, thanh toán phải ghi audit (BR13). +- Giá trên hợp đồng/gia hạn là giá **chụp tại thời điểm**; đổi bảng giá không sửa ngược (BR14). +- Thiếu cấu hình phí/chính sách → từ chối thao tác, không tự dùng mức mặc định (SRS mục 2). +- Các bước đặt chỗ, gán unit, thanh toán, gia hạn, bàn giao chạy trong **một giao dịch**; gọi lặp trả kết quả cũ (7.1). + +## Phân quyền + +| Vai trò | Phạm vi dữ liệu | +|---|---| +| Khách hàng | Dữ liệu công bố + bản ghi của chính mình | +| Nhân viên / Quản lý cơ sở | Chỉ cơ sở đang được phân công ACTIVE (BR12); tối đa 1 phân công ACTIVE/người (A06) | +| Quản lý vận hành KD | Toàn hệ thống, phần kinh doanh | +| Quản trị hệ thống | Toàn hệ thống, phần tài khoản/quyền; không mặc định duyệt tiền hay sửa hợp đồng | + +Kiểm tra quyền ở **máy chủ**, không tin giao diện. + +## Trạng thái chính (SRS mục 8) + +| Đối tượng | Chuyển tiếp | +|---|---| +| Reservation | PENDING_PAYMENT → UNIT_ASSIGNED → CONFIRMED → CHECKED_IN; huỷ → CANCELLED; hết giờ → EXPIRED; không đến → NO_SHOW | +| Contract | DRAFT → ACTIVE → EXPIRING → OVERDUE; → RETURN_PENDING → COMPLETED; DRAFT → CANCELLED; → TERMINATED | +| Unit | AVAILABLE → ASSIGNED → OCCUPIED → RETURN_PENDING → INSPECTION → AVAILABLE hoặc MAINTENANCE; OUT_OF_SERVICE | +| Payment | PENDING → PAID / FAILED; PAID → REFUNDED | +| Renewal | PENDING → APPROVED / REJECTED / CANCELLED; APPROVED → PAID | +| Handover | SCHEDULED → VERIFIED → HANDED_OVER; → CANCELLED | +| Ticket | OPEN → ASSIGNED → IN_PROGRESS → RESOLVED → CLOSED; OPEN/ASSIGNED → CANCELLED | +| Credential | ACTIVE → RETURNED / LOST / REVOKED / REPLACED | + +Giao diện khách hàng hiện dùng tập trạng thái đơn giản hơn (vd. `PENDING_VERIFICATION`, `ENDED`) — bảng đối chiếu ở +`BE-CONTRACT.md` mục 2. Khi thêm trạng thái mới, sửa cả `src/lib/status.js` và `src/api/mappers.js`. + +## Quy tắc hay bị làm sai + +- **Bàn giao** chỉ khi reservation hợp lệ, contract DRAFT, unit sẵn sàng, đã đáp ứng thanh toán (BR07); thành công thì + đồng thời unit OCCUPIED, contract ACTIVE, reservation CHECKED_IN (BR08). +- **Trả kho**: unit chỉ AVAILABLE sau inspection COMPLETED (BR09); trả kho vật lý và công nợ là hai việc riêng (A10). +- **Gia hạn**: Manager duyệt và thanh toán đủ rồi mới cập nhật `end_date`, chỉ một lần (A09, BR24); mỗi hợp đồng chỉ một + renewal PENDING/APPROVED chưa xong. +- **Quá hạn**: hết kỳ chưa có bằng chứng trả → contract OVERDUE, không tự thành kho trống (BR11); không tạo trùng overdue_case (BR26). +- **Tiền**: giá kỳ = giá tháng × số tháng, sau giảm/miễn không âm; cọc ghi riêng (BR22). Không hoàn một phần, không trừ cọc tự động (BR27–BR28). +- **Ticket** bắt buộc gắn contract của khách (A07). +- **Bảo trì** chưa có ngày kết thúc → loại unit khỏi phân bổ (BR30). + +## Luồng đặt chỗ đã chốt theo Figma + +Chuyển khoản QR lúc đặt → "Chờ đối soát" → nhân viên đối soát → quản lý phân bổ kho → nhận kho theo lịch (D02). +SRS mục A03 cần sửa cho khớp. Hợp đồng chưa bàn giao không cho gia hạn / trả kho (D11). diff --git a/docs/conventions.md b/docs/conventions.md new file mode 100644 index 0000000..94a4783 --- /dev/null +++ b/docs/conventions.md @@ -0,0 +1,40 @@ +# Quy ước code + +## Chung + +- Giao diện, thông báo lỗi cho người dùng, tài liệu: **tiếng Việt**. Tên biến/hàm/endpoint/bảng: **tiếng Anh**. +- Sửa ít file nhất có thể cho tính năng đang làm. Không đổi tên, không format lại file không liên quan. +- Không thêm thư viện mới khi chưa ghi lý do vào `DECISIONS.md`. + +## Backend (.NET) + +- **Endpoint**: file `StorageProject.Api/Endpoints/Endpoints.cs`, hàm mở rộng `MapEndpoints`, + `MapGroup("/api/...")`, `.WithTags(...)`, `.RequireAuthorization()` (thêm policy vai trò khi cần). +- Endpoint mỏng: lấy `userId` bằng `user.GetUserId()`, gọi service, map kết quả sang `Results.Ok / Created / BadRequest / NotFound`. +- Lỗi nghiệp vụ: service ném `ArgumentException` hoặc `InvalidOperationException` với thông điệp tiếng Việt; + endpoint bắt và trả `400 { error }`. Sai mật khẩu không trả 401 (giao diện coi 401 là hết phiên). +- **Service**: interface trong `Core/Interfaces/IServices.cs`, cài đặt trong `Infrastructure/Services/`, primary constructor + `(AppDbContext dbContext)`, luôn nhận `CancellationToken ct`. Truy vấn đọc dùng `AsNoTracking()` và `Select` thẳng ra DTO. +- Luôn kiểm tra **quyền sở hữu / phạm vi cơ sở** trong service trước khi đọc/ghi (BR05, BR12). +- Thao tác nhiều bảng: bọc trong transaction (`dbContext.Database.BeginTransactionAsync`). +- **DTO**: `record` trong `Core/DTOs//Dtos.cs`. Không trả entity ra ngoài. +- **Schema**: sửa Entity + Configuration → `dotnet ef migrations add --project StorageProject.Infrastructure --startup-project StorageProject.Api`. Không sửa migration cũ. +- Dữ liệu khởi tạo thêm vào `DbSeeder` theo kiểu chạy lại được (chỉ thêm phần thiếu). +- Endpoint mới: thêm request mẫu vào `StorageProject.Api.http` và cập nhật `BE-CONTRACT.md`. + +## Frontend (React + Vite) + +- Không có TypeScript, không có thư viện UI/CSS ngoài. Style dùng class + token trong `src/styles/ss.css`; không hard-code màu. +- Màn mới: `src/pages/.jsx`, thêm route trong `CustomerApp.jsx` (hoặc `admin/AdminApp.jsx`) và dòng tương ứng + trong `CUSTOMER-FLOW-COVERAGE.md` / `ADMIN-FLOW-COVERAGE.md`. +- Page **không gọi fetch trực tiếp**: gọi lệnh qua store → `reducer.js` (chế độ trình duyệt) hoặc `ApiProvider` → `src/api/*`. +- Dữ liệu backend đi qua `src/api/mappers.js` trước khi tới component. Nhãn trạng thái lấy từ `src/lib/status.js`. +- Tiền và ngày định dạng bằng `src/lib/format.js`. Ngày từ backend coi là UTC (D10). +- Text lấy đúng từ Figma. Không có chữ "demo", "sample", "dữ liệu mẫu" (D07). +- Ảnh: file trong `public/images/`, gán qua `src/config/media.js` (D06). +- Nghiệp vụ mới trong `reducer.js` phải có test trong `tests/reducer.test.js`. + +## Git + +- Nhánh `feature/` → PR vào `main` (D08). Commit: `feat(F05): gửi yêu cầu gia hạn 1/3/6 tháng`. +- Không commit: `node_modules/`, `dist/`, `bin/`, `obj/`, `.env.local`, `appsettings.*.json`. diff --git a/docs/figma-review-2026-09-26.md b/docs/figma-review-2026-09-26.md new file mode 100644 index 0000000..0aa1b5d --- /dev/null +++ b/docs/figma-review-2026-09-26.md @@ -0,0 +1,52 @@ +# Rà soát Figma ngày 26/09/2026 + +File: "SafeSpace - Modern UI" (https://www.figma.com/design/SX8EvOf1TJkxfMl90bZsGN/SafeSpace---Modern-UI). +Phạm vi: mâu thuẫn về luồng, trạng thái, nhân vật, liên kết prototype giữa các màn. +**Không** xét ảnh, giá tiền, số liệu thống kê — các thứ này lấy từ backend. + +## Mốc dữ liệu chung đã chốt + +Mọi màn dùng chung một câu chuyện tại **14/09/2026**, sau khi nhân viên đối soát (09:20) và quản lý phân bổ kho (10:03): + +| Đối tượng | Trạng thái tại 14/09 | +|---|---| +| Đơn SS-20260914-0142 / HĐ-2026-0142 / Kho A-102 (Nguyễn Thị Mai) | Đã đối soát, đã phân bổ A-102, **chờ nhận kho** 20/09 09:00. Chưa bàn giao → chưa gia hạn / trả kho được | +| Kho B-015 / HĐ-2026-0086 (Nguyễn Thị Mai) | Đang thuê, sắp hết hạn 25/09. **Chưa gửi** yêu cầu gia hạn (hạn gửi 18/09) | +| HT-0082 | Lỗi thẻ ra vào tại **B-015**, nhân viên Trần Văn Long xử lý | +| Kho C-012 (Lê Văn An) | Hợp đồng quá hạn 4 ngày, hẹn kiểm tra trả kho 20/09 10:00 | +| Kho C-208 (Lê Văn Tùng), F-077 (Đỗ Minh Khang) | Yêu cầu gia hạn đang chờ quản lý duyệt | +| Kho A-045, D-019 | Quá hạn thanh toán 3 ngày | +| Tên cơ sở | Một tên duy nhất "SafeSpace Nguyễn Lương Bằng" (bỏ "SafeSpace Quận 7" vì Quận 7 có 2 cơ sở) | +| Nhân viên cơ sở | Một người: Trần Văn Long (bỏ "Trần Minh", "Lê Anh") | + +## Đã sửa trong Figma + +**Khách hàng** +- C01: kho A-102 → "Chờ nhận kho"; "Kho đang thuê" 2 → 1; bỏ các dòng nói gia hạn B-015 "đã gửi / chờ duyệt"; quy tắc "gia hạn chậm nhất 7 ngày trước khi kết thúc"; 4 ô "Hành động nhanh" nay có liên kết (C07b, C07, C11, C12). +- C06, C07: A-102 "Chờ nhận kho", khóa/mã bàn giao khi nhận kho. Nút ở C07 đổi thành "Xem lịch nhận kho" (→ C11) và "Đổi lịch nhận kho" (→ C12). +- C08, C09: đổi tên thành "(sau khi nhận kho)" — chỉ dùng khi hợp đồng đã bàn giao, như C07b → C08b / C09b. +- C08, C08b: câu tiền cọc thống nhất "Tiền cọc đang giữ được chuyển sang kỳ mới, không thu thêm" (C08 cũ ghi "Không hoàn lại tiền cọc"). +- C10: "Xem hợp đồng" → C07b (trước trỏ C07 dù yêu cầu là của B-015). +- C11: bỏ dòng "Gia hạn đề xuất SS-0142-REN" (gắn nhầm đơn A-102, và B-015 chưa gửi gia hạn); ghi rõ khoản thuộc kho nào. +- C12: kho liên quan A-102 → B-015; tiêu đề "Lỗi thẻ ra vào" khớp S05 / M06. +- C14: SS-0142 "Chờ đối soát" → "Đã xác nhận" (khớp C11, C01); "Xem đơn SS-0142" → C11. +- A02 (đăng ký): "Tạo tài khoản" → C02 thay vì dashboard đã có kho của khách khác. +- P01: bậc diện tích "2–5 m²" → "Dưới 10 m²" (không còn khoảng trống 5–10 m²). + +**Nhân viên / Quản lý / Quản trị** +- S01: việc kiểm tra trả kho khớp với S04 (C-012, Lê Văn An, 20/09 10:00). +- S09: "Xác nhận đã thu" → S01 (bước tiếp là quản lý phân bổ, không phải xác minh khách); thêm liên kết "Báo sai lệch" → S06, S03 "Xác nhận bàn giao" → S01. +- S05, M06: HT-0082 thuộc B-015; nhân viên phụ trách Trần Văn Long. +- M02: A-102 "Chờ bàn giao". M03: bỏ B-015 khỏi danh sách chờ duyệt (thay bằng C-208). M07: bỏ A-102 (không có gì cần xử lý), tên khách B-015 sai → thay bằng A-045 và F-077. M03 "Từ chối" có liên kết. +- A02: bỏ "gửi lời mời qua email" → mật khẩu tạm thời hiển thị một lần (khớp A05 và SRS: chưa gửi email). +- A04: 10:03 là "Phân bổ kho A-102" (không phải duyệt gia hạn B-015); đăng nhập sai của Lê Quang Huy chuyển sau lúc tài khoản được tạo. +- A05: ngày tạo tài khoản 01/08/2026 (khớp lịch sử phân công); phân công cũ là "SafeSpace Him Lam". A01: bấm dòng Phạm Thu Hà → A05. + +## Còn lệch nhưng thuộc dữ liệu (không sửa) + +Giá, số tiền (vd. C04 3.450.000 đ và tổng ban đầu 4.600.000 đ), ảnh (C03c "x trên 4"), danh sách / khu vực cơ sở, +số liệu thống kê, tham số chính sách (B02). Các giá trị này lấy từ backend. + +## Hoàn tác + +Figma lưu lịch sử phiên bản (File → Show version history): chọn bản trước 20:50 ngày 26/09/2026 để xem hoặc khôi phục. diff --git a/docs/templates/sprint-contract.md b/docs/templates/sprint-contract.md new file mode 100644 index 0000000..1b67180 --- /dev/null +++ b/docs/templates/sprint-contract.md @@ -0,0 +1,33 @@ +# Sprint contract: — + +> Dùng cho tính năng lớn (nhiều file, cả FE và BE). Chép file này thành `docs/sprints/Fxx.md`, +> điền trước khi cho AI code, để AI biết rõ được làm gì và không được làm gì. + +## Mục tiêu + + +## Nguồn yêu cầu +- Use case: UCxx (SRS mục 15.x) +- Quy tắc: BRxx, Axx +- Màn Figma: + +## Phạm vi (được sửa) +- Backend: +- Frontend: +- Tài liệu: `BE-CONTRACT.md`, `*-FLOW-COVERAGE.md` + +## Ngoài phạm vi (KHÔNG làm) +- + +## Tiêu chí hoàn thành +- [ ] +- [ ] +- [ ] `./init.sh` pass +- [ ] Đã cập nhật `feature_list.json`, `progress.md` + +## Chấm điểm (người kiểm điền) +| Tiêu chí | A | B | C | D | +|---|---|---|---|---| +| Đúng nghiệp vụ | Đúng cả luồng chính và lỗi | Đúng luồng chính | Đúng một phần | Sai | +| Test | Có test luồng chính + lỗi | Chỉ luồng chính | Chỉ khung | Không có | +| Khớp Figma | Khớp | Lệch nhỏ | Lệch nhiều | Không theo | diff --git a/docs/verification.md b/docs/verification.md new file mode 100644 index 0000000..63a57b5 --- /dev/null +++ b/docs/verification.md @@ -0,0 +1,38 @@ +# Kiểm chứng — thế nào là "xong" + +"Xong" nghĩa là **có bằng chứng chạy được**, không phải AI nói "code trông ổn". + +## Lệnh kiểm chứng + +| Phạm vi | Lệnh | Hiện trạng (2026-09-26) | +|---|---|---| +| Toàn bộ | `./init.sh` hoặc `.\init.ps1` | FE pass; BE chưa chạy trên máy thiết lập | +| Nghiệp vụ FE | `npm test` (trong thư mục frontend) | 28/28 pass | +| Render mọi route | `npm run test:render` | 38 route PASS | +| Build FE | `npm run build` | OK | +| Build BE | `dotnet build StorageProject.slnx` | — | +| Test BE | `dotnet test StorageProject.slnx` | Chưa có project test (F28) | +| Gọi thử API | `StorageProject.Api/StorageProject.Api.http` hoặc Swagger `http://localhost:5151/index.html` | Thủ công | + +## Mức kiểm chứng theo loại thay đổi + +| Thay đổi | Tối thiểu phải chạy | +|---|---| +| Chỉ giao diện | `npm test` + `npm run test:render` + `npm run build` + mở màn hình đó xem thật | +| Nghiệp vụ trong `reducer.js` | Như trên + test mới trong `tests/reducer.test.js` | +| Mapper / gọi API | Như trên + test trong `tests/api-mappers.test.js` + chạy với backend thật | +| Backend | `dotnet build` + gọi thử endpoint (thành công và lỗi) + `dotnet test` khi đã có F28 | +| Schema / migration | Như backend + `dotnet ef database update` trên database mới tạo | + +## Định nghĩa "xong" cho một tính năng + +1. Lệnh `verification` của tính năng trong `feature_list.json` pass. +2. `./init.sh` pass toàn bộ. +3. Kịch bản chính và ít nhất một kịch bản lỗi đã thử (ví dụ: gia hạn khi đã có yêu cầu chờ → báo lỗi đúng). +4. Đúng tiêu chí nghiệm thu trong SRS mục 13 và đặc tả UC ở mục 15. +5. Đã ghi `evidence` (ngày, lệnh, kết quả, commit) vào `feature_list.json`. + +## Người làm ≠ người kiểm + +Sau khi AI báo xong, một người khác trong nhóm (hoặc một phiên AI mới chưa thấy code) kiểm lại theo mục trên +trước khi merge PR. AI thường tự khen công việc của mình. diff --git a/feature_list.json b/feature_list.json new file mode 100644 index 0000000..14cd7da --- /dev/null +++ b/feature_list.json @@ -0,0 +1,200 @@ +{ + "_readme": "Danh sách tính năng = ranh giới phạm vi cho AI agent. Mỗi mục: behavior (hành vi), verification (lệnh/cách kiểm chứng), state. state: not_started -> active -> passing | blocked. Chỉ đổi sang passing khi verification pass và ghi evidence. Mỗi phiên chỉ một mục active.", + "_fe": "cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm test && npm run test:render && npm run build", + "_be": "dotnet build StorageProject.slnx", + "updated": "2026-09-26", + "features": [ + { + "id": "F01", "flow": 1, "uc": ["UC01"], "actor": "Khách hàng", + "behavior": "Xem 12 cơ sở, lọc theo loại kho / diện tích / khu vực, xem chi tiết cơ sở, bảng giá, kiểm tra kho trống (GET /api/facilities, /unit-types, /rates; POST /api/availability/check)", + "verification": "_fe; mở #/find và #/find/:id khi API chạy", + "state": "passing", + "evidence": "2026-09-26: npm test 28/28, test:render 38 route PASS, build OK (commit 5177812)" + }, + { + "id": "F02", "flow": 1, "uc": ["UC02"], "actor": "Khách hàng", + "behavior": "Tạo đơn đặt chỗ PENDING_PAYMENT, đếm ngược giữ chỗ, hết giờ tự huỷ (POST /api/reservations, POST /api/reservations/{id}/cancel), xem danh sách/chi tiết đơn", + "verification": "_fe; đặt chỗ ở #/checkout/:id, chờ hết VITE_PAYMENT_TIMEOUT_SECONDS → #/checkout/:id/failed", + "state": "passing", + "evidence": "2026-09-26: npm test + test:render PASS" + }, + { + "id": "F03", "flow": 1, "uc": ["UC03"], "actor": "Khách hàng", + "behavior": "Khách bấm 'Tôi đã chuyển khoản' → đơn chuyển PENDING_VERIFICATION trên backend", + "verification": "_be; POST /api/reservations/{id}/confirm-transfer trả 200, sau expiresAt trả lỗi EXPIRED; _fe", + "state": "blocked", + "blocked_reason": "Backend chưa có endpoint confirm-transfer và đối soát (luồng đã chốt theo Figma, DECISIONS D02)", + "evidence": null + }, + { + "id": "F04", "flow": 2, "uc": ["UC04"], "actor": "Khách hàng", + "behavior": "Khách xem lịch nhận kho và xác nhận đã nhận kho (POST /api/handovers/{id}/confirm)", + "verification": "_fe", + "state": "passing", + "evidence": "2026-09-26: npm test + test:render PASS" + }, + { + "id": "F05", "flow": 6, "uc": ["UC05"], "actor": "Khách hàng", + "behavior": "Xem kho đang thuê, hợp đồng; gửi yêu cầu gia hạn 1/3/6 tháng (POST /api/contracts/{id}/renewals); khoá nút khi đang có yêu cầu chờ", + "verification": "_fe", + "state": "passing", + "evidence": "2026-09-26: npm test + test:render PASS" + }, + { + "id": "F06", "flow": 3, "uc": ["UC05"], "actor": "Khách hàng", + "behavior": "Đăng ký trả kho (ngày, khung giờ, ghi chú) lưu ở backend", + "verification": "_be; POST /api/contracts/{id}/move-out tạo lịch MOVE_OUT PENDING; _fe", + "state": "blocked", + "blocked_reason": "Backend chưa có API move-out; giao diện đang lưu trong trình duyệt", + "evidence": null + }, + { + "id": "F07", "flow": 7, "uc": ["UC06"], "actor": "Khách hàng", + "behavior": "Gửi, xem, huỷ yêu cầu hỗ trợ (/api/tickets)", + "verification": "_fe", + "state": "passing", + "evidence": "2026-09-26: npm test + test:render PASS" + }, + { + "id": "F08", "flow": 7, "uc": ["UC06"], "actor": "Khách hàng", + "behavior": "Ảnh đính kèm yêu cầu hỗ trợ (≤3 ảnh, ≤5MB) lưu ở backend; khách chưa có hợp đồng vẫn gửi được", + "verification": "_be; POST /api/tickets multipart; _fe", + "state": "blocked", + "blocked_reason": "Backend bắt buộc ContractId và chưa nhận file; SRS 1.3 ghi lưu ảnh ngoài phạm vi cơ bản — cần nhóm chốt", + "evidence": null + }, + { + "id": "F09", "flow": null, "uc": [], "actor": "Khách hàng", + "behavior": "Thông báo trong header lưu ở backend (GET /api/notifications, POST /api/notifications/read)", + "verification": "_be; _fe", + "state": "blocked", + "blocked_reason": "Backend chưa có API thông báo", + "evidence": null + }, + { + "id": "F10", "flow": null, "uc": [], "actor": "Khách hàng", + "behavior": "Hồ sơ: đổi tên hiển thị, đổi mật khẩu, quên mật khẩu (GET/PUT /api/auth/profile, POST change-password, forgot-password)", + "verification": "_be; _fe", + "state": "blocked", + "blocked_reason": "Backend chưa có API; giao diện đang khoá đổi/quên mật khẩu", + "evidence": null + }, + { + "id": "F11", "flow": 2, "uc": ["UC07", "UC08"], "actor": "Nhân viên cơ sở", + "behavior": "Nhân viên tra đơn khi khách đến, xác minh điều kiện nhận, bàn giao unit và cấp credential (khoá/thẻ/mã)", + "verification": "_be; _fe; kịch bản SRS 15.7–15.8", + "state": "not_started", "depends_on": ["F21"], "evidence": null + }, + { + "id": "F12", "flow": 5, "uc": ["UC09"], "actor": "Nhân viên cơ sở", + "behavior": "Cập nhật trạng thái unit theo chuyển tiếp hợp lệ (SRS 8.1), ghi unit_status_history", + "verification": "_be; thử chuyển trạng thái sai phải bị từ chối", + "state": "not_started", "depends_on": ["F21"], "evidence": null + }, + { + "id": "F13", "flow": 3, "uc": ["UC10"], "actor": "Nhân viên cơ sở", + "behavior": "Kiểm tra tình trạng kho khi khách trả, ghi return_inspection, thu hồi credential", + "verification": "_be; _fe", + "state": "not_started", "depends_on": ["F06", "F12"], "evidence": null + }, + { + "id": "F14", "flow": 7, "uc": ["UC11"], "actor": "Nhân viên cơ sở", + "behavior": "Tiếp nhận và xử lý ticket tại cơ sở: OPEN → ASSIGNED → IN_PROGRESS → RESOLVED → CLOSED", + "verification": "_be; _fe", + "state": "not_started", "depends_on": ["F21"], "evidence": null + }, + { + "id": "F15", "flow": 5, "uc": ["UC12"], "actor": "Nhân viên cơ sở", + "behavior": "Danh sách việc trong ngày: khách nhận kho, trả kho, cần hỗ trợ", + "verification": "_be; _fe", + "state": "not_started", "depends_on": ["F11", "F14"], "evidence": null + }, + { + "id": "F16", "flow": 5, "uc": ["UC13"], "actor": "Quản lý cơ sở", + "behavior": "Quản lý unit tại cơ sở được phân công: loại, kích thước, vị trí, giá, trạng thái", + "verification": "_be; _fe; chỉ thấy dữ liệu cơ sở mình phụ trách", + "state": "not_started", "depends_on": ["F21"], "evidence": null + }, + { + "id": "F17", "flow": 1, "uc": ["UC14"], "actor": "Quản lý cơ sở", + "behavior": "Phân bổ unit cho reservation (không trùng thời gian) và tạo hợp đồng DRAFT", + "verification": "_be; phân bổ 2 đơn trùng khoảng [start,end) cho cùng unit phải bị từ chối", + "state": "not_started", "depends_on": ["F16"], "evidence": null + }, + { + "id": "F18", "flow": 3, "uc": ["UC15", "UC16"], "actor": "Quản lý cơ sở", + "behavior": "Theo dõi khách, hợp đồng, thanh toán; duyệt gia hạn, trả kho; xử lý quá hạn (overdue_cases)", + "verification": "_be; _fe", + "state": "not_started", "depends_on": ["F17"], "evidence": null + }, + { + "id": "F19", "flow": 5, "uc": ["UC17"], "actor": "Quản lý cơ sở", + "behavior": "Phân công nhân viên cho bàn giao, kiểm tra, xử lý sự cố", + "verification": "_be; _fe", + "state": "not_started", "depends_on": ["F11", "F14"], "evidence": null + }, + { + "id": "F20", "flow": 4, "uc": ["UC18"], "actor": "Quản lý cơ sở", + "behavior": "Báo cáo cơ sở: kho trống, đang thuê, doanh thu, tỷ lệ sử dụng, quá hạn (công thức SRS mục 10)", + "verification": "_be; so số liệu báo cáo với truy vấn DB tay", + "state": "not_started", "depends_on": ["F18"], "evidence": null + }, + { + "id": "F21", "flow": null, "uc": ["UC24", "UC26"], "actor": "Chung", + "behavior": "Đăng nhập và giao diện riêng cho vai trò Nhân viên / Quản lý (hiện trang đăng nhập báo chưa có giao diện); phân quyền theo cơ sở ở máy chủ", + "verification": "_be; _fe; staff01 đăng nhập vào được khu nhân viên", + "state": "not_started", "evidence": null + }, + { + "id": "F22", "flow": 4, "uc": ["UC19", "UC20", "UC21"], "actor": "Quản lý vận hành KD", + "behavior": "Quản lý danh sách cơ sở, chính sách chung (cọc, gia hạn, huỷ, trả, quá hạn), khung giá, phí, giảm giá/miễn phí", + "verification": "_be; _fe", + "state": "not_started", "depends_on": ["F24"], "evidence": null + }, + { + "id": "F23", "flow": 4, "uc": ["UC22", "UC23"], "actor": "Quản lý vận hành KD", + "behavior": "Giám sát doanh thu, hiệu suất từng cơ sở; xem và xuất báo cáo toàn hệ thống", + "verification": "_be; _fe; file xuất mở được", + "state": "not_started", "depends_on": ["F22"], "evidence": null + }, + { + "id": "F24", "flow": null, "uc": ["UC25"], "actor": "Chung", + "behavior": "Backend có vai trò Quản lý vận hành KD (OPERATIONS / BUSINESS_OPS_MANAGER) như SRS và Figma", + "verification": "_be; GET /api/admin/roles có vai trò mới; giao diện quản trị tự hiện", + "state": "not_started", "evidence": null + }, + { + "id": "F25", "flow": null, "uc": ["UC24"], "actor": "Quản trị hệ thống", + "behavior": "Quản lý tài khoản: danh sách, tìm, lọc, tạo, sửa, khoá, đặt lại mật khẩu (A01, A02, chi tiết)", + "verification": "_fe; đăng nhập admin → #/admin", + "state": "passing", + "evidence": "2026-09-26: npm test (có admin.test.js) + test:render PASS" + }, + { + "id": "F26", "flow": null, "uc": ["UC25", "UC26"], "actor": "Quản trị hệ thống", + "behavior": "Gán/thu hồi vai trò, ma trận quyền × vai trò, phân công cơ sở (A03)", + "verification": "_fe", + "state": "passing", + "evidence": "2026-09-26: npm test + test:render PASS" + }, + { + "id": "F27", "flow": null, "uc": ["UC27"], "actor": "Quản trị hệ thống", + "behavior": "Lịch sử đăng nhập và nhật ký hoạt động (A04)", + "verification": "_fe", + "state": "passing", + "evidence": "2026-09-26: npm test + test:render PASS. Hạn chế: backend chưa ghi đăng nhập thất bại và IP" + }, + { + "id": "F28", "flow": null, "uc": [], "actor": "Kỹ thuật", + "behavior": "Tạo project test cho backend (StorageProject.Tests, xUnit) và đưa vào init.sh — hiện backend không có test tự động", + "verification": "dotnet test StorageProject.slnx có ít nhất 1 test cho ReservationService pass", + "state": "not_started", "evidence": null + }, + { + "id": "F29", "flow": 3, "uc": ["UC05"], "actor": "Khách hàng", + "behavior": "Đồng bộ giao diện khách hàng với Figma đã rà 26/09 (D11): hợp đồng chưa bàn giao (handed_over = false) ở C07 chỉ hiện 'Xem lịch nhận kho' (→ #/payments) và 'Đổi lịch nhận kho' (→ hỗ trợ chủ đề SCHEDULE), ẩn gia hạn / trả kho; câu tiền cọc ở C08 = 'Tiền cọc đang giữ được chuyển sang kỳ mới, không thu thêm.'; tiêu đề chủ đề ACCESS = 'Lỗi thẻ ra vào'", + "verification": "_fe; test reducer/render mới cho hợp đồng chưa bàn giao; mở #/units/:id của hợp đồng chưa bàn giao", + "state": "not_started", "evidence": null + } + ] +} diff --git a/init.ps1 b/init.ps1 new file mode 100644 index 0000000..a38ae3e --- /dev/null +++ b/init.ps1 @@ -0,0 +1,46 @@ +# init.ps1 — bản Windows của init.sh. Chạy ĐẦU mỗi phiên làm việc với AI. +# Dùng: .\init.ps1 (đầy đủ) +# .\init.ps1 -FeOnly (bỏ qua backend) +# Nếu bị chặn: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned +param([switch]$FeOnly) +$ErrorActionPreference = "Stop" +$Root = $PSScriptRoot +$Fe = Join-Path $Root "SafeSpace-Customer-UI\SafeSpace-Customer-UI" + +function Step($t) { Write-Host "`n=== $t ===" -ForegroundColor Cyan } +function Fail($t) { Write-Host "`n[LỖI] $t" -ForegroundColor Red; exit 1 } +function Run($cmd) { & cmd /c $cmd; if ($LASTEXITCODE -ne 0) { Fail "Lệnh thất bại: $cmd" } } + +Step "1. Kiểm tra công cụ" +if (-not (Get-Command node -ErrorAction SilentlyContinue)) { Fail "Chưa cài Node.js (cần >= 22.12)" } +$v = (node -v).TrimStart("v").Split(".") | ForEach-Object { [int]$_ } +if ($v[0] -lt 22 -or ($v[0] -eq 22 -and $v[1] -lt 12)) { Fail "Node $(node -v) quá cũ, cần >= 22.12" } +Write-Host "Node $(node -v)" +$HasDotnet = [bool](Get-Command dotnet -ErrorAction SilentlyContinue) +if ($HasDotnet) { Write-Host ".NET $(dotnet --version)" } +if (-not $FeOnly -and -not $HasDotnet) { Fail "Chưa cài .NET SDK 10, hoặc chạy .\init.ps1 -FeOnly" } + +Step "2. Frontend: cài thư viện" +Push-Location $Fe +if (-not (Test-Path node_modules)) { Run "npm ci" } else { Write-Host "node_modules đã có" } + +Step "3. Frontend: test nghiệp vụ"; Run "npm test" +Step "4. Frontend: render toàn bộ route"; Run "npm run test:render" +Step "5. Frontend: build"; Run "npm run build" +Pop-Location + +if (-not $FeOnly) { + Step "6. Backend: khôi phục công cụ + build" + Push-Location $Root + Run "dotnet tool restore" + Run "dotnet build StorageProject.slnx --nologo -v quiet" + if (Get-ChildItem -Directory -Filter "*Tests*" -ErrorAction SilentlyContinue) { + Step "7. Backend: test"; Run "dotnet test StorageProject.slnx --nologo" + } else { Write-Host "(Chưa có project test backend — xem F28 trong feature_list.json)" } + Pop-Location +} + +Step "Trạng thái repo" +git -C $Root status --short +git -C $Root log --oneline -5 +Write-Host "`n=== MÔI TRƯỜNG ỔN — đọc progress.md và feature_list.json để chọn việc ===" -ForegroundColor Green diff --git a/init.sh b/init.sh new file mode 100644 index 0000000..47c8f31 --- /dev/null +++ b/init.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# init.sh — chạy ĐẦU mỗi phiên làm việc với AI (và trước khi commit). +# Kiểm tra công cụ, cài thư viện, chạy test + build. Có lỗi → dừng, sửa môi trường trước khi code. +# Dùng: ./init.sh (đầy đủ) +# ./init.sh --fe-only (bỏ qua backend, khi máy không có .NET) +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")" && pwd)" +FE="$ROOT/SafeSpace-Customer-UI/SafeSpace-Customer-UI" +FE_ONLY=false +[[ "${1:-}" == "--fe-only" ]] && FE_ONLY=true + +step() { printf '\n=== %s ===\n' "$1"; } +fail() { printf '\n[LỖI] %s\n' "$1"; exit 1; } + +step "1. Kiểm tra công cụ" +command -v node >/dev/null || fail "Chưa cài Node.js (cần >= 22.12)" +node -e 'const [a,b]=process.versions.node.split(".").map(Number); process.exit(a>22||(a===22&&b>=12)?0:1)' \ + || fail "Node $(node -v) quá cũ, cần >= 22.12" +echo "Node $(node -v)" +HAS_DOTNET=false +if command -v dotnet >/dev/null; then HAS_DOTNET=true; echo ".NET $(dotnet --version)"; fi +if ! $FE_ONLY && ! $HAS_DOTNET; then + fail "Chưa cài .NET SDK 10. Cài vào, hoặc chạy ./init.sh --fe-only nếu phiên này chỉ sửa giao diện" +fi + +step "2. Frontend: cài thư viện" +cd "$FE" +if [[ ! -d node_modules ]]; then npm ci; else echo "node_modules đã có"; fi +[[ -f .env.local ]] || echo "(Gợi ý) chưa có .env.local — giao diện dùng mặc định trong .env.example" + +step "3. Frontend: test nghiệp vụ" +npm test + +step "4. Frontend: render toàn bộ route" +npm run test:render + +step "5. Frontend: build" +npm run build >/dev/null && echo "build OK" + +if ! $FE_ONLY; then + cd "$ROOT" + step "6. Backend: khôi phục công cụ + build" + dotnet tool restore >/dev/null + dotnet build StorageProject.slnx --nologo -v quiet + + if ls "$ROOT"/*Tests* >/dev/null 2>&1; then + step "7. Backend: test" + dotnet test StorageProject.slnx --nologo + else + echo "(Chưa có project test backend — xem F28 trong feature_list.json)" + fi +fi + +step "Trạng thái repo" +cd "$ROOT" +git status --short | head -20 || true +git log --oneline -5 || true + +printf '\n=== MÔI TRƯỜNG ỔN — đọc progress.md và feature_list.json để chọn việc ===\n' diff --git a/progress.md b/progress.md new file mode 100644 index 0000000..c1c2337 --- /dev/null +++ b/progress.md @@ -0,0 +1,55 @@ +# Nhật ký tiến độ (progress.md) + +> Mỗi phiên làm việc với AI thêm MỘT mục ở đầu danh sách (mới nhất trên cùng). +> Ghi đủ để phiên sau tiếp tục ngay mà không phải hỏi lại. Không xoá mục cũ. + +## Mẫu một mục + +``` +## Phiên N — YYYY-MM-DD — +- Tính năng: Fxx — +- Đã xong: … +- Đang dở: … +- Kiểm chứng: → +- Bị chặn / rủi ro: … +- Phiên sau nên: … +``` + +--- + +## Phiên 1 — 2026-09-26 — Rà mâu thuẫn Figma + +- Tính năng: (không có — rà soát thiết kế trước khi chốt "Figma là chuẩn") +- Đã xong: đọc chữ và liên kết prototype của toàn bộ màn trong Figma "SafeSpace - Modern UI"; sửa trực tiếp + trong Figma các chỗ mâu thuẫn về luồng / trạng thái / nhân vật / liên kết (bỏ qua ảnh, giá, số liệu). + Danh sách đầy đủ: `docs/figma-review-2026-09-26.md`. Chốt D02 theo Figma, thêm D11. +- Kiểm chứng: quét lại toàn file Figma không còn "SafeSpace Quận 7", "Trần Minh", "Lê Anh", gia hạn B-015 "đã gửi"; + chụp lại C01, C07, C11, C14, M03, M07, A04 để kiểm tra bố cục. +- Bị chặn / rủi ro: code giao diện còn cho gia hạn / trả kho khi hợp đồng chưa bàn giao và câu tiền cọc cũ → F29. + SRS mục A03 cần sửa cho khớp D02. +- Phiên sau nên: làm F29 (nhỏ, chỉ giao diện) hoặc F28. + +## Phiên 0 — 2026-09-26 — Thiết lập harness + +- Tính năng: (không có — phiên khởi tạo, chưa viết code tính năng) +- Căn cứ: hướng dẫn Harness Engineering tại https://learnharness.org/#dinh-nghia và https://skills.learnharness.org/ + (thầy Hoàng Giáo Làng giới thiệu tại Build With AI #3: From Working Code To Reliable Product). +- Đã xong: thêm `AGENTS.md`, `CLAUDE.md`, `feature_list.json`, `progress.md`, `DECISIONS.md`, + `init.sh`, `init.ps1`, `docs/` (architecture, business-rules, conventions, verification, templates/sprint-contract). +- Hiện trạng code (commit `5177812`, main): + - Giao diện khách hàng C01–C14 và quản trị A01–A04 đã có, gọi API thật cho các luồng backend đã hỗ trợ. + - Backend .NET: auth, facilities/rates/availability, reservations, contracts, payments, renewals, + handover confirm, tickets, toàn bộ `/api/admin/*`. + - Chưa có: giao diện Nhân viên / Quản lý cơ sở / Quản lý vận hành KD (UC07–UC23). +- Kiểm chứng: + - `npm test` → 28/28 pass + - `npm run test:render` → 38 route PASS + - `npm run build` → OK + - `dotnet build` → **chưa chạy** (máy thiết lập không có .NET). Phiên sau chạy `./init.sh` trên máy có .NET để xác nhận. +- Bị chặn / rủi ro: + - Backend không có test tự động → kiểm chứng backend yếu (F28). + - Luồng thanh toán lúc đặt (Figma) lệch SRS A03 → đã chốt theo Figma ở Phiên 1 (D02). + - `README.md` gốc chưa khớp code: ghi .NET 9 (project là `net10.0`); mục cấu trúc frontend còn tên cũ + (`services/`, `customer.css`); nhắc tag "BẢN DEMO UI" không còn trong code. +- Phiên sau nên: chạy `./init.sh` đầy đủ trên máy có .NET; sau đó làm F28 (test backend) hoặc F21 + (khu Nhân viên / Quản lý) tuỳ nhóm ưu tiên. From 845abdf0b9120b190a2e15966efc218ac3c65e81 Mon Sep 17 00:00:00 2001 From: Vector Date: Thu, 1 Oct 2026 16:47:34 +0700 Subject: [PATCH 02/24] =?UTF-8?q?docs:=20c=E1=BA=ADp=20nh=E1=BA=ADt=20harn?= =?UTF-8?q?ess=20sau=20phi=C3=AAn=202=20(D12=E2=80=93D15,=20F11=E2=80=93F2?= =?UTF-8?q?1=20ch=E1=BB=9D=20/api/ops/*,=20F30)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 9 +++-- DECISIONS.md | 24 +++++++++++++ docs/architecture.md | 19 ++++++---- feature_list.json | 82 ++++++++++++++++++++++++++++++++++---------- progress.md | 18 ++++++++++ 5 files changed, 125 insertions(+), 27 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 92ec72e..e3088a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,12 +33,14 @@ Hệ thống quản lý và cho thuê kho tự phục vụ **SafeSpace** cho 5 n | `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 + quản trị | +| `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/ops/` | Khu Nhân viên `#/staff` + Quản lý cơ sở `#/manager` (gọi `/api/ops/*`, D15) | | `…/src/state/reducer.js` | Nghiệp vụ phía giao diện (hàm thuần, có test) | | `…/src/state/store.jsx` | Phiên đăng nhập, 2 chế độ: API / lưu trình duyệt | | `…/src/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 | -| `…/CUSTOMER-FLOW-COVERAGE.md`, `ADMIN-FLOW-COVERAGE.md` | Đối chiếu màn Figma ↔ route ↔ component ↔ API | +| `…/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` | +| `…/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) @@ -63,7 +65,8 @@ cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm run dev # UI: http:// Cần: .NET SDK 10 (project đặt `net10.0`), Node ≥ 22.12, SQL Server (mặc định `.\SQLEXPRESS`). Tài khoản seed: `customer01`/`Customer@123`, `staff01`/`Staff@123`, `admin`/`Admin@123`. -Không có backend: tạo `.env.local` với `VITE_USE_API=false`. +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 diff --git a/DECISIONS.md b/DECISIONS.md index 0e50ff4..c423cbd 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -51,3 +51,27 @@ - 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. diff --git a/docs/architecture.md b/docs/architecture.md index 4133533..5fc06a4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -4,7 +4,9 @@ ``` Trình duyệt (React 19 + Vite, hash router) - ├── Khu khách hàng #/home, #/find, #/overview, #/units, #/payments, #/support, #/profile … + ├── Khu khách hàng #/home, #/find, #/find/map, #/overview, #/units, #/payments, #/support, #/profile … + ├── Khu nhân viên #/staff/* (vai trò STAFF) + ├── Khu quản lý #/manager/* (vai trò MANAGER) └── Khu quản trị #/admin/* (chỉ vai trò ADMIN, chỉ chế độ API) │ fetch + Bearer JWT (VITE_API_URL, mặc định http://localhost:5151) ▼ @@ -44,15 +46,20 @@ Mỗi lệnh tương ứng một endpoint trong `BE-CONTRACT.md`. Page chỉ g | Thư mục | Vai trò | |---|---| | `src/pages/` | Mỗi màn Figma một component | -| `src/components/` | Header + thông báo, lịch, thư viện ảnh, mã QR, UI dùng chung (`UI.jsx`) | +| `src/components/` | Header + thông báo, lịch, thư viện ảnh, mã QR, sơ đồ ô kho (`UnitMap.jsx`), thanh tìm kiếm, UI dùng chung (`UI.jsx`, `Inline.jsx`) | | `src/admin/` | Khu quản trị A01–A04 | +| `src/ops/` | Khu Nhân viên (S01–S05, S09) và Quản lý cơ sở (M01–M07): `api.js` gọi `/api/ops/*`, `store.jsx` (OpsProvider, dự phòng trình duyệt — D15), `reducer.js` nghiệp vụ, `tasks.jsx` lưới 3×3 | | `src/api/` | `http.js` (fetch + token), `endpoints.js`, `admin.js`, `mappers.js` (backend → giao diện) | -| `src/lib/` | router, định dạng tiền/ngày, trạng thái → nhãn (`status.js`), vai trò, VietQR | -| `src/config/` | địa chỉ API, ảnh, tài khoản nhận chuyển khoản | +| `src/lib/` | router, định dạng tiền/ngày, trạng thái → nhãn (`status.js`), vai trò, VietQR, xếp ô kho (`units.js`) | +| `src/config/` | địa chỉ API, ảnh, toạ độ cơ sở (`geo.js`), tài khoản nhận chuyển khoản | | `src/styles/ss.css` | Token màu / chữ / bo góc theo Figma | | `tests/` | `node --test`: reducer, mappers, admin; `render.test.mjs` render mọi route | +Khu vận hành (`src/ops/`) có provider riêng: tải `GET /api/ops/board`, gửi lệnh `POST /api/ops/...`, tải lại bảng. +Backend trả 404 → dùng `src/ops/data.js` + `reducer.js` lưu trình duyệt và hiện dòng báo (D15). + ## Chưa có (theo SRS) -Giao diện và phần lớn API cho Nhân viên cơ sở, Quản lý cơ sở, Quản lý vận hành KD (UC07–UC23), -vai trò Quản lý vận hành KD ở backend, project test backend. Xem `feature_list.json`. +- API `/api/ops/*`, tài khoản seed MANAGER, lọc theo cơ sở được phân công — xem `BACKEND-TODO.md` mục A. +- Giao diện và API cho Quản lý vận hành KD (UC19–UC23), vai trò này ở backend (F24), project test backend (F28). + Xem `feature_list.json`. diff --git a/feature_list.json b/feature_list.json index 14cd7da..a61b8e9 100644 --- a/feature_list.json +++ b/feature_list.json @@ -2,7 +2,7 @@ "_readme": "Danh sách tính năng = ranh giới phạm vi cho AI agent. Mỗi mục: behavior (hành vi), verification (lệnh/cách kiểm chứng), state. state: not_started -> active -> passing | blocked. Chỉ đổi sang passing khi verification pass và ghi evidence. Mỗi phiên chỉ một mục active.", "_fe": "cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm test && npm run test:render && npm run build", "_be": "dotnet build StorageProject.slnx", - "updated": "2026-09-26", + "updated": "2026-10-01", "features": [ { "id": "F01", "flow": 1, "uc": ["UC01"], "actor": "Khách hàng", @@ -23,7 +23,7 @@ "behavior": "Khách bấm 'Tôi đã chuyển khoản' → đơn chuyển PENDING_VERIFICATION trên backend", "verification": "_be; POST /api/reservations/{id}/confirm-transfer trả 200, sau expiresAt trả lỗi EXPIRED; _fe", "state": "blocked", - "blocked_reason": "Backend chưa có endpoint confirm-transfer và đối soát (luồng đã chốt theo Figma, DECISIONS D02)", + "blocked_reason": "Backend chưa có endpoint confirm-transfer và đối soát (luồng đã chốt theo Figma, DECISIONS D02); phía nhân viên đối soát (S09) đã có giao diện, chờ /api/ops/payments/{id}/confirm", "evidence": null }, { @@ -83,85 +83,122 @@ "id": "F11", "flow": 2, "uc": ["UC07", "UC08"], "actor": "Nhân viên cơ sở", "behavior": "Nhân viên tra đơn khi khách đến, xác minh điều kiện nhận, bàn giao unit và cấp credential (khoá/thẻ/mã)", "verification": "_be; _fe; kịch bản SRS 15.7–15.8", - "state": "not_started", "depends_on": ["F21"], "evidence": null + "state": "blocked", + "depends_on": ["F21"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F12", "flow": 5, "uc": ["UC09"], "actor": "Nhân viên cơ sở", "behavior": "Cập nhật trạng thái unit theo chuyển tiếp hợp lệ (SRS 8.1), ghi unit_status_history", "verification": "_be; thử chuyển trạng thái sai phải bị từ chối", - "state": "not_started", "depends_on": ["F21"], "evidence": null + "state": "blocked", + "depends_on": ["F21"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F13", "flow": 3, "uc": ["UC10"], "actor": "Nhân viên cơ sở", "behavior": "Kiểm tra tình trạng kho khi khách trả, ghi return_inspection, thu hồi credential", "verification": "_be; _fe", - "state": "not_started", "depends_on": ["F06", "F12"], "evidence": null + "state": "blocked", + "depends_on": ["F06", "F12"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F14", "flow": 7, "uc": ["UC11"], "actor": "Nhân viên cơ sở", "behavior": "Tiếp nhận và xử lý ticket tại cơ sở: OPEN → ASSIGNED → IN_PROGRESS → RESOLVED → CLOSED", "verification": "_be; _fe", - "state": "not_started", "depends_on": ["F21"], "evidence": null + "state": "blocked", + "depends_on": ["F21"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F15", "flow": 5, "uc": ["UC12"], "actor": "Nhân viên cơ sở", "behavior": "Danh sách việc trong ngày: khách nhận kho, trả kho, cần hỗ trợ", "verification": "_be; _fe", - "state": "not_started", "depends_on": ["F11", "F14"], "evidence": null + "state": "blocked", + "depends_on": ["F11", "F14"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F16", "flow": 5, "uc": ["UC13"], "actor": "Quản lý cơ sở", "behavior": "Quản lý unit tại cơ sở được phân công: loại, kích thước, vị trí, giá, trạng thái", "verification": "_be; _fe; chỉ thấy dữ liệu cơ sở mình phụ trách", - "state": "not_started", "depends_on": ["F21"], "evidence": null + "state": "blocked", + "depends_on": ["F21"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F17", "flow": 1, "uc": ["UC14"], "actor": "Quản lý cơ sở", "behavior": "Phân bổ unit cho reservation (không trùng thời gian) và tạo hợp đồng DRAFT", "verification": "_be; phân bổ 2 đơn trùng khoảng [start,end) cho cùng unit phải bị từ chối", - "state": "not_started", "depends_on": ["F16"], "evidence": null + "state": "blocked", + "depends_on": ["F16"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F18", "flow": 3, "uc": ["UC15", "UC16"], "actor": "Quản lý cơ sở", "behavior": "Theo dõi khách, hợp đồng, thanh toán; duyệt gia hạn, trả kho; xử lý quá hạn (overdue_cases)", "verification": "_be; _fe", - "state": "not_started", "depends_on": ["F17"], "evidence": null + "state": "blocked", + "depends_on": ["F17"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F19", "flow": 5, "uc": ["UC17"], "actor": "Quản lý cơ sở", "behavior": "Phân công nhân viên cho bàn giao, kiểm tra, xử lý sự cố", "verification": "_be; _fe", - "state": "not_started", "depends_on": ["F11", "F14"], "evidence": null + "state": "blocked", + "depends_on": ["F11", "F14"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F20", "flow": 4, "uc": ["UC18"], "actor": "Quản lý cơ sở", "behavior": "Báo cáo cơ sở: kho trống, đang thuê, doanh thu, tỷ lệ sử dụng, quá hạn (công thức SRS mục 10)", "verification": "_be; so số liệu báo cáo với truy vấn DB tay", - "state": "not_started", "depends_on": ["F18"], "evidence": null + "state": "blocked", + "depends_on": ["F18"], + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", + "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." }, { "id": "F21", "flow": null, "uc": ["UC24", "UC26"], "actor": "Chung", "behavior": "Đăng nhập và giao diện riêng cho vai trò Nhân viên / Quản lý (hiện trang đăng nhập báo chưa có giao diện); phân quyền theo cơ sở ở máy chủ", "verification": "_be; _fe; staff01 đăng nhập vào được khu nhân viên", - "state": "not_started", "evidence": null + "state": "blocked", + "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật. staff01 vào #/staff.", + "blocked_reason": "FE đã xong (đăng nhập STAFF → #/staff, MANAGER → #/manager); backend chưa có tài khoản seed vai trò MANAGER và chưa lọc dữ liệu theo cơ sở được phân công (UserFacility) — BACKEND-TODO.md mục A." }, { "id": "F22", "flow": 4, "uc": ["UC19", "UC20", "UC21"], "actor": "Quản lý vận hành KD", "behavior": "Quản lý danh sách cơ sở, chính sách chung (cọc, gia hạn, huỷ, trả, quá hạn), khung giá, phí, giảm giá/miễn phí", "verification": "_be; _fe", - "state": "not_started", "depends_on": ["F24"], "evidence": null + "state": "not_started", + "depends_on": ["F24"], + "evidence": null }, { "id": "F23", "flow": 4, "uc": ["UC22", "UC23"], "actor": "Quản lý vận hành KD", "behavior": "Giám sát doanh thu, hiệu suất từng cơ sở; xem và xuất báo cáo toàn hệ thống", "verification": "_be; _fe; file xuất mở được", - "state": "not_started", "depends_on": ["F22"], "evidence": null + "state": "not_started", + "depends_on": ["F22"], + "evidence": null }, { "id": "F24", "flow": null, "uc": ["UC25"], "actor": "Chung", "behavior": "Backend có vai trò Quản lý vận hành KD (OPERATIONS / BUSINESS_OPS_MANAGER) như SRS và Figma", "verification": "_be; GET /api/admin/roles có vai trò mới; giao diện quản trị tự hiện", - "state": "not_started", "evidence": null + "state": "not_started", + "evidence": null }, { "id": "F25", "flow": null, "uc": ["UC24"], "actor": "Quản trị hệ thống", @@ -188,13 +225,22 @@ "id": "F28", "flow": null, "uc": [], "actor": "Kỹ thuật", "behavior": "Tạo project test cho backend (StorageProject.Tests, xUnit) và đưa vào init.sh — hiện backend không có test tự động", "verification": "dotnet test StorageProject.slnx có ít nhất 1 test cho ReservationService pass", - "state": "not_started", "evidence": null + "state": "not_started", + "evidence": null }, { "id": "F29", "flow": 3, "uc": ["UC05"], "actor": "Khách hàng", "behavior": "Đồng bộ giao diện khách hàng với Figma đã rà 26/09 (D11): hợp đồng chưa bàn giao (handed_over = false) ở C07 chỉ hiện 'Xem lịch nhận kho' (→ #/payments) và 'Đổi lịch nhận kho' (→ hỗ trợ chủ đề SCHEDULE), ẩn gia hạn / trả kho; câu tiền cọc ở C08 = 'Tiền cọc đang giữ được chuyển sang kỳ mới, không thu thêm.'; tiêu đề chủ đề ACCESS = 'Lỗi thẻ ra vào'", "verification": "_fe; test reducer/render mới cho hợp đồng chưa bàn giao; mở #/units/:id của hợp đồng chưa bàn giao", - "state": "not_started", "evidence": null + "state": "not_started", + "evidence": null + }, + { + "id": "F30", "flow": 1, "uc": ["UC01", "UC02"], "actor": "Khách hàng", + "behavior": "Sơ đồ tình trạng ô kho trong chi tiết cơ sở (ô trống màu xanh, chọn ô cập nhật tóm tắt đặt trước); tìm kho trên bản đồ #/find/map (chỉ hiện bản đồ, popup 'Xem chi tiết cơ sở'); nút chuyển Danh sách / Bản đồ", + "verification": "_fe; mở #/find/:id?view=map và #/find/map", + "state": "passing", + "evidence": "2026-10-01: npm test 38/38, test:render 76 route PASS, build OK; số ô trống lấy từ POST /api/availability/check (đã kiểm với mock)" } ] } diff --git a/progress.md b/progress.md index c1c2337..eb4cded 100644 --- a/progress.md +++ b/progress.md @@ -17,6 +17,24 @@ --- +## Phiên 2 — 2026-10-01 — Giao diện theo Figma 30/09, khu Nhân viên / Quản lý cơ sở + +- Tính năng: F30 (mới), F21, F11–F20 (phía giao diện). Nhánh `feature/figma-3009-staff-manager`. +- Đã xong (chỉ frontend, không sửa backend): + - Figma: ô trống màu xanh, bỏ ảnh sơ đồ mặt bằng khỏi thư viện ảnh, sửa nút đen, xếp frame theo vai trò và thứ tự luồng. + - Khách hàng: sơ đồ ô kho trong chi tiết cơ sở (D13), tìm kho trên bản đồ + nút Danh sách / Bản đồ (D12), + bỏ footer mọi trang, một dòng thông báo khi chưa có kho. + - Khu Nhân viên `#/staff` (S01–S05, S09) và Quản lý cơ sở `#/manager` (M01–M07) trong `src/ops/`, lưới 3×3 (D14). + - Hợp đồng `/api/ops/*` + dự phòng lưu trình duyệt (D15); việc backend còn thiếu: `BACKEND-TODO.md`. +- Kiểm chứng: `npm test` → 38/38 pass; `npm run test:render` → 76 route PASS; `npm run build` → OK; + chạy tay luồng khách / nhân viên / quản lý trên mock (`MOCK_OPS=1`). **Chưa chạy với backend .NET thật.** +- Bị chặn / rủi ro: + - Backend chưa có `/api/ops/*`, tài khoản seed MANAGER, lọc theo cơ sở (UserFacility) → F11–F21 để `blocked`. + - D13 cần nhóm chốt có cho khách giữ đúng ô đã chọn không. + - Luồng nghiệp vụ D02 không đổi. F29 chưa kiểm lại, giữ nguyên trạng thái. +- Phiên sau nên: người phụ trách backend làm `BACKEND-TODO.md` mục A, chạy `npm run dev` với backend thật + và đi hết luồng đặt → đối soát → phân bổ → xác minh → bàn giao; pass thì đổi F11–F21 sang `passing`. + ## Phiên 1 — 2026-09-26 — Rà mâu thuẫn Figma - Tính năng: (không có — rà soát thiết kế trước khi chốt "Figma là chuẩn") From 1b4165004f5c7224955c7e2ca5d361c8eceb93da Mon Sep 17 00:00:00 2001 From: TienPhanSE Date: Mon, 12 Oct 2026 21:04:31 +0700 Subject: [PATCH 03/24] Code adjustment --- .../src/admin/AdminApp.jsx | 53 ++- .../src/admin/AdminCreateUser.jsx | 341 +++++++++++++++++- .../src/admin/AdminUsers.jsx | 283 +++++++++++++++ SafeSpace-Customer-UI/package-lock.json | 2 +- 4 files changed, 676 insertions(+), 3 deletions(-) diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx index 0906752..907799a 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx @@ -1,3 +1,16 @@ +/* + * ADMIN APP - ĐIỀU HƯỚNG TRANG QUẢN TRỊ + * + * Chức năng chính: + * - Nhận thông tin đường dẫn (URL) từ component cha. + * - Xác định Admin đang truy cập chức năng nào. + * - Hiển thị component tương ứng với đường dẫn. + * - Sử dụng AdminShell làm layout chung cho các trang Admin. + * + * File này KHÔNG trực tiếp xử lý dữ liệu người dùng + * hoặc gọi API. Nó chỉ quyết định component nào được hiển thị. + */ + import React from "react"; import { Empty, LinkButton } from "../components/UI"; import AdminCreateUser from "./AdminCreateUser"; @@ -9,20 +22,53 @@ 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 }) { + + // Lấy hai phần đầu tiên của đường dẫn. + // a: tên chức năng đang truy cập (users, new, logs,...). + // b: tham số bổ sung, thường là ID người dùng. const [a, b] = parts; + + // tab xác định mục menu đang được chọn trong AdminShell. + // Mặc định là chuỗi rỗng. let tab = ""; + + // body lưu component sẽ được hiển thị + // bên trong layout AdminShell. let body; + + // TRƯỜNG HỢP 1: Admin truy cập #/admin + // Không có phần đường dẫn bổ sung (!a). + // Hiển thị trang danh sách người dùng mặc định. if (!a) body = ; - else if (a === "users" && b) body = ; + + // TRƯỜNG HỢP 2: Admin truy cập #/admin/users/:id + // a phải là "users" và b phải có giá trị. + // Hiển thị trang chi tiết của người dùng có ID tương ứng. + // key={b} giúp React tạo lại component khi ID thay đổi. + else if (a === "users" && b) + body = ; + + // TRƯỜNG HỢP 3: Admin truy cập #/admin/new + // Chọn tab "new" và hiển thị form tạo tài khoản mới. else if (a === "new") { tab = "new"; body = ; + + // TRƯỜNG HỢP 4: Admin truy cập #/admin/permissions + // Chọn tab "permissions" và hiển thị trang quản lý phân quyền. } else if (a === "permissions") { tab = "permissions"; body = ; + + // TRƯỜNG HỢP 5: Admin truy cập #/admin/logs + // Chọn tab "logs" và hiển thị nhật ký hệ thống. } else if (a === "logs") { tab = "logs"; body = ; + + // TRƯỜNG HỢP 6: URL không khớp với chức năng nào. + // Hiển thị thông báo không tìm thấy trang. + // Cung cấp nút quay lại trang quản lý tài khoản. } else body = (
@@ -31,5 +77,10 @@ export default function AdminApp({ parts }) {
); + + // Render layout chung của Admin. + // tab: truyền mục menu hiện tại cho AdminShell. + // body: nội dung trang được chọn ở các điều kiện phía trên. + // {body} được truyền vào AdminShell thông qua children. return {body}; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx index e2a5655..f433b57 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx @@ -1,3 +1,19 @@ + +/* + * ADMIN CREATE USER - TẠO TÀI KHOẢN NGƯỜI DÙNG + * + * Chức năng: + * - Admin nhập thông tin tài khoản mới. + * - Tự tạo username từ email nếu Admin chưa tự sửa. + * - Tự sinh mật khẩu tạm thời. + * - Chọn vai trò cho tài khoản. + * - Phân công cơ sở nếu là Staff hoặc Manager. + * - Kiểm tra dữ liệu trước khi gửi. + * - Gọi API tạo tài khoản trên backend. + * - Hiển thị thông tin đăng nhập sau khi tạo thành công. + */ + + import React, { useState } from "react"; import { adminApi } from "../api/admin"; import { Select } from "../components/Pickers"; @@ -8,52 +24,207 @@ import { go } from "../lib/router"; import { useApp } from "../state/store"; import { tempPassword, useLoad, usernameFrom } from "./util"; +/* + * EMPTY - DỮ LIỆU FORM MẶC ĐỊNH + * + * Tất cả trường được khởi tạo là chuỗi rỗng. + * Được dùng khi mở form và khi tạo tài khoản tiếp theo. + */ const EMPTY = { fullName: "", email: "", phone: "", username: "", password: "", roleId: "", facilityId: "" }; + export default function AdminCreateUser() { + + // onApiError: xử lý lỗi liên quan đến API, đặc biệt HTTP 401. + // notify: hiển thị thông báo toast trên giao diện. const { onApiError, notify } = useApp(); + + + /* + * LẤY DANH SÁCH VAI TRÒ VÀ CƠ SỞ TỪ BACKEND + * + * Promise.all gọi đồng thời hai API: + * 1. adminApi.roles(): lấy các vai trò trong hệ thống. + * 2. adminApi.facilities(): lấy danh sách cơ sở. + * + * Sau khi nhận dữ liệu: + * - Sắp xếp các vai trò bằng sortRoles. + * - Chỉ giữ những cơ sở có trạng thái ACTIVE. + * + * useLoad quản lý: + * - meta.data: dữ liệu API trả về. + * - meta.loading: đang tải dữ liệu. + * - meta.error: lỗi khi gọi API. + */ + const meta = useLoad(async () => { const [roles, facilities] = await Promise.all([adminApi.roles(), adminApi.facilities()]); return { roles: sortRoles(roles, (r) => r.roleName), facilities: facilities.filter((f) => f.status === "ACTIVE") }; }, [], onApiError); + + + /* + * STATE CỦA COMPONENT + */ + + // Lưu toàn bộ thông tin người dùng đang nhập. + // Mật khẩu mặc định được tạo bằng tempPassword(). const [form, setForm] = useState(() => ({ ...EMPTY, password: tempPassword() })); + + // Kiểm tra Admin đã tự chỉnh username hay chưa. + // false: username được tự động tạo theo email. + // true: giữ username do Admin tự nhập. const [userTouched, setUserTouched] = useState(false); + + // Lưu các lỗi validation theo từng trường. + // Ví dụ: { email: "Email không hợp lệ" }. const [errors, setErrors] = useState({}); + + // Trạng thái đang gửi request tạo tài khoản. + // Dùng để disable nút và tránh gửi lặp. const [busy, setBusy] = useState(false); + + // Lưu kết quả sau khi tạo tài khoản thành công. + // null: chưa tạo thành công, chưa hiện Modal. + // Có dữ liệu: hiện Modal thông tin đăng nhập. const [done, setDone] = useState(null); + + /* + * XÁC ĐỊNH VAI TRÒ ĐANG CHỌN + */ + + // Lấy danh sách vai trò từ API. + // Nếu chưa tải xong thì sử dụng mảng rỗng. const roles = meta.data?.roles || []; + + // Tìm object vai trò dựa trên roleId trong form. + // Chuyển sang String để so sánh được cả ID số và chuỗi. const role = roles.find((r) => String(r.roleId) === String(form.roleId)); + + // scoped = true nếu vai trò bắt buộc gắn với một cơ sở. + // Ví dụ: STAFF hoặc MANAGER. + // Vai trò toàn hệ thống không cần chọn cơ sở. const scoped = role && FACILITY_ROLES.includes(role.roleName); + + /* + * HÀM SET - CẬP NHẬT DỮ LIỆU FORM + * + * k: tên trường cần cập nhật. + * v: giá trị mới của trường. + * + * Ví dụ: + * set("fullName", "Nguyen Van A") + * set("email", "abc@gmail.com") + */ + const set = (k, v) => { + + // Cập nhật trường tương ứng nhưng giữ nguyên + // các trường khác bằng spread operator (...f). setForm((f) => { const next = { ...f, [k]: v }; + + // Nếu đang nhập email và Admin chưa tự sửa username, + // tự tạo username từ email mới. if (k === "email" && !userTouched) next.username = usernameFrom(v); + return next; }); + + // Xóa lỗi của trường vừa được sửa. + // Đồng thời xóa lỗi chung của form để người dùng thử lại. setErrors((e) => ({ ...e, [k]: undefined, form: undefined })); }; + + /* + * VALIDATE - KIỂM TRA FORM TRƯỚC KHI TẠO TÀI KHOẢN + * + * Hàm chỉ kiểm tra và trả về object chứa các lỗi. + * Không gọi API và không lưu dữ liệu. + * + * Nếu object trả về rỗng {} => form hợp lệ. + */ + const validate = () => { + + // Object dùng để lưu các lỗi tìm được. const e = {}; + + // Họ tên bắt buộc nhập, không được chỉ chứa khoảng trắng. if (!form.fullName.trim()) e.fullName = "Vui lòng nhập họ và tên."; + + // Kiểm tra định dạng địa chỉ email. if (!isEmail(form.email)) e.email = "Nhập email hợp lệ, ví dụ ten@safespace.vn."; + + // Số điện thoại không bắt buộc. + // Nhưng nếu đã nhập thì phải đúng định dạng. if (form.phone && !isPhone(form.phone)) e.phone = "Số điện thoại chưa đúng định dạng."; + + // Username phải dài 3-50 ký tự. + // Chỉ được chứa chữ cái, số, dấu chấm, _, @ và -. if (!/^[a-zA-Z0-9._@-]{3,50}$/.test(form.username)) e.username = "Tên đăng nhập 3–50 ký tự: chữ, số, dấu . _ - @"; + + // Mật khẩu tạm thời tối thiểu 8 ký tự. if (form.password.length < 8) e.password = "Mật khẩu tạm thời cần ít nhất 8 ký tự."; + + // Bắt buộc lựa chọn một vai trò. if (!form.roleId) e.roleId = "Chọn vai trò cho tài khoản."; + + // Nhân viên và quản lý cơ sở phải được phân công cơ sở. + // Các vai trò không thuộc nhóm scoped được bỏ qua điều kiện. if (scoped && !form.facilityId) e.facilityId = "Nhân viên và Quản lý cơ sở cần có cơ sở phụ trách."; + + // Trả về danh sách lỗi để hàm submit xử lý. return e; }; + + /* + * SUBMIT - XỬ LÝ KHI ADMIN NHẤN "TẠO TÀI KHOẢN" + * + * Luồng xử lý: + * 1. Ngăn form reload. + * 2. Validate dữ liệu. + * 3. Gọi API tạo tài khoản. + * 4. Nếu có cơ sở phụ trách => gọi API phân công. + * 5. Lưu kết quả để hiển thị Modal. + */ + const submit = async (ev) => { + + // Ngăn hành vi submit mặc định của trình duyệt. ev.preventDefault(); + + // Kiểm tra toàn bộ dữ liệu trước khi gọi API. const e = validate(); + + // Nếu có ít nhất một lỗi, hiển thị lỗi và dừng. if (Object.keys(e).length) return setErrors(e); + + // Bật trạng thái xử lý để vô hiệu hóa nút submit. setBusy(true); + + // Biến lưu thông tin tài khoản được backend tạo. let created; + try { + + /* + * GỌI API TẠO TÀI KHOẢN + * + * Dữ liệu gửi đi: + * - username: tên đăng nhập. + * - password: mật khẩu tạm thời. + * - fullName: họ tên. + * - email: chuyển chữ thường. + * - phone: loại bỏ khoảng trắng, dấu . và -. + * - initialRoleId: ID vai trò được chọn. + * - status: tài khoản được tạo ở trạng thái ACTIVE. + */ + created = await adminApi.createUser({ username: form.username.trim(), password: form.password, @@ -63,108 +234,276 @@ export default function AdminCreateUser() { initialRoleId: Number(form.roleId), status: "ACTIVE", }); + } catch (err) { + + // Xử lý lỗi API, ví dụ phiên đăng nhập hết hạn. onApiError(err); + + // Tắt trạng thái đang xử lý. setBusy(false); + + // Lấy thông báo lỗi từ backend. + // Nếu không có thì sử dụng thông báo mặc định. const msg = err.message || "Không tạo được tài khoản."; + + // Nếu lỗi liên quan đến username, + // hiển thị ngay tại trường Tên đăng nhập. if (/Tên đăng nhập/i.test(msg)) return setErrors({ username: msg }); + + // Nếu lỗi liên quan đến email, + // hiển thị ngay tại trường Email. if (/Email/i.test(msg)) return setErrors({ email: msg }); + + // Các lỗi khác hiển thị phía trên form. return setErrors({ form: msg }); } + + + /* + * PHÂN CÔNG CƠ SỞ SAU KHI TẠO TÀI KHOẢN + * + * Đây là request riêng, chạy sau createUser. + * Nếu phân công lỗi, tài khoản vẫn đã được tạo. + */ + + // Biến lưu lỗi phân công cơ sở (nếu có). let facilityError = null; + + // Chỉ phân công khi vai trò cần cơ sở + // và Admin đã chọn một cơ sở. if (scoped && form.facilityId) { try { + + // Gọi API gán cơ sở cho tài khoản vừa tạo. + // userId: ID tài khoản mới. + // facilityId: cơ sở Admin chọn. + // assignedFrom: ngày bắt đầu phân công. + // assignedTo: null nghĩa là chưa xác định ngày kết thúc. await adminApi.assignFacility({ userId: created.userId, facilityId: Number(form.facilityId), assignedFrom: today(), assignedTo: null }); + } catch (err) { + + // Lưu lỗi để cảnh báo trong Modal. + // Không hủy kết quả tạo tài khoản trước đó. facilityError = err.message; } } + + // Hoàn tất quá trình gửi API. setBusy(false); + + // Lưu kết quả thành công. + // State done có giá trị sẽ làm Modal xuất hiện. + // Lưu password để Admin xem và sao chép một lần. setDone({ user: created, password: form.password, facilityError }); }; + + /* + * COPY - SAO CHÉP THÔNG TIN ĐĂNG NHẬP + * + * Dùng Clipboard API của trình duyệt. + * Sao chép username hoặc mật khẩu tạm thời. + */ + const copy = async (text) => { try { + + // Ghi chuỗi được truyền vào clipboard. await navigator.clipboard.writeText(text); + + // Hiển thị toast sao chép thành công. notify("Đã sao chép."); + } catch { + + // Thông báo nếu trình duyệt không cho phép sao chép. notify("Không sao chép được, vui lòng chép thủ công.", "error"); } }; + + /* + * RENDER GIAO DIỆN TẠO TÀI KHOẢN + */ + return (
+ + {/* FORM CHÍNH + onSubmit gọi hàm submit khi Admin nhấn Tạo tài khoản. + noValidate tắt validation mặc định của HTML, + để sử dụng hàm validate tự viết phía trên. */}
+

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.

+ + {/* Hiển thị lỗi khi tải danh sách vai trò/cơ sở. */} {meta.error && {meta.error}} + + {/* Hiển thị lỗi chung khi tạo tài khoản thất bại. */} {errors.form &&

{errors.form}

} + + + {/* TRƯỜNG HỌ VÀ TÊN + Lấy giá trị từ form.fullName. + Khi nhập, gọi set để cập nhật state. */} set("fullName", e.target.value)} /> + + + {/* TRƯỜNG EMAIL + Khi email thay đổi, hàm set có thể tự tạo username + nếu Admin chưa chỉnh tên đăng nhập thủ công. */} set("email", e.target.value)} /> + + + {/* TRƯỜNG SỐ ĐIỆN THOẠI - KHÔNG BẮT BUỘC */} set("phone", e.target.value)} /> + + + {/* HAI TRƯỜNG USERNAME VÀ MẬT KHẨU TẠM THỜI */}
+ + {/* USERNAME + Khi Admin tự sửa username: + - setUserTouched(true) ngừng tự sinh theo email. + - trim() loại bỏ khoảng trắng đầu/cuối. */} { setUserTouched(true); set("username", e.target.value.trim()); }} /> + + {/* MẬT KHẨU TẠM THỜI + Admin có thể sửa hoặc nhấn Tạo mới để sinh lại. */} + + {/* Hiển thị mật khẩu đang được lưu trong form. */} set("password", e.target.value)} /> + + {/* Tạo mật khẩu ngẫu nhiên mới bằng tempPassword(). */}
+ + + {/* KHU VỰC CHỌN VAI TRÒ + Hiển thị mỗi role dưới dạng một nút lựa chọn. */}
Vai trò
+ + {/* Render danh sách vai trò lấy từ API. */} {roles.map((r) => ( ))} + + {/* Trong lúc API tải vai trò, hiển thị thông báo. */} {meta.loading && Đang tải vai trò…}
+ + {/* Hiển thị lỗi nếu chưa chọn vai trò. */} {errors.roleId &&

{errors.roleId}

}
+ + + {/* CHỌN CƠ SỞ PHỤ TRÁCH + Chỉ bật khi scoped = true (Staff/Manager). + Vai trò toàn hệ thống không cần chọn cơ sở. */} + + + {/* GHI CHÚ GIẢI THÍCH QUY TẮC PHÂN CÔNG CƠ SỞ */}

"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.

+ + + {/* NÚT TẠO TÀI KHOẢN + disabled khi đang gửi request hoặc đang tải metadata. + Text đổi thành "Đang tạo..." trong lúc xử lý. */} + + {/* QUAY LẠI DANH SÁCH TÀI KHOẢN */}

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

+ + {/* MODAL SAU KHI TẠO TÀI KHOẢN THÀNH CÔNG + Chỉ xuất hiện khi done khác null. + Khi đóng Modal sẽ chuyển sang trang chi tiết User. */} {done && ( go(`admin/users/${done.user.userId}`)}> + + {/* Thông báo Admin cần gửi thông tin đăng nhập + cho người dùng mới và mật khẩu chỉ hiển thị một lần. */}

Gửi thông tin đăng nhập dưới đây cho {done.user.fullName}. Mật khẩu chỉ hiển thị một lần.

+ + {/* HIỂN THỊ USERNAME VÀ PASSWORD */}
+ + {/* Username của tài khoản vừa được tạo. + Nút Chép gọi hàm copy(username). */}
Tên đăng nhập
{done.user.username}
+ + {/* Mật khẩu tạm thời. + Nút Chép gọi hàm copy(password). */}
Mật khẩu tạm thời
{done.password}
+ + {/* Nếu tạo User thành công nhưng phân công cơ sở lỗi, + hiển thị thông báo để Admin phân công lại sau. */} {done.facilityError && Chưa phân công được cơ sở: {done.facilityError}. Bạn có thể phân công lại trong trang chi tiết.} +
+ + {/* Chuyển đến trang chi tiết User vừa tạo. */} + + {/* RESET FORM ĐỂ TẠO THÊM TÀI KHOẢN + - Đóng Modal. + - Đưa các trường về giá trị mặc định. + - Tạo mật khẩu tạm thời mới. + - Cho phép username tự sinh lại theo email. */}
); -} +} \ No newline at end of file diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUsers.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUsers.jsx index d5d014e..f8b0419 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUsers.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUsers.jsx @@ -1,3 +1,17 @@ + +/* + * ADMIN USERS - TRANG QUẢN LÝ DANH SÁCH TÀI KHOẢN + * + * Chức năng chính: + * - Hiển thị thống kê số lượng tài khoản trong hệ thống. + * - Lấy danh sách người dùng từ Backend API. + * - Tìm kiếm người dùng theo từ khóa. + * - Lọc người dùng theo vai trò và trạng thái. + * - Hiển thị cơ sở mà nhân viên hoặc quản lý phụ trách. + * - Phân trang danh sách (10 tài khoản/trang). + * - Chuyển đến trang chi tiết hoặc tạo tài khoản mới. + */ + import React, { useEffect, useMemo, useState } from "react"; import { adminApi } from "../api/admin"; import { Pagination, Select } from "../components/Pickers"; @@ -10,53 +24,171 @@ import { useLoad } from "./util"; const PAGE_SIZE = 10; export default function AdminUsers() { + + // Lấy hàm xử lý lỗi API từ Context. + // Ví dụ: kết thúc phiên khi token hết hạn (HTTP 401). const { onApiError } = useApp(); + + + /* + * STATE - LƯU TRẠNG THÁI BỘ LỌC VÀ PHÂN TRANG + */ + + // ID vai trò đang được chọn để lọc. + // "" nghĩa là hiển thị tất cả vai trò. const [roleId, setRoleId] = useState(""); + + // Trạng thái tài khoản đang lọc. + // "" nghĩa là không giới hạn trạng thái. const [status, setStatus] = useState(""); + + // Nội dung người dùng đang nhập vào ô tìm kiếm. const [search, setSearch] = useState(""); + + // Từ khóa thực sự dùng để gọi API tìm kiếm. + // Được cập nhật sau khi người dùng ngừng gõ 300ms. const [term, setTerm] = useState(""); + + // Trang hiện tại của bảng danh sách. + // Mặc định bắt đầu từ trang 1. const [page, setPage] = useState(1); + + // Lưu tên cơ sở phụ trách theo ID người dùng. + // Ví dụ: { 5: "SafeSpace Quận 1" }. const [scopes, setScopes] = useState({}); + + /* + * DEBOUNCE TÌM KIẾM + * + * Mục đích: + * - Không gọi API liên tục mỗi khi người dùng gõ một ký tự. + * - Chờ 300ms sau lần nhập cuối mới cập nhật từ khóa. + * - Khi tìm kiếm mới, quay về trang 1. + */ + useEffect(() => { const t = setTimeout(() => { setTerm(search.trim()); setPage(1); }, 300); + + // Hủy timer cũ nếu người dùng tiếp tục nhập, + // tránh thực hiện tìm kiếm với từ khóa cũ. return () => clearTimeout(t); }, [search]); + + /* + * API 1 - LẤY THỐNG KÊ VÀ DANH SÁCH VAI TRÒ + * + * adminApi.stats(): lấy số lượng tài khoản, trạng thái,... + * adminApi.roles(): lấy danh sách vai trò trong hệ thống. + * + * Promise.all giúp gọi hai API đồng thời. + * sortRoles sắp xếp vai trò trước khi sử dụng. + * + * [] nghĩa là không cần tải lại theo bộ lọc. + */ + const meta = useLoad(async () => { const [stats, roles] = await Promise.all([adminApi.stats(), adminApi.roles()]); return { stats, roles: sortRoles(roles, (r) => r.roleName) }; }, [], onApiError); + + + /* + * API 2 - LẤY DANH SÁCH NGƯỜI DÙNG + * + * Gửi các tham số: + * - page: trang hiện tại. + * - pageSize: số tài khoản mỗi trang (10). + * - searchTerm: từ khóa tìm kiếm. + * - status: trạng thái cần lọc. + * - roleId: vai trò cần lọc. + * + * Khi page, term, status hoặc roleId thay đổi, + * useLoad sẽ tải lại danh sách từ backend. + */ + const list = useLoad(() => adminApi.users({ page, pageSize: PAGE_SIZE, searchTerm: term, status, roleId }), [page, term, status, roleId], onApiError); + + /* + * LẤY CƠ SỞ PHỤ TRÁCH CỦA NHÂN VIÊN / QUẢN LÝ + * + * Mỗi tài khoản có vai trò cần gán cơ sở sẽ được + * gọi API để tìm cơ sở đang được phân công. + * + * Khách hàng thông thường không cần xử lý phần này. + */ + // Cơ sở phụ trách của nhân viên / quản lý trong trang hiện tại useEffect(() => { + + // Lấy danh sách tài khoản đang hiển thị. + // Nếu chưa có dữ liệu thì dùng mảng rỗng. const items = list.data?.items || []; + + // Cờ đánh dấu effect còn hiệu lực. + // Tránh setState từ request cũ sau khi cleanup. let alive = true; + items + + // Chỉ lấy những người cần phân công cơ sở + // và chưa có dữ liệu cơ sở trong scopes. .filter((u) => needsFacility(u.roles) && scopes[u.userId] === undefined) + + // Gọi API riêng cho từng tài khoản phù hợp. .forEach(async (u) => { try { + + // Lấy danh sách cơ sở được phân công cho User. const rows = await adminApi.userFacilities(u.userId); + + // Tìm cơ sở có trạng thái phân công ACTIVE. const active = rows.find((r) => r.status === "ACTIVE"); + + // Nếu có cơ sở đang hoạt động thì lưu tên cơ sở. + // Nếu không có thì hiển thị "Chưa phân công". if (alive) setScopes((s) => ({ ...s, [u.userId]: active ? active.facilityName : "Chưa phân công" })); + } catch { + + // Nếu API lỗi, hiển thị dấu "—" cho tài khoản đó. if (alive) setScopes((s) => ({ ...s, [u.userId]: "—" })); } }); + + // Cleanup khi effect kết thúc hoặc dữ liệu thay đổi. + // Request cũ sẽ không cập nhật scopes nữa. return () => { alive = false; }; + }, [list.data]); // eslint-disable-line react-hooks/exhaustive-deps + + /* + * XỬ LÝ DỮ LIỆU THỐNG KÊ + */ + + // Lấy dữ liệu thống kê đã tải từ API. const stats = meta.data?.stats; + + // Đối tượng chứa số lượng tài khoản theo từng vai trò. + // Nếu chưa có dữ liệu thì dùng object rỗng. const byRole = stats?.usersByRole || {}; + + // Tính tổng số tài khoản thuộc nhóm nhân viên / quản lý. + // Loại trừ CUSTOMER và ADMIN khỏi phép tính. const staffCount = Object.entries(byRole) .filter(([k]) => k !== "CUSTOMER" && k !== "ADMIN") .reduce((a, [, v]) => a + v, 0); + + // Dữ liệu cho bốn thẻ thống kê ở đầu trang. + // Mỗi phần tử gồm: [số lượng, nhãn, màu]. const cards = [ [stats?.totalUsers, "Tổng tài khoản", ""], [byRole.CUSTOMER || 0, "Khách hàng", "blue"], @@ -64,32 +196,93 @@ export default function AdminUsers() { [stats?.inactiveUsersCount || 0, "Đang khoá / ngưng", "red"], ]; + + /* + * XÁC ĐỊNH PHẠM VI PHỤ TRÁCH CỦA USER + * + * ADMIN: hiển thị "Toàn hệ thống". + * Nhân viên / quản lý cơ sở: hiển thị tên cơ sở. + * Các vai trò hệ thống khác CUSTOMER: + * hiển thị "Toàn hệ thống". + * CUSTOMER: hiển thị "—". + */ + const scopeOf = (u) => { + + // Admin có phạm vi toàn hệ thống. if (u.roles.includes("ADMIN")) return "Toàn hệ thống"; + + // Nhân viên hoặc quản lý cần gán cơ sở. + // "…" nghĩa là dữ liệu cơ sở chưa tải xong. if (needsFacility(u.roles)) return scopes[u.userId] ?? "…"; + + // Vai trò khác CUSTOMER được hiển thị toàn hệ thống. if (u.roles.some((r) => r !== "CUSTOMER")) return "Toàn hệ thống"; + + // Khách hàng không có cơ sở phụ trách. return "—"; }; + + + /* + * XỬ LÝ THÔNG TIN PHÂN TRANG + */ + + // Dữ liệu danh sách người dùng trả về từ API. const data = list.data; + + // Tính vị trí bắt đầu của bản ghi trên trang hiện tại. + // Ví dụ: trang 2, 10 tài khoản/trang => bắt đầu từ 11. const from = data ? (data.page - 1) * data.pageSize + 1 : 0; + + // Tính tổng số trang dựa trên tổng số tài khoản. + // Math.ceil làm tròn lên để tính cả trang cuối. + // Math.max đảm bảo số trang không nhỏ hơn 1. const totalPages = data ? Math.max(1, Math.ceil(data.totalItems / data.pageSize)) : 1; + + // Danh sách vai trò lấy từ API. const roles = meta.data?.roles || []; + + // Thêm lựa chọn "Tất cả" (roleId rỗng) + // vào đầu danh sách vai trò để tạo bộ lọc. + // useMemo chỉ tính lại khi roles thay đổi. const chips = useMemo(() => [{ roleId: "", roleName: "" }, ...roles], [roles]); + + /* + * RENDER GIAO DIỆN QUẢN LÝ TÀI KHOẢN + */ + return (
+ + {/* HEADER - TIÊU ĐỀ VÀ NÚT THÊM TÀI KHOẢN */}

Quản lý tài khoản người dùng

+ + {/* Hiển thị tổng số tài khoản từ API. + Nếu chưa tải xong thì hiển thị "Đang tải…". */}

{stats ? `${stats.totalUsers} tài khoản trong hệ thống` : "Đang tải…"}

+
+ + {/* Điều hướng đến form tạo tài khoản mới. */} + Thêm tài khoản mới
+ + {/* HIỂN THỊ LỖI KHI KHÔNG TẢI ĐƯỢC THỐNG KÊ / VAI TRÒ */} {meta.error && {meta.error}} + + + {/* BỐN THẺ THỐNG KÊ TÀI KHOẢN */}
+ + {/* Duyệt mảng cards và tạo từng thẻ thống kê. + tone dùng để xác định màu chữ cho số lượng. */} {cards.map(([n, label, tone]) => (
{n ?? "—"} @@ -98,27 +291,57 @@ export default function AdminUsers() { ))}
+ + {/* THANH CÔNG CỤ - LỌC VAI TRÒ, TÌM KIẾM, TRẠNG THÁI */}
+ + {/* BỘ LỌC THEO VAI TRÒ */}
+ + {/* Render nút cho từng vai trò trong chips. */} {chips.map((r) => ( ))}
+ + + {/* KHU VỰC TÌM KIẾM VÀ LỌC TRẠNG THÁI */}
+ + {/* Ô tìm kiếm theo tên, email hoặc số điện thoại. + onChange cập nhật search mỗi khi người dùng nhập. + useEffect phía trên sẽ đợi 300ms trước khi tìm. */} setSearch(e.target.value)} /> + + {/* Dropdown lọc tài khoản theo trạng thái. + Khi thay đổi trạng thái sẽ quay lại trang 1. */} update({ sort: e.target.value, page: "" })}> - @@ -101,7 +97,7 @@ export default function FindList({ query }) {

{f.name}

- {f.distance_km != null ? `${f.city} · Cách bạn ${distanceLabel(f.distance_km)}` : [f.district, f.city].filter(Boolean).join(", ")} + {[f.district, f.city].filter(Boolean).join(", ")}

{compactLabel(offer.size_label)} · {typeLabel(offer.type)} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx index c1956da..c515a7e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx @@ -10,7 +10,7 @@ import { go, href, qs } from "../lib/router"; import { useApp } from "../state/store"; import { filtersFromQuery } from "./FindList"; -// Nhãn loại kho & diện tích trên thẻ / popup: "Kho thường · Kiểm soát nhiệt độ | 2 – 5 m² · 10 – 20 m²" +// Nhãn loại kho & diện tích trên thẻ / popup: "Kho thường · Kho lạnh | Cỡ M · 15 m² · Cỡ L · 30 m²" function specLabel(f) { const types = offerTypes(f).map(typeLabel).join(" · "); const sizes = [...new Set(f.offers.map((o) => o.size_label.replaceAll(" – ", "–")))].slice(0, 2).join(" · "); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx index 9c78160..5fba6a6 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx @@ -1,96 +1,274 @@ import React, { useState } from "react"; import { Photo } from "../components/Photo"; -import { Pagination } from "../components/Pickers"; +import { Select } from "../components/Pickers"; import { Icon, LinkButton } from "../components/UI"; -import { minRate, offerTypes, typeLabel } from "../lib/catalog"; +import { SIZE_BANDS, UNIT_TYPES, areaLabel, listAreas, minRate } from "../lib/catalog"; import { money } from "../lib/format"; +import { go, href, qs } from "../lib/router"; import { useApp } from "../state/store"; -const PER_PAGE = 9; +// Trang chủ theo Figma "START · SafeSpace / Trang chủ" (14/10): +// hero ảnh + tìm kho 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. +// Gợi ý theo khu vực khách chọn, không theo vị trí người dùng. -const FEATURES = [ - ["bolt", "Tiện lợi", "Đặt kho, quản lý và gia hạn chỉ trong vài thao tác, mọi lúc mọi nơi."], - ["shield", "An toàn", "Giám sát 24/7, kiểm soát ra vào chặt chẽ và bảo vệ tài sản của bạn."], - ["auto", "Tự động hoá", "Theo dõi tình trạng kho, lịch hẹn và hợp đồng rõ ràng trong một tài khoản."], +const UNITS_PER_FACILITY = 12; // 8 kho thường (4 M + 4 L) + 4 kho lạnh (2 M + 2 L) +const CARDS_SHOWN = 6; + +const KINDS = [ + { type: "normal", band: "M", note: "Đồ đạc một phòng, hàng shop online, hồ sơ giấy tờ." }, + { type: "normal", band: "L", note: "Đồ chuyển nhà 2–3 phòng ngủ, hàng tồn kho số lượng lớn." }, + { type: "climate", band: "M", note: "Thiết bị điện tử, tài liệu, đồ gỗ cần tránh ẩm." }, + { type: "climate", band: "L", note: "Hàng hoá cần giữ nhiệt độ ổn định, kho hàng cho cửa hàng." }, +]; + +const STEPS = [ + ["Chọn khu vực", "Chọn quận bạn muốn gửi đồ, SafeSpace gợi ý các cơ sở trong khu vực đó."], + ["Chọn loại và cỡ kho", "Kho thường hoặc kho lạnh, cỡ M hay L. Giá hiện rõ theo tháng."], + ["Xem ô trống và đặt chỗ", "Xem sơ đồ từng ô, tiền thuê, tiền cọc và thanh toán bằng QR."], ]; +const districtOf = (area) => area.split(",")[0].trim(); +const lowest = (facilities, filter) => { + const rates = facilities.map((f) => minRate(f, filter)).filter((x) => x != null); + return rates.length ? Math.min(...rates) : null; +}; + +function HeroSearch({ facilities }) { + const [draft, setDraft] = useState({ area: "", type: "", band: "" }); + const set = (key) => (e) => setDraft({ ...draft, [key]: e.target.value }); + return ( +

{ + e.preventDefault(); + go(`find${qs(draft)}`); + }} + > + + + + +
+ ); +} + +function FacilityCard({ f }) { + const from = minRate(f); + const types = [...new Set(f.offers.map((o) => o.type))]; + return ( + + +
+ {f.district || districtOf(areaLabel(f))} +

{f.name}

+
    + {types.includes("normal") &&
  • Kho thường
  • } + {types.includes("climate") &&
  • Kho lạnh
  • } +
  • Cỡ M · L
  • +
+
+

+ Từ + {from != null ? `${money(from)} / tháng` : "Liên hệ"} +

+ Xem ô trống → +
+
+
+ ); +} + export default function Home() { const { data, authed } = useApp(); - const [page, setPage] = useState(1); - const total = data.facilities.length; - const pages = Math.ceil(total / PER_PAGE); - const from = (page - 1) * PER_PAGE; - const shown = data.facilities.slice(from, from + PER_PAGE); + const facilities = data.facilities; + const [area, setArea] = useState(""); + const areas = listAreas(facilities); + const inArea = area ? facilities.filter((f) => areaLabel(f) === area) : facilities; + const shown = inArea.slice(0, CARDS_SHOWN); + const hours = facilities[0]?.hours || "06:00–22:00"; return ( <> -
-
-
- HỆ THỐNG KHO BÃI TỰ ĐỘNG -

- Thêm không gian. -
- Thêm an tâm. -

-

Tìm kho vừa nhu cầu, đặt chỗ rõ ràng và quản lý không gian lưu trữ của bạn ở một nơi.

-
- Bắt đầu ngay - Tìm hiểu thêm -
+
+ {facilities[0] && } +
+ {facilities.length} cơ sở · TP. Hồ Chí Minh +

+ Kho riêng an toàn, +
+ gần nơi bạn cần. +

+

+ Chọn khu vực, chọn kho thường hoặc kho lạnh cỡ M hay L,{" "} +
+ xem ô còn trống và chi phí trước khi đặt. +

+ +
+
+ +
+
+

{facilities.length}cơ sở tại TP.HCM

+

{facilities.length * UNITS_PER_FACILITY}ô kho cỡ M và L

+

24/7camera giám sát

+

{hours}ra vào mỗi ngày

+
+
+ +
+
+
+ Loại kho +

Hai cỡ kho, thường hoặc lạnh

+

Mỗi cơ sở có 8 kho thường và 4 kho lạnh, chia đều cỡ M và L.

+
+
+ {KINDS.map(({ type, band, note }) => { + const size = SIZE_BANDS.find((b) => b.id === band); + const from = lowest(facilities, { type, band }); + return ( + + {type === "climate" ? "Kho lạnh" : "Kho thường"} +

{size.label}

+

{note}

+

+ Giá từ + {from != null ? `${money(from)} / tháng` : "Xem giá theo cơ sở"} +

+ Xem cơ sở còn trống → +
+ ); + })}
-
-
-
- {FEATURES.map(([icon, title, text], i) => ( -
- - - -

{title}

-

{text}

-
- ))} +
+
+
+ Cách đặt kho +

Đặt kho trong 3 bước

+
+
    + {STEPS.map(([title, text], i) => ( +
  1. + {i + 1} +

    {title}

    +

    {text}

    +
  2. + ))} +
-
-

Một không gian phù hợp, gần bạn

-

Xem hình ảnh cơ sở, diện tích và giá thuê trước khi đặt chỗ.

-
- {shown.map((f) => ( -
- -

{f.name}

-

{minRate(f) != null ? `Từ ${money(minRate(f))} / tháng` : "Liên hệ để nhận giá"}

-

{offerTypes(f).map(typeLabel).join(" · ") || "Kho thường"}

- Khám phá cơ sở -
- ))} +
+
+
+ Cơ sở +

Chọn khu vực, xem cơ sở gần đó

+
+
+ + {areas.map((a) => ( + + ))} +
+
+ {shown.map((f) => ( + + ))} +
+ + {area ? `Xem tất cả ${inArea.length} cơ sở tại ${districtOf(area)} →` : `Xem tất cả ${facilities.length} cơ sở →`} +
-
-
-

Sẵn sàng bắt đầu?

-

{authed ? "Chào mừng bạn quay lại SafeSpace." : "Khách hàng mới tạo tài khoản nhanh chóng chưa đầy 1 phút."}

-
- {authed ? ( - <> - Tìm kho mới - Xem tổng quan - - ) : ( - <> - Tạo tài khoản khách hàng - Đăng nhập - - )} +
+
+
+
+

{authed ? "Chào mừng bạn quay lại SafeSpace" : "Quản lý mọi kho thuê trong một tài khoản"}

+

Theo dõi đặt chỗ, hợp đồng, thanh toán, gia hạn và yêu cầu hỗ trợ.

+
+
+ {authed ? ( + <> + Xem tổng quan + Tìm kho mới + + ) : ( + <> + Tạo tài khoản + Đăng nhập + + )} +
+
+ + ); } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx index eb434c7..ceb4f20 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx @@ -8,16 +8,21 @@ export function Pricing() { const { data } = useApp(); return (
- -
+ +
{SIZE_BANDS.map((b) => { - const rates = data.facilities.map((f) => minRate(f, { band: b.id })).filter((x) => x != null); - const min = rates.length ? Math.min(...rates) : null; + const from = (type) => { + const rates = data.facilities.map((f) => minRate(f, { band: b.id, type })).filter((x) => x != null); + return rates.length ? Math.min(...rates) : null; + }; + const normal = from("normal"); + const cold = from("climate"); return (

{b.name}

- {b.label.replaceAll(" – ", "–")} -

{min == null || b.id === "L" ? "Xem giá theo cơ sở" : `Từ ${money(min)} / tháng`}

+ {b.short} +

{normal == null ? "Xem giá theo cơ sở" : `Từ ${money(normal)} / tháng`}

+ {cold != null &&

Kho lạnh từ {money(cold)} / tháng

}

{b.note}

Tìm kho phù hợp
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/styles/ss.css b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/styles/ss.css index 1b0843e..6a449a3 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/styles/ss.css +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/styles/ss.css @@ -169,21 +169,6 @@ h4 { font-size: 16px; font-weight: 700; color: var(--ink); } .pagination p { font-size: 13px; color: var(--muted); } /* ---------- Home ---------- */ -.hero { background: var(--ink); color: #fff; } -.hero__inner { max-width: 1440px; margin: 0 auto; padding: 72px var(--pad-x); display: grid; grid-template-columns: 1fr 1.15fr; gap: 56px; align-items: center; } -.hero h1 { font-size: 46px; line-height: 1.12; font-weight: 800; margin: 18px 0 16px; color: #fff; } -.hero p { color: #cbd5e1; font-size: 17px; max-width: 460px; } -.hero__actions { display: flex; gap: 12px; margin-top: 28px; } -.hero__photo { border-radius: 16px; overflow: hidden; aspect-ratio: 16 / 10; } -.features { background: #eef1f8; padding: 44px 0; margin-bottom: 0; } -.features__grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; } -.feature { padding: 22px 24px; display: grid; gap: 8px; } -.feature__icon { width: 36px; height: 36px; border-radius: 10px; background: var(--soft); color: var(--blue); display: grid; place-items: center; } -.feature__icon--dark { background: var(--ink); color: #fff; } -.feature p { color: var(--muted); font-size: 14.5px; } -.home-list { padding-top: 56px; padding-bottom: 72px; } -.home-list h2 { font-size: 26px; font-weight: 800; } -.home-list .lead { margin: 8px 0 24px; font-size: 15px; } .facility-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; } .facility-card { padding: 12px 12px 20px; display: grid; gap: 6px; align-content: start; } .facility-card h3 { font-size: 19px; margin-top: 12px; } @@ -194,10 +179,6 @@ h4 { font-size: 16px; font-weight: 700; color: var(--ink); } .facility-card--compact .price { font-size: 14px; } .facility-card--compact .muted { font-size: 13px; } .facility-card .price { margin-top: 8px; } -.cta { background: var(--ink); color: #fff; text-align: center; padding: 56px 24px 64px; } -.cta h2 { color: #fff; font-size: 26px; font-weight: 800; } -.cta p { color: #cbd5e1; margin: 10px 0 22px; } -.cta__actions { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; } /* Photos */ .photo { position: relative; overflow: hidden; border-radius: 10px; background: #dbeafe; aspect-ratio: 16 / 10; } @@ -424,6 +405,7 @@ a.cell-strong:hover { color: var(--blue); } .usermenu__btn:hover { background: var(--soft); } .usermenu__btn strong { font-size: 15px; font-weight: 500; color: var(--text); } .usermenu__btn small { font-size: 12.5px; color: var(--red); font-weight: 600; } +.usermenu__facility { font-size: 12px; color: var(--muted); font-weight: 400; } .usermenu__pop { position: absolute; right: 0; top: calc(100% + 8px); background: #fff; border: 1px solid var(--line); border-radius: 12px; box-shadow: 0 14px 34px rgba(16, 21, 42, 0.15); padding: 12px; min-width: 220px; z-index: 55; display: grid; gap: 10px; } .usermenu__pop p { font-size: 14px; font-weight: 600; color: var(--ink); } .usermenu__pop p span { font-weight: 400; color: var(--muted); font-size: 13px; } @@ -468,6 +450,7 @@ a.cell-strong:hover { color: var(--blue); } .inline-form { flex-direction: column; align-items: stretch; } .admin-form { padding: 22px 18px; } .usermenu__btn strong { max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; } + .usermenu__facility { max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; } } /* ---------- Responsive ---------- */ @@ -524,10 +507,11 @@ a.cell-strong:hover { color: var(--blue); } .unit-dot--service, .unit-tile--service { background: #f9e9e5; } .unit-dot--free { border-color: var(--blue); } .unit-plan { background: #f7f9fc; border: 1px solid var(--line); border-radius: 10px; padding: 16px; display: grid; gap: 12px; } -.unit-row { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 16px; } -.unit-tile { border: 0; border-radius: 10px; min-height: 130px; padding: 12px 6px; display: grid; align-content: center; justify-items: center; gap: 6px; cursor: pointer; color: var(--text); font-size: 14px; box-shadow: inset 0 0 0 0 transparent; transition: transform 0.12s, box-shadow 0.12s; } +.unit-row { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 12px; } +.unit-tile { border: 0; border-radius: 10px; min-height: 130px; padding: 12px 4px; text-align: center; display: grid; align-content: center; justify-items: center; gap: 6px; cursor: pointer; color: var(--text); font-size: 14px; box-shadow: inset 0 0 0 0 transparent; transition: transform 0.12s, box-shadow 0.12s; } .unit-row--tall .unit-tile { min-height: 170px; } .unit-tile strong { font-size: 22px; font-weight: 700; } +.unit-tile span { font-size: 13px; white-space: nowrap; } .unit-tile--free { color: #fff; } .unit-tile:hover { transform: translateY(-2px); } .unit-tile.is-selected { box-shadow: inset 0 0 0 4px var(--soft), 0 0 0 2px var(--blue); } @@ -677,3 +661,93 @@ label.search-input input { border: 0; outline: 0; flex: 1; font-size: 14px; back .map-empty strong { font-size: 18px; color: var(--ink); } .map-empty span { color: var(--muted); } .ops-banner { max-width: 1440px; margin: 16px auto 0; padding: 10px var(--pad-x); background: var(--amber-bg); color: var(--amber); font-size: 14px; } + +/* ---------- Trang chủ (Figma START · Trang chủ, 14/10) ---------- */ +.home-hero { position: relative; overflow: hidden; background: var(--ink); color: #fff; } +.home-hero__bg { position: absolute; inset: 0; aspect-ratio: auto; border-radius: 0; z-index: 0; } +.home-hero::after { content: ""; position: absolute; inset: 0; z-index: 1; background: linear-gradient(90deg, rgba(16, 21, 42, 0.94) 0%, rgba(16, 21, 42, 0.72) 55%, rgba(16, 21, 42, 0.25) 100%); } +.home-hero__inner { position: relative; z-index: 2; max-width: 1440px; margin: 0 auto; padding: 104px var(--pad-x) 72px; display: grid; gap: 20px; justify-items: start; } +.home-hero__badge { border: 1px solid rgba(255, 255, 255, 0.3); background: rgba(255, 255, 255, 0.14); border-radius: 999px; padding: 6px 14px; font-size: 14px; font-weight: 600; letter-spacing: 0.04em; } +.home-hero h1 { font-size: 64px; line-height: 1.08; font-weight: 800; letter-spacing: -0.02em; color: #fff; } +.home-hero p { font-size: 19px; line-height: 1.5; color: rgba(255, 255, 255, 0.86); } +.home-search { margin-top: 36px; width: 100%; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)) auto; align-items: center; background: #fff; color: var(--text); border-radius: 20px; padding: 12px; box-shadow: 0 18px 48px rgba(10, 20, 51, 0.28); } +.home-search__field { display: grid; gap: 4px; padding: 8px 20px; border-right: 1px solid var(--line); } +.home-search__field:nth-child(3) { border-right: 0; } +.home-search__field > span { font-size: 12px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); } +.home-search__field select { border: 0; background-color: transparent; padding-left: 0; font-size: 17px; font-weight: 600; color: var(--text); } +.home-search__submit { padding: 18px 28px; border-radius: 14px; font-size: 16px; } +.home-stats { background: var(--white); border-bottom: 1px solid var(--line); } +.home-stats__grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); padding-top: 32px; padding-bottom: 32px; } +.home-stats__grid p { display: grid; gap: 2px; padding-left: 28px; border-left: 1px solid var(--line); } +.home-stats__grid p:first-child { padding-left: 0; border-left: 0; } +.home-stats__grid strong { font-size: 30px; font-weight: 800; color: var(--ink); line-height: 1.2; } +.home-stats__grid span { color: var(--muted); font-size: 15px; } +.home-section { background: var(--white); padding: 88px 0; } +.home-section--tint { background: var(--bg); } +.home-head { display: grid; gap: 8px; margin-bottom: 36px; } +.home-head h2 { font-size: 36px; font-weight: 800; letter-spacing: -0.01em; color: var(--text); } +.home-head p { color: var(--muted); font-size: 17px; } +.home-eyebrow { font-size: 13px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--blue); } +.home-link { color: var(--blue); font-weight: 600; font-size: 15px; } +.home-kinds { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 24px; } +.home-kind { background: var(--white); border: 1px solid var(--line); border-radius: 20px; padding: 24px; display: grid; gap: 12px; align-content: start; color: var(--text); transition: transform 0.15s, box-shadow 0.15s; } +.home-kind:hover, .home-facility:hover { transform: translateY(-3px); box-shadow: 0 14px 30px rgba(16, 21, 42, 0.1); } +.home-kind__tag { justify-self: start; background: var(--soft); color: var(--blue); border-radius: 999px; padding: 4px 10px; font-size: 13px; font-weight: 600; } +.home-kind__tag--cold { background: #e0f2fe; color: #0369a1; } +.home-kind h3 { font-size: 24px; font-weight: 800; } +.home-kind__note { color: var(--muted); font-size: 15px; min-height: 45px; } +.home-kind__price { display: grid; border-top: 1px solid var(--line); padding-top: 14px; } +.home-kind__price small, .home-facility__foot small { color: var(--muted); font-size: 13px; } +.home-kind__price strong { font-size: 20px; font-weight: 700; color: var(--ink); } +.home-steps { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 24px; } +.home-steps li { border: 1px solid var(--line); border-radius: 20px; padding: 28px; display: grid; gap: 12px; align-content: start; } +.home-steps__num { width: 44px; height: 44px; border-radius: 999px; background: var(--blue); color: #fff; display: grid; place-items: center; font-weight: 800; font-size: 18px; } +.home-steps h3 { font-size: 21px; font-weight: 800; } +.home-steps p { color: var(--muted); font-size: 15px; } +.home-chips { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 28px; } +.home-chip { border: 1px solid var(--line); background: var(--white); border-radius: 999px; padding: 9px 16px; font-size: 15px; font-weight: 500; cursor: pointer; color: var(--text); } +.home-chip span { color: var(--muted); margin-left: 4px; } +.home-chip.is-on { background: var(--ink); border-color: var(--ink); color: #fff; font-weight: 600; } +.home-chip.is-on span { color: rgba(255, 255, 255, 0.7); } +.home-facilities { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 24px; } +.home-facility { background: var(--white); border: 1px solid var(--line); border-radius: 20px; overflow: hidden; display: grid; color: var(--text); transition: transform 0.15s, box-shadow 0.15s; } +.home-facility .photo { border-radius: 0; aspect-ratio: 16 / 9.2; } +.home-facility__body { padding: 20px 24px 24px; display: grid; gap: 10px; } +.home-facility h3 { font-size: 21px; font-weight: 800; } +.home-tags { display: flex; flex-wrap: wrap; gap: 8px; } +.home-tags li { background: var(--bg); color: var(--muted); border-radius: 999px; padding: 3px 10px; font-size: 13px; font-weight: 500; } +.home-facility__foot { display: flex; justify-content: space-between; align-items: flex-end; padding-top: 6px; } +.home-facility__foot p { display: grid; } +.home-facility__foot strong { font-size: 18px; font-weight: 700; color: var(--ink); } +.home-more { margin-top: 28px; } +.home-cta { background: var(--ink); color: #fff; border-radius: 28px; padding: 56px; display: flex; justify-content: space-between; align-items: center; gap: 32px; } +.home-cta h2 { color: #fff; font-size: 32px; font-weight: 800; } +.home-cta p { color: rgba(255, 255, 255, 0.78); margin-top: 10px; font-size: 17px; } +.home-cta__actions { display: flex; gap: 12px; flex-shrink: 0; } +.home-footer { background: var(--white); border-top: 1px solid var(--line); padding: 56px 0 40px; } +.home-footer__cols { display: grid; grid-template-columns: 2fr 1fr 1fr 1.2fr; gap: 48px; } +.home-footer__cols > * { display: grid; gap: 10px; align-content: start; } +.home-footer__cols strong { font-size: 15px; color: var(--text); } +.home-footer__brand { font-size: 24px !important; font-weight: 800; color: var(--blue) !important; } +.home-footer__cols p, .home-footer__cols a { color: var(--muted); font-size: 15px; } +.home-footer__cols a:hover { color: var(--blue); } +.home-footer__copy { color: var(--muted); font-size: 13px; margin-top: 40px; } +@media (max-width: 1100px) { + .home-hero__inner { padding-top: 80px; padding-bottom: 56px; } + .home-kinds { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .home-facilities { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .home-search { grid-template-columns: 1fr; gap: 4px; } + .home-search__field { border-right: 0; border-bottom: 1px solid var(--line); padding: 10px 12px; } + .home-search__submit { margin-top: 8px; } +} +@media (max-width: 720px) { + .home-hero h1 { font-size: 36px; } + .home-hero p br { display: none; } + .home-stats__grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; } + .home-stats__grid p:nth-child(3) { padding-left: 0; border-left: 0; } + .home-section { padding: 56px 0; } + .home-head h2 { font-size: 28px; } + .home-kinds, .home-steps, .home-facilities, .home-footer__cols { grid-template-columns: 1fr; } + .home-cta { flex-direction: column; align-items: flex-start; padding: 36px 24px; } + .home-cta h2 { font-size: 26px; } +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js index 18fac75..603b5bc 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js @@ -58,8 +58,8 @@ test("danh mục: cơ sở, quận / thành phố, giờ mở cửa và gói kho assert.equal(tb.city, "TP. Hồ Chí Minh"); assert.equal(tb.hours, "07:00–22:00"); assert.deepEqual(tb.offers.map((o) => [o.unit_type_id, o.type, o.band, o.monthly_rate]), [ - [1, "normal", "S", 500000], - [2, "climate", "S", 1500000], + [1, "normal", "M", 500000], + [2, "climate", "M", 1500000], [3, "climate", "M", 3000000], ]); assert.equal(tb.offers[1].size_label, "4 m²"); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js index 866afad..1ad6ab1 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js @@ -44,8 +44,11 @@ test("đặt chỗ: kiểm tra đầu vào", () => { const s = createSeedData(T); assert.match(book(s, { start_date: "2026-09-20" }).error.message, /quá khứ/); assert.match(book(s, { months: 2 }).error.message, /1, 3 hoặc 6/); - assert.match(book(s, { facility_id: 8, type: "climate" }).error.message, /chưa có loại kho/); + // Figma 14/10: cơ sở nào cũng có kho lạnh → giả lập một cơ sở thiếu loại kho để kiểm tra thông báo + const noCold = { ...s, facilities: s.facilities.map((f) => (f.facility_id === 8 ? { ...f, has_climate: false, offers: f.offers.filter((o) => o.type !== "climate") } : f)) }; + assert.match(book(noCold, { facility_id: 8, type: "climate" }).error.message, /chưa có loại kho/); assert.match(book(s, { band: "X" }).error.message, /diện tích/); + assert.match(book(s, { band: "S" }).error.message, /diện tích/); // cỡ S đã bỏ, chỉ còn M và L }); test("chuyển khoản trong hạn: chờ đối soát, sinh 2 khoản thu, thông báo", () => { @@ -84,7 +87,7 @@ test("gia hạn: chỉ 1 yêu cầu chờ duyệt, chặn trả kho song song, h assert.equal(a.state.renewals[0].status, "PENDING"); assert.equal(a.state.renewals[0].new_end, addMonths(s.contracts[1].end_date, 3)); assert.equal(a.state.ledger.at(-1).status, "RENEWAL_PENDING"); - assert.equal(a.state.ledger.at(-1).amount, 3 * 500000); + assert.equal(a.state.ledger.at(-1).amount, 3 * 1380000); // B-015: kho lạnh cỡ M tại Nguyễn Lương Bằng assert.match(run(a.state, "REQUEST_RENEWAL", { contract_id: "HĐ-2026-0086", months: 1 }).error.message, /đang chờ/); assert.match(run(a.state, "REQUEST_RETURN", { contract_id: "HĐ-2026-0086", date: T, slot: "09:00–09:30" }).error.message, /gia hạn/); assert.match(run(s, "REQUEST_RENEWAL", { contract_id: "HĐ-2026-0086", months: 2 }).error.message, /1, 3 hoặc 6/); @@ -138,12 +141,12 @@ test("nhân viên đối soát: tạo hợp đồng + lịch nhận kho, khoản assert.deepEqual(mine, ["DEPOSIT_HELD", "RECONCILED"]); }); -test("tìm cơ sở: lọc khu vực Quận 7 → 3 cơ sở; kho lạnh loại bỏ cơ sở không có; sắp xếp giá", () => { +test("tìm cơ sở: lọc khu vực Quận 7 → 5 cơ sở; cả 12 cơ sở có kho lạnh; sắp xếp giá", () => { const s = createSeedData(T); const q7 = searchFacilities(s.facilities, { area: "Quận 7, TP. Hồ Chí Minh" }); - assert.deepEqual(q7.map((f) => f.facility_id), [1, 2, 3]); + assert.deepEqual(q7.map((f) => f.facility_id), [1, 2, 3, 4, 5]); const cold = searchFacilities(s.facilities, { type: "climate" }); - assert.ok(cold.every((f) => f.has_climate) && cold.length === 9); + assert.ok(cold.every((f) => f.has_climate) && cold.length === 12); const cheap = searchFacilities(s.facilities, { sort: "price" }); assert.equal(cheap[0].facility_id, 8); // Bình Chánh 790.000 assert.equal(rateFor(s.facilities[0], "normal", "M"), 1150000); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs index 072583d..c5c7945 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs @@ -20,7 +20,7 @@ try { const { OPS_ACCOUNTS } = await vite.ssrLoadModule("/src/ops/data.js"); const seed = (authed, opsUser = null) => memory.set(STORAGE_KEY, JSON.stringify({ version: 5, authed, data: createSeedData(), opsUser })); - const publicRoutes = ["home", "login", "register", "pricing", "guide", "find", "find?type=climate&band=S", "find/map", "find/map?type=climate", "find/map?area=Kh%C3%B4ng%20c%C3%B3", "find/1", "find/1?view=map&unit=K02", "find/8?type=climate&view=map", "find/999", "nope"]; + const publicRoutes = ["home", "login", "register", "pricing", "guide", "find", "find?type=climate&band=M", "find/map", "find/map?type=climate", "find/map?area=Kh%C3%B4ng%20c%C3%B3", "find/1", "find/1?view=map&unit=K02", "find/8?type=climate&view=map", "find/999", "nope"]; const privateRoutes = [ "overview", "units", "units/HĐ-2026-0142", "units/HĐ-2026-0086/renew", "units/HĐ-2026-0142/return", "units/unknown", "sent?type=renew&contract=HĐ-2026-0086", "reservations", "reservations/SS-20260914-0142", "reservations/none", diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/units.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/units.test.js index a7e4a36..6852081 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/units.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/units.test.js @@ -1,38 +1,57 @@ -// Sơ đồ tình trạng ô kho (src/lib/units.js) +// Sơ đồ tình trạng ô kho (src/lib/units.js) — Figma 14/10: 12 ô mỗi cơ sở import test from "node:test"; import assert from "node:assert/strict"; import { createFacilities } from "../src/data/seed.js"; import { countBy, unitsFor } from "../src/lib/units.js"; -test("mỗi cơ sở có 10 ô, giá khớp gói kho, cơ sở đầu theo đúng Figma", () => { +const kinds = (units) => units.map((u) => `${u.row}:${u.type}`); + +test("mỗi cơ sở có 12 ô: dãy A cỡ M (4 thường + 2 lạnh), dãy B cỡ L (4 thường + 2 lạnh), giá khớp gói kho", () => { const facilities = createFacilities(); for (const f of facilities) { const units = unitsFor(f); - assert.equal(units.length, 10); + assert.equal(units.length, 12); + assert.deepEqual(kinds(units), [ + "A:normal", "A:normal", "A:normal", "A:normal", "A:climate", "A:climate", + "B:normal", "B:normal", "B:normal", "B:normal", "B:climate", "B:climate", + ]); + assert.ok(units.filter((u) => u.row === "A").every((u) => u.area === 15)); + assert.ok(units.filter((u) => u.row === "B").every((u) => u.area === 30)); for (const u of units) assert.equal(u.monthly_rate, f.offers.find((o) => o.key === u.offer_key).monthly_rate); - if (!f.has_climate) assert.ok(units.every((u) => u.type === "normal")); } const nlb = unitsFor(facilities[0]); - assert.deepEqual(countBy(nlb), { FREE: 5, RENTED: 3, HELD: 1, SERVICE: 1 }); + assert.deepEqual(countBy(nlb), { FREE: 6, RENTED: 4, HELD: 1, SERVICE: 1 }); assert.equal(nlb.find((u) => u.code === "K02").status, "RENTED"); + assert.equal(nlb.find((u) => u.code === "K12").position, "Tầng trệt · Dãy B"); }); -test("dữ liệu backend: ô kho lấy loại kho từ bảng giá, số ô trống khớp /api/availability/check", async () => { +test("dữ liệu backend: ô kho lấy đúng loại + cỡ từ bảng giá, số ô trống khớp /api/availability/check", async () => { const { mapCatalog } = await import("../src/api/mappers.js"); const unitTypes = [ - { unitTypeId: 1, typeName: "Kho Mini S", area: 1, climateControlled: false, status: "ACTIVE" }, - { unitTypeId: 2, typeName: "Kho M", area: 4, climateControlled: true, status: "ACTIVE" }, - { unitTypeId: 3, typeName: "Kho L", area: 9, climateControlled: true, status: "ACTIVE" }, + { unitTypeId: 1, typeName: "Kho thường M", area: 15, climateControlled: false, status: "ACTIVE" }, + { unitTypeId: 2, typeName: "Kho thường L", area: 30, climateControlled: false, status: "ACTIVE" }, + { unitTypeId: 3, typeName: "Kho lạnh M", area: 15, climateControlled: true, status: "ACTIVE" }, + { unitTypeId: 4, typeName: "Kho lạnh L", area: 30, climateControlled: true, status: "ACTIVE" }, ]; - const rates = [1, 2, 3].map((id) => ({ facilityId: 7, unitTypeId: id, monthlyRate: id * 500000 })); + const rates = [1, 2, 3, 4].map((id) => ({ facilityId: 7, unitTypeId: id, monthlyRate: id * 500000 })); const { facilities } = mapCatalog({ facilities: [{ facilityId: 7, name: "SafeSpace Nhà Bè", address: "Nhà Bè, TP. Hồ Chí Minh", status: "ACTIVE" }], unitTypes, rates }); const f = facilities[0]; - const units = unitsFor(f, { "ut-1": 2, "ut-2": 0, "ut-3": 1 }); - assert.equal(units.length, 10); - assert.ok(units.every((u) => f.offers.some((o) => o.key === u.offer_key)), "mỗi ô gắn với một loại kho thật"); + const units = unitsFor(f, { "ut-1": 2, "ut-2": 0, "ut-3": 1, "ut-4": 2 }); + assert.equal(units.length, 12); + assert.deepEqual(units.map((u) => u.offer_key), ["ut-1", "ut-1", "ut-1", "ut-1", "ut-3", "ut-3", "ut-2", "ut-2", "ut-2", "ut-2", "ut-4", "ut-4"]); const free = (key) => units.filter((u) => u.offer_key === key && u.status === "FREE").length; assert.equal(free("ut-1"), 2); assert.equal(free("ut-2"), 0); assert.equal(free("ut-3"), 1); - assert.equal(units.find((u) => u.offer_key === "ut-1").area_label, "1 m²"); + assert.equal(free("ut-4"), 2); + assert.equal(units.find((u) => u.offer_key === "ut-2").area_label, "30 m²"); +}); + +test("dữ liệu backend thiếu loại kho: ô vẫn gắn với một gói có thật", async () => { + const { mapCatalog } = await import("../src/api/mappers.js"); + const unitTypes = [{ unitTypeId: 9, typeName: "Kho thường M", area: 15, climateControlled: false, status: "ACTIVE" }]; + const { facilities } = mapCatalog({ facilities: [{ facilityId: 3, name: "SafeSpace Phú Xuân", address: "Quận 7, TP. Hồ Chí Minh", status: "ACTIVE" }], unitTypes, rates: [{ facilityId: 3, unitTypeId: 9, monthlyRate: 890000 }] }); + const units = unitsFor(facilities[0]); + assert.equal(units.length, 12); + assert.ok(units.every((u) => u.offer_key === "ut-9" && u.monthly_rate === 890000)); }); diff --git a/progress.md b/progress.md index 5d72e25..037d7d1 100644 --- a/progress.md +++ b/progress.md @@ -17,6 +17,26 @@ --- +## Phiên 4 — 2026-10-14 — Đồng bộ giao diện với Figma 14/10 (Claude) + +- Tính năng: F30 (sơ đồ ô kho) + trang chủ, danh mục kho, header khu vận hành. Nhánh `feature/figma-1410-sync`. Quyết định D17. +- Đã xong (chỉ frontend): + - Trang chủ mới (`pages/Home.jsx`): hero ảnh + tìm theo khu vực / loại / cỡ, dải số liệu, 4 loại kho, 3 bước, + cơ sở theo chip khu vực, khối kêu gọi, footer. Bỏ CSS trang chủ cũ không còn dùng. + - Sơ đồ 12 ô (`lib/units.js`, `UnitMap.jsx`): dãy A cỡ M, dãy B cỡ L; dữ liệu backend gắn ô theo loại + cỡ. + - Bỏ cỡ S (`lib/catalog.js`), 2 cỡ M 15 m² / L 30 m²; bảng giá P01 còn 2 thẻ, có giá kho lạnh. + - Bỏ "Gần bạn nhất", "Cách bạn … km", `distance_km`, `distanceLabel`. + - 12 cơ sở đều có kho lạnh; sửa quận Tân Thuận, Phú Mỹ Hưng về Quận 7; đơn mẫu B-015 đổi sang kho lạnh cỡ M. + - Header khu Nhân viên / Quản lý hiện tên cơ sở phụ trách dưới vai trò. +- Test đã sửa theo quy tắc mới (không phải để cho pass): `units.test.js` (10 → 12 ô), `reducer.test.js` + (Quận 7 có 5 cơ sở, cả 12 có kho lạnh, giá B-015 mới, thêm kiểm tra cỡ S bị từ chối), `api-mappers.test.js` + (loại kho ≤ 20 m² là cỡ M), `render.test.mjs` (lọc cỡ M thay cỡ S). +- Kiểm chứng: `npm test` → 39/39 pass; `npm run test:render` → 76 route PASS; `npm run build` → OK; + chụp màn hình trang chủ (1440 px và 390 px), sơ đồ 12 ô, header quản lý / nhân viên ở chế độ không backend. +- Chưa làm: dữ liệu khu vận hành (`ops/data.js`) vẫn dùng diện tích cũ và 86 ô; backend chưa đổi seed (D17); + dòng thông báo trong `OpsShell.jsx` còn chữ "dữ liệu mẫu" (trái D07/D15). +- Phiên sau nên: cập nhật `DbSeeder` theo D17, rồi chạy giao diện với backend thật. + ## Phiên 3 — 2026-10-14 — Backend khu Quản lý vận hành KD (Claude) - Tính năng: F24 (role OPERATIONS), F22 (cơ sở, chính sách, bảng giá), F23 (báo cáo + xuất CSV) — phía backend. From 86af076daff2ac823262e47e2eaaacf6a7583232 Mon Sep 17 00:00:00 2001 From: Vector Date: Wed, 14 Oct 2026 23:21:20 +0700 Subject: [PATCH 06/24] =?UTF-8?q?feat(F03,F11-F21):=20backend=20khu=20Nh?= =?UTF-8?q?=C3=A2n=20vi=C3=AAn=20/=20Qu=E1=BA=A3n=20l=C3=BD=20c=C6=A1=20s?= =?UTF-8?q?=E1=BB=9F,=20confirm-transfer,=20seed=20D17?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 4 +- DECISIONS.md | 22 +- README.md | 5 +- .../SafeSpace-Customer-UI/BACKEND-TODO.md | 17 +- .../SafeSpace-Customer-UI/BE-CONTRACT.md | 2 +- .../SafeSpace-Customer-UI/mock/mock-api.mjs | 21 +- .../scripts/dev-mock.mjs | 4 +- .../src/api/endpoints.js | 2 + .../SafeSpace-Customer-UI/src/api/mappers.js | 3 +- .../src/ops/OpsShell.jsx | 2 +- .../SafeSpace-Customer-UI/src/ops/api.js | 6 +- .../SafeSpace-Customer-UI/src/ops/data.js | 137 ++--- .../SafeSpace-Customer-UI/src/ops/reducer.js | 4 +- .../SafeSpace-Customer-UI/src/ops/store.jsx | 6 +- .../SafeSpace-Customer-UI/src/state/store.jsx | 13 +- .../tests/api-mappers.test.js | 9 + .../tests/ops-api.test.mjs | 24 +- .../SafeSpace-Customer-UI/tests/ops.test.js | 18 +- .../Endpoints/FacilityOpsEndpoints.cs | 129 +++++ .../Endpoints/ReservationEndpoints.cs | 24 + StorageProject.Api/Program.cs | 2 + .../DTOs/FacilityOps/FacilityOpsDtos.cs | 88 ++++ StorageProject.Core/Entities/Reservation.cs | 2 +- .../Exceptions/ReservationExpiredException.cs | 4 + .../Interfaces/IFacilityOpsService.cs | 30 ++ StorageProject.Core/Interfaces/IServices.cs | 1 + .../ReservationContractConfigurations.cs | 2 +- .../Data/DbSeeder.Catalog.cs | 197 +++++++ .../Data/DbSeeder.FacilityOps.cs | 274 ++++++++++ .../Data/DbSeeder.cs | 412 +-------------- ...14150000_ReservationPendingVerification.cs | 47 ++ .../Migrations/AppDbContextModelSnapshot.cs | 2 +- .../Services/FacilityOpsService.Actions.cs | 498 ++++++++++++++++++ .../Services/FacilityOpsService.Board.cs | 386 ++++++++++++++ .../Services/FacilityOpsService.cs | 220 ++++++++ .../Services/FacilityService.cs | 2 +- .../Services/HandoverService.cs | 2 +- .../Services/RenewalService.cs | 6 +- .../Services/ReservationService.cs | 65 ++- docs/facility-ops-api.md | 78 +++ feature_list.json | 26 +- progress.md | 22 + 42 files changed, 2286 insertions(+), 532 deletions(-) create mode 100644 StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs create mode 100644 StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs create mode 100644 StorageProject.Core/Exceptions/ReservationExpiredException.cs create mode 100644 StorageProject.Core/Interfaces/IFacilityOpsService.cs create mode 100644 StorageProject.Infrastructure/Data/DbSeeder.Catalog.cs create mode 100644 StorageProject.Infrastructure/Data/DbSeeder.FacilityOps.cs create mode 100644 StorageProject.Infrastructure/Migrations/20261014150000_ReservationPendingVerification.cs create mode 100644 StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs create mode 100644 StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs create mode 100644 StorageProject.Infrastructure/Services/FacilityOpsService.cs create mode 100644 docs/facility-ops-api.md diff --git a/AGENTS.md b/AGENTS.md index d278381..94ecb5d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,6 +42,7 @@ Hệ thống quản lý và cho thuê kho tự phục vụ **SafeSpace** cho 5 n | `…/src/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) @@ -66,7 +67,8 @@ cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm run dev # UI: http:// ``` Cần: .NET SDK 10 (project đặt `net10.0`), Node ≥ 22.12, SQL Server (mặc định `.\SQLEXPRESS`). -Tài khoản seed: `customer01`/`Customer@123`, `staff01`/`Staff@123`, `ops01`/`Ops@123` (Vận hành KD), `admin`/`Admin@123`. +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`). diff --git a/DECISIONS.md b/DECISIONS.md index ab865f4..dd4dddf 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -94,5 +94,25 @@ - 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 cần đổi seed cho khớp (4 loại kho, 12 cơ sở, 12 ô mỗi cơ sở) — chưa làm. +- 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. diff --git a/README.md b/README.md index 355340e..511cd19 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,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)*. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index b3375fa..b344726 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -17,13 +17,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 +52,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`. ### 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`). --- diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md index 98c15f0..d42c39b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -79,7 +79,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: | 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}/confirm-transfer` | → `PENDING_VERIFICATION`; sau `expiresAt` trả lỗi mã `EXPIRED` — **đã có** (D18) | | 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` | 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..0792109 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs @@ -104,8 +104,8 @@ export function createState() { return { users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals: [], tickets, 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) => @@ -131,7 +131,7 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M const S = createState(); 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(); @@ -159,7 +159,7 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M 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); }; @@ -426,6 +426,19 @@ 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+)\/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ệ."); 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..42232fc 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs @@ -26,7 +26,7 @@ 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. 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/api/endpoints.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js index 4b6ef08..7972762 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js @@ -18,6 +18,8 @@ export const api = { reservation: (id) => request(`/api/reservations/${id}`), createReservation: (body) => request("/api/reservations", { method: "POST", body }), cancelReservation: (id, reason) => request(`/api/reservations/${id}/cancel`, { method: "POST", body: { reason } }), + // C04: khách báo đã chuyển khoản → PENDING_VERIFICATION (nhân viên đối soát ở S09) + confirmTransfer: (id) => request(`/api/reservations/${id}/confirm-transfer`, { method: "POST" }), // Hợp đồng, thanh toán, gia hạn, bàn giao contracts: () => request("/api/contracts"), diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js index c732f67..2ab5fc0 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js @@ -94,6 +94,7 @@ export function mapCatalog({ facilities = [], unitTypes = [], rates = [] }) { // ---------- Trạng thái ---------- const RESERVATION = { PENDING_PAYMENT: "PENDING_PAYMENT", + PENDING_VERIFICATION: "PENDING_VERIFICATION", UNIT_ASSIGNED: "CONFIRMED", CONFIRMED: "CONFIRMED", CHECKED_IN: "CHECKED_IN", @@ -109,7 +110,7 @@ const TICKET_NOTE = { RESOLVED: "Yêu cầu đã được xử lý.", CANCELLED: "Bạn đã huỷ yêu cầu này.", }; -const RENEWAL = { PENDING_PAYMENT: "PENDING", PENDING_APPROVAL: "PENDING", APPROVED: "APPROVED", COMPLETED: "APPROVED", REJECTED: "REJECTED", CANCELLED: "REJECTED" }; +const RENEWAL = { PENDING: "PENDING", PENDING_PAYMENT: "PENDING", PENDING_APPROVAL: "PENDING", PAID: "APPROVED", APPROVED: "APPROVED", COMPLETED: "APPROVED", REJECTED: "REJECTED", CANCELLED: "REJECTED" }; function offerOfType(unitTypes, id, name) { const t = unitTypes.find((x) => x.unitTypeId === id) || unitTypes.find((x) => x.typeName === name); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx index 45189d7..80b926b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx @@ -148,7 +148,7 @@ export default function OpsShell({ role, active, children }) { {mode === "api" && source === "local" && (

- Backend chưa có API cho khu vận hành (GET /api/ops/board trả 404) — đang hiển thị dữ liệu mẫu lưu trong trình duyệt. + Chưa kết nối được dữ liệu vận hành của cơ sở. Thao tác trên màn hình này đang được lưu tạm trên trình duyệt.

)} {children} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js index 237f29a..9131363 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js @@ -1,6 +1,6 @@ -// API khu vận hành (Nhân viên cơ sở / Quản lý cơ sở). Backend StorageProject.Api CHƯA có các endpoint này; -// hợp đồng đề xuất nằm ở BE-CONTRACT.md mục 5 và được mock/mock-api.mjs làm mẫu chạy được. -// Khi backend trả 404 cho GET /api/ops/board, giao diện tự dùng dữ liệu mẫu trong trình duyệt. +// API khu vận hành (Nhân viên cơ sở / Quản lý cơ sở): StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs, +// tài liệu ở docs/facility-ops-api.md; mock/mock-api.mjs (MOCK_OPS=1) chạy cùng hợp đồng để thử không cần .NET. +// Backend cũ trả 404 cho GET /api/ops/board → giao diện dùng dữ liệu cục bộ trong trình duyệt (ops/store.jsx). import { request } from "../api/http.js"; const enc = encodeURIComponent; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js index f8ec3a9..5df7be7 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js @@ -1,6 +1,6 @@ -// Dữ liệu vận hành tại cơ sở cho khu Nhân viên (S01–S09) và Quản lý cơ sở (M01–M08). -// Backend chưa có API cho hai vai trò này → dữ liệu khởi tạo ở đây, lưu trong trình duyệt -// (ops/store.jsx). Khi có API, thay từng nhánh trong ops/store.jsx, giữ nguyên hình dạng dữ liệu. +// Dữ liệu vận hành tại cơ sở cho khu Nhân viên (S01–S09) và Quản lý cơ sở (M01–M08) khi chạy không backend +// (VITE_USE_API=false) hoặc máy chủ giả lập. Có backend thì dữ liệu lấy từ GET /api/ops/board (ops/api.js); +// hình dạng dữ liệu hai bên giống nhau. import { addDays, addMonths, today } from "../lib/format.js"; export const OPS_PASSWORD = "SafeSpace@123"; @@ -30,57 +30,35 @@ export const UNIT_STATE = { }; const at = (iso, time) => `${iso}T${time}:00`; -const ZONES = ["A", "B", "C", "D", "E", "F"]; -const SIZES = [6, 8, 10, 12, 15]; -const NAMES = [ - "Lê Minh Châu", "Phạm Gia Huy", "Trịnh Thu Trang", "Võ Quốc Việt", "Đặng Mỹ Linh", "Bùi Anh Tuấn", "Hồ Ngọc Hân", - "Ngô Thành Đạt", "Đỗ Khánh Vy", "Mai Xuân Lộc", "Tạ Minh Khôi", "Lâm Bảo Ngọc", "Châu Gia Kiệt", "Kiều Phương Anh", + +// 12 ô kho của cơ sở theo D17 (Figma 14/10) — cùng sơ đồ với giao diện khách (src/lib/units.js) và DbSeeder: +// dãy A cỡ M 15 m² (K01–K04 thường, K05–K06 lạnh), dãy B cỡ L 30 m² (K07–K10 thường, K11–K12 lạnh). +const LAYOUT = [ + ["K01", "normal", 15], ["K02", "normal", 15], ["K03", "normal", 15], ["K04", "normal", 15], + ["K05", "climate", 15], ["K06", "climate", 15], + ["K07", "normal", 30], ["K08", "normal", 30], ["K09", "normal", 30], ["K10", "normal", 30], + ["K11", "climate", 30], ["K12", "climate", 30], ]; -// 86 ô kho của cơ sở (Figma M01: 86 kho, tỷ lệ lấp đầy 78%) function createUnits(t) { - const named = [ - { code: "A-102", tenant: "Nguyễn Thị Mai", area: 12, floor: 1, type: "normal", status: "WAITING_HANDOVER", end: addMonths(addDays(t, 6), 3) }, - { code: "C-208", tenant: "Lê Văn Tùng", area: 8, floor: 2, type: "normal", status: "EXPIRING", end: addDays(t, 14) }, - { code: "A-045", tenant: "Trần Quốc Bảo", area: 15, floor: 1, type: "normal", status: "OVERDUE", end: addDays(t, -3) }, - { code: "D-019", tenant: "Hoàng Thị Lan", area: 10, floor: 1, type: "climate", status: "OVERDUE", end: addDays(t, -3) }, - { code: "E-301", tenant: null, area: 6, floor: 3, type: "normal", status: "EMPTY", end: null }, - { code: "C-012", tenant: "Lê Văn An", area: 10, floor: 1, type: "normal", status: "OVERDUE", end: addDays(t, -4) }, - { code: "B-015", tenant: "Nguyễn Thị Mai", area: 5, floor: 1, type: "climate", status: "EXPIRING", end: addDays(t, 5) }, - { code: "F-077", tenant: "Đỗ Minh Khang", area: 12, floor: 2, type: "normal", status: "EXPIRING", end: addDays(t, 6) }, - { code: "A-108", tenant: null, area: 15, floor: 1, type: "normal", status: "EMPTY", end: null }, - { code: "A-110", tenant: "Phan Quốc Huy", area: 10, floor: 1, type: "normal", status: "WAITING_HANDOVER", end: addMonths(addDays(t, 1), 6) }, - { code: "B-021", tenant: "Đặng Thu Trang", area: 6, floor: 1, type: "climate", status: "WAITING_HANDOVER", end: addMonths(addDays(t, 2), 3) }, - { code: "A-104", tenant: null, area: 12, floor: 1, type: "normal", status: "EMPTY", end: null }, - { code: "A-115", tenant: "Võ Thị Hạnh", area: 12, floor: 1, type: "normal", status: "WAITING_HANDOVER", end: addMonths(t, 3) }, - { code: "B-004", tenant: null, area: 5, floor: 1, type: "climate", status: "EMPTY", end: null }, - { code: "D-006", tenant: null, area: 4, floor: 1, type: "climate", status: "EMPTY", end: null }, - ]; - const taken = new Set(named.map((u) => u.code)); - const out = [...named]; - let i = 0; - while (out.length < 86) { - const zone = ZONES[i % ZONES.length]; - const num = 100 + Math.floor(i / ZONES.length) * 7 + (i % 5); - const code = `${zone}-${String(num).padStart(3, "0")}`; - i++; - if (taken.has(code)) continue; - taken.add(code); - // ~78% đang có khách; còn lại trống / bảo trì - const r = (i * 37) % 100; - const status = r < 70 ? "ACTIVE" : r < 76 ? "EXPIRING" : r < 96 ? "EMPTY" : "MAINTENANCE"; - const rented = status === "ACTIVE" || status === "EXPIRING"; - out.push({ - code, - tenant: rented ? NAMES[i % NAMES.length] : null, - area: SIZES[i % SIZES.length], - floor: Number(num.toString()[0]), - type: zone === "D" || zone === "B" ? "climate" : "normal", - status, - end: rented ? addDays(t, status === "EXPIRING" ? 5 + (i % 20) : 40 + ((i * 11) % 200)) : null, - }); - } - return out; + const usage = { + K01: ["Nguyễn Thị Mai", "WAITING_HANDOVER", addMonths(addDays(t, 6), 3)], + K02: ["Lê Văn Tùng", "EXPIRING", addDays(t, 14)], + K03: ["Trần Quốc Bảo", "OVERDUE", addDays(t, -3)], + K04: ["Lê Văn An", "OVERDUE", addDays(t, -4)], + K05: ["Võ Thị Hạnh", "WAITING_HANDOVER", addMonths(t, 3)], + K06: [null, "EMPTY", null], + K07: ["Đỗ Minh Khang", "EXPIRING", addDays(t, 6)], + K08: ["Phan Quốc Huy", "WAITING_HANDOVER", addMonths(addDays(t, 1), 6)], + K09: [null, "EMPTY", null], + K10: ["Hoàng Thị Lan", "OVERDUE", addDays(t, -3)], + K11: ["Đặng Thu Trang", "WAITING_HANDOVER", addMonths(addDays(t, 2), 3)], + K12: ["Nguyễn Thị Mai", "EXPIRING", addDays(t, 5)], + }; + return LAYOUT.map(([code, type, area]) => { + const [tenant, status, end] = usage[code]; + return { code, tenant, area, floor: "trệt", type, status, end }; + }); } export function createOpsData(t = today()) { @@ -95,17 +73,17 @@ export function createOpsData(t = today()) { payments: [ { id: "SS-20260914-0142", customer: "Nguyễn Thị Mai", amount: 4600000, method: "Chuyển khoản ngân hàng", - reported_at: at(t, "09:12"), memo: "SS 20260914 0142 MAI", offer: "Kho thường · 10–20 m²", + reported_at: at(t, "09:12"), memo: "SS 20260914 0142 MAI", offer: "Kho thường · Cỡ M · 15 m²", start: pickup, end: addMonths(pickup, 3), pickup: at(pickup, "09:00"), status: "PENDING", }, { id: "SS-20260913-0147", customer: "Trương Gia Bảo", amount: 2520000, method: "Chuyển khoản ngân hàng", - reported_at: at(addDays(t, -1), "20:41"), memo: "SS 20260913 0147 BAO", offer: "Kiểm soát nhiệt độ · 2–5 m²", + reported_at: at(addDays(t, -1), "20:41"), memo: "SS 20260913 0147 BAO", offer: "Kho lạnh · Cỡ M · 15 m²", start: addDays(t, 3), end: addMonths(addDays(t, 3), 3), pickup: at(addDays(t, 3), "15:00"), status: "PENDING", }, { id: "SS-20260930-0151", customer: "Lý Minh Đức", amount: 2160000, method: "Chuyển khoản ngân hàng", - reported_at: at(t, "07:55"), memo: "SS 20260930 0151 DUC", offer: "Kho thường · 2–5 m²", + reported_at: at(t, "07:55"), memo: "SS 20260930 0151 DUC", offer: "Kho thường · Cỡ L · 30 m²", start: addDays(t, 4), end: addMonths(addDays(t, 4), 3), pickup: at(addDays(t, 4), "10:00"), status: "PENDING", }, ], @@ -113,31 +91,31 @@ export function createOpsData(t = today()) { // M05 · Đơn đã đối soát, chờ quản lý phân bổ ô kho allocations: [ { - id: "SS-20260912-0138", customer: "Hồ Ngọc Hân", type: "normal", offer: "Kho thường · 10–20 m²", min_area: 10, max_area: 20, + id: "SS-20260912-0138", customer: "Hồ Ngọc Hân", type: "normal", offer: "Kho thường · Cỡ L · 30 m²", min_area: 30, max_area: 30, start: addDays(t, 6), end: addMonths(addDays(t, 6), 3), pickup: at(addDays(t, 6), "10:30"), status: "PENDING", unit: null, }, ], // S02 · Xác minh khách khi đến nhận kho verifications: [ - { id: "XM-0115", reservation_id: "SS-20260908-0115", customer: "Võ Thị Hạnh", unit: "A-115", appointment: at(t, "15:30"), status: "DONE", doc_type: "Căn cước công dân", doc_last4: "4821", verified_at: at(t, "08:40") }, - { id: "XM-0142", reservation_id: "SS-20260914-0142", customer: "Nguyễn Thị Mai", unit: "A-102", appointment: at(pickup, "09:00"), status: "TODO" }, - { id: "XM-0131", reservation_id: "SS-20260910-0131", customer: "Phan Quốc Huy", unit: "A-110", appointment: at(addDays(t, 1), "08:30"), status: "TODO" }, - { id: "XM-0135", reservation_id: "SS-20260911-0135", customer: "Đặng Thu Trang", unit: "B-021", appointment: at(addDays(t, 2), "14:00"), status: "TODO" }, + { id: "XM-0115", reservation_id: "SS-20260908-0115", customer: "Võ Thị Hạnh", unit: "K05", appointment: at(t, "15:30"), status: "DONE", doc_type: "Căn cước công dân", doc_last4: "4821", verified_at: at(t, "08:40") }, + { id: "XM-0142", reservation_id: "SS-20260914-0142", customer: "Nguyễn Thị Mai", unit: "K01", appointment: at(pickup, "09:00"), status: "TODO" }, + { id: "XM-0131", reservation_id: "SS-20260910-0131", customer: "Phan Quốc Huy", unit: "K08", appointment: at(addDays(t, 1), "08:30"), status: "TODO" }, + { id: "XM-0135", reservation_id: "SS-20260911-0135", customer: "Đặng Thu Trang", unit: "K11", appointment: at(addDays(t, 2), "14:00"), status: "TODO" }, ], // S03 · Bàn giao kho (sau khi xác minh) handovers: [ - { id: "BG-0115", verification_id: "XM-0115", unit: "A-115", customer: "Võ Thị Hạnh", status: "WAITING", method: null }, - { id: "BG-0142", verification_id: "XM-0142", unit: "A-102", customer: "Nguyễn Thị Mai", status: "WAITING", method: null }, - { id: "BG-0131", verification_id: "XM-0131", unit: "A-110", customer: "Phan Quốc Huy", status: "WAITING", method: null }, - { id: "BG-0135", verification_id: "XM-0135", unit: "B-021", customer: "Đặng Thu Trang", status: "WAITING", method: null }, + { id: "BG-0115", verification_id: "XM-0115", unit: "K05", customer: "Võ Thị Hạnh", status: "WAITING", method: null }, + { id: "BG-0142", verification_id: "XM-0142", unit: "K01", customer: "Nguyễn Thị Mai", status: "WAITING", method: null }, + { id: "BG-0131", verification_id: "XM-0131", unit: "K08", customer: "Phan Quốc Huy", status: "WAITING", method: null }, + { id: "BG-0135", verification_id: "XM-0135", unit: "K11", customer: "Đặng Thu Trang", status: "WAITING", method: null }, ], // S04 · Kiểm tra trả kho returns: [ { - id: "TK-0098", contract: "HĐ-0098", unit: "C-012", customer: "Lê Văn An", appointment: at(pickup, "10:00"), + id: "TK-0098", contract: "HĐ-0098", unit: "K04", customer: "Lê Văn An", appointment: at(pickup, "10:00"), deposit: 1150000, unpaid: 460000, status: "SCHEDULED", report: null, }, ], @@ -145,47 +123,46 @@ export function createOpsData(t = today()) { // S05 · Yêu cầu hỗ trợ tại cơ sở tickets: [ { - id: "HT-0082", unit: "B-015", customer: "Nguyễn Thị Mai", title: "Thẻ ra vào không mở được cổng", created_at: at(t, "09:45"), + id: "HT-0082", unit: "K12", customer: "Nguyễn Thị Mai", title: "Thẻ ra vào không mở được cổng", created_at: at(t, "09:45"), schedule: at(t, "14:00"), status: "OPEN", assignee: null, notes: [], }, { - id: "HT-0079", unit: "A-045", customer: "Trần Quốc Bảo", title: "Cửa cuốn kho kẹt khi mở", created_at: at(addDays(t, -1), "16:20"), + id: "HT-0079", unit: "K03", customer: "Trần Quốc Bảo", title: "Cửa cuốn kho kẹt khi mở", created_at: at(addDays(t, -1), "16:20"), schedule: at(addDays(t, 1), "09:00"), status: "IN_PROGRESS", assignee: "NV-01", notes: [], }, ], // M03 · Yêu cầu gia hạn chờ duyệt renewals: [ - { id: "GH-0208", contract: "HĐ-0088", customer: "Lê Văn Tùng", unit: "C-208", from: addDays(t, 14), to: addMonths(addDays(t, 14), 3), months: 3, requested: at(addDays(t, -1), "10:05"), status: "PENDING" }, - { id: "GH-0077", contract: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "F-077", from: addDays(t, 6), to: addMonths(addDays(t, 6), 3), months: 3, requested: at(addDays(t, -2), "15:40"), status: "PENDING" }, - { id: "GH-0015", contract: "HĐ-2026-0086", customer: "Nguyễn Thị Mai", unit: "B-015", from: addDays(t, 5), to: addMonths(addDays(t, 5), 1), months: 1, requested: at(addDays(t, -2), "08:12"), status: "PENDING" }, - { id: "GH-0120", contract: "HĐ-0120", customer: "Lê Minh Châu", unit: "E-120", from: addDays(t, 9), to: addMonths(addDays(t, 9), 6), months: 6, requested: at(addDays(t, -3), "19:02"), status: "PENDING" }, + { id: "GH-0208", contract: "HĐ-0088", customer: "Lê Văn Tùng", unit: "K02", from: addDays(t, 14), to: addMonths(addDays(t, 14), 3), months: 3, requested: at(addDays(t, -1), "10:05"), status: "PENDING" }, + { id: "GH-0077", contract: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "K07", from: addDays(t, 6), to: addMonths(addDays(t, 6), 3), months: 3, requested: at(addDays(t, -2), "15:40"), status: "PENDING" }, + { id: "GH-0015", contract: "HĐ-2026-0086", customer: "Nguyễn Thị Mai", unit: "K12", from: addDays(t, 5), to: addMonths(addDays(t, 5), 1), months: 1, requested: at(addDays(t, -2), "08:12"), status: "PENDING" }, ], // M07 · Hợp đồng quá hạn / cần xử lý contracts: [ - { id: "HĐ-0061", customer: "Trần Quốc Bảo", unit: "A-045", end: addDays(t, -3), due: "Tiền thuê kỳ mới · Chưa thanh toán", amount: 1250000, state: "OVERDUE", reminders: [] }, - { id: "HĐ-0098", customer: "Lê Văn An", unit: "C-012", end: addDays(t, -4), due: "460.000 đ · Chờ đối soát", amount: 460000, state: "OVERDUE", reminders: [] }, - { id: "HĐ-0073", customer: "Hoàng Thị Lan", unit: "D-019", end: addDays(t, -3), due: "Tiền thuê kỳ mới · Chưa thanh toán", amount: 1380000, state: "OVERDUE", reminders: [] }, - { id: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "F-077", end: addDays(t, 6), due: "Yêu cầu gia hạn", amount: 0, state: "RENEWAL", reminders: [] }, + { id: "HĐ-0061", customer: "Trần Quốc Bảo", unit: "K03", end: addDays(t, -3), due: "Tiền thuê kỳ mới · Chưa thanh toán", amount: 1250000, state: "OVERDUE", reminders: [] }, + { id: "HĐ-0098", customer: "Lê Văn An", unit: "K04", end: addDays(t, -4), due: "460.000 đ · Chờ đối soát", amount: 460000, state: "OVERDUE", reminders: [] }, + { id: "HĐ-0073", customer: "Hoàng Thị Lan", unit: "K10", end: addDays(t, -3), due: "Tiền thuê kỳ mới · Chưa thanh toán", amount: 1380000, state: "OVERDUE", reminders: [] }, + { id: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "K07", end: addDays(t, 6), due: "Yêu cầu gia hạn", amount: 0, state: "RENEWAL", reminders: [] }, ], // M06 · Công việc được phân công assignments: [ - { id: "PC-01", title: "Bàn giao A-102 · Nguyễn Thị Mai", when: at(pickup, "09:00"), staff: "NV-01", status: "ACCEPTED", ref: "BG-0142" }, - { id: "PC-02", title: "Kiểm tra trả kho C-012", when: at(pickup, "10:00"), staff: "NV-01", status: "WAITING", ref: "TK-0098" }, + { id: "PC-01", title: "Bàn giao K01 · Nguyễn Thị Mai", when: at(pickup, "09:00"), staff: "NV-01", status: "ACCEPTED", ref: "BG-0142" }, + { id: "PC-02", title: "Kiểm tra trả kho K04 · Lê Văn An", when: at(pickup, "10:00"), staff: "NV-01", status: "WAITING", ref: "TK-0098" }, { id: "PC-03", title: "HT-0082 · Lỗi thẻ ra vào", when: at(t, "14:00"), staff: null, status: "OPEN", ref: "HT-0082" }, ], - // M04 · Doanh thu 6 tháng gần nhất (triệu đồng) và cơ cấu theo loại kho + // M04 · Doanh thu thuê và phí 6 tháng gần nhất (triệu đồng) và cơ cấu theo loại kho của tháng này revenue: { - months: [66.0, 72.7, 69.6, 81.3, 87.0, 92.4].map((value, i) => { + months: [11.2, 12.4, 11.9, 13.1, 14.6, 15.8].map((value, i) => { const m = new Date(`${addMonths(t.slice(0, 8) + "01", i - 5)}T00:00:00`); return { label: `Tháng ${m.getMonth() + 1}`, month: m.getMonth() + 1, year: m.getFullYear(), value }; }), by_type: [ - { label: "Kho thường", value: 58.4 }, - { label: "Kiểm soát nhiệt độ", value: 34.0 }, + { label: "Kho thường", value: 10.6 }, + { label: "Kho lạnh", value: 5.2 }, ], as_of: t, }, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js index 4b02ec3..e35bed9 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js @@ -15,10 +15,12 @@ const addLog = (state, now, text, to, role = "ALL") => ({ log: [{ id: `L-${now.getTime()}-${state.log.length}`, text, to, role, at: iso(now), read: false }, ...state.log].slice(0, 60), }); -// Diện tích từ nhãn gói ("Kho thường · 10–20 m²") → khoảng m² +// Diện tích từ nhãn gói → khoảng m² ("Kho lạnh · Cỡ M · 15 m²" → [15, 15]; nhãn cũ "10–20 m²" → [10, 20]) export function areaRange(offer = "") { const m = offer.match(/(\d+)\s*[–-]\s*(\d+)\s*m²/); if (m) return [Number(m[1]), Number(m[2])]; + const one = offer.match(/(\d+)\s*m²/); + if (one) return [Number(one[1]), Number(one[1])]; if (/Trên\s*20/.test(offer)) return [20, 999]; return [0, 999]; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx index dab6eb4..529a620 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx @@ -6,7 +6,7 @@ import { reduceOps } from "./reducer"; // Kho dữ liệu vận hành cho khu Nhân viên & Quản lý cơ sở. // - mode "api": đọc GET /api/ops/board, mỗi thao tác gọi endpoint tương ứng (ops/api.js) rồi nạp lại. -// - backend chưa có API (404) hoặc chạy không backend: dữ liệu mẫu lưu trong trình duyệt, dùng chung +// - backend không có /api/ops (404, bản backend cũ) hoặc chạy không backend: dữ liệu cục bộ lưu trong trình duyệt, dùng chung // giữa nhân viên và quản lý (thao tác bên này hiện ngay bên kia, kể cả khác tab). export const OPS_KEY = "safespace.ops.v1"; const OpsContext = createContext(null); @@ -49,7 +49,7 @@ export function OpsProvider({ children, notify, mode = "local", onApiError }) { setSource("api"); } catch (e) { if (e instanceof ApiError && (e.status === 404 || e.status === 405)) { - // Backend chưa có endpoint vận hành → dữ liệu mẫu + // Backend không có endpoint vận hành (bản cũ) → dữ liệu cục bộ commit(readOps()); setSource("local"); } else { @@ -63,7 +63,7 @@ export function OpsProvider({ children, notify, mode = "local", onApiError }) { if (mode === "api") reload(); }, [mode, reload]); - // Lưu + đồng bộ giữa các tab khi dùng dữ liệu mẫu + // Lưu + đồng bộ giữa các tab khi dùng dữ liệu cục bộ useEffect(() => { if (source !== "local" || !state) return; try { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx index 9f07dae..fae43e6 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx @@ -441,7 +441,18 @@ function ApiProvider({ children }) { if (!r) return fail("Không tìm thấy đơn đặt chỗ.", "NOT_FOUND"); if (r.status === "CANCELLED") return fail("Đơn đặt chỗ đã hết thời gian giữ chỗ.", "EXPIRED"); if (r.status !== "PENDING_PAYMENT") return { ok: true, reservation_id: r.reservation_id }; - updateOverlay((o) => ({ ...o, transfers: { ...o.transfers, [r.api_id]: Date.now() } })); + try { + await api.confirmTransfer(r.api_id); + } catch (e) { + if (e instanceof ApiError && e.data?.code === "EXPIRED") { + await loadCustomer().catch(() => {}); + return fail(e.message, "EXPIRED"); + } + // Backend cũ chưa có confirm-transfer: ghi nhận tạm trên trình duyệt như trước + if (!(e instanceof ApiError && (e.status === 404 || e.status === 405))) throw e; + updateOverlay((o) => ({ ...o, transfers: { ...o.transfers, [r.api_id]: Date.now() } })); + } + await loadCustomer().catch(() => {}); remember("Đã nhận thông tin đặt chỗ", `${shortCode(r.reservation_id)} · Chờ nhân viên đối soát chuyển khoản.`, "reservations", `Đơn ${shortCode(r.reservation_id)} đã gửi — chờ đối soát thanh toán`); return { ok: true, reservation_id: r.reservation_id }; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js index 603b5bc..218f384 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js @@ -121,3 +121,12 @@ test("tên đăng nhập backend sinh từ email (≤ 50 ký tự)", () => { assert.equal(usernameFromEmail(" Mai.Tran@Example.com "), "mai.tran@example.com"); assert.ok(usernameFromEmail(`${"a".repeat(60)}@example.com`).length <= 50); }); + +test("backend trả PENDING_VERIFICATION (confirm-transfer) → chờ đối soát, không bị huỷ theo giờ giữ chỗ trong trình duyệt", () => { + const verifying = { ...remote, reservations: remote.reservations.map((r) => (r.reservationId === 2 ? { ...r, status: "PENDING_VERIFICATION" } : r)) }; + const hold = { holds: { 2: NOW.getTime() - 10000 } }; + const later = new Date(NOW.getTime() + 55000); + const d = composeData({ catalog, remote: verifying, overlay: hold, session, timeoutSeconds: 60, now: later }); + assert.equal(d.reservations[1].status, "PENDING_VERIFICATION"); + assert.equal(reservationsToExpire({ remote: verifying, overlay: { holds: hold.holds, transfers: {} }, timeoutSeconds: 60, now: later }).length, 0); +}); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops-api.test.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops-api.test.mjs index e4cd0df..e23a4e2 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops-api.test.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops-api.test.mjs @@ -59,7 +59,7 @@ test("khu vận hành qua API: nhân viên xử lý, quản lý phân bổ / duy board = fromApi((await call("GET", "/api/ops/board", undefined, manager)).data); assert.equal(board.units.find((u) => u.code === unit.code).status, "WAITING_HANDOVER"); - assert.equal(board.units.find((u) => u.code === "A-102").status, "ACTIVE"); + assert.equal(board.units.find((u) => u.code === "K01").status, "ACTIVE"); assert.equal(board.contracts.find((c) => c.id === "HĐ-0098").state, "CLOSED"); assert.ok(board.revenue.by_type.length === 2, "báo cáo có cơ cấu theo loại kho"); } finally { @@ -78,3 +78,25 @@ test("backend chưa bật ops → GET /api/ops/board trả 404 (giao diện chuy server.close(); } }); + +test("khách báo đã chuyển khoản qua API → PENDING_VERIFICATION, gọi lại vẫn an toàn; đơn không còn chờ thì báo lỗi", async () => { + const { server } = await startMockApi(PORT + 2); + try { + const url = `http://localhost:${PORT + 2}`; + const post = async (path, token) => { + const res = await fetch(url + path, { method: "POST", headers: { Authorization: `Bearer ${token}` } }); + return { status: res.status, data: await res.json() }; + }; + const { token } = await (await fetch(`${url}/api/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: "customer01", password: "Customer@123" }) })).json(); + let out = await post("/api/reservations/2/confirm-transfer", token); + assert.equal(out.status, 200); + assert.equal(out.data.status, "PENDING_VERIFICATION"); + out = await post("/api/reservations/2/confirm-transfer", token); + assert.equal(out.status, 200, "bấm hai lần không lỗi"); + out = await post("/api/reservations/1/confirm-transfer", token); + assert.equal(out.status, 400, "đơn đã nhận kho không còn chờ chuyển khoản"); + assert.equal((await post("/api/reservations/999/confirm-transfer", token)).status, 404); + } finally { + server.close(); + } +}); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js index ae0418d..9d51f96 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js @@ -7,10 +7,14 @@ import { candidateUnits, reduceOps } from "../src/ops/reducer.js"; const T = "2026-09-14"; const run = (s, type, payload) => reduceOps(s, { type, payload }, new Date(`${T}T10:00:00`)); -test("dữ liệu khởi tạo: 86 kho, 3 khoản chờ đối soát, 3 khách cần xác minh", () => { +test("dữ liệu khởi tạo: 12 ô theo D17, 3 khoản chờ đối soát, 3 khách cần xác minh", () => { const s = createOpsData(T); - assert.equal(s.units.length, 86); - assert.equal(new Set(s.units.map((u) => u.code)).size, 86); + assert.equal(s.units.length, 12); + assert.deepEqual(s.units.map((u) => u.code), ["K01", "K02", "K03", "K04", "K05", "K06", "K07", "K08", "K09", "K10", "K11", "K12"]); + assert.deepEqual(s.units.map((u) => `${u.type}:${u.area}`).join(" "), "normal:15 normal:15 normal:15 normal:15 climate:15 climate:15 normal:30 normal:30 normal:30 normal:30 climate:30 climate:30"); + // Mọi ô được nhắc tới trong việc vận hành đều có thật trong sơ đồ + const codes = new Set(s.units.map((u) => u.code)); + for (const x of [...s.verifications, ...s.handovers, ...s.returns, ...s.tickets, ...s.renewals, ...s.contracts]) assert.ok(codes.has(x.unit), x.id); assert.equal(s.payments.filter((p) => p.status === "PENDING").length, 3); assert.equal(s.verifications.filter((v) => v.status === "TODO").length, 3); assert.equal(s.revenue.months.at(-1).label, "Tháng 9"); @@ -23,7 +27,7 @@ test("đối soát đơn chưa có kho → chuyển quản lý phân bổ, rồi s = out.state; const a = s.allocations.find((x) => x.id === "SS-20260913-0147"); assert.equal(a.type, "climate"); - assert.deepEqual([a.min_area, a.max_area], [2, 5]); + assert.deepEqual([a.min_area, a.max_area], [15, 15]); const unit = candidateUnits(s, a)[0]; assert.ok(unit); out = run(s, "ALLOCATE", { id: a.id, unit: unit.code }); @@ -40,7 +44,7 @@ test("không bàn giao khi chưa xác minh; xác minh rồi bàn giao thì kho h s = run(s, "VERIFY_CUSTOMER", { id: "XM-0142", doc_type: "CCCD", doc_no: "079123456789", photo_ok: true, info_ok: true }).state; assert.equal(s.verifications.find((v) => v.id === "XM-0142").doc_last4, "6789"); s = run(s, "HANDOVER", { id: "BG-0142", method: "PIN" }).state; - assert.equal(s.units.find((u) => u.code === "A-102").status, "ACTIVE"); + assert.equal(s.units.find((u) => u.code === "K01").status, "ACTIVE"); }); test("trả kho → quản lý xác nhận hoàn cọc = cọc − khoản nợ, kho trống lại", () => { @@ -49,7 +53,7 @@ test("trả kho → quản lý xác nhận hoàn cọc = cọc − khoản nợ, assert.equal(s.contracts.find((c) => c.id === "HĐ-0098").state, "RETURNED"); const out = run(s, "CONFIRM_REFUND", { id: "HĐ-0098" }); assert.equal(out.result.refund, 1150000 - 460000); - assert.equal(out.state.units.find((u) => u.code === "C-012").status, "EMPTY"); + assert.equal(out.state.units.find((u) => u.code === "K04").status, "EMPTY"); }); test("duyệt / từ chối gia hạn; từ chối bắt buộc có lý do", () => { @@ -59,7 +63,7 @@ test("duyệt / từ chối gia hạn; từ chối bắt buộc có lý do", () assert.equal(s.contracts.find((c) => c.id === "HĐ-0077").state, "RESOLVED"); s = run(s, "DECIDE_RENEWAL", { id: "GH-0208", approve: true }).state; const r = s.renewals.find((x) => x.id === "GH-0208"); - assert.equal(s.units.find((u) => u.code === "C-208").end, r.to); + assert.equal(s.units.find((u) => u.code === "K02").end, r.to); }); test("phân công việc hỗ trợ cho nhân viên → yêu cầu chuyển sang đang xử lý", () => { diff --git a/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs new file mode 100644 index 0000000..979eb0e --- /dev/null +++ b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs @@ -0,0 +1,129 @@ +using System.Security.Claims; +using StorageProject.Api.Extensions; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Interfaces; + +namespace StorageProject.Api.Endpoints; + +/// +/// Khu Nhân viên cơ sở (Figma S01–S09) và Quản lý cơ sở (M01–M08) — BACKEND-TODO.md mục A2, A3. +/// Role STAFF hoặc MANAGER; thao tác của quản lý trả 403 với nhân viên. Chỉ dữ liệu cơ sở được phân công (SRS A06). +/// Lỗi: 400 { error } · 403 { error } · 404 { error }. +/// +public static class FacilityOpsEndpoints +{ + public static void MapFacilityOpsEndpoints(this IEndpointRouteBuilder routes) + { + var group = routes.MapGroup("/api/ops") + .WithTags("Facility Operations") + .RequireAuthorization(policy => policy.RequireRole("STAFF", "MANAGER")); + + group.MapGet("/board", (ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => Results.Ok(ToJson(await ops.GetBoardAsync(Actor(user), ct))))) + .WithSummary("Dữ liệu vận hành của cơ sở được phân công (nhân viên: S01–S09; quản lý: thêm M01–M08)"); + + // ---- Nhân viên (quản lý cũng làm được) + group.MapPost("/payments/{id}/confirm", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.ConfirmPaymentAsync(Actor(user), id, ct); return Done(); })) + .WithSummary("S09 · Xác nhận đã thu: đơn PENDING_VERIFICATION → CONFIRMED, chuyển quản lý phân bổ ô"); + + group.MapPost("/payments/{id}/mismatch", (string id, OpsNoteRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.ReportMismatchAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S09 · Báo sai lệch chuyển khoản (note bắt buộc)"); + + group.MapPost("/verifications/{id}", (string id, OpsVerifyRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.VerifyCustomerAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S02 · Xác minh khách nhận kho; chỉ lưu 4 số cuối giấy tờ"); + + group.MapPost("/handovers/{id}/complete", (string id, OpsHandoverRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.CompleteHandoverAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S03 · Bàn giao kho (CARD / PIN / FINGER): hợp đồng ACTIVE, ô OCCUPIED, cấp phương thức mở khoá"); + + group.MapPost("/returns/{id}/inspection", (string id, OpsReturnInspectionRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.SubmitReturnInspectionAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S04 · Biên bản kiểm tra trả kho; ô → INSPECTION, chờ quản lý hoàn cọc"); + + group.MapPost("/tickets/{id}/responses", (string id, OpsTicketResponseRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.RespondTicketAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S05 · Phản hồi yêu cầu hỗ trợ: IN_PROGRESS / WAITING_CUSTOMER / DONE"); + + // ---- Chỉ quản lý cơ sở + group.MapPost("/allocations/{id}", (string id, OpsAllocateRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.AllocateAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("M05 · Phân bổ ô trống đúng loại cho đơn đã đối soát → hợp đồng nháp + lịch bàn giao"); + + group.MapPut("/assignments/{id}", (string id, OpsAssignRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.AssignAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("M06 · Giao việc bàn giao / trả kho / hỗ trợ cho nhân viên cùng cơ sở"); + + group.MapPost("/renewals/{id}/approve", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.ApproveRenewalAsync(Actor(user), id, ct); return Done(); })) + .WithSummary("M03 · Duyệt gia hạn: cập nhật ngày hết hạn, tạo khoản gia hạn chờ thanh toán"); + + group.MapPost("/renewals/{id}/reject", (string id, OpsRejectRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.RejectRenewalAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("M03 · Từ chối gia hạn (reason bắt buộc)"); + + group.MapPost("/contracts/{id}/reminders", (string id, OpsNoteRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.RemindAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("M07 · Ghi lần nhắc khách (quá hạn / còn nợ)"); + + group.MapPost("/contracts/{id}/refund", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => + { + var refund = await ops.ConfirmRefundAsync(Actor(user), id, ct); + return Results.Ok(new { message = "Đã cập nhật.", refund }); + })) + .WithSummary("M07 · Xác nhận hoàn cọc sau biên bản trả kho: cọc − khoản còn nợ, đóng hợp đồng, ô trống lại"); + } + + private static OpsActor Actor(ClaimsPrincipal user) => new(user.GetUserId(), user.IsInRole("MANAGER")); + + private static IResult Done() => Results.Ok(new { message = "Đã cập nhật." }); + + /// + /// Nhân viên không nhận các phần của quản lý — bỏ hẳn khoá thay vì trả null, + /// vì giao diện gộp kết quả vào giá trị mặc định (src/ops/api.js loadBoard). + /// + private static Dictionary ToJson(OpsBoardDto b) + { + var json = new Dictionary + { + ["facility"] = b.Facility, + ["me"] = b.Me, + ["staff"] = b.Staff, + ["units"] = b.Units, + ["payments"] = b.Payments, + ["verifications"] = b.Verifications, + ["handovers"] = b.Handovers, + ["returns"] = b.Returns, + ["tickets"] = b.Tickets, + }; + if (b.Allocations != null) json["allocations"] = b.Allocations; + if (b.Renewals != null) json["renewals"] = b.Renewals; + if (b.Contracts != null) json["contracts"] = b.Contracts; + if (b.Assignments != null) json["assignments"] = b.Assignments; + if (b.Revenue != null) json["revenue"] = b.Revenue; + return json; + } + + private static async Task Run(Func> action) + { + try + { + return await action(); + } + catch (UnauthorizedAccessException ex) + { + return Results.Json(new { error = ex.Message }, statusCode: StatusCodes.Status403Forbidden); + } + catch (KeyNotFoundException ex) + { + return Results.NotFound(new { error = ex.Message }); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + return Results.BadRequest(new { error = ex.Message }); + } + } +} diff --git a/StorageProject.Api/Endpoints/ReservationEndpoints.cs b/StorageProject.Api/Endpoints/ReservationEndpoints.cs index 4a57382..696c95b 100644 --- a/StorageProject.Api/Endpoints/ReservationEndpoints.cs +++ b/StorageProject.Api/Endpoints/ReservationEndpoints.cs @@ -1,6 +1,7 @@ using System.Security.Claims; using StorageProject.Api.Extensions; using StorageProject.Core.DTOs.Reservation; +using StorageProject.Core.Exceptions; using StorageProject.Core.Interfaces; namespace StorageProject.Api.Endpoints; @@ -57,6 +58,29 @@ public static RouteGroupBuilder MapReservationEndpoints(this IEndpointRouteBuild } }); + // C04 / F03: khách báo đã chuyển khoản → PENDING_VERIFICATION (nhân viên đối soát ở S09) + group.MapPost("/{id:long}/confirm-transfer", async (long id, ClaimsPrincipal user, IReservationService reservationService, CancellationToken ct) => + { + try + { + var reservation = await reservationService.ConfirmTransferAsync(user.GetUserId(), id, ct); + return Results.Ok(reservation); + } + catch (KeyNotFoundException ex) + { + return Results.NotFound(new { error = ex.Message }); + } + catch (ReservationExpiredException ex) + { + return Results.BadRequest(new { error = ex.Message, code = "EXPIRED" }); + } + catch (InvalidOperationException ex) + { + return Results.BadRequest(new { error = ex.Message }); + } + }) + .WithSummary("Khách báo đã chuyển khoản: đơn chuyển sang chờ nhân viên đối soát (PENDING_VERIFICATION)"); + return group; } } diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs index eaa3f52..75acbe2 100644 --- a/StorageProject.Api/Program.cs +++ b/StorageProject.Api/Program.cs @@ -90,6 +90,7 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); var app = builder.Build(); @@ -120,6 +121,7 @@ app.MapSupportTicketEndpoints(); app.MapAdminEndpoints(); app.MapOperationsEndpoints(); +app.MapFacilityOpsEndpoints(); // Root status check app.MapGet("/health", () => Results.Ok(new diff --git a/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs b/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs new file mode 100644 index 0000000..0ce72e3 --- /dev/null +++ b/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs @@ -0,0 +1,88 @@ +namespace StorageProject.Core.DTOs.FacilityOps; + +// Khu Nhân viên cơ sở (Figma S01–S09) và Quản lý cơ sở (M01–M08) — GET /api/ops/board và các thao tác. +// Hình dạng JSON khớp src/ops/api.js + mẫu trong BACKEND-TODO.md (camelCase, id dạng chuỗi). +// Ngày "yyyy-MM-dd"; ngày giờ là giờ Việt Nam dạng "yyyy-MM-ddTHH:mm:ss" (giao diện hiển thị nguyên giờ). + +/// Người đang gọi API: STAFF hoặc MANAGER (quản lý làm được mọi việc của nhân viên). +public record OpsActor(long UserId, bool IsManager); + +public record OpsFacilityInfoDto(long FacilityId, string Name, string Address); + +public record OpsStaffDto(string StaffId, string FullName, string Shift); + +public record OpsUnitDto(string Code, string? Tenant, decimal Area, string Floor, string Type, string Status, DateOnly? End); + +public record OpsPaymentDto( + string Id, string Customer, decimal Amount, string Method, string ReportedAt, string Memo, string Offer, + DateOnly Start, DateOnly End, string Pickup, string Status, string? Note, string? HandledAt); + +public record OpsAllocationDto( + string Id, string Customer, string Type, string Offer, decimal MinArea, decimal MaxArea, + DateOnly Start, DateOnly End, string Pickup, string Status, string? Unit); + +public record OpsVerificationDto( + string Id, string ReservationId, string Customer, string Unit, string Appointment, string Status, + string? DocType, string? DocLast4, string? VerifiedAt); + +public record OpsHandoverDto(string Id, string VerificationId, string Unit, string Customer, string Status, string? Method, string? DoneAt); + +public record OpsReturnReportDto(string Items, string Walls, string Keys, string Proposal); + +public record OpsReturnDto( + string Id, string Contract, string Unit, string Customer, string Appointment, decimal Deposit, decimal Unpaid, + string Status, OpsReturnReportDto? Report, string? SubmittedAt); + +public record OpsNoteDto(string Text, string At, string? Staff); + +public record OpsTicketDto( + string Id, string Unit, string Customer, string Title, string CreatedAt, string Schedule, string Status, + string? Assignee, IReadOnlyList Notes); + +public record OpsRenewalDto( + string Id, string Contract, string Customer, string Unit, DateOnly From, DateOnly To, int Months, + string Requested, string Status, string? Reason, string? DecidedAt); + +public record OpsReminderDto(string Text, string At); + +public record OpsContractDto( + string Id, string Customer, string Unit, DateOnly End, string Due, decimal Amount, string State, + IReadOnlyList Reminders); + +public record OpsAssignmentDto(string Id, string Title, string When, string? Staff, string Status, string Ref); + +public record OpsRevenueMonthDto(string Label, int Month, int Year, decimal Value); + +public record OpsRevenueTypeDto(string Label, decimal Value); + +public record OpsRevenueDto(IReadOnlyList Months, IReadOnlyList ByType, DateOnly AsOf); + +/// +/// Dữ liệu vận hành của cơ sở được phân công. Nhân viên chỉ nhận phần S01–S09; +/// các phần của quản lý (allocations … revenue) để null và không được trả về. +/// +public record OpsBoardDto( + OpsFacilityInfoDto Facility, + OpsStaffDto? Me, + IReadOnlyList Staff, + IReadOnlyList Units, + IReadOnlyList Payments, + IReadOnlyList Verifications, + IReadOnlyList Handovers, + IReadOnlyList Returns, + IReadOnlyList Tickets, + IReadOnlyList? Allocations, + IReadOnlyList? Renewals, + IReadOnlyList? Contracts, + IReadOnlyList? Assignments, + OpsRevenueDto? Revenue); + +// ---- Thân request (BACKEND-TODO A2, A3) +public record OpsNoteRequest(string? Note); +public record OpsVerifyRequest(string? DocType, string? DocNumber, bool PhotoMatched, bool InfoMatched); +public record OpsHandoverRequest(string? UnlockMethod); +public record OpsReturnInspectionRequest(string? Items, string? Walls, string? Keys, string? Proposal); +public record OpsTicketResponseRequest(string? Note, string? NextStatus); +public record OpsRejectRequest(string? Reason); +public record OpsAllocateRequest(string? UnitCode); +public record OpsAssignRequest(string? StaffId); diff --git a/StorageProject.Core/Entities/Reservation.cs b/StorageProject.Core/Entities/Reservation.cs index ff0e9f0..e941755 100644 --- a/StorageProject.Core/Entities/Reservation.cs +++ b/StorageProject.Core/Entities/Reservation.cs @@ -13,7 +13,7 @@ public class Reservation public decimal QuotedMonthlyRate { get; set; } public decimal EstimatedAmount { get; set; } public decimal RequiredDeposit { get; set; } - // PENDING_PAYMENT, CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW + // PENDING_PAYMENT, PENDING_VERIFICATION (khách báo đã chuyển khoản, chờ đối soát), CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW public string Status { get; set; } = "PENDING_PAYMENT"; public string? CancellationReason { get; set; } public DateTime CreatedAt { get; set; } diff --git a/StorageProject.Core/Exceptions/ReservationExpiredException.cs b/StorageProject.Core/Exceptions/ReservationExpiredException.cs new file mode 100644 index 0000000..7e124c0 --- /dev/null +++ b/StorageProject.Core/Exceptions/ReservationExpiredException.cs @@ -0,0 +1,4 @@ +namespace StorageProject.Core.Exceptions; + +/// Đơn đặt chỗ đã quá thời gian giữ chỗ. Endpoint trả 400 kèm code = "EXPIRED" (BE-CONTRACT C04). +public class ReservationExpiredException(string message) : InvalidOperationException(message); diff --git a/StorageProject.Core/Interfaces/IFacilityOpsService.cs b/StorageProject.Core/Interfaces/IFacilityOpsService.cs new file mode 100644 index 0000000..ac9cd6f --- /dev/null +++ b/StorageProject.Core/Interfaces/IFacilityOpsService.cs @@ -0,0 +1,30 @@ +using StorageProject.Core.DTOs.FacilityOps; + +namespace StorageProject.Core.Interfaces; + +/// +/// Khu Nhân viên cơ sở (UC07–UC12) và Quản lý cơ sở (UC13–UC18), chỉ trong cơ sở được phân công (SRS A06). +/// Lỗi: KeyNotFoundException → 404 · InvalidOperationException/ArgumentException → 400 · +/// UnauthorizedAccessException → 403 (chưa được phân công cơ sở / không đủ quyền). +/// Id trong đường dẫn là mã hiển thị ("SS-20261014-0012", "BG-0007", "HĐ-2026-0003"…). +/// +public interface IFacilityOpsService +{ + Task GetBoardAsync(OpsActor actor, CancellationToken ct = default); + + // Nhân viên (và quản lý) + Task ConfirmPaymentAsync(OpsActor actor, string id, CancellationToken ct = default); + Task ReportMismatchAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default); + Task VerifyCustomerAsync(OpsActor actor, string id, OpsVerifyRequest request, CancellationToken ct = default); + Task CompleteHandoverAsync(OpsActor actor, string id, OpsHandoverRequest request, CancellationToken ct = default); + Task SubmitReturnInspectionAsync(OpsActor actor, string id, OpsReturnInspectionRequest request, CancellationToken ct = default); + Task RespondTicketAsync(OpsActor actor, string id, OpsTicketResponseRequest request, CancellationToken ct = default); + + // Chỉ quản lý + Task AllocateAsync(OpsActor actor, string id, OpsAllocateRequest request, CancellationToken ct = default); + Task AssignAsync(OpsActor actor, string id, OpsAssignRequest request, CancellationToken ct = default); + Task ApproveRenewalAsync(OpsActor actor, string id, CancellationToken ct = default); + Task RejectRenewalAsync(OpsActor actor, string id, OpsRejectRequest request, CancellationToken ct = default); + Task RemindAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default); + Task ConfirmRefundAsync(OpsActor actor, string id, CancellationToken ct = default); +} diff --git a/StorageProject.Core/Interfaces/IServices.cs b/StorageProject.Core/Interfaces/IServices.cs index 9571868..16a198c 100644 --- a/StorageProject.Core/Interfaces/IServices.cs +++ b/StorageProject.Core/Interfaces/IServices.cs @@ -31,6 +31,7 @@ public interface IReservationService Task GetReservationDetailAsync(long customerId, long reservationId, CancellationToken ct = default); Task CreateReservationAsync(long customerId, CreateReservationRequest request, CancellationToken ct = default); Task CancelReservationAsync(long customerId, long reservationId, string reason, CancellationToken ct = default); + Task ConfirmTransferAsync(long customerId, long reservationId, CancellationToken ct = default); } public interface IContractService diff --git a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs index b4be776..a482679 100644 --- a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs +++ b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs @@ -15,7 +15,7 @@ public void Configure(EntityTypeBuilder b) t.HasCheckConstraint("CK_reservations_estimated_amount", "[EstimatedAmount] >= 0"); t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); t.HasCheckConstraint("CK_reservations_status", - "[Status] IN ('PENDING_PAYMENT','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); }); b.HasKey(r => r.ReservationId); b.Property(r => r.ReservationId).UseIdentityColumn(); diff --git a/StorageProject.Infrastructure/Data/DbSeeder.Catalog.cs b/StorageProject.Infrastructure/Data/DbSeeder.Catalog.cs new file mode 100644 index 0000000..4d50dac --- /dev/null +++ b/StorageProject.Infrastructure/Data/DbSeeder.Catalog.cs @@ -0,0 +1,197 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Data; + +/// +/// Danh mục kho theo D17 (Figma 14/10): +/// - 4 loại kho: thường / lạnh × cỡ M (15 m²) / cỡ L (30 m²). +/// - 12 cơ sở SafeSpace (khớp src/data/seed.js của giao diện), cơ sở nào cũng có kho lạnh. +/// - Mỗi cơ sở 12 ô: 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). +/// - Giá = giá gốc cơ sở × hệ số cỡ (M 1, L 1,75) × hệ số loại (thường 1, lạnh 1,2), làm tròn 10.000 đ +/// — cùng công thức với src/lib/catalog.js. +/// Dữ liệu cũ (cỡ S/M/L/XL, cơ sở "Quận 7") được ngừng dùng, không xoá để giữ lịch sử. +/// +public static partial class DbSeeder +{ + public sealed record SeedCatalog(Facility Home, UnitType NormalM, UnitType NormalL, UnitType ColdM, UnitType ColdL); + + private sealed record SeedFacility(string Name, string District, decimal BasePrice, string Street, string Phone, string? OldAddress = null); + + // Thứ tự và giá gốc giống src/data/seed.js. Cơ sở đầu tiên là nơi staff01 / manager01 phụ trách. + private static readonly SeedFacility[] SafeSpaceFacilities = + [ + new("SafeSpace Nguyễn Lương Bằng", "Quận 7", 1150000m, "Số 12 Nguyễn Lương Bằng, Tân Phú", "02837001012", + "12 Nguyễn Lương Bằng, Phường Tân Phú, Quận 7, TP. Hồ Chí Minh"), + new("SafeSpace Him Lam", "Quận 7", 1050000m, "Khu dân cư Him Lam, Tân Hưng", "02837001013", + "Khu dân cư Him Lam, Phường Tân Hưng, Quận 7, TP. Hồ Chí Minh"), + new("SafeSpace Phú Xuân", "Quận 7", 890000m, "Đường Nguyễn Hữu Thọ, Phú Xuân", "02837001014", + "Đường Nguyễn Hữu Thọ, Xã Phú Xuân, Huyện Nhà Bè, TP. Hồ Chí Minh"), + new("SafeSpace Tân Thuận", "Quận 7", 1100000m, "Đường Huỳnh Tấn Phát, Tân Thuận", "02837001015", + "Đường Huỳnh Tấn Phát, Phường Tân Thuận Đông, Quận 7, TP. Hồ Chí Minh"), + new("SafeSpace Phú Mỹ Hưng", "Quận 7", 1250000m, "Đường Nguyễn Lương Bằng, Tân Phong", "02837001016", + "Đường Nguyễn Văn Linh, Phường Tân Phong, Quận 7, TP. Hồ Chí Minh"), + new("SafeSpace Bình Thạnh", "Quận Bình Thạnh", 980000m, "Đường Nguyễn Xí, Phường 26", "02837001017", + "Đường Nguyễn Xí, Phường 26, Quận Bình Thạnh, TP. Hồ Chí Minh"), + new("SafeSpace Nhà Bè", "Huyện Nhà Bè", 850000m, "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè", "02837001018", + "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè, Huyện Nhà Bè, TP. Hồ Chí Minh"), + new("SafeSpace Bình Chánh", "Huyện Bình Chánh", 790000m, "Quốc lộ 50, Bình Hưng", "02837001019", + "Quốc lộ 50, Xã Bình Hưng, Huyện Bình Chánh, TP. Hồ Chí Minh"), + new("SafeSpace Thủ Đức", "TP. Thủ Đức", 920000m, "Đường Võ Văn Ngân, Linh Chiểu", "02837001020", + "Đường Võ Văn Ngân, Phường Linh Chiểu, TP. Thủ Đức, TP. Hồ Chí Minh"), + new("SafeSpace Gò Vấp", "Quận Gò Vấp", 930000m, "Đường Quang Trung, Phường 10", "02837001021", + "Đường Quang Trung, Phường 10, Quận Gò Vấp, TP. Hồ Chí Minh"), + new("SafeSpace Tân Bình", "Quận Tân Bình", 1020000m, "Đường Cộng Hòa, Phường 13", "02838112233", + "123 Hoàng Hoa Thám, Phường 13, Quận Tân Bình, TP. Hồ Chí Minh"), + new("SafeSpace Bình Tân", "Quận Bình Tân", 820000m, "Đường Kinh Dương Vương, An Lạc", "02837001023"), + ]; + + // (mã ô, dãy, lạnh?, cỡ L?) + private static readonly (string Code, string Row, bool Cold, bool Large)[] UnitLayout = + [ + ("K01", "A", false, false), ("K02", "A", false, false), ("K03", "A", false, false), ("K04", "A", false, false), + ("K05", "A", true, false), ("K06", "A", true, false), + ("K07", "B", false, true), ("K08", "B", false, true), ("K09", "B", false, true), ("K10", "B", false, true), + ("K11", "B", true, true), ("K12", "B", true, true), + ]; + + private static readonly string[] LegacyUnitTypeNames = + ["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)"]; + + private static readonly string[] LegacyFacilityNames = ["SafeSpace Quận 7", "SSFRMS Chi nhánh Quận 7"]; + + public static decimal SeedRate(decimal basePrice, bool cold, bool large) => + Math.Round(basePrice * (large ? 1.75m : 1m) * (cold ? 1.2m : 1m) / 10000m, MidpointRounding.AwayFromZero) * 10000m; + + private static async Task EnsureCatalogAsync(AppDbContext context, long adminId) + { + var now = DateTime.UtcNow; + + // --- 4 loại kho + async Task TypeAsync(string name, decimal area, decimal length, decimal width, bool cold, string description) + { + var type = await context.UnitTypes.FirstOrDefaultAsync(t => t.TypeName == name); + if (type != null) return type; + type = new UnitType + { + TypeName = name, Area = area, Length = length, Width = width, Height = 3.0m, ClimateControlled = cold, + Description = description, Status = "ACTIVE", CreatedAt = now, UpdatedAt = now + }; + context.UnitTypes.Add(type); + await context.SaveChangesAsync(); + return type; + } + + var normalM = await TypeAsync("Kho thường M", 15m, 5m, 3m, false, "Đồ đạc một phòng, hàng shop online, hồ sơ giấy tờ."); + var normalL = await TypeAsync("Kho thường L", 30m, 6m, 5m, false, "Đồ chuyển nhà 2–3 phòng ngủ, hàng tồn kho số lượng lớn."); + var coldM = await TypeAsync("Kho lạnh M", 15m, 5m, 3m, true, "Thiết bị điện tử, tài liệu, đồ gỗ cần tránh ẩm."); + var coldL = await TypeAsync("Kho lạnh L", 30m, 6m, 5m, true, "Hàng hoá cần giữ nhiệt độ ổn định, kho hàng cho cửa hàng."); + + await RetireLegacyCatalogAsync(context); + + // --- Đổi tên cơ sở seed đời đầu (chỉ khi còn tên cũ) + var oldTanBinh = await context.Facilities.FirstOrDefaultAsync(f => f.Name == "SSFRMS Chi nhánh Tân Bình"); + if (oldTanBinh != null && !await context.Facilities.AnyAsync(f => f.Name == "SafeSpace Tân Bình")) + { + oldTanBinh.Name = "SafeSpace Tân Bình"; + oldTanBinh.UpdatedAt = now; + await context.SaveChangesAsync(); + } + + // --- 12 cơ sở, bảng giá, 12 ô mỗi cơ sở + var effectiveFrom = DateOnly.FromDateTime(now.AddHours(7)).AddDays(-30); + Facility? home = null; + foreach (var seed in SafeSpaceFacilities) + { + var address = $"{seed.Street}, {seed.District}, TP. Hồ Chí Minh"; + var facility = await context.Facilities.FirstOrDefaultAsync(f => f.Name == seed.Name); + if (facility == null) + { + facility = new Facility + { + Name = seed.Name, Address = address, ContactPhone = seed.Phone, + OpeningTime = new TimeOnly(6, 0), ClosingTime = new TimeOnly(22, 0), + Status = "ACTIVE", CreatedAt = now, UpdatedAt = now + }; + context.Facilities.Add(facility); + await context.SaveChangesAsync(); + } + else if (seed.OldAddress != null && facility.Address == seed.OldAddress) + { + // Địa chỉ seed cũ → địa chỉ theo Figma 14/10 (không đụng địa chỉ Vận hành KD đã tự sửa) + facility.Address = address; + facility.UpdatedAt = now; + } + home ??= facility; + + foreach (var (type, cold, large) in new[] { (normalM, false, false), (normalL, false, true), (coldM, true, false), (coldL, true, true) }) + { + var hasRate = await context.RentalRates.AnyAsync(r => r.FacilityId == facility.FacilityId && r.UnitTypeId == type.UnitTypeId); + if (!hasRate) + { + context.RentalRates.Add(new RentalRate + { + FacilityId = facility.FacilityId, UnitTypeId = type.UnitTypeId, SetBy = adminId, + MonthlyRate = SeedRate(seed.BasePrice, cold, large), EffectiveFrom = effectiveFrom, + Status = "ACTIVE", CreatedAt = now + }); + } + } + + var existingCodes = await context.StorageUnits + .Where(u => u.FacilityId == facility.FacilityId) + .Select(u => u.UnitNumber) + .ToListAsync(); + foreach (var (code, row, cold, large) in UnitLayout) + { + if (existingCodes.Contains(code)) continue; + var type = cold ? (large ? coldL : coldM) : (large ? normalL : normalM); + context.StorageUnits.Add(new StorageUnit + { + FacilityId = facility.FacilityId, UnitTypeId = type.UnitTypeId, UnitNumber = code, + Floor = "Tầng trệt", Zone = $"Dãy {row}", + LocationDescription = $"Tầng trệt · Dãy {row} · {(cold ? "Kho lạnh" : "Kho thường")} cỡ {(large ? "L" : "M")}", + Status = "AVAILABLE", CreatedAt = now, UpdatedAt = now + }); + } + await context.SaveChangesAsync(); + } + + return new SeedCatalog(home!, normalM, normalL, coldM, coldL); + } + + /// Ngừng dùng loại kho cỡ S/M/L/XL và cơ sở "Quận 7" của bản seed cũ — giữ lại để không mất lịch sử. + private static async Task RetireLegacyCatalogAsync(AppDbContext context) + { + var now = DateTime.UtcNow; + var legacyTypes = await context.UnitTypes.Where(t => LegacyUnitTypeNames.Contains(t.TypeName)).ToListAsync(); + if (legacyTypes.Count > 0) + { + var ids = legacyTypes.Select(t => t.UnitTypeId).ToList(); + foreach (var t in legacyTypes.Where(t => t.Status == "ACTIVE")) + { + t.Status = "INACTIVE"; + t.UpdatedAt = now; + } + var rates = await context.RentalRates.Where(r => ids.Contains(r.UnitTypeId) && r.Status == "ACTIVE").ToListAsync(); + foreach (var r in rates) r.Status = "INACTIVE"; + // Ô trống của loại cũ không nhận khách mới; ô đang có khách giữ nguyên tới khi trả kho + var units = await context.StorageUnits.Where(u => ids.Contains(u.UnitTypeId) && u.Status == "AVAILABLE").ToListAsync(); + foreach (var u in units) + { + u.Status = "OUT_OF_SERVICE"; + u.UpdatedAt = now; + } + } + + var legacyFacilities = await context.Facilities.Where(f => LegacyFacilityNames.Contains(f.Name) && f.Status == "ACTIVE").ToListAsync(); + foreach (var f in legacyFacilities) + { + var busy = await context.RentalContracts.AnyAsync(c => c.Unit.FacilityId == f.FacilityId && (c.Status == "ACTIVE" || c.Status == "EXPIRING" || c.Status == "OVERDUE" || c.Status == "RETURN_PENDING" || c.Status == "DRAFT")) + || await context.Reservations.AnyAsync(r => r.FacilityId == f.FacilityId && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED" || r.Status == "UNIT_ASSIGNED")); + f.Status = busy ? "TEMPORARILY_CLOSED" : "INACTIVE"; + f.UpdatedAt = now; + } + await context.SaveChangesAsync(); + } +} diff --git a/StorageProject.Infrastructure/Data/DbSeeder.FacilityOps.cs b/StorageProject.Infrastructure/Data/DbSeeder.FacilityOps.cs new file mode 100644 index 0000000..46c98f9 --- /dev/null +++ b/StorageProject.Infrastructure/Data/DbSeeder.FacilityOps.cs @@ -0,0 +1,274 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Data; + +/// +/// Khu Nhân viên cơ sở / Quản lý cơ sở (BACKEND-TODO A1): +/// - Quyền của role STAFF, MANAGER; tài khoản manager01 / Manager@123 và staff02 / Staff@123. +/// - Phân công cơ sở: staff01, staff02, manager01 → SafeSpace Nguyễn Lương Bằng (SRS A06: mỗi người 1 cơ sở). +/// - Dữ liệu vận hành mẫu tại cơ sở đó để màn S01–S09, M01–M08 có việc để xử lý ngay sau khi tạo DB. +/// +public static partial class DbSeeder +{ + private static readonly string[] StaffPermissionCodes = ["HANDOVER_MANAGE", "RETURN_MANAGE", "TICKET_MANAGE", "PAYMENT_CONFIRM"]; + + private static readonly string[] ManagerPermissionCodes = + ["HANDOVER_MANAGE", "RETURN_MANAGE", "TICKET_MANAGE", "PAYMENT_CONFIRM", "UNIT_MANAGE", "ASSIGNMENT_MANAGE", "RENEWAL_MANAGE", "REPORT_VIEW"]; + + private static async Task EnsureUserAsync(AppDbContext context, string username, string email, string password, string fullName, string phone, string roleName) + { + var user = await context.Users.FirstOrDefaultAsync(u => u.Username == username); + if (user == null) + { + user = new User + { + Username = username, Email = email, PasswordHash = BCrypt.Net.BCrypt.HashPassword(password), + FullName = fullName, Phone = phone, Status = "ACTIVE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow + }; + context.Users.Add(user); + await context.SaveChangesAsync(); + } + var role = await context.Roles.FirstAsync(r => r.RoleName == roleName); + if (!await context.UserRoles.AnyAsync(ur => ur.UserId == user.UserId && ur.RoleId == role.RoleId)) + { + context.UserRoles.Add(new UserRole { UserId = user.UserId, RoleId = role.RoleId, AssignedAt = DateTime.UtcNow }); + await context.SaveChangesAsync(); + } + return user; + } + + private static async Task EnsureFacilityRolesAsync(AppDbContext context) + { + var staffRole = await context.Roles.FirstAsync(r => r.RoleName == "STAFF"); + var managerRole = await context.Roles.FirstAsync(r => r.RoleName == "MANAGER"); + var permissions = await context.Permissions.ToListAsync(); + var pairs = await context.RolePermissions.Select(rp => new { rp.RoleId, rp.PermissionId }).ToListAsync(); + + foreach (var perm in permissions) + { + if (StaffPermissionCodes.Contains(perm.PermissionCode) && !pairs.Any(x => x.RoleId == staffRole.RoleId && x.PermissionId == perm.PermissionId)) + { + context.RolePermissions.Add(new RolePermission { RoleId = staffRole.RoleId, PermissionId = perm.PermissionId }); + } + if (ManagerPermissionCodes.Contains(perm.PermissionCode) && !pairs.Any(x => x.RoleId == managerRole.RoleId && x.PermissionId == perm.PermissionId)) + { + context.RolePermissions.Add(new RolePermission { RoleId = managerRole.RoleId, PermissionId = perm.PermissionId }); + } + } + await context.SaveChangesAsync(); + + await EnsureUserAsync(context, "manager01", "manager01@storage.vn", "Manager@123", "Phạm Thu Hà", "0900000005", "MANAGER"); + await EnsureUserAsync(context, "staff02", "staff02@storage.vn", "Staff@123", "Nguyễn Minh Tâm", "0900000006", "STAFF"); + } + + /// Gán cơ sở cho tài khoản chưa có cơ sở nào đang hiệu lực (không ghi đè phân công do quản trị đặt). + private static async Task EnsureFacilityAssignmentsAsync(AppDbContext context, long facilityId, long adminId) + { + var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + foreach (var username in new[] { "staff01", "staff02", "manager01" }) + { + var user = await context.Users.FirstOrDefaultAsync(u => u.Username == username); + if (user == null) continue; + var hasActive = await context.UserFacilities.AnyAsync(uf => uf.UserId == user.UserId && uf.Status == "ACTIVE"); + if (hasActive) continue; + context.UserFacilities.Add(new UserFacility + { + UserId = user.UserId, FacilityId = facilityId, AssignedBy = adminId, + AssignedFrom = today.AddDays(-30), Status = "ACTIVE", CreatedAt = DateTime.UtcNow + }); + } + await context.SaveChangesAsync(); + } + + /// + /// Dữ liệu vận hành mẫu tại cơ sở đầu tiên. Chỉ chạy khi cơ sở này chưa có đơn đặt chỗ nào. + /// Ô kho: K01, K09 đang thuê · K02 sắp hết hạn + chờ duyệt gia hạn · K03 quá hạn · K05 chờ bàn giao · + /// K07 chờ kiểm tra trả kho · K10 bảo trì · còn lại trống. Thêm 2 khoản chờ đối soát, 1 đơn chờ phân bổ, + /// 1 đơn chờ chuyển khoản (để khách thử "Tôi đã chuyển khoản"). + /// + private static async Task SeedFacilityOperationsAsync(AppDbContext context, SeedCatalog catalog) + { + var home = catalog.Home; + if (await context.Reservations.AnyAsync(r => r.FacilityId == home.FacilityId)) return; + + var nowUtc = DateTime.UtcNow; + var today = DateOnly.FromDateTime(nowUtc.AddHours(7)); + DateTime Utc(DateOnly d, int hour, int minute = 0) => + DateTime.SpecifyKind(d.ToDateTime(new TimeOnly(hour, minute)).AddHours(-7), DateTimeKind.Utc); + + var staff01 = await context.Users.FirstAsync(u => u.Username == "staff01"); + var manager = await context.Users.FirstAsync(u => u.Username == "manager01"); + var cust01 = await context.Users.FirstAsync(u => u.Username == "customer01"); + var cust02 = await context.Users.FirstAsync(u => u.Username == "customer02"); + var cust03 = await EnsureUserAsync(context, "customer03", "tung.le@example.com", "Customer@123", "Lê Văn Tùng", "0903000003", "CUSTOMER"); + var cust04 = await EnsureUserAsync(context, "customer04", "lan.hoang@example.com", "Customer@123", "Hoàng Thị Lan", "0903000004", "CUSTOMER"); + var cust05 = await EnsureUserAsync(context, "customer05", "huy.phan@example.com", "Customer@123", "Phan Quốc Huy", "0903000005", "CUSTOMER"); + var cust06 = await EnsureUserAsync(context, "customer06", "trang.dang@example.com", "Customer@123", "Đặng Thu Trang", "0903000006", "CUSTOMER"); + + var units = await context.StorageUnits.Where(u => u.FacilityId == home.FacilityId).ToDictionaryAsync(u => u.UnitNumber); + // Giá đang áp dụng của từng loại kho (có thể có nhiều bản ACTIVE nếu Vận hành KD đã lên lịch giá mới) + var rates = (await context.RentalRates + .Where(r => r.FacilityId == home.FacilityId && r.Status == "ACTIVE" && r.EffectiveFrom <= today) + .ToListAsync()) + .GroupBy(r => r.UnitTypeId) + .ToDictionary(g => g.Key, g => g.OrderByDescending(r => r.EffectiveFrom).First().MonthlyRate); + + void Log(long? userId, string action, string entityType, long entityId, object value, DateTime at) => + context.ActivityLogs.Add(new ActivityLog + { + UserId = userId, Action = action, EntityType = entityType, EntityId = entityId, + NewValue = JsonSerializer.Serialize(value), LoggedAt = at + }); + + async Task ReserveAsync(User customer, UnitType type, DateOnly start, int months, string status, DateTime createdAt) + { + var rate = rates[type.UnitTypeId]; + var r = new Reservation + { + CustomerId = customer.UserId, FacilityId = home.FacilityId, UnitTypeId = type.UnitTypeId, + StartDate = start, RentalPeriodMonths = months, ExpectedEndDate = start.AddMonths(months), + CheckInAppointmentAt = Utc(start, 9), QuotedMonthlyRate = rate, EstimatedAmount = rate * months, + RequiredDeposit = rate, Status = status, CreatedAt = createdAt, + ExpiresAt = status == "PENDING_PAYMENT" ? nowUtc.AddHours(24) : createdAt.AddHours(24) + }; + context.Reservations.Add(r); + await context.SaveChangesAsync(); + return r; + } + + // Thuê một ô: đơn đặt chỗ + phân bổ + hợp đồng + cọc và tiền thuê đã thu + biên bản bàn giao + async Task RentAsync(User customer, string code, UnitType type, DateOnly start, int months, + string contractStatus, string unitStatus, User handoverStaff, bool handedOver) + { + var unit = units[code]; + var paidAt = Utc(start.AddDays(-2), 10); + var reservation = await ReserveAsync(customer, type, start, months, handedOver ? "CHECKED_IN" : "UNIT_ASSIGNED", paidAt.AddHours(-1)); + context.UnitAssignments.Add(new UnitAssignment + { + ReservationId = reservation.ReservationId, UnitId = unit.UnitId, AssignedBy = manager.UserId, + Status = "ACTIVE", AssignedAt = paidAt.AddHours(2) + }); + var contract = new RentalContract + { + ReservationId = reservation.ReservationId, CustomerId = customer.UserId, UnitId = unit.UnitId, + StartDate = start, EndDate = start.AddMonths(months), AgreedMonthlyRate = reservation.QuotedMonthlyRate, + DepositAmount = reservation.RequiredDeposit, Status = contractStatus, CreatedAt = paidAt.AddHours(2), + ActivatedAt = handedOver ? Utc(start, 9) : null + }; + context.RentalContracts.Add(contract); + await context.SaveChangesAsync(); + + var reference = $"SS-{reservation.CreatedAt.AddHours(7):yyyyMMdd}-{reservation.ReservationId:0000}"; + foreach (var (kind, amount) in new[] { ("DEPOSIT", reservation.RequiredDeposit), ("RENT", reservation.EstimatedAmount) }) + { + context.Payments.Add(new Payment + { + ContractId = contract.ContractId, PaymentType = kind, Amount = amount, Currency = "VND", + PaymentMethod = "BANK_TRANSFER", TransactionReference = reference, DueDate = start, + PaidAt = paidAt, Status = "PAID", CreatedAt = paidAt, UpdatedAt = paidAt + }); + } + Log(staff01.UserId, "PAYMENT_CONFIRMED", "RESERVATION", reservation.ReservationId, + new { amount = reservation.EstimatedAmount + reservation.RequiredDeposit }, paidAt); + + context.HandoverRecords.Add(new HandoverRecord + { + ContractId = contract.ContractId, StaffId = handoverStaff.UserId, ScheduledAt = Utc(start, 9), + VerifiedAt = handedOver ? Utc(start, 9) : null, HandoverAt = handedOver ? Utc(start, 9, 15) : null, + InitialCondition = "Kho sạch, cửa cuốn và khoá hoạt động tốt", + CustomerConfirmed = handedOver, StaffConfirmed = handedOver, + Status = handedOver ? "HANDED_OVER" : "SCHEDULED", CreatedAt = paidAt.AddHours(2) + }); + if (handedOver) + { + context.AccessCredentials.Add(new AccessCredential + { + ContractId = contract.ContractId, UnitId = unit.UnitId, IssuedBy = handoverStaff.UserId, + CredentialType = "ACCESS_CARD", CredentialReference = $"CARD-{code}-{start:yyMMdd}", + IssuedAt = Utc(start, 9, 15), Status = "ACTIVE" + }); + } + unit.Status = unitStatus; + unit.UpdatedAt = paidAt; + await context.SaveChangesAsync(); + return contract; + } + + // K01 · customer01 đang thuê + 1 yêu cầu hỗ trợ chưa phân công + var k01 = await RentAsync(cust01, "K01", catalog.NormalM, today.AddDays(-15), 3, "ACTIVE", "OCCUPIED", staff01, true); + context.SupportTickets.Add(new SupportTicket + { + CustomerId = cust01.UserId, ContractId = k01.ContractId, UnitId = units["K01"].UnitId, IssueType = "UNIT", + Title = "Cửa cuốn kho kẹt khi mở", Description = "Cửa cuốn ô K01 kéo lên được nửa thì kẹt, nhờ cơ sở kiểm tra.", + Priority = "NORMAL", Status = "OPEN", CreatedAt = Utc(today.AddDays(-1), 16, 20) + }); + + // K02 · sắp hết hạn, khách xin gia hạn 3 tháng + var k02Start = today.AddDays(10).AddMonths(-3); + var k02 = await RentAsync(cust03, "K02", catalog.NormalM, k02Start, 3, "ACTIVE", "OCCUPIED", staff01, true); + context.ContractRenewals.Add(new ContractRenewal + { + ContractId = k02.ContractId, OldEndDate = k02.EndDate, NewEndDate = k02.EndDate.AddMonths(3), RenewalPeriodMonths = 3, + OldMonthlyRate = k02.AgreedMonthlyRate, NewMonthlyRate = k02.AgreedMonthlyRate, RenewalAmount = k02.AgreedMonthlyRate * 3, + Status = "PENDING", RequestedAt = Utc(today.AddDays(-1), 10, 5), CreatedAt = Utc(today.AddDays(-1), 10, 5) + }); + + // K03 · quá hạn 3 ngày, chưa thanh toán kỳ mới + var k03Start = today.AddDays(-3).AddMonths(-1); + var k03 = await RentAsync(cust04, "K03", catalog.NormalM, k03Start, 1, "OVERDUE", "OCCUPIED", staff01, true); + context.Payments.Add(new Payment + { + ContractId = k03.ContractId, PaymentType = "RENT", Amount = k03.AgreedMonthlyRate, Currency = "VND", + PaymentMethod = "BANK_TRANSFER", DueDate = k03.EndDate, Status = "PENDING", + CreatedAt = Utc(k03.EndDate.AddDays(-7), 8), UpdatedAt = Utc(k03.EndDate.AddDays(-7), 8) + }); + context.OverdueCases.Add(new OverdueCase + { + ContractId = k03.ContractId, OverdueFrom = k03.EndDate.AddDays(1), GraceDeadline = k03.EndDate.AddDays(8), + OutstandingAmount = k03.AgreedMonthlyRate, Status = "OPEN", OpenedAt = Utc(k03.EndDate.AddDays(1), 8) + }); + + // K05 · kho lạnh M đã phân bổ, chờ khách đến xác minh + nhận kho (giao cho staff01) + await RentAsync(cust05, "K05", catalog.ColdM, today.AddDays(1), 3, "DRAFT", "RESERVED", staff01, false); + + // K07 · khách đã đăng ký trả kho, chờ kiểm tra (chưa phân công nhân viên) + còn nợ phí vệ sinh + var k07Start = today.AddDays(1).AddMonths(-3); + var k07 = await RentAsync(cust06, "K07", catalog.NormalL, k07Start, 3, "RETURN_PENDING", "RETURN_PENDING", staff01, true); + context.ReturnInspections.Add(new ReturnInspection + { + ContractId = k07.ContractId, StaffId = manager.UserId, ScheduledAt = Utc(today.AddDays(1), 10), + Status = "SCHEDULED", CreatedAt = Utc(today.AddDays(-2), 9) + }); + context.Payments.Add(new Payment + { + ContractId = k07.ContractId, PaymentType = "CLEANING_FEE", Amount = 200000m, Currency = "VND", + PaymentMethod = "BANK_TRANSFER", DueDate = k07.EndDate, Status = "PENDING", + CreatedAt = Utc(today.AddDays(-2), 9), UpdatedAt = Utc(today.AddDays(-2), 9) + }); + + // K09 · customer02 đang thuê dài hạn + await RentAsync(cust02, "K09", catalog.NormalL, today.AddDays(-40), 6, "ACTIVE", "OCCUPIED", staff01, true); + + // K10 · bảo trì + units["K10"].Status = "MAINTENANCE"; + units["K10"].UpdatedAt = nowUtc; + + // Khoản chờ đối soát (S09): khách đã bấm "Tôi đã chuyển khoản" + var pv1 = await ReserveAsync(cust02, catalog.NormalM, today.AddDays(5), 3, "PENDING_VERIFICATION", nowUtc.AddMinutes(-50)); + Log(cust02.UserId, "TRANSFER_REPORTED", "RESERVATION", pv1.ReservationId, new { amount = pv1.EstimatedAmount + pv1.RequiredDeposit }, nowUtc.AddMinutes(-45)); + var pv2 = await ReserveAsync(cust01, catalog.ColdL, today.AddDays(3), 1, "PENDING_VERIFICATION", nowUtc.AddHours(-14)); + Log(cust01.UserId, "TRANSFER_REPORTED", "RESERVATION", pv2.ReservationId, new { amount = pv2.EstimatedAmount + pv2.RequiredDeposit }, nowUtc.AddHours(-13.9)); + + // Đơn đã đối soát, chờ quản lý phân bổ ô (M05) — ô phù hợp: K06 + var confirmed = await ReserveAsync(cust06, catalog.ColdM, today.AddDays(6), 3, "CONFIRMED", nowUtc.AddDays(-1).AddHours(-3)); + Log(staff01.UserId, "PAYMENT_CONFIRMED", "RESERVATION", confirmed.ReservationId, + new { amount = confirmed.EstimatedAmount + confirmed.RequiredDeposit }, nowUtc.AddDays(-1)); + + // Đơn chờ chuyển khoản của customer01 — dùng để thử nút "Tôi đã chuyển khoản" + await ReserveAsync(cust01, catalog.NormalL, today.AddDays(5), 1, "PENDING_PAYMENT", nowUtc); + + await context.SaveChangesAsync(); + } +} diff --git a/StorageProject.Infrastructure/Data/DbSeeder.cs b/StorageProject.Infrastructure/Data/DbSeeder.cs index 3e54a99..23351f6 100644 --- a/StorageProject.Infrastructure/Data/DbSeeder.cs +++ b/StorageProject.Infrastructure/Data/DbSeeder.cs @@ -3,7 +3,13 @@ namespace StorageProject.Infrastructure.Data; -public static class DbSeeder +/// +/// Dữ liệu khởi tạo. Mọi bước đều "chỉ thêm phần còn thiếu", nên chạy lại nhiều lần vẫn an toàn và +/// database tạo từ trước cũng được bổ sung khi khởi động lại API. +/// - Danh mục kho theo D17 (Figma 14/10): xem DbSeeder.Catalog.cs +/// - Tài khoản nhân viên / quản lý cơ sở và dữ liệu vận hành mẫu: xem DbSeeder.FacilityOps.cs +/// +public static partial class DbSeeder { public static async Task SeedAsync(AppDbContext context) { @@ -60,7 +66,6 @@ public static async Task SeedAsync(AppDbContext context) await context.SaveChangesAsync(); } - // 2. Users if (!await context.Users.AnyAsync()) { @@ -125,135 +130,18 @@ public static async Task SeedAsync(AppDbContext context) await context.SaveChangesAsync(); } - // 2b. Vai trò Quản lý vận hành KD (OPERATIONS) + tài khoản ops01 — chạy lại được với DB đã có + // 2b. Vai trò Quản lý vận hành KD (OPERATIONS) + tài khoản ops01 await EnsureOperationsRoleAsync(context); - var admin = await context.Users.FirstAsync(u => u.Username == "admin"); - var staff = await context.Users.FirstAsync(u => u.Username == "staff01"); - var cust1 = await context.Users.FirstAsync(u => u.Username == "customer01"); - - // 3. Facilities - if (!await context.Facilities.AnyAsync()) - { - var fac1 = new Facility - { - Name = "SSFRMS Chi nhánh Tân Bình", - Address = "123 Hoàng Hoa Thám, Phường 13, Quận Tân Bình, TP. Hồ Chí Minh", - ContactPhone = "02838112233", - OpeningTime = new TimeOnly(7, 0), - ClosingTime = new TimeOnly(22, 0), - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }; - - var fac2 = new Facility - { - Name = "SSFRMS Chi nhánh Quận 7", - Address = "456 Nguyễn Thị Thập, Phường Tân Quy, Quận 7, TP. Hồ Chí Minh", - ContactPhone = "02837778899", - OpeningTime = new TimeOnly(6, 0), - ClosingTime = new TimeOnly(23, 0), - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }; - - context.Facilities.AddRange(fac1, fac2); - await context.SaveChangesAsync(); - } - - var tanBinhFac = await context.Facilities.FirstAsync(f => f.Name.Contains("Tân Bình")); - var quan7Fac = await context.Facilities.FirstAsync(f => f.Name.Contains("Quận 7")); - - // 4. Unit Types - if (!await context.UnitTypes.AnyAsync()) - { - var types = new List - { - new() - { - TypeName = "Kho Mini S (1m x 1m)", - Length = 1.0m, - Width = 1.0m, - Height = 2.5m, - Area = 1.0m, - ClimateControlled = false, - Description = "Kho nhỏ tiết kiệm, phù hợp cất giữ vali, tài liệu, phụ kiện gia đình", - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }, - new() - { - TypeName = "Kho Tiêu Chuẩn M (2m x 2m)", - Length = 2.0m, - Width = 2.0m, - Height = 2.8m, - Area = 4.0m, - ClimateControlled = true, - Description = "Kho điều hòa mát mẻ, phù hợp đồ nội thất, thiết bị điện tử, hàng shop online", - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }, - new() - { - TypeName = "Kho Lớn L (3m x 3m)", - Length = 3.0m, - Width = 3.0m, - Height = 3.0m, - Area = 9.0m, - ClimateControlled = true, - Description = "Kho điều hòa sức chứa lớn, phù hợp lưu trữ đồ chuyển nhà 2-3 phòng ngủ", - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }, - new() - { - TypeName = "Kho Doanh Nghiệp XL (4m x 4m)", - Length = 4.0m, - Width = 4.0m, - Height = 3.2m, - Area = 16.0m, - ClimateControlled = true, - Description = "Kho chuyên biệt cho doanh nghiệp lưu trữ tài liệu chứng từ hoặc kiện hàng thương mại", - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - } - }; - - context.UnitTypes.AddRange(types); - await context.SaveChangesAsync(); - } + // 2c. Quyền của STAFF / MANAGER + tài khoản manager01, staff02 (BACKEND-TODO A1) + await EnsureFacilityRolesAsync(context); - var typeS = await context.UnitTypes.FirstAsync(t => t.TypeName.Contains("Kho Mini S")); - var typeM = await context.UnitTypes.FirstAsync(t => t.TypeName.Contains("Kho Tiêu Chuẩn M")); - var typeL = await context.UnitTypes.FirstAsync(t => t.TypeName.Contains("Kho Lớn L")); - var typeXL = await context.UnitTypes.FirstAsync(t => t.TypeName.Contains("Kho Doanh Nghiệp XL")); - - // 5. Rental Rates - if (!await context.RentalRates.AnyAsync()) - { - var today = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-30)); - var rates = new List - { - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeS.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 500000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeM.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 1500000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeL.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 3000000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeS.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 550000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeM.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 1600000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeL.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 3200000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeXL.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 5500000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - }; + var admin = await context.Users.FirstAsync(u => u.Username == "admin"); - context.RentalRates.AddRange(rates); - await context.SaveChangesAsync(); - } + // 3. Danh mục kho theo D17: 4 loại kho, 12 cơ sở, mỗi cơ sở 12 ô + bảng giá + var catalog = await EnsureCatalogAsync(context, admin.UserId); - // 6. Policies + // 4. Policies if (!await context.Policies.AnyAsync()) { var policies = new List @@ -290,170 +178,13 @@ public static async Task SeedAsync(AppDbContext context) await context.SaveChangesAsync(); } - // 7. Storage Units - if (!await context.StorageUnits.AnyAsync()) - { - var units = new List - { - // Tân Bình - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeS.UnitTypeId, UnitNumber = "TB-S-101", Floor = "Tầng 1", Zone = "Khu A", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeS.UnitTypeId, UnitNumber = "TB-S-102", Floor = "Tầng 1", Zone = "Khu A", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeM.UnitTypeId, UnitNumber = "TB-M-103", Floor = "Tầng 1", Zone = "Khu B", Status = "OCCUPIED", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeM.UnitTypeId, UnitNumber = "TB-M-104", Floor = "Tầng 1", Zone = "Khu B", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeL.UnitTypeId, UnitNumber = "TB-L-201", Floor = "Tầng 2", Zone = "Khu C", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeL.UnitTypeId, UnitNumber = "TB-L-202", Floor = "Tầng 2", Zone = "Khu C", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - - // Quận 7 - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeS.UnitTypeId, UnitNumber = "Q7-S-101", Floor = "Tầng 1", Zone = "Khu 1", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeS.UnitTypeId, UnitNumber = "Q7-S-102", Floor = "Tầng 1", Zone = "Khu 1", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeM.UnitTypeId, UnitNumber = "Q7-M-103", Floor = "Tầng 1", Zone = "Khu 2", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeM.UnitTypeId, UnitNumber = "Q7-M-104", Floor = "Tầng 1", Zone = "Khu 2", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeL.UnitTypeId, UnitNumber = "Q7-L-201", Floor = "Tầng 2", Zone = "Khu 3", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeXL.UnitTypeId, UnitNumber = "Q7-XL-301", Floor = "Tầng 3", Zone = "Khu VIP", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - }; - - context.StorageUnits.AddRange(units); - await context.SaveChangesAsync(); - } - - // 7b. Mạng lưới 12 cơ sở SafeSpace theo thiết kế Figma. - // Chạy lại nhiều lần vẫn an toàn: chỉ thêm cơ sở / bảng giá / phòng kho còn thiếu, - // nên database đã tạo từ trước cũng được bổ sung khi khởi động lại API. - await SeedSafeSpaceNetworkAsync(context, admin.UserId, typeS, typeM, typeL, typeXL); - - // 8. Sample Customer Data (Reservation, Contract, Payment, SupportTicket for customer01) - if (!await context.Reservations.AnyAsync()) - { - var occupiedUnit = await context.StorageUnits.FirstAsync(u => u.UnitNumber == "TB-M-103"); - - // Reservation 1: Converted to Contract - var startDate1 = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-15)); - var endDate1 = startDate1.AddMonths(3); - - var res1 = new Reservation - { - CustomerId = cust1.UserId, - FacilityId = tanBinhFac.FacilityId, - UnitTypeId = typeM.UnitTypeId, - StartDate = startDate1, - ExpectedEndDate = endDate1, - RentalPeriodMonths = 3, - QuotedMonthlyRate = 1500000m, - EstimatedAmount = 4500000m, - RequiredDeposit = 1500000m, - Status = "CHECKED_IN", - CreatedAt = DateTime.UtcNow.AddDays(-16), - ExpiresAt = DateTime.UtcNow.AddDays(-15) - }; - context.Reservations.Add(res1); - await context.SaveChangesAsync(); - - // Contract for Reservation 1 - var contract = new RentalContract - { - ReservationId = res1.ReservationId, - CustomerId = cust1.UserId, - UnitId = occupiedUnit.UnitId, - StartDate = startDate1, - EndDate = endDate1, - AgreedMonthlyRate = 1500000m, - DepositAmount = 1500000m, - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow.AddDays(-15), - ActivatedAt = DateTime.UtcNow.AddDays(-15) - }; - context.RentalContracts.Add(contract); - await context.SaveChangesAsync(); - - // Handover Record - var handover = new HandoverRecord - { - ContractId = contract.ContractId, - StaffId = staff.UserId, - InitialCondition = "Kho sạch sẽ, hệ thống điều hòa hoạt động tốt, đã bàn giao khóa", - ScheduledAt = DateTime.UtcNow.AddDays(-15), - HandoverAt = DateTime.UtcNow.AddDays(-15), - CustomerConfirmed = true, - StaffConfirmed = true, - Status = "HANDED_OVER", - CreatedAt = DateTime.UtcNow.AddDays(-15) - }; - context.HandoverRecords.Add(handover); - - // Payments (Deposit + Rent) - var depositPayment = new Payment - { - ContractId = contract.ContractId, - PaymentType = "DEPOSIT", - Amount = 1500000m, - Currency = "VND", - PaymentMethod = "BANK_TRANSFER", - TransactionReference = "VNPAY-DEP-10001", - DueDate = startDate1, - PaidAt = DateTime.UtcNow.AddDays(-15), - Status = "PAID", - CreatedAt = DateTime.UtcNow.AddDays(-15), - UpdatedAt = DateTime.UtcNow.AddDays(-15) - }; - - var rentPayment = new Payment - { - ContractId = contract.ContractId, - PaymentType = "RENT", - Amount = 1500000m, - Currency = "VND", - PaymentMethod = "BANK_TRANSFER", - TransactionReference = "VNPAY-RENT-10002", - DueDate = startDate1, - PaidAt = DateTime.UtcNow.AddDays(-15), - Status = "PAID", - CreatedAt = DateTime.UtcNow.AddDays(-15), - UpdatedAt = DateTime.UtcNow.AddDays(-15) - }; - - context.Payments.AddRange(depositPayment, rentPayment); - - // Support Ticket - var ticket = new SupportTicket - { - CustomerId = cust1.UserId, - ContractId = contract.ContractId, - UnitId = occupiedUnit.UnitId, - 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 = DateTime.UtcNow.AddDays(-2) - }; - context.SupportTickets.Add(ticket); - - // Reservation 2: Pending payment for customer01 - var startDate2 = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(5)); - var res2 = new Reservation - { - CustomerId = cust1.UserId, - FacilityId = tanBinhFac.FacilityId, - UnitTypeId = typeS.UnitTypeId, - StartDate = startDate2, - ExpectedEndDate = startDate2.AddMonths(1), - RentalPeriodMonths = 1, - QuotedMonthlyRate = 500000m, - EstimatedAmount = 500000m, - RequiredDeposit = 500000m, - Status = "PENDING_PAYMENT", - CreatedAt = DateTime.UtcNow, - ExpiresAt = DateTime.UtcNow.AddHours(24) - }; - context.Reservations.Add(res2); - - await context.SaveChangesAsync(); - } + // 5. Phân công cơ sở (SRS A06: mỗi nhân viên / quản lý 1 cơ sở) + dữ liệu vận hành mẫu tại cơ sở đó + await EnsureFacilityAssignmentsAsync(context, catalog.Home.FacilityId, admin.UserId); + await SeedFacilityOperationsAsync(context, catalog); } // ------------------------------------------------------------------------------------------ // Quản lý vận hành kinh doanh (SRS: Business Operations Manager — UC19–UC23) - // Chỉ thêm phần còn thiếu nên DB tạo từ trước cũng được bổ sung khi khởi động lại API. // ------------------------------------------------------------------------------------------ private static async Task EnsureOperationsRoleAsync(AppDbContext context) { @@ -523,113 +254,4 @@ private static async Task EnsureOperationsRoleAsync(AppDbContext context) await context.SaveChangesAsync(); } } - - // ------------------------------------------------------------------------------------------ - // Mạng lưới cơ sở SafeSpace (Figma C02 / Trang chủ) - // RateM = giá kho Tiêu Chuẩn M; các loại khác tính theo tỉ lệ (S ≈ 40%, L = 2×, XL = 3,5×). - // ------------------------------------------------------------------------------------------ - private sealed record SeedFacility(string Code, string Name, string Address, string Phone, int OpenHour, int CloseHour, decimal RateM, bool HasXL); - - private static readonly SeedFacility[] SafeSpaceNetwork = - [ - new("NLB", "SafeSpace Nguyễn Lương Bằng", "12 Nguyễn Lương Bằng, Phường Tân Phú, Quận 7, TP. Hồ Chí Minh", "02837001012", 6, 22, 1150000m, true), - new("HL", "SafeSpace Him Lam", "Khu dân cư Him Lam, Phường Tân Hưng, Quận 7, TP. Hồ Chí Minh", "02837001013", 6, 22, 1050000m, false), - new("PX", "SafeSpace Phú Xuân", "Đường Nguyễn Hữu Thọ, Xã Phú Xuân, Huyện Nhà Bè, TP. Hồ Chí Minh", "02837001014", 6, 22, 890000m, false), - new("TT", "SafeSpace Tân Thuận", "Đường Huỳnh Tấn Phát, Phường Tân Thuận Đông, Quận 7, TP. Hồ Chí Minh", "02837001015", 6, 22, 1100000m, true), - new("PMH", "SafeSpace Phú Mỹ Hưng", "Đường Nguyễn Văn Linh, Phường Tân Phong, Quận 7, TP. Hồ Chí Minh", "02837001016", 6, 22, 1250000m, true), - new("BT", "SafeSpace Bình Thạnh", "Đường Nguyễn Xí, Phường 26, Quận Bình Thạnh, TP. Hồ Chí Minh", "02837001017", 6, 22, 980000m, false), - new("NB", "SafeSpace Nhà Bè", "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè, Huyện Nhà Bè, TP. Hồ Chí Minh", "02837001018", 6, 22, 850000m, false), - new("BC", "SafeSpace Bình Chánh", "Quốc lộ 50, Xã Bình Hưng, Huyện Bình Chánh, TP. Hồ Chí Minh", "02837001019", 6, 22, 790000m, true), - new("TD", "SafeSpace Thủ Đức", "Đường Võ Văn Ngân, Phường Linh Chiểu, TP. Thủ Đức, TP. Hồ Chí Minh", "02837001020", 6, 22, 920000m, false), - new("GV", "SafeSpace Gò Vấp", "Đường Quang Trung, Phường 10, Quận Gò Vấp, TP. Hồ Chí Minh", "02837001021", 6, 22, 930000m, false), - ]; - - private static decimal RoundRate(decimal value) => Math.Round(value / 10000m, MidpointRounding.AwayFromZero) * 10000m; - - private static async Task SeedSafeSpaceNetworkAsync(AppDbContext context, long adminId, UnitType typeS, UnitType typeM, UnitType typeL, UnitType typeXL) - { - // Đổi tên 2 cơ sở seed ban đầu sang thương hiệu SafeSpace (chỉ đổi khi còn tên cũ) - var renames = new Dictionary - { - ["SSFRMS Chi nhánh Tân Bình"] = "SafeSpace Tân Bình", - ["SSFRMS Chi nhánh Quận 7"] = "SafeSpace Quận 7", - }; - var oldNames = renames.Keys.ToList(); - var toRename = await context.Facilities.Where(f => oldNames.Contains(f.Name)).ToListAsync(); - foreach (var f in toRename) - { - f.Name = renames[f.Name]; - f.UpdatedAt = DateTime.UtcNow; - } - if (toRename.Count > 0) await context.SaveChangesAsync(); - - var effectiveFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-30)); - - foreach (var seed in SafeSpaceNetwork) - { - var facility = await context.Facilities.FirstOrDefaultAsync(f => f.Name == seed.Name); - if (facility == null) - { - facility = new Facility - { - Name = seed.Name, - Address = seed.Address, - ContactPhone = seed.Phone, - OpeningTime = new TimeOnly(seed.OpenHour, 0), - ClosingTime = new TimeOnly(seed.CloseHour, 0), - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }; - context.Facilities.Add(facility); - await context.SaveChangesAsync(); - } - - // (loại kho, giá/tháng, số phòng, ký hiệu, số phòng bắt đầu, tầng, khu) - var plan = new List<(UnitType Type, decimal Rate, int Count, string Size, int FirstNo, string Floor, string Zone)> - { - (typeS, RoundRate(seed.RateM * 0.4m), 2, "S", 101, "Tầng 1", "Khu A"), - (typeM, seed.RateM, 2, "M", 111, "Tầng 1", "Khu B"), - (typeL, RoundRate(seed.RateM * 2m), 1, "L", 201, "Tầng 2", "Khu C"), - }; - if (seed.HasXL) plan.Add((typeXL, RoundRate(seed.RateM * 3.5m), 1, "XL", 301, "Tầng 3", "Khu D")); - - foreach (var item in plan) - { - var hasRate = await context.RentalRates.AnyAsync(r => r.FacilityId == facility.FacilityId && r.UnitTypeId == item.Type.UnitTypeId); - if (!hasRate) - { - context.RentalRates.Add(new RentalRate - { - FacilityId = facility.FacilityId, - UnitTypeId = item.Type.UnitTypeId, - SetBy = adminId, - MonthlyRate = item.Rate, - EffectiveFrom = effectiveFrom, - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow - }); - } - - for (var i = 0; i < item.Count; i++) - { - var unitNumber = $"{seed.Code}-{item.Size}-{item.FirstNo + i}"; - var exists = await context.StorageUnits.AnyAsync(u => u.FacilityId == facility.FacilityId && u.UnitNumber == unitNumber); - if (exists) continue; - context.StorageUnits.Add(new StorageUnit - { - FacilityId = facility.FacilityId, - UnitTypeId = item.Type.UnitTypeId, - UnitNumber = unitNumber, - Floor = item.Floor, - Zone = item.Zone, - Status = "AVAILABLE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }); - } - } - await context.SaveChangesAsync(); - } - } } diff --git a/StorageProject.Infrastructure/Migrations/20261014150000_ReservationPendingVerification.cs b/StorageProject.Infrastructure/Migrations/20261014150000_ReservationPendingVerification.cs new file mode 100644 index 0000000..e6752ba --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261014150000_ReservationPendingVerification.cs @@ -0,0 +1,47 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using StorageProject.Infrastructure.Data; + +#nullable disable + +namespace StorageProject.Infrastructure.Migrations +{ + /// + /// F03 / BACKEND-TODO A4: đơn đặt chỗ có thêm trạng thái PENDING_VERIFICATION + /// (khách đã bấm "Tôi đã chuyển khoản", chờ nhân viên đối soát). + /// Viết tay vì chỉ đổi một ràng buộc CHECK; AppDbContextModelSnapshot đã cập nhật tương ứng. + /// + [DbContext(typeof(AppDbContext))] + [Migration("20261014150000_ReservationPendingVerification")] + public partial class ReservationPendingVerification : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropCheckConstraint( + name: "CK_reservations_status", + table: "reservations"); + + migrationBuilder.AddCheckConstraint( + name: "CK_reservations_status", + table: "reservations", + sql: "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + // Đơn đang chờ đối soát quay về chờ chuyển khoản trước khi bỏ trạng thái + migrationBuilder.Sql("UPDATE [reservations] SET [Status] = 'PENDING_PAYMENT' WHERE [Status] = 'PENDING_VERIFICATION'"); + + migrationBuilder.DropCheckConstraint( + name: "CK_reservations_status", + table: "reservations"); + + migrationBuilder.AddCheckConstraint( + name: "CK_reservations_status", + table: "reservations", + sql: "[Status] IN ('PENDING_PAYMENT','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index a2c6714..f8886b4 100644 --- a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -865,7 +865,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); - t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); }); }); diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs new file mode 100644 index 0000000..0bafe6c --- /dev/null +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs @@ -0,0 +1,498 @@ +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Services; + +/// +/// Thao tác của nhân viên (S02–S05, S09) và quản lý (M03, M05–M07). Mỗi thao tác lưu trong một lần SaveChanges +/// (một giao dịch) và ghi activity_logs. Điều kiện chặn giống src/ops/reducer.js (có test ở giao diện). +/// +public partial class FacilityOpsService +{ + private static readonly Regex DocNumberPattern = new(@"^\d{9}$|^\d{12}$|^[A-Z]\d{7}$", RegexOptions.IgnoreCase); + private static readonly string[] UnlockMethods = ["CARD", "PIN", "FINGER"]; + private static readonly string[] TicketNextStates = ["IN_PROGRESS", "WAITING_CUSTOMER", "DONE"]; + + // ------------------------------------------------------------------ + // Tải thực thể trong cơ sở được phân công (khác cơ sở → 404, không lộ dữ liệu) + // ------------------------------------------------------------------ + private async Task ReservationAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "SS-", "đơn đặt chỗ"); + return await dbContext.Reservations + .Include(r => r.UnitType) + .Include(r => r.UnitAssignments) + .FirstOrDefaultAsync(r => r.ReservationId == id && r.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy đơn đặt chỗ tại cơ sở của bạn."); + } + + private async Task HandoverAsync(long facilityId, string code, string prefix, CancellationToken ct) + { + var id = ParseCode(code, prefix, prefix == "XM-" ? "lịch xác minh" : "phiếu bàn giao"); + return await dbContext.HandoverRecords + .Include(h => h.Contract).ThenInclude(c => c.Unit) + .Include(h => h.Contract).ThenInclude(c => c.Reservation) + .Include(h => h.Contract).ThenInclude(c => c.AccessCredentials) + .FirstOrDefaultAsync(h => h.HandoverId == id && h.Contract.Unit.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy lịch bàn giao tại cơ sở của bạn."); + } + + private async Task InspectionAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "TK-", "lịch trả kho"); + return await dbContext.ReturnInspections + .Include(i => i.Contract).ThenInclude(c => c.Unit) + .Include(i => i.Contract).ThenInclude(c => c.AccessCredentials) + .FirstOrDefaultAsync(i => i.InspectionId == id && i.Contract.Unit.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy lịch trả kho tại cơ sở của bạn."); + } + + private async Task TicketAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "HT-", "yêu cầu hỗ trợ"); + return await dbContext.SupportTickets + .FirstOrDefaultAsync(t => t.TicketId == id + && ((t.Unit != null && t.Unit.FacilityId == facilityId) + || (t.Contract != null && t.Contract.Unit.FacilityId == facilityId)), ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu hỗ trợ tại cơ sở của bạn."); + } + + private async Task ContractAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "HĐ-", "hợp đồng"); + return await dbContext.RentalContracts + .Include(c => c.Unit) + .Include(c => c.Payments) + .Include(c => c.ReturnInspections) + .Include(c => c.OverdueCases) + .Include(c => c.AccessCredentials) + .FirstOrDefaultAsync(c => c.ContractId == id && c.Unit.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy hợp đồng tại cơ sở của bạn."); + } + + // ===================================================================== + // S09 · Đối soát chuyển khoản + // ===================================================================== + public async Task ConfirmPaymentAsync(OpsActor actor, string id, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var r = await ReservationAsync(facility.FacilityId, id, ct); + if (r.Status != "PENDING_VERIFICATION") throw new InvalidOperationException("Khoản này đã được xử lý."); + + // Chưa có ô kho → vào hàng chờ phân bổ của quản lý (M05) + r.Status = "CONFIRMED"; + Log(actor.UserId, LogAction.PaymentConfirmed, LogEntity.Reservation, r.ReservationId, new { amount = r.EstimatedAmount + r.RequiredDeposit }); + await dbContext.SaveChangesAsync(ct); + } + + public async Task ReportMismatchAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var r = await ReservationAsync(facility.FacilityId, id, ct); + if (r.Status != "PENDING_VERIFICATION") throw new InvalidOperationException("Khoản này đã được xử lý."); + var note = Clip(request.Note, 500); + if (note.Length == 0) throw new ArgumentException("Vui lòng ghi rõ sai lệch (số tiền, nội dung hoặc thời gian)."); + + var last = await dbContext.ActivityLogs + .Where(l => l.EntityType == LogEntity.Reservation && l.EntityId == r.ReservationId + && (l.Action == LogAction.PaymentMismatch || l.Action == LogAction.TransferReported)) + .OrderByDescending(l => l.LoggedAt) + .FirstOrDefaultAsync(ct); + if (last?.Action == LogAction.PaymentMismatch) throw new InvalidOperationException("Khoản này đã được xử lý."); + + // Đơn vẫn chờ đối soát; quản lý liên hệ khách rồi nhân viên xác nhận lại khi đã khớp + Log(actor.UserId, LogAction.PaymentMismatch, LogEntity.Reservation, r.ReservationId, new { note }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // S02 · Xác minh khách khi đến nhận kho — chỉ lưu 4 số cuối giấy tờ + // ===================================================================== + public async Task VerifyCustomerAsync(OpsActor actor, string id, OpsVerifyRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var h = await HandoverAsync(facility.FacilityId, id, "XM-", ct); + if (h.Status != "SCHEDULED") throw new InvalidOperationException("Khách hàng này đã được xác minh."); + + var docNumber = (request.DocNumber ?? string.Empty).Trim(); + if (!DocNumberPattern.IsMatch(docNumber)) + { + throw new ArgumentException("Số giấy tờ gồm 9 hoặc 12 chữ số (CCCD/CMND) hoặc 1 chữ + 7 số (hộ chiếu)."); + } + if (!request.PhotoMatched || !request.InfoMatched) + { + throw new ArgumentException("Đánh dấu cả hai mục đối chiếu trước khi xác minh."); + } + + var docType = Clip(request.DocType, 50); + h.Status = "VERIFIED"; + h.VerifiedAt = NowUtc; + if (!actor.IsManager) h.StaffId = actor.UserId; + Log(actor.UserId, LogAction.CustomerVerified, LogEntity.Handover, h.HandoverId, + new { docType = docType.Length > 0 ? docType : "Căn cước công dân", docLast4 = docNumber[^4..] }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // S03 · Bàn giao kho + cấp phương thức mở khoá + // ===================================================================== + public async Task CompleteHandoverAsync(OpsActor actor, string id, OpsHandoverRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var h = await HandoverAsync(facility.FacilityId, id, "BG-", ct); + if (h.Status == "HANDED_OVER") throw new InvalidOperationException("Kho này đã được bàn giao."); + if (h.Status != "VERIFIED") throw new InvalidOperationException("Cần xác minh khách hàng trước khi bàn giao kho."); + var method = (request.UnlockMethod ?? string.Empty).Trim().ToUpperInvariant(); + if (!UnlockMethods.Contains(method)) throw new ArgumentException("Chọn phương thức mở khoá."); + + var contract = h.Contract; + if (contract.Status != "DRAFT") throw new InvalidOperationException("Hợp đồng không ở trạng thái chờ bàn giao."); + + var now = NowUtc; + h.Status = "HANDED_OVER"; + h.HandoverAt = now; + h.StaffConfirmed = true; + h.CustomerConfirmed = true; // khách có mặt và ký nhận tại quầy + if (!actor.IsManager) h.StaffId = actor.UserId; + + contract.Status = "ACTIVE"; + contract.ActivatedAt = now; + contract.Reservation.Status = "CHECKED_IN"; + SetUnitStatus(contract.Unit, "OCCUPIED", actor.UserId, $"Bàn giao cho khách · {HandoverCode(h.HandoverId)}"); + + foreach (var old in contract.AccessCredentials.Where(a => a.Status == "ACTIVE")) + { + old.Status = "REPLACED"; + old.ReturnedAt = now; + } + // Thẻ từ → ACCESS_CARD; mã PIN và vân tay đăng ký tại máy → ACCESS_CODE (không lưu bí mật) + dbContext.AccessCredentials.Add(new AccessCredential + { + ContractId = contract.ContractId, + UnitId = contract.UnitId, + IssuedBy = actor.UserId, + CredentialType = method == "CARD" ? "ACCESS_CARD" : "ACCESS_CODE", + CredentialReference = $"{method}-{contract.Unit.UnitNumber}-{now + VnOffset:yyMMdd}", + IssuedAt = now, + Status = "ACTIVE" + }); + Log(actor.UserId, LogAction.HandoverCompleted, LogEntity.Handover, h.HandoverId, new { method }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // S04 · Kiểm tra trả kho → chờ quản lý xác nhận hoàn cọc + // ===================================================================== + public async Task SubmitReturnInspectionAsync(OpsActor actor, string id, OpsReturnInspectionRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var i = await InspectionAsync(facility.FacilityId, id, ct); + if (i.Status == "COMPLETED") throw new InvalidOperationException("Biên bản trả kho đã được gửi."); + if (i.Status == "CANCELLED") throw new InvalidOperationException("Lịch trả kho đã huỷ."); + + var items = Clip(request.Items, 500); + var walls = Clip(request.Walls, 500); + var keys = Clip(request.Keys, 500); + var proposal = Clip(request.Proposal, 500); + if (items.Length == 0 || walls.Length == 0 || keys.Length == 0 || proposal.Length == 0) + { + throw new ArgumentException("Điền đủ 4 mục kiểm tra trước khi gửi biên bản."); + } + + var now = NowUtc; + i.Status = "COMPLETED"; + i.InspectedAt = now; + i.DamageDescription = walls; + i.Notes = $"Đồ đạc còn lại: {items}\nTường, sàn, cửa: {walls}\nChìa khoá, thẻ: {keys}\nĐề xuất: {proposal}"; + if (!actor.IsManager) i.StaffId = actor.UserId; + + var contract = i.Contract; + if (contract.Status is "ACTIVE" or "EXPIRING" or "OVERDUE") contract.Status = "RETURN_PENDING"; + SetUnitStatus(contract.Unit, "INSPECTION", actor.UserId, $"Khách trả kho · {ReturnCode(i.InspectionId)}"); + foreach (var cred in contract.AccessCredentials.Where(a => a.Status == "ACTIVE")) + { + cred.Status = "RETURNED"; + cred.ReturnedAt = now; + } + Log(actor.UserId, LogAction.ReturnInspected, LogEntity.Return, i.InspectionId, new { items, walls, keys, proposal }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // S05 · Phản hồi yêu cầu hỗ trợ + // ===================================================================== + public async Task RespondTicketAsync(OpsActor actor, string id, OpsTicketResponseRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var t = await TicketAsync(facility.FacilityId, id, ct); + if (t.Status is "CLOSED" or "CANCELLED") throw new InvalidOperationException("Yêu cầu đã đóng."); + var note = Clip(request.Note, 1000); + if (note.Length == 0) throw new ArgumentException("Ghi nhận nội dung xử lý trước khi lưu."); + var next = (request.NextStatus ?? string.Empty).Trim().ToUpperInvariant(); + if (!TicketNextStates.Contains(next)) throw new ArgumentException("Chọn trạng thái tiếp theo."); + + var now = NowUtc; + if (t.AssignedStaffId == null) + { + t.AssignedStaffId = actor.UserId; + t.AssignedAt = now; + } + switch (next) + { + case "IN_PROGRESS": + t.Status = "IN_PROGRESS"; + break; + case "WAITING_CUSTOMER": // đã xử lý, chờ khách xác nhận + t.Status = "RESOLVED"; + t.ResolvedAt = now; + break; + default: // DONE + t.Status = "CLOSED"; + t.ResolvedAt ??= now; + t.ClosedAt = now; + break; + } + Log(actor.UserId, LogAction.TicketResponse, LogEntity.Ticket, t.TicketId, new { note, status = next, staff = StaffCode(actor.UserId) }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // M05 · Phân bổ ô cho đơn đã đối soát → hợp đồng nháp + lịch xác minh / bàn giao + // ===================================================================== + public async Task AllocateAsync(OpsActor actor, string id, OpsAllocateRequest request, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var r = await ReservationAsync(facility.FacilityId, id, ct); + if (r.Status == "UNIT_ASSIGNED" || r.UnitAssignments.Any(a => a.Status == "ACTIVE")) + { + throw new InvalidOperationException("Đơn này đã được phân bổ kho."); + } + if (r.Status != "CONFIRMED") throw new InvalidOperationException("Đơn chưa được xác nhận thanh toán nên chưa phân bổ được."); + + var unitCode = (request.UnitCode ?? string.Empty).Trim(); + var unit = await dbContext.StorageUnits + .FirstOrDefaultAsync(u => u.FacilityId == facility.FacilityId && u.UnitNumber == unitCode, ct); + if (unit == null || unit.Status != "AVAILABLE" || unit.UnitTypeId != r.UnitTypeId) + { + throw new InvalidOperationException("Kho đã chọn không còn trống hoặc không khớp đơn đặt chỗ."); + } + var busy = await dbContext.RentalContracts.AnyAsync(c => c.UnitId == unit.UnitId + && HeldContractStatuses.Contains(c.Status) + && c.StartDate < r.ExpectedEndDate && c.EndDate > r.StartDate, ct); + if (busy) throw new InvalidOperationException("Kho đã chọn không còn trống hoặc không khớp đơn đặt chỗ."); + + var now = NowUtc; + var code = ReservationCode(r); + var confirmedAt = await dbContext.ActivityLogs + .Where(l => l.EntityType == LogEntity.Reservation && l.EntityId == r.ReservationId && l.Action == LogAction.PaymentConfirmed) + .OrderByDescending(l => l.LoggedAt) + .Select(l => (DateTime?)l.LoggedAt) + .FirstOrDefaultAsync(ct) ?? now; + + dbContext.UnitAssignments.Add(new UnitAssignment + { + ReservationId = r.ReservationId, UnitId = unit.UnitId, AssignedBy = actor.UserId, Status = "ACTIVE", AssignedAt = now + }); + r.Status = "UNIT_ASSIGNED"; + SetUnitStatus(unit, "RESERVED", actor.UserId, $"Phân bổ cho đơn {code}"); + + var contract = new RentalContract + { + ReservationId = r.ReservationId, CustomerId = r.CustomerId, UnitId = unit.UnitId, + StartDate = r.StartDate, EndDate = r.ExpectedEndDate, AgreedMonthlyRate = r.QuotedMonthlyRate, + DepositAmount = r.RequiredDeposit, Status = "DRAFT", CreatedAt = now + }; + // Khoản khách đã chuyển (nhân viên đã đối soát ở S09): cọc + tiền thuê cả kỳ + foreach (var (kind, amount) in new[] { ("DEPOSIT", r.RequiredDeposit), ("RENT", r.EstimatedAmount) }) + { + contract.Payments.Add(new Payment + { + PaymentType = kind, Amount = amount, Currency = "VND", PaymentMethod = "BANK_TRANSFER", + TransactionReference = code, DueDate = r.StartDate, PaidAt = confirmedAt, Status = "PAID", + CreatedAt = now, UpdatedAt = now + }); + } + // Chưa giao cho nhân viên nào: người phụ trách tạm là quản lý (bảng M06 hiện "Cần xử lý") + contract.HandoverRecord = new HandoverRecord + { + StaffId = actor.UserId, + ScheduledAt = r.CheckInAppointmentAt ?? UtcFromLocal(r.StartDate, 9), + Status = "SCHEDULED", + CreatedAt = now + }; + dbContext.RentalContracts.Add(contract); + Log(actor.UserId, LogAction.UnitAllocated, LogEntity.Reservation, r.ReservationId, new { unit = unit.UnitNumber }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // M06 · Giao việc bàn giao / trả kho / hỗ trợ cho nhân viên cùng cơ sở + // ===================================================================== + public async Task AssignAsync(OpsActor actor, string id, OpsAssignRequest request, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var staff = await FacilityStaffAsync(facility.FacilityId, ct); + var staffUser = staff.FirstOrDefault(u => StaffCode(u.UserId) == (request.StaffId ?? string.Empty).Trim()) + ?? throw new ArgumentException("Chọn nhân viên phụ trách."); + + var reference = (id ?? string.Empty).Trim(); + if (reference.StartsWith("PC-", StringComparison.OrdinalIgnoreCase)) reference = reference[3..]; + + if (reference.StartsWith("BG-", StringComparison.OrdinalIgnoreCase)) + { + var h = await HandoverAsync(facility.FacilityId, reference, "BG-", ct); + if (h.Status is "HANDED_OVER" or "CANCELLED") throw new InvalidOperationException("Công việc đã hoàn tất."); + h.StaffId = staffUser.UserId; + Log(actor.UserId, LogAction.TaskAssigned, LogEntity.Handover, h.HandoverId, new { staff = StaffCode(staffUser.UserId) }); + } + else if (reference.StartsWith("TK-", StringComparison.OrdinalIgnoreCase)) + { + var i = await InspectionAsync(facility.FacilityId, reference, ct); + if (i.Status is "COMPLETED" or "CANCELLED") throw new InvalidOperationException("Công việc đã hoàn tất."); + i.StaffId = staffUser.UserId; + Log(actor.UserId, LogAction.TaskAssigned, LogEntity.Return, i.InspectionId, new { staff = StaffCode(staffUser.UserId) }); + } + else if (reference.StartsWith("HT-", StringComparison.OrdinalIgnoreCase)) + { + var t = await TicketAsync(facility.FacilityId, reference, ct); + if (t.Status is "RESOLVED" or "CLOSED" or "CANCELLED") throw new InvalidOperationException("Công việc đã hoàn tất."); + t.AssignedStaffId = staffUser.UserId; + t.AssignedAt = NowUtc; + if (t.Status == "OPEN") t.Status = "ASSIGNED"; + Log(actor.UserId, LogAction.TaskAssigned, LogEntity.Ticket, t.TicketId, new { staff = StaffCode(staffUser.UserId) }); + } + else + { + throw new KeyNotFoundException("Không tìm thấy công việc."); + } + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // M03 · Duyệt / từ chối gia hạn + // ===================================================================== + private async Task RenewalAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "GH-", "yêu cầu gia hạn"); + return await dbContext.ContractRenewals + .Include(r => r.Contract).ThenInclude(c => c.Unit) + .FirstOrDefaultAsync(r => r.RenewalId == id && r.Contract.Unit.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu gia hạn tại cơ sở của bạn."); + } + + public async Task ApproveRenewalAsync(OpsActor actor, string id, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var r = await RenewalAsync(facility.FacilityId, id, ct); + if (r.Status != "PENDING") throw new InvalidOperationException("Yêu cầu này đã được xử lý."); + var contract = r.Contract; + if (contract.Status is not ("ACTIVE" or "EXPIRING" or "OVERDUE")) + { + throw new InvalidOperationException("Hợp đồng không còn hiệu lực để gia hạn."); + } + + var now = NowUtc; + r.Status = "APPROVED"; + r.ApprovedBy = actor.UserId; + r.ApprovedAt = now; + contract.EndDate = r.NewEndDate; + if (contract.Status is "EXPIRING" or "OVERDUE") contract.Status = "ACTIVE"; + + // Khoản gia hạn khách cần thanh toán (hiện ở "Thanh toán" của khách) + dbContext.Payments.Add(new Payment + { + ContractId = contract.ContractId, RenewalId = r.RenewalId, PaymentType = "RENEWAL", Amount = r.RenewalAmount, + Currency = "VND", PaymentMethod = "BANK_TRANSFER", DueDate = r.OldEndDate, Status = "PENDING", + CreatedAt = now, UpdatedAt = now + }); + Log(actor.UserId, LogAction.RenewalApproved, LogEntity.Renewal, r.RenewalId, new { newEndDate = r.NewEndDate.ToString("yyyy-MM-dd") }); + await dbContext.SaveChangesAsync(ct); + } + + public async Task RejectRenewalAsync(OpsActor actor, string id, OpsRejectRequest request, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var r = await RenewalAsync(facility.FacilityId, id, ct); + if (r.Status != "PENDING") throw new InvalidOperationException("Yêu cầu này đã được xử lý."); + var reason = Clip(request.Reason, 500); + if (reason.Length == 0) throw new ArgumentException("Nhập lý do từ chối để gửi cho khách hàng."); + + r.Status = "REJECTED"; + r.ApprovedBy = actor.UserId; // người quyết định + r.ApprovedAt = NowUtc; + Log(actor.UserId, LogAction.RenewalRejected, LogEntity.Renewal, r.RenewalId, new { reason }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // M07 · Nhắc khách / xác nhận hoàn cọc sau trả kho + // ===================================================================== + public async Task RemindAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var contract = await ContractAsync(facility.FacilityId, id, ct); + var note = Clip(request.Note, 500); + if (note.Length == 0) note = "Đã liên hệ nhắc khách thanh toán / xử lý hợp đồng."; + + var stamp = (NowUtc + VnOffset).ToString("dd/MM/yyyy HH:mm", Invariant); + foreach (var oc in contract.OverdueCases.Where(o => o.Status is not ("RESOLVED" or "ESCALATED"))) + { + oc.Status = "CONTACTED"; + oc.Notes = string.IsNullOrWhiteSpace(oc.Notes) ? $"{stamp}: {note}" : $"{oc.Notes}\n{stamp}: {note}"; + } + Log(actor.UserId, LogAction.OverdueReminder, LogEntity.Contract, contract.ContractId, new { note }); + await dbContext.SaveChangesAsync(ct); + } + + public async Task ConfirmRefundAsync(OpsActor actor, string id, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var contract = await ContractAsync(facility.FacilityId, id, ct); + if (contract.Status != "RETURN_PENDING" || !contract.ReturnInspections.Any(i => i.Status == "COMPLETED")) + { + throw new InvalidOperationException("Hợp đồng chưa có biên bản trả kho."); + } + + var now = NowUtc; + var unpaidPayments = contract.Payments.Where(p => (p.Status == "PENDING" || p.Status == "FAILED") && p.PaymentType != "REFUND").ToList(); + var unpaid = unpaidPayments.Sum(p => p.Amount); + var refund = Math.Max(0, contract.DepositAmount - unpaid); + + // Khoản còn nợ được trừ vào tiền cọc + foreach (var p in unpaidPayments) + { + p.Status = "PAID"; + p.PaidAt = now; + p.TransactionReference = "Trừ vào tiền cọc"; + p.UpdatedAt = now; + } + if (refund > 0) + { + dbContext.Payments.Add(new Payment + { + ContractId = contract.ContractId, PaymentType = "REFUND", Amount = refund, Currency = "VND", + PaymentMethod = "BANK_TRANSFER", TransactionReference = $"Hoàn cọc {ContractCode(contract)}", + PaidAt = now, Status = "PAID", CreatedAt = now, UpdatedAt = now + }); + } + contract.Status = "COMPLETED"; + contract.CompletedAt = now; + foreach (var oc in contract.OverdueCases.Where(o => o.Status != "RESOLVED")) + { + oc.Status = "RESOLVED"; + oc.ResolvedAt = now; + } + SetUnitStatus(contract.Unit, "AVAILABLE", actor.UserId, $"Đã trả kho, hoàn cọc · {ContractCode(contract)}"); + Log(actor.UserId, LogAction.DepositRefunded, LogEntity.Contract, contract.ContractId, new { refund, deducted = unpaid }); + await dbContext.SaveChangesAsync(ct); + return refund; + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs new file mode 100644 index 0000000..d599f22 --- /dev/null +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs @@ -0,0 +1,386 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Services; + +/// GET /api/ops/board — toàn bộ dữ liệu màn S01–S09 (và M01–M08 nếu là quản lý) của cơ sở được phân công. +public partial class FacilityOpsService +{ + public async Task GetBoardAsync(OpsActor actor, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var fid = facility.FacilityId; + var now = NowUtc; + var today = VnToday; + var recent = now.AddDays(-RecentDays); + + var staffUsers = await FacilityStaffAsync(fid, ct); + var staffIds = staffUsers.Select(u => u.UserId).ToHashSet(); + string? StaffOf(long? userId) => userId.HasValue && staffIds.Contains(userId.Value) ? StaffCode(userId.Value) : null; + var shift = Shift(facility); + + var meUser = await dbContext.Users.AsNoTracking().FirstAsync(u => u.UserId == actor.UserId, ct); + var me = new OpsStaffDto(StaffCode(meUser.UserId), meUser.FullName, shift); + var staff = staffUsers.Select(u => new OpsStaffDto(StaffCode(u.UserId), u.FullName, shift)).ToList(); + + // ---- Dữ liệu gốc của cơ sở + var units = await dbContext.StorageUnits + .AsNoTracking() + .Include(u => u.UnitType) + .Where(u => u.FacilityId == fid) + .OrderBy(u => u.UnitNumber) + .ToListAsync(ct); + + var contracts = await dbContext.RentalContracts + .AsNoTracking() + .AsSplitQuery() + .Include(c => c.Customer) + .Include(c => c.Reservation) + .Include(c => c.Unit).ThenInclude(u => u.UnitType) + .Include(c => c.HandoverRecord) + .Include(c => c.ReturnInspections) + .Include(c => c.ContractRenewals) + .Include(c => c.Payments) + .Include(c => c.AccessCredentials) + .Where(c => c.Unit.FacilityId == fid + && (HeldContractStatuses.Contains(c.Status) + || (c.Status == "COMPLETED" && c.CompletedAt >= recent))) + .ToListAsync(ct); + + var reservations = await dbContext.Reservations + .AsNoTracking() + .Include(r => r.Customer) + .Include(r => r.UnitType) + .Include(r => r.UnitAssignments).ThenInclude(a => a.Unit) + .Where(r => r.FacilityId == fid + && (r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED" + || ((r.Status == "UNIT_ASSIGNED" || r.Status == "CHECKED_IN") && r.CreatedAt >= now.AddDays(-60)))) + .ToListAsync(ct); + + var tickets = await dbContext.SupportTickets + .AsNoTracking() + .Include(t => t.Customer) + .Include(t => t.Unit) + .Include(t => t.Contract).ThenInclude(c => c!.Unit) + .Where(t => ((t.Unit != null && t.Unit.FacilityId == fid) || (t.Contract != null && t.Contract.Unit.FacilityId == fid)) + && t.Status != "CANCELLED" + && ((t.Status != "RESOLVED" && t.Status != "CLOSED") + || (t.ClosedAt ?? t.ResolvedAt ?? t.CreatedAt) >= recent)) + .OrderByDescending(t => t.CreatedAt) + .ToListAsync(ct); + + var reservationLogs = await LogsAsync(LogEntity.Reservation, reservations.Select(r => r.ReservationId).ToList(), ct); + var handoverLogs = await LogsAsync(LogEntity.Handover, contracts.Where(c => c.HandoverRecord != null).Select(c => c.HandoverRecord!.HandoverId).ToList(), ct); + var returnLogs = await LogsAsync(LogEntity.Return, contracts.SelectMany(c => c.ReturnInspections).Select(i => i.InspectionId).ToList(), ct); + var ticketLogs = await LogsAsync(LogEntity.Ticket, tickets.Select(t => t.TicketId).ToList(), ct); + var renewalLogs = await LogsAsync(LogEntity.Renewal, contracts.SelectMany(c => c.ContractRenewals).Select(r => r.RenewalId).ToList(), ct); + var contractLogs = await LogsAsync(LogEntity.Contract, contracts.Select(c => c.ContractId).ToList(), ct); + + ActivityLog? Last(List logs, long id, params string[] actions) => + logs.LastOrDefault(l => l.EntityId == id && actions.Contains(l.Action)); + + // ---- M01/M02 · Ô kho + var heldByUnit = contracts + .Where(c => HeldContractStatuses.Contains(c.Status)) + .GroupBy(c => c.UnitId) + .ToDictionary(g => g.Key, g => g.OrderByDescending(c => c.CreatedAt).First()); + + string UnitState(StorageUnit u) + { + heldByUnit.TryGetValue(u.UnitId, out var c); + switch (u.Status) + { + case "AVAILABLE": return "EMPTY"; + case "RESERVED": + case "ASSIGNED": return "WAITING_HANDOVER"; + case "INSPECTION": return "INSPECTION"; + case "MAINTENANCE": + case "OUT_OF_SERVICE": return "MAINTENANCE"; + } + if (c == null) return "ACTIVE"; + if (c.Status == "OVERDUE" || c.EndDate < today) return "OVERDUE"; + if (c.Status == "EXPIRING" || c.EndDate <= today.AddDays(14)) return "EXPIRING"; + return "ACTIVE"; + } + + var unitDtos = units.Select(u => + { + heldByUnit.TryGetValue(u.UnitId, out var c); + var floor = (u.Floor ?? string.Empty).Replace("Tầng", string.Empty).Trim(); + return new OpsUnitDto(u.UnitNumber, c?.Customer.FullName, u.UnitType.Area, floor.Length > 0 ? floor : "trệt", + TypeKey(u.UnitType), UnitState(u), c?.EndDate); + }).ToList(); + + // ---- S09 · Đối soát chuyển khoản + var payments = new List(); + foreach (var r in reservations) + { + var reported = Last(reservationLogs, r.ReservationId, LogAction.TransferReported); + var decision = Last(reservationLogs, r.ReservationId, LogAction.PaymentConfirmed, LogAction.PaymentMismatch); + string status; + if (r.Status == "PENDING_VERIFICATION") + { + status = decision?.Action == LogAction.PaymentMismatch && (reported == null || decision.LoggedAt >= reported.LoggedAt) ? "MISMATCH" : "PENDING"; + } + else if (decision?.Action == LogAction.PaymentConfirmed && decision.LoggedAt >= now.AddDays(-3)) + { + status = "CONFIRMED"; + } + else continue; + + var code = ReservationCode(r); + payments.Add(new OpsPaymentDto( + code, r.Customer.FullName, r.EstimatedAmount + r.RequiredDeposit, "Chuyển khoản ngân hàng", + Local(reported?.LoggedAt ?? r.CreatedAt)!, code, OfferLabel(r.UnitType), r.StartDate, r.ExpectedEndDate, + LocalOrDate(r.CheckInAppointmentAt, r.StartDate), status, + status == "MISMATCH" ? Read(decision!, "note") : null, + status == "PENDING" ? null : Local(decision?.LoggedAt))); + } + payments = payments.OrderBy(p => p.Status == "PENDING" ? 0 : 1).ThenByDescending(p => p.ReportedAt).ToList(); + + // ---- S02 / S03 · Xác minh khách + bàn giao + var handoverContracts = contracts + .Where(c => c.HandoverRecord != null + && c.HandoverRecord.Status != "CANCELLED" + && (c.HandoverRecord.Status != "HANDED_OVER" || c.HandoverRecord.HandoverAt >= now.AddDays(-3))) + .OrderBy(c => c.HandoverRecord!.ScheduledAt) + .ToList(); + + var verifications = handoverContracts.Select(c => + { + var h = c.HandoverRecord!; + var verified = Last(handoverLogs, h.HandoverId, LogAction.CustomerVerified); + return new OpsVerificationDto( + VerificationCode(h.HandoverId), ReservationCode(c.Reservation), c.Customer.FullName, c.Unit.UnitNumber, + LocalOrDate(h.ScheduledAt, c.StartDate), h.Status == "SCHEDULED" ? "TODO" : "DONE", + verified != null ? Read(verified, "docType") : null, + verified != null ? Read(verified, "docLast4") : null, + Local(h.VerifiedAt)); + }).ToList(); + + var handovers = handoverContracts.Select(c => + { + var h = c.HandoverRecord!; + var done = Last(handoverLogs, h.HandoverId, LogAction.HandoverCompleted); + var method = done != null ? Read(done, "method") : h.Status == "HANDED_OVER" ? MethodOf(c.AccessCredentials) : null; + return new OpsHandoverDto(HandoverCode(h.HandoverId), VerificationCode(h.HandoverId), c.Unit.UnitNumber, c.Customer.FullName, + h.Status == "HANDED_OVER" ? "DONE" : "WAITING", method, Local(h.HandoverAt)); + }).ToList(); + + // ---- S04 · Kiểm tra trả kho + var inspections = contracts + .SelectMany(c => c.ReturnInspections.Select(i => (Contract: c, Inspection: i))) + .Where(x => x.Inspection.Status != "CANCELLED" + && (x.Inspection.Status != "COMPLETED" || x.Inspection.InspectedAt >= recent)) + .OrderBy(x => x.Inspection.ScheduledAt) + .ToList(); + + var returns = inspections.Select(x => + { + var (c, i) = x; + var submitted = Last(returnLogs, i.InspectionId, LogAction.ReturnInspected); + OpsReturnReportDto? report = submitted == null ? null : new OpsReturnReportDto( + Read(submitted, "items") ?? "", Read(submitted, "walls") ?? "", Read(submitted, "keys") ?? "", Read(submitted, "proposal") ?? ""); + return new OpsReturnDto(ReturnCode(i.InspectionId), ContractCode(c), c.Unit.UnitNumber, c.Customer.FullName, + LocalOrDate(i.ScheduledAt, c.EndDate), c.DepositAmount, Unpaid(c), i.Status == "COMPLETED" ? "SUBMITTED" : "SCHEDULED", + report, Local(i.InspectedAt)); + }).ToList(); + + // ---- S05 · Yêu cầu hỗ trợ + var ticketDtos = tickets.Select(t => + { + var notes = ticketLogs + .Where(l => l.EntityId == t.TicketId && l.Action == LogAction.TicketResponse) + .Select(l => new OpsNoteDto(Read(l, "note") ?? "", Local(l.LoggedAt)!, Read(l, "staff"))) + .ToList(); + var unitCode = t.Unit?.UnitNumber ?? t.Contract?.Unit.UnitNumber ?? "—"; + return new OpsTicketDto(TicketCode(t.TicketId), unitCode, t.Customer.FullName, t.Title, Local(t.CreatedAt)!, + Local(t.AssignedAt ?? t.CreatedAt)!, TicketState(t), t.AssignedStaffId.HasValue ? StaffCode(t.AssignedStaffId.Value) : null, notes); + }).ToList(); + + if (!actor.IsManager) + { + return new OpsBoardDto(new OpsFacilityInfoDto(fid, facility.Name, facility.Address), me, staff, unitDtos, + payments, verifications, handovers, returns, ticketDtos, null, null, null, null, null); + } + + // ---- M05 · Đơn chờ phân bổ ô + var allocations = new List(); + foreach (var r in reservations) + { + var allocated = Last(reservationLogs, r.ReservationId, LogAction.UnitAllocated); + string status; + string? unit = null; + if (r.Status == "CONFIRMED" && !r.UnitAssignments.Any(a => a.Status == "ACTIVE")) status = "PENDING"; + else if (r.Status == "UNIT_ASSIGNED" && allocated != null && allocated.LoggedAt >= now.AddDays(-3)) + { + status = "DONE"; + unit = r.UnitAssignments.Where(a => a.Status == "ACTIVE").OrderByDescending(a => a.AssignedAt).FirstOrDefault()?.Unit.UnitNumber; + } + else continue; + allocations.Add(new OpsAllocationDto(ReservationCode(r), r.Customer.FullName, TypeKey(r.UnitType), OfferLabel(r.UnitType), + r.UnitType.Area, r.UnitType.Area, r.StartDate, r.ExpectedEndDate, LocalOrDate(r.CheckInAppointmentAt, r.StartDate), status, unit)); + } + allocations = allocations.OrderBy(a => a.Status == "PENDING" ? 0 : 1).ThenBy(a => a.Start).ToList(); + + // ---- M03 · Gia hạn + var renewals = contracts + .SelectMany(c => c.ContractRenewals.Select(r => (Contract: c, Renewal: r))) + .Where(x => x.Renewal.Status == "PENDING" || (x.Renewal.ApprovedAt.HasValue && x.Renewal.ApprovedAt >= recent)) + .OrderBy(x => x.Renewal.Status == "PENDING" ? 0 : 1).ThenBy(x => x.Renewal.RequestedAt) + .Select(x => + { + var (c, r) = x; + var rejected = Last(renewalLogs, r.RenewalId, LogAction.RenewalRejected); + var status = r.Status switch { "PAID" => "APPROVED", "CANCELLED" => "REJECTED", _ => r.Status }; + return new OpsRenewalDto(RenewalCode(r.RenewalId), ContractCode(c), c.Customer.FullName, c.Unit.UnitNumber, + r.OldEndDate, r.NewEndDate, r.RenewalPeriodMonths, Local(r.RequestedAt)!, status, + status == "REJECTED" && rejected != null ? Read(rejected, "reason") : null, Local(r.ApprovedAt)); + }) + .ToList(); + + // ---- M07 · Hợp đồng cần xử lý + var contractDtos = new List(); + foreach (var c in contracts.OrderBy(c => c.EndDate)) + { + var unpaid = Unpaid(c); + var inspected = c.ReturnInspections.Any(i => i.Status == "COMPLETED"); + var lastRenewal = c.ContractRenewals.OrderByDescending(r => r.RequestedAt).FirstOrDefault(); + string state, due; + decimal amount = 0; + + if (c.Status == "COMPLETED") + { + var refunded = Last(contractLogs, c.ContractId, LogAction.DepositRefunded); + if (refunded == null) continue; + state = "CLOSED"; + due = $"Hoàn cọc {Money(decimal.TryParse(Read(refunded, "refund"), System.Globalization.NumberStyles.Number, Invariant, out var rf) ? rf : 0)} sau khi trừ khoản còn nợ"; + } + else if (c.Status == "RETURN_PENDING" && inspected) + { + state = "RETURNED"; + due = $"{Money(unpaid)} · Chờ quản lý xác nhận hoàn cọc"; + amount = unpaid; + } + else if (lastRenewal?.Status == "PENDING") + { + state = "RENEWAL"; + due = "Yêu cầu gia hạn"; + } + else if (c.Status == "OVERDUE" || (c.Status is "ACTIVE" or "EXPIRING" && c.EndDate < today)) + { + state = "OVERDUE"; + due = unpaid > 0 ? "Tiền thuê kỳ mới · Chưa thanh toán" : "Đã hết hạn · Chưa gia hạn hoặc trả kho"; + amount = unpaid; + } + else if (lastRenewal is { ApprovedAt: not null } && lastRenewal.ApprovedAt >= recent) + { + state = "RESOLVED"; + var reason = Read(Last(renewalLogs, lastRenewal.RenewalId, LogAction.RenewalRejected) ?? new ActivityLog(), "reason"); + due = lastRenewal.Status == "REJECTED" + ? $"Từ chối gia hạn · {reason}" + : $"Đã duyệt gia hạn đến {lastRenewal.NewEndDate:dd/MM/yyyy}"; + } + else continue; + + var reminders = contractLogs + .Where(l => l.EntityId == c.ContractId && l.Action == LogAction.OverdueReminder) + .Select(l => new OpsReminderDto(Read(l, "note") ?? "", Local(l.LoggedAt)!)) + .ToList(); + contractDtos.Add(new OpsContractDto(ContractCode(c), c.Customer.FullName, c.Unit.UnitNumber, c.EndDate, due, amount, state, reminders)); + } + + // ---- M06 · Phân công công việc + var assignments = new List(); + foreach (var c in handoverContracts) + { + var h = c.HandoverRecord!; + var done = h.Status == "HANDED_OVER"; + var who = StaffOf(h.StaffId); + assignments.Add(new OpsAssignmentDto($"PC-{HandoverCode(h.HandoverId)}", $"Bàn giao {c.Unit.UnitNumber} · {c.Customer.FullName}", + LocalOrDate(h.ScheduledAt, c.StartDate), who, done ? "DONE" : who == null ? "OPEN" : h.Status == "VERIFIED" ? "ACCEPTED" : "WAITING", + HandoverCode(h.HandoverId))); + } + foreach (var (c, i) in inspections) + { + var who = StaffOf(i.StaffId); + assignments.Add(new OpsAssignmentDto($"PC-{ReturnCode(i.InspectionId)}", $"Kiểm tra trả kho {c.Unit.UnitNumber} · {c.Customer.FullName}", + LocalOrDate(i.ScheduledAt, c.EndDate), who, i.Status == "COMPLETED" ? "DONE" : who == null ? "OPEN" : i.Status == "IN_PROGRESS" ? "ACCEPTED" : "WAITING", + ReturnCode(i.InspectionId))); + } + foreach (var t in tickets) + { + var who = StaffOf(t.AssignedStaffId); + var state = TicketState(t); + assignments.Add(new OpsAssignmentDto($"PC-{TicketCode(t.TicketId)}", $"{TicketCode(t.TicketId)} · {t.Title}", + Local(t.AssignedAt ?? t.CreatedAt), who, + state == "DONE" || state == "WAITING_CUSTOMER" ? "DONE" : who == null ? "OPEN" : state == "IN_PROGRESS" && t.Status == "IN_PROGRESS" ? "ACCEPTED" : "WAITING", + TicketCode(t.TicketId))); + } + assignments = assignments.OrderBy(a => a.Status == "DONE" ? 1 : 0).ThenBy(a => a.When).ToList(); + + var revenue = await RevenueAsync(fid, ct); + + return new OpsBoardDto(new OpsFacilityInfoDto(fid, facility.Name, facility.Address), me, staff, unitDtos, + payments, verifications, handovers, returns, ticketDtos, allocations, renewals, contractDtos, assignments, revenue); + } + + /// + /// Trạng thái hỗ trợ theo giao diện: OPEN (chưa phân công) · IN_PROGRESS · WAITING_CUSTOMER (đã xử lý, chờ khách xác nhận) · DONE. + /// + private static string TicketState(SupportTicket t) => t.Status switch + { + "OPEN" => t.AssignedStaffId.HasValue ? "IN_PROGRESS" : "OPEN", + "ASSIGNED" or "IN_PROGRESS" => "IN_PROGRESS", + "RESOLVED" => "WAITING_CUSTOMER", + _ => "DONE", + }; + + private static string? MethodOf(IEnumerable credentials) + { + var cred = credentials.OrderByDescending(a => a.IssuedAt).FirstOrDefault(); + if (cred == null) return null; + if (cred.CredentialType == "ACCESS_CARD") return "CARD"; + return (cred.CredentialReference ?? string.Empty).StartsWith("FINGER", StringComparison.Ordinal) ? "FINGER" : "PIN"; + } + + /// + /// M04 · Doanh thu thuê và phí 6 tháng gần nhất (triệu đồng, theo ngày thu giờ Việt Nam) — không gồm tiền cọc + /// và hoàn tiền (cùng định nghĩa "rentalAndFeeRevenue" của báo cáo Vận hành KD, SRS 10.2). + /// Cơ cấu theo loại kho là của tháng hiện tại. + /// + private async Task RevenueAsync(long facilityId, CancellationToken ct) + { + var today = VnToday; + var firstMonth = new DateOnly(today.Year, today.Month, 1).AddMonths(-5); + var fromUtc = UtcFromLocal(firstMonth, 0); + + var rows = await dbContext.Payments + .AsNoTracking() + .Where(p => p.Contract.Unit.FacilityId == facilityId + && p.PaidAt != null && p.PaidAt >= fromUtc + && (p.Status == "PAID" || p.Status == "REFUNDED" || p.Status == "PARTIALLY_REFUNDED") + && p.PaymentType != "DEPOSIT" && p.PaymentType != "REFUND") + .Select(p => new { p.Amount, p.PaidAt, Cold = p.Contract.Unit.UnitType.ClimateControlled }) + .ToListAsync(ct); + + static decimal Million(decimal v) => Math.Round(v / 1_000_000m, 1, MidpointRounding.AwayFromZero); + + var months = Enumerable.Range(0, 6).Select(i => + { + var m = firstMonth.AddMonths(i); + var sum = rows.Where(r => { var d = r.PaidAt!.Value + VnOffset; return d.Year == m.Year && d.Month == m.Month; }).Sum(r => r.Amount); + return new OpsRevenueMonthDto($"Tháng {m.Month}", m.Month, m.Year, Million(sum)); + }).ToList(); + + var current = rows.Where(r => { var d = r.PaidAt!.Value + VnOffset; return d.Year == today.Year && d.Month == today.Month; }).ToList(); + var byType = new List + { + new("Kho thường", Million(current.Where(r => !r.Cold).Sum(r => r.Amount))), + new("Kho lạnh", Million(current.Where(r => r.Cold).Sum(r => r.Amount))), + }; + + return new OpsRevenueDto(months, byType, today); + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.cs new file mode 100644 index 0000000..849caf9 --- /dev/null +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.cs @@ -0,0 +1,220 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Entities; +using StorageProject.Core.Interfaces; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +/// +/// Khu Nhân viên cơ sở (S01–S09) và Quản lý cơ sở (M01–M08) — /api/ops/*. +/// Mọi truy vấn và thao tác chỉ trong cơ sở đang được phân công cho tài khoản (SRS A06). +/// Phần dùng chung: xác định cơ sở, mã hiển thị, giờ Việt Nam, nhật ký. Màn hình: FacilityOpsService.Board.cs; +/// thao tác: FacilityOpsService.Actions.cs. Nghiệp vụ khớp src/ops/reducer.js của giao diện. +/// +public partial class FacilityOpsService(AppDbContext dbContext) : IFacilityOpsService +{ + private static readonly TimeSpan VnOffset = TimeSpan.FromHours(7); + private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; + + // Hợp đồng còn gắn với ô kho (ô đang có khách hoặc đã giữ cho khách) + private static readonly string[] HeldContractStatuses = ["DRAFT", "ACTIVE", "EXPIRING", "OVERDUE", "RETURN_PENDING"]; + + // Khoảng thời gian còn hiện việc đã xong trên bảng (để nhân viên / quản lý thấy kết quả vừa xử lý) + private const int RecentDays = 14; + + private static DateTime NowUtc => DateTime.UtcNow; + private static DateOnly VnToday => DateOnly.FromDateTime(DateTime.UtcNow + VnOffset); + + /// Giờ Việt Nam "yyyy-MM-ddTHH:mm:ss" (DB lưu UTC — D10). + private static string? Local(DateTime? utc) => + utc.HasValue ? (utc.Value + VnOffset).ToString("yyyy-MM-dd'T'HH:mm:ss", Invariant) : null; + + private static string LocalOrDate(DateTime? utc, DateOnly fallback, int hour = 9) => + Local(utc) ?? fallback.ToDateTime(new TimeOnly(hour, 0)).ToString("yyyy-MM-dd'T'HH:mm:ss", Invariant); + + private static DateTime UtcFromLocal(DateOnly date, int hour) => + DateTime.SpecifyKind(date.ToDateTime(new TimeOnly(hour, 0)) - VnOffset, DateTimeKind.Utc); + + private static string Money(decimal amount) => + string.Format(CultureInfo.GetCultureInfo("vi-VN"), "{0:#,0} đ", amount); + + // ------------------------------------------------------------------ + // Mã hiển thị — giống mã khách hàng thấy (src/api/mappers.js) + // ------------------------------------------------------------------ + internal static string ReservationCode(Reservation r) => + $"SS-{(r.CreatedAt + VnOffset):yyyyMMdd}-{r.ReservationId:0000}"; + internal static string ContractCode(RentalContract c) => $"HĐ-{c.StartDate.Year}-{c.ContractId:0000}"; + internal static string VerificationCode(long handoverId) => $"XM-{handoverId:0000}"; + internal static string HandoverCode(long handoverId) => $"BG-{handoverId:0000}"; + internal static string ReturnCode(long inspectionId) => $"TK-{inspectionId:0000}"; + internal static string TicketCode(long ticketId) => $"HT-{ticketId:0000}"; + internal static string RenewalCode(long renewalId) => $"GH-{renewalId:0000}"; + internal static string StaffCode(long userId) => $"NV-{userId:00}"; + + /// Đọc số cuối của mã ("SS-20261014-0012" → 12). Sai tiền tố / không có số → 404. + internal static long ParseCode(string? code, string prefix, string what) + { + var text = (code ?? string.Empty).Trim(); + if (!text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + throw new KeyNotFoundException($"Không tìm thấy {what}."); + } + var m = Regex.Match(text, @"(\d+)$"); + if (!m.Success || !long.TryParse(m.Groups[1].Value, out var id) || id <= 0) + { + throw new KeyNotFoundException($"Không tìm thấy {what}."); + } + return id; + } + + private static string OfferLabel(UnitType type) => + $"{(type.ClimateControlled ? "Kho lạnh" : "Kho thường")} · Cỡ {(type.Area <= 20 ? "M" : "L")} · {type.Area.ToString("0.#", Invariant)} m²"; + + private static string TypeKey(UnitType type) => type.ClimateControlled ? "climate" : "normal"; + + // ------------------------------------------------------------------ + // Cơ sở được phân công + nhân viên của cơ sở + // ------------------------------------------------------------------ + private async Task FacilityOfAsync(OpsActor actor, CancellationToken ct) + { + var today = VnToday; + var assignment = await dbContext.UserFacilities + .AsNoTracking() + .Include(uf => uf.Facility) + .Where(uf => uf.UserId == actor.UserId + && uf.Status == "ACTIVE" + && uf.AssignedFrom <= today + && (uf.AssignedTo == null || uf.AssignedTo >= today)) + .OrderByDescending(uf => uf.AssignedFrom) + .FirstOrDefaultAsync(ct); + + return assignment?.Facility + ?? throw new UnauthorizedAccessException("Tài khoản chưa được phân công cơ sở. Liên hệ quản trị hệ thống."); + } + + private static void RequireManager(OpsActor actor) + { + if (!actor.IsManager) + { + throw new UnauthorizedAccessException("Chỉ quản lý cơ sở được thực hiện thao tác này."); + } + } + + /// Nhân viên (role STAFF) đang được phân công cùng cơ sở. + private async Task> FacilityStaffAsync(long facilityId, CancellationToken ct) + { + var today = VnToday; + return await dbContext.Users + .AsNoTracking() + .Where(u => u.Status == "ACTIVE" + && u.UserRoles.Any(ur => ur.Role.RoleName == "STAFF") + && u.UserFacilities.Any(uf => uf.FacilityId == facilityId + && uf.Status == "ACTIVE" + && uf.AssignedFrom <= today + && (uf.AssignedTo == null || uf.AssignedTo >= today))) + .OrderBy(u => u.FullName) + .ToListAsync(ct); + } + + private static string Shift(Facility f) => + f.OpeningTime.HasValue && f.ClosingTime.HasValue + ? $"{f.OpeningTime.Value:HH\\:mm}–{f.ClosingTime.Value:HH\\:mm}" + : "Theo giờ cơ sở"; + + // ------------------------------------------------------------------ + // Nhật ký (activity_logs, BR13) — cũng là nơi lưu phần giao diện cần mà bảng chưa có cột + // (giấy tờ đã xác minh, biên bản trả kho, phản hồi hỗ trợ, lý do từ chối, lần nhắc khách) + // ------------------------------------------------------------------ + private static class LogAction + { + public const string TransferReported = "TRANSFER_REPORTED"; + public const string PaymentConfirmed = "PAYMENT_CONFIRMED"; + public const string PaymentMismatch = "PAYMENT_MISMATCH"; + public const string CustomerVerified = "CUSTOMER_VERIFIED"; + public const string HandoverCompleted = "HANDOVER_COMPLETED"; + public const string ReturnInspected = "RETURN_INSPECTED"; + public const string TicketResponse = "TICKET_RESPONSE"; + public const string UnitAllocated = "UNIT_ALLOCATED"; + public const string TaskAssigned = "TASK_ASSIGNED"; + public const string RenewalApproved = "RENEWAL_APPROVED"; + public const string RenewalRejected = "RENEWAL_REJECTED"; + public const string OverdueReminder = "OVERDUE_REMINDER"; + public const string DepositRefunded = "DEPOSIT_REFUNDED"; + } + + private static class LogEntity + { + public const string Reservation = "RESERVATION"; + public const string Handover = "HANDOVER_RECORD"; + public const string Return = "RETURN_INSPECTION"; + public const string Ticket = "SUPPORT_TICKET"; + public const string Renewal = "CONTRACT_RENEWAL"; + public const string Contract = "RENTAL_CONTRACT"; + } + + private void Log(long userId, string action, string entityType, long entityId, object value) => + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = userId, + Action = action, + EntityType = entityType, + EntityId = entityId, + NewValue = JsonSerializer.Serialize(value), + LoggedAt = NowUtc + }); + + private static string? Read(ActivityLog log, string field) + { + if (string.IsNullOrWhiteSpace(log.NewValue)) return null; + try + { + using var doc = JsonDocument.Parse(log.NewValue); + return doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty(field, out var v) + ? v.ValueKind == JsonValueKind.String ? v.GetString() : v.ToString() + : null; + } + catch (JsonException) + { + return null; + } + } + + private async Task> LogsAsync(string entityType, ICollection ids, CancellationToken ct) + { + if (ids.Count == 0) return []; + return await dbContext.ActivityLogs + .AsNoTracking() + .Where(l => l.EntityType == entityType && l.EntityId != null && ids.Contains(l.EntityId.Value)) + .OrderBy(l => l.LoggedAt) + .ToListAsync(ct); + } + + private void SetUnitStatus(StorageUnit unit, string status, long userId, string reason) + { + if (unit.Status == status) return; + dbContext.UnitStatusHistories.Add(new UnitStatusHistory + { + UnitId = unit.UnitId, + ChangedBy = userId, + OldStatus = unit.Status, + NewStatus = status, + Reason = reason.Length > 255 ? reason[..255] : reason, + ChangedAt = NowUtc + }); + unit.Status = status; + unit.UpdatedAt = NowUtc; + } + + private static decimal Unpaid(RentalContract c) => + c.Payments.Where(p => (p.Status == "PENDING" || p.Status == "FAILED") && p.PaymentType != "REFUND").Sum(p => p.Amount); + + private static string Clip(string? text, int max = 1000) + { + var t = (text ?? string.Empty).Trim(); + return t.Length > max ? t[..max] : t; + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityService.cs b/StorageProject.Infrastructure/Services/FacilityService.cs index 8ea92c3..9cf044b 100644 --- a/StorageProject.Infrastructure/Services/FacilityService.cs +++ b/StorageProject.Infrastructure/Services/FacilityService.cs @@ -153,7 +153,7 @@ public async Task> GetActiveRatesAsync(long? facili var reservedUnitsCount = await dbContext.Reservations .CountAsync(r => r.FacilityId == request.FacilityId && r.UnitTypeId == request.UnitTypeId - && (r.Status == "PENDING_PAYMENT" || r.Status == "CONFIRMED") + && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED") && r.StartDate < expectedEndDate && r.ExpectedEndDate > request.StartDate, ct); diff --git a/StorageProject.Infrastructure/Services/HandoverService.cs b/StorageProject.Infrastructure/Services/HandoverService.cs index 77da152..9be444e 100644 --- a/StorageProject.Infrastructure/Services/HandoverService.cs +++ b/StorageProject.Infrastructure/Services/HandoverService.cs @@ -19,7 +19,7 @@ public async Task ConfirmCustomerHandoverAsync(long customerId, long handoverId, // If staff already confirmed, or now both confirmed, complete handover if (handover.StaffConfirmed) { - handover.Status = "COMPLETED"; + handover.Status = "HANDED_OVER"; // CHECK chỉ cho SCHEDULED/VERIFIED/HANDED_OVER/CANCELLED handover.HandoverAt = DateTime.UtcNow; // Activate contract diff --git a/StorageProject.Infrastructure/Services/RenewalService.cs b/StorageProject.Infrastructure/Services/RenewalService.cs index 4dc73ff..de0d153 100644 --- a/StorageProject.Infrastructure/Services/RenewalService.cs +++ b/StorageProject.Infrastructure/Services/RenewalService.cs @@ -51,14 +51,14 @@ public async Task RequestRenewalAsync(long customerId, long contract .FirstOrDefaultAsync(ct) ?? throw new InvalidOperationException("Không tìm thấy hợp đồng hợp lệ."); - if (contract.Status != "ACTIVE") + if (contract.Status != "ACTIVE" && contract.Status != "EXPIRING") { throw new InvalidOperationException($"Chỉ hợp đồng ở trạng thái 'ACTIVE' mới có thể gia hạn. Trạng thái hiện tại: {contract.Status}"); } // Check if there is already a pending renewal var hasPendingRenewal = await dbContext.ContractRenewals - .AnyAsync(r => r.ContractId == contractId && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_APPROVAL"), ct); + .AnyAsync(r => r.ContractId == contractId && r.Status == "PENDING", ct); if (hasPendingRenewal) { @@ -88,7 +88,7 @@ public async Task RequestRenewalAsync(long customerId, long contract OldMonthlyRate = contract.AgreedMonthlyRate, NewMonthlyRate = newRate, RenewalAmount = renewalAmount, - Status = "PENDING_PAYMENT", + Status = "PENDING", // chờ quản lý cơ sở duyệt (M03); CHECK chỉ cho PENDING/APPROVED/REJECTED/PAID/CANCELLED RequestedAt = DateTime.UtcNow, CreatedAt = DateTime.UtcNow }; diff --git a/StorageProject.Infrastructure/Services/ReservationService.cs b/StorageProject.Infrastructure/Services/ReservationService.cs index 564c456..f40105f 100644 --- a/StorageProject.Infrastructure/Services/ReservationService.cs +++ b/StorageProject.Infrastructure/Services/ReservationService.cs @@ -1,6 +1,8 @@ +using System.Text.Json; using Microsoft.EntityFrameworkCore; using StorageProject.Core.DTOs.Reservation; using StorageProject.Core.Entities; +using StorageProject.Core.Exceptions; using StorageProject.Core.Interfaces; using StorageProject.Infrastructure.Data; @@ -121,7 +123,7 @@ public async Task CreateReservationAsync(long customerId, Create var existingReservationsCount = await dbContext.Reservations .CountAsync(r => r.FacilityId == request.FacilityId && r.UnitTypeId == request.UnitTypeId - && (r.Status == "PENDING_PAYMENT" || r.Status == "CONFIRMED") + && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED") && r.StartDate < expectedEndDate && r.ExpectedEndDate > request.StartDate, ct); @@ -195,4 +197,65 @@ public async Task CancelReservationAsync(long customerId, long reservationId, st await dbContext.SaveChangesAsync(ct); } + + /// + /// C04 / F03: khách bấm "Tôi đã chuyển khoản" → đơn chờ nhân viên đối soát (S09). + /// Gọi lại khi đơn đã chờ đối soát thì trả về đơn như cũ (an toàn khi bấm hai lần). + /// + public async Task ConfirmTransferAsync(long customerId, long reservationId, CancellationToken ct = default) + { + var reservation = await dbContext.Reservations + .Include(r => r.Facility) + .Include(r => r.UnitType) + .FirstOrDefaultAsync(r => r.ReservationId == reservationId && r.CustomerId == customerId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy đơn đặt chỗ."); + + if (reservation.Status == "PENDING_VERIFICATION") return ToDto(reservation); + if (reservation.Status != "PENDING_PAYMENT") + { + throw new InvalidOperationException("Đơn đặt chỗ này không còn chờ chuyển khoản."); + } + + var now = DateTime.UtcNow; + if (reservation.ExpiresAt.HasValue && reservation.ExpiresAt.Value <= now) + { + reservation.Status = "EXPIRED"; + reservation.CancelledAt = now; + reservation.CancellationReason = "Quá thời gian giữ chỗ chưa xác nhận chuyển khoản"; + await dbContext.SaveChangesAsync(ct); + throw new ReservationExpiredException("Đơn đặt chỗ đã hết thời gian giữ chỗ."); + } + + reservation.Status = "PENDING_VERIFICATION"; + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = customerId, + Action = "TRANSFER_REPORTED", + EntityType = "RESERVATION", + EntityId = reservation.ReservationId, + NewValue = JsonSerializer.Serialize(new { amount = reservation.EstimatedAmount + reservation.RequiredDeposit }), + LoggedAt = now + }); + await dbContext.SaveChangesAsync(ct); + return ToDto(reservation); + } + + private static ReservationDto ToDto(Reservation r) => new( + r.ReservationId, + r.FacilityId, + r.Facility.Name, + r.UnitTypeId, + r.UnitType.TypeName, + r.StartDate, + r.ExpectedEndDate, + r.RentalPeriodMonths, + r.QuotedMonthlyRate, + r.EstimatedAmount, + r.RequiredDeposit, + r.Status, + r.ExpiresAt, + r.CancelledAt, + r.CancellationReason, + r.CreatedAt + ); } diff --git a/docs/facility-ops-api.md b/docs/facility-ops-api.md new file mode 100644 index 0000000..5a3b441 --- /dev/null +++ b/docs/facility-ops-api.md @@ -0,0 +1,78 @@ +# API Nhân viên cơ sở & Quản lý cơ sở (`/api/ops/*`) + +Dành cho role **STAFF** (Figma S01–S09) và **MANAGER** (M01–M08). Code: `StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs`, +`StorageProject.Infrastructure/Services/FacilityOpsService*.cs`. Giao diện gọi ở `src/ops/api.js`. + +Tài khoản seed (cùng cơ sở **SafeSpace Nguyễn Lương Bằng**): `staff01` / `Staff@123`, `staff02` / `Staff@123`, +`manager01` / `Manager@123`. + +Quy ước chung: + +- Mỗi tài khoản chỉ thấy và sửa dữ liệu của **cơ sở đang được phân công** (SRS A06, bảng `user_facilities`). + Chưa được phân công → **403**. Dữ liệu cơ sở khác → **404**. +- Thao tác của quản lý gọi bằng tài khoản nhân viên → **403**. Quản lý làm được mọi thao tác của nhân viên. +- Lỗi: `400 { error }` dữ liệu sai / sai trạng thái · `403 { error }` · `404 { error }`. Thành công: `200 { message }`. +- `id` trong đường dẫn là **mã hiển thị**, giống mã khách thấy: `SS-20261014-0012` (đơn đặt chỗ), `XM-0007` / `BG-0007` + (xác minh / bàn giao), `TK-0003` (trả kho), `HT-0005` (hỗ trợ), `GH-0002` (gia hạn), `HĐ-2026-0004` (hợp đồng), + `PC-BG-0007` (công việc), `NV-02` (nhân viên). +- Ngày `yyyy-MM-dd`; ngày giờ là **giờ Việt Nam** `yyyy-MM-ddTHH:mm:ss` (DB vẫn lưu UTC). Tiền là số VND. +- Mọi thao tác ghi `activity_logs`. Những thông tin bảng chưa có cột (giấy tờ đã xác minh, biên bản trả kho, + phản hồi hỗ trợ, lý do từ chối gia hạn, lần nhắc khách) cũng đọc lại từ đây — D18. + +## 1. Bảng dữ liệu — `GET /api/ops/board` + +Mẫu JSON ở cuối `BACKEND-TODO.md`. Nhân viên nhận: `facility, me, staff, units, payments, verifications, handovers, +returns, tickets`. Quản lý nhận thêm: `allocations, renewals, contracts, assignments, revenue`. + +| Phần | Lấy từ | Ghi chú | +|---|---|---| +| `units` | `storage_units` + hợp đồng đang giữ ô | `EMPTY` · `WAITING_HANDOVER` (RESERVED) · `ACTIVE` · `EXPIRING` (hết hạn trong 14 ngày) · `OVERDUE` · `INSPECTION` · `MAINTENANCE` | +| `payments` (S09) | đơn `PENDING_VERIFICATION` | `PENDING`; `MISMATCH` nếu nhân viên đã báo sai lệch; `CONFIRMED` hiện thêm 3 ngày | +| `verifications`, `handovers` (S02, S03) | `handover_records` | `SCHEDULED` → `TODO`/`WAITING`; `VERIFIED` → xác minh `DONE`; `HANDED_OVER` → bàn giao `DONE` | +| `returns` (S04) | `return_inspections` | `unpaid` = khoản PENDING/FAILED của hợp đồng | +| `tickets` (S05) | `support_tickets` của ô / hợp đồng tại cơ sở | `OPEN` · `IN_PROGRESS` · `WAITING_CUSTOMER` (DB `RESOLVED`) · `DONE` (DB `CLOSED`) | +| `allocations` (M05) | đơn `CONFIRMED` chưa có ô | `minArea = maxArea` = diện tích loại kho | +| `renewals` (M03) | `contract_renewals` `PENDING` (+ đã quyết trong 14 ngày) | | +| `contracts` (M07) | hợp đồng `OVERDUE` / chờ gia hạn / đã có biên bản trả kho | `state`: `OVERDUE` · `RENEWAL` · `RETURNED` · `RESOLVED` · `CLOSED` | +| `assignments` (M06) | bàn giao, trả kho, hỗ trợ chưa xong | `staff = null` → `OPEN` (chưa giao ai) | +| `revenue` (M04) | `payments` đã thu 6 tháng, theo giờ VN | Triệu đồng; không gồm cọc và hoàn tiền; `byType` là của tháng này | + +## 2. Nhân viên (STAFF, MANAGER) + +| Màn | Endpoint | Body | Kết quả | +|---|---|---|---| +| S09 | `POST /api/ops/payments/{id}/confirm` | — | Đơn `PENDING_VERIFICATION` → `CONFIRMED`, vào hàng phân bổ của quản lý | +| S09 | `POST /api/ops/payments/{id}/mismatch` | `{ note }` | Ghi sai lệch; đơn vẫn chờ đối soát. `note` rỗng → 400 | +| S02 | `POST /api/ops/verifications/{id}` | `{ docType, docNumber, photoMatched, infoMatched }` | Số giấy tờ 9/12 số hoặc hộ chiếu 1 chữ + 7 số; hai ô đối chiếu phải `true`. **Chỉ lưu 4 số cuối.** → `VERIFIED` | +| S03 | `POST /api/ops/handovers/{id}/complete` | `{ unlockMethod: "CARD" \| "PIN" \| "FINGER" }` | Chưa xác minh → 400. Hợp đồng `ACTIVE`, ô `OCCUPIED`, đơn `CHECKED_IN`, cấp `access_credentials` | +| S04 | `POST /api/ops/returns/{id}/inspection` | `{ items, walls, keys, proposal }` | Đủ 4 mục. Hợp đồng `RETURN_PENDING`, ô `INSPECTION`, thu hồi thẻ / mã | +| S05 | `POST /api/ops/tickets/{id}/responses` | `{ note, nextStatus: "IN_PROGRESS" \| "WAITING_CUSTOMER" \| "DONE" }` | Ghi phản hồi; chưa có người nhận thì giao cho người phản hồi | + +## 3. Quản lý cơ sở (MANAGER) + +| Màn | Endpoint | Body | Kết quả | +|---|---|---|---| +| M05 | `POST /api/ops/allocations/{id}` | `{ unitCode }` | Ô phải `AVAILABLE` và **đúng loại kho** của đơn. Tạo `unit_assignments`, hợp đồng `DRAFT`, khoản cọc + thuê `PAID`, lịch bàn giao; ô `RESERVED` | +| M06 | `PUT /api/ops/assignments/{id}` | `{ staffId }` | `id` = `PC-BG-…` / `PC-TK-…` / `PC-HT-…`; nhân viên phải cùng cơ sở | +| M03 | `POST /api/ops/renewals/{id}/approve` | — | `APPROVED`, đổi ngày hết hạn hợp đồng, tạo khoản `RENEWAL` chờ thanh toán | +| M03 | `POST /api/ops/renewals/{id}/reject` | `{ reason }` | `reason` rỗng → 400 | +| M07 | `POST /api/ops/contracts/{id}/reminders` | `{ note }` | Ghi lần nhắc; ca quá hạn → `CONTACTED` | +| M07 | `POST /api/ops/contracts/{id}/refund` | — | Chỉ sau biên bản trả kho. Hoàn = cọc − khoản còn nợ (khoản nợ được trừ vào cọc). Hợp đồng `COMPLETED`, ô `AVAILABLE`. Trả `{ message, refund }` | + +## 4. Khách báo đã chuyển khoản (F03) + +`POST /api/reservations/{id}/confirm-transfer` (tài khoản khách, chủ đơn): + +- `PENDING_PAYMENT` → `PENDING_VERIFICATION` (trạng thái mới, migration `20261014150000_ReservationPendingVerification`). +- Gọi lại khi đã chờ đối soát → 200, không đổi gì. Đơn ở trạng thái khác → 400. +- Quá `expiresAt` → đơn `EXPIRED`, trả `400 { error, code: "EXPIRED" }`. +- Đơn chờ đối soát vẫn giữ chỗ khi tính số ô trống (`/api/availability/check`, tạo đơn mới). + +## 5. Chạy thử nhanh + +1. Xoá database cũ cho sạch (seed D17 chỉ thêm phần thiếu, không xoá dữ liệu cũ): trong SSMS xoá database + `SSFRMS` (tên trong chuỗi kết nối `appsettings.json`), rồi chạy API — migration + seed tự chạy. +2. `dotnet run --project StorageProject.Api --launch-profile http`, rồi `npm run dev` ở thư mục giao diện. +3. Khách `customer01` → "Đơn đặt chỗ" → đơn chờ chuyển khoản → "Tôi đã chuyển khoản". +4. `staff01` → Đối soát → xác nhận đơn vừa báo. `manager01` → Phân bổ → chọn ô trống đúng loại → Phân công cho `staff01`. +5. `staff01` → Xác minh khách → Bàn giao. Ô chuyển "Đang hoạt động" ở `manager01` → Ô kho. diff --git a/feature_list.json b/feature_list.json index a61b8e9..cda0983 100644 --- a/feature_list.json +++ b/feature_list.json @@ -2,7 +2,7 @@ "_readme": "Danh sách tính năng = ranh giới phạm vi cho AI agent. Mỗi mục: behavior (hành vi), verification (lệnh/cách kiểm chứng), state. state: not_started -> active -> passing | blocked. Chỉ đổi sang passing khi verification pass và ghi evidence. Mỗi phiên chỉ một mục active.", "_fe": "cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm test && npm run test:render && npm run build", "_be": "dotnet build StorageProject.slnx", - "updated": "2026-10-01", + "updated": "2026-10-14", "features": [ { "id": "F01", "flow": 1, "uc": ["UC01"], "actor": "Khách hàng", @@ -23,7 +23,7 @@ "behavior": "Khách bấm 'Tôi đã chuyển khoản' → đơn chuyển PENDING_VERIFICATION trên backend", "verification": "_be; POST /api/reservations/{id}/confirm-transfer trả 200, sau expiresAt trả lỗi EXPIRED; _fe", "state": "blocked", - "blocked_reason": "Backend chưa có endpoint confirm-transfer và đối soát (luồng đã chốt theo Figma, DECISIONS D02); phía nhân viên đối soát (S09) đã có giao diện, chờ /api/ops/payments/{id}/confirm", + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing.", "evidence": null }, { @@ -86,7 +86,7 @@ "state": "blocked", "depends_on": ["F21"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F12", "flow": 5, "uc": ["UC09"], "actor": "Nhân viên cơ sở", @@ -95,7 +95,7 @@ "state": "blocked", "depends_on": ["F21"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F13", "flow": 3, "uc": ["UC10"], "actor": "Nhân viên cơ sở", @@ -104,7 +104,7 @@ "state": "blocked", "depends_on": ["F06", "F12"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F14", "flow": 7, "uc": ["UC11"], "actor": "Nhân viên cơ sở", @@ -113,7 +113,7 @@ "state": "blocked", "depends_on": ["F21"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F15", "flow": 5, "uc": ["UC12"], "actor": "Nhân viên cơ sở", @@ -122,7 +122,7 @@ "state": "blocked", "depends_on": ["F11", "F14"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F16", "flow": 5, "uc": ["UC13"], "actor": "Quản lý cơ sở", @@ -131,7 +131,7 @@ "state": "blocked", "depends_on": ["F21"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F17", "flow": 1, "uc": ["UC14"], "actor": "Quản lý cơ sở", @@ -140,7 +140,7 @@ "state": "blocked", "depends_on": ["F16"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F18", "flow": 3, "uc": ["UC15", "UC16"], "actor": "Quản lý cơ sở", @@ -149,7 +149,7 @@ "state": "blocked", "depends_on": ["F17"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F19", "flow": 5, "uc": ["UC17"], "actor": "Quản lý cơ sở", @@ -158,7 +158,7 @@ "state": "blocked", "depends_on": ["F11", "F14"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F20", "flow": 4, "uc": ["UC18"], "actor": "Quản lý cơ sở", @@ -167,7 +167,7 @@ "state": "blocked", "depends_on": ["F18"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F21", "flow": null, "uc": ["UC24", "UC26"], "actor": "Chung", @@ -175,7 +175,7 @@ "verification": "_be; _fe; staff01 đăng nhập vào được khu nhân viên", "state": "blocked", "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật. staff01 vào #/staff.", - "blocked_reason": "FE đã xong (đăng nhập STAFF → #/staff, MANAGER → #/manager); backend chưa có tài khoản seed vai trò MANAGER và chưa lọc dữ liệu theo cơ sở được phân công (UserFacility) — BACKEND-TODO.md mục A." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F22", "flow": 4, "uc": ["UC19", "UC20", "UC21"], "actor": "Quản lý vận hành KD", diff --git a/progress.md b/progress.md index 037d7d1..e378158 100644 --- a/progress.md +++ b/progress.md @@ -17,6 +17,28 @@ --- +## Phiên 5 — 2026-10-14 — Backend khu Nhân viên / Quản lý cơ sở + seed D17 (Claude) + +- Tính năng: F03, F11–F21 (phần backend) + seed theo D17. Nhánh `feature/ops-backend` (tách từ `feature/figma-1410-sync`). Quyết định D18. +- Đã xong: + - `DbSeeder` tách 3 file: 4 loại kho (thường/lạnh × M 15 m²/L 30 m²), 12 cơ sở, 12 ô K01–K12 mỗi cơ sở, giá theo + `lib/catalog.js`; loại kho / cơ sở đời cũ chuyển ngừng dùng. Quyền STAFF, MANAGER; tài khoản `manager01`, `staff02`, + `customer03`–`customer06`; gán cơ sở Nguyễn Lương Bằng; dữ liệu vận hành mẫu (2 khoản chờ đối soát, 1 đơn chờ phân bổ, + 1 khách chờ bàn giao, 1 gia hạn chờ duyệt, 1 hợp đồng quá hạn, 1 lịch trả kho, 1 yêu cầu hỗ trợ). + - `/api/ops/*` (`FacilityOpsEndpoints.cs`, `FacilityOpsService*.cs`): board + 12 thao tác đúng `src/ops/api.js`. + - `POST /api/reservations/{id}/confirm-transfer` + trạng thái `PENDING_VERIFICATION` (migration viết tay). + - Sửa lỗi CHECK cũ: `HandoverService` (`COMPLETED` → `HANDED_OVER`), `RenewalService` (`PENDING_PAYMENT` → `PENDING`). + - Giao diện: "Tôi đã chuyển khoản" gọi API thật; `ops/data.js` còn 12 ô; bỏ chữ "dữ liệu mẫu" trên banner khu vận hành. + - Tài liệu: `docs/facility-ops-api.md`, `BACKEND-TODO.md` mục A, README / AGENTS (tài khoản). +- Kiểm chứng: + - `npm test` → 41/41 pass (thêm test confirm-transfer qua mock, test mapper PENDING_VERIFICATION, test 12 ô) + - `npm run test:render` → 76 route PASS · `npm run build` → OK + - Backend: máy làm không tải được NuGet → **chưa chạy `dotnet build` thật**; đã biên dịch kiểm kiểu các file sửa + với bản giả lập EF Core → 0 lỗi. **Chưa chạy với SQL Server.** +- Bị chặn / rủi ro: cần một bạn chạy `dotnet build` + chạy API trên máy có SQL Server, đi luồng ở + `docs/facility-ops-api.md` mục 5. Nên xoá database cũ trước (seed chỉ thêm phần thiếu). +- Phiên sau nên: chạy thử luồng trên; pass thì đổi F03, F11–F21 sang `passing`. Sau đó giao diện B01–B05 (Vận hành KD). + ## Phiên 4 — 2026-10-14 — Đồng bộ giao diện với Figma 14/10 (Claude) - Tính năng: F30 (sơ đồ ô kho) + trang chủ, danh mục kho, header khu vận hành. Nhánh `feature/figma-1410-sync`. Quyết định D17. From 4ae32ad325816cdaf663298aeb35e69558d1b0b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Phan=20Ti=E1=BA=BFn?= Date: Thu, 15 Oct 2026 16:43:17 +0700 Subject: [PATCH 07/24] feat(business-ops): hoan thien giao dien frontend Quan ly van hanh KD --- BUSINESS_FRONTEND_CHANGED_FILES.md | 41 +++ BUSINESS_FRONTEND_README.md | 85 ++++++ BUSINESS_FRONTEND_REVIEW.md | 77 ++++++ .../BUSINESS-FLOW-COVERAGE.md | 28 ++ .../SafeSpace-Customer-UI/mock/mock-api.mjs | 14 +- .../mock/mock-business.mjs | 260 ++++++++++++++++++ .../SafeSpace-Customer-UI/package.json | 2 + .../public/fonts/manrope/LICENSE | 93 +++++++ .../manrope/manrope-latin-700-normal.woff2 | Bin 0 -> 14212 bytes .../manrope-vietnamese-700-normal.woff2 | Bin 0 -> 4552 bytes .../public/images/business/bell.svg | 7 + .../public/images/business/brand.svg | 12 + .../scripts/dev-business.mjs | 12 + .../SafeSpace-Customer-UI/src/CustomerApp.jsx | 24 +- .../SafeSpace-Customer-UI/src/api/business.js | 51 ++++ .../src/business/BusinessApp.jsx | 40 +++ .../src/business/BusinessShell.jsx | 187 +++++++++++++ .../src/business/Facilities.jsx | 44 +++ .../src/business/Overview.jsx | 88 ++++++ .../src/business/Policies.jsx | 48 ++++ .../src/business/Pricing.jsx | 188 +++++++++++++ .../src/business/Reports.jsx | 226 +++++++++++++++ .../src/business/actions.js | 23 ++ .../src/business/design.css | 146 ++++++++++ .../src/business/export.js | 60 ++++ .../src/business/format.js | 181 ++++++++++++ .../src/business/parts.jsx | 199 ++++++++++++++ .../src/business/policy-fields.js | 63 +++++ .../SafeSpace-Customer-UI/src/lib/roles.js | 3 +- .../SafeSpace-Customer-UI/src/pages/Auth.jsx | 4 +- .../SafeSpace-Customer-UI/src/state/store.jsx | 8 +- .../tests/business-frontend.test.mjs | 69 +++++ docs/business-frontend-api-reference.md | 150 ++++++++++ docs/sprints/F31-business-frontend-only.md | 15 + feature_list.json | 7 + progress.md | 13 + 36 files changed, 2454 insertions(+), 14 deletions(-) create mode 100644 BUSINESS_FRONTEND_CHANGED_FILES.md create mode 100644 BUSINESS_FRONTEND_README.md create mode 100644 BUSINESS_FRONTEND_REVIEW.md create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/LICENSE create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-latin-700-normal.woff2 create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-vietnamese-700-normal.woff2 create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/bell.svg create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/brand.svg create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-business.mjs create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/business.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessApp.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessShell.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Overview.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Policies.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Pricing.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Reports.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/actions.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/export.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/parts.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/policy-fields.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs create mode 100644 docs/business-frontend-api-reference.md create mode 100644 docs/sprints/F31-business-frontend-only.md diff --git a/BUSINESS_FRONTEND_CHANGED_FILES.md b/BUSINESS_FRONTEND_CHANGED_FILES.md new file mode 100644 index 0000000..8e96572 --- /dev/null +++ b/BUSINESS_FRONTEND_CHANGED_FILES.md @@ -0,0 +1,41 @@ +# Các tệp thay đổi so với SSFRMS(1).zip + +191 tệp khác giữ nguyên byte, trong đó 77 source/config backend. + +| Tệp | Trạng thái | +|---|---| +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs` | Sửa | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json` | Sửa | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx` | Sửa | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/roles.js` | Sửa | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Auth.jsx` | Sửa | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx` | Sửa | +| `feature_list.json` | Sửa | +| `progress.md` | Sửa | +| `BUSINESS_FRONTEND_README.md` | Thêm | +| `BUSINESS_FRONTEND_REVIEW.md` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/LICENSE` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-latin-700-normal.woff2` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/fonts/manrope/manrope-vietnamese-700-normal.woff2` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/bell.svg` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/business/brand.svg` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-business.mjs` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/business.js` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessApp.jsx` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessShell.jsx` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Overview.jsx` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Policies.jsx` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Pricing.jsx` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Reports.jsx` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/actions.js` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/export.js` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/parts.jsx` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/policy-fields.js` | Thêm | +| `SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs` | Thêm | +| `docs/business-frontend-api-reference.md` | Thêm | +| `docs/sprints/F31-business-frontend-only.md` | Thêm | diff --git a/BUSINESS_FRONTEND_README.md b/BUSINESS_FRONTEND_README.md new file mode 100644 index 0000000..857847e --- /dev/null +++ b/BUSINESS_FRONTEND_README.md @@ -0,0 +1,85 @@ +# Frontend Quản lý vận hành KD + +Bản này được làm trên `SSFRMS(1).zip`, chỉ thêm/sửa frontend. Tất cả source .NET, cấu hình DB, +seeder và migration giữ nguyên so với ZIP đầu vào. + +## Xem giao diện ngay, không cần backend hoặc SQL Server + +Mở thư mục `SSFRMS` trong VS Code, chạy: + +```powershell +cd SafeSpace-Customer-UI/SafeSpace-Customer-UI +npm ci +npm run dev:business +``` + +Mở địa chỉ Vite in ra (thường `http://127.0.0.1:5173/#/login`). +Tài khoản kiểm tra frontend: **ops01 / Ops@123**. Đăng nhập tự vào `#/business`. +Bấm tên góc phải để Đăng xuất. Khi chạy lệnh này, các request HTTP dùng máy chủ giả lập +trong bộ nhớ ở cổng 5199; tắt tiến trình thì các thay đổi thử nghiệm không được giữ lại. +Không chạy `dotnet` để kiểm tra frontend ở chế độ này. + +Nếu cổng API 5199 bị chiếm: + +```powershell +$env:MOCK_API_PORT=5299 +npm run dev:business +``` + +PowerShell chặn npm.ps1: thay `npm` bằng `npm.cmd`. + +## Nối API thật khi backend phát triển xong + +```powershell +$env:VITE_USE_API="true" +$env:VITE_API_URL="http://localhost:5151" +npm run dev +``` + +`npm run dev` dùng API thật theo cấu hình, không tự chuyển sang dữ liệu giả lập. +API đăng nhập chung `/api/auth/login` phải trả JWT có role `OPERATIONS`. +Không thêm tài khoản vào DB và không thay đổi backend để chạy frontend. + +## Màn hình + +| Route | Nội dung | +|---|---| +| `#/business` | B01 tổng quan hệ thống, thẻ số liệu, bảng cơ sở và 3 nút điều hướng | +| `#/business/facilities` | B05 chọn cơ sở, xem thông tin, mở báo cáo của cơ sở | +| `#/business/policies` | B02 đủ 8 ô trong 4 nhóm; sửa, kiểm tra, lưu và tải lại | +| `#/business/pricing` | B03 sửa khung giá/phí theo loại kho, thêm quy tắc giảm giá, lưu | +| `#/business/reports` | B04 4 tab báo cáo, biểu đồ/bảng, xuất XLSX | + +Giữ bố cục theo Figma. Tên, số lượng cơ sở/loại kho, giá và ngày lấy từ API nên có thể khác hình minh hoạ. +Không bổ sung nút CRUD cơ sở hoặc bảng giá ngoài các màn Figma. + +## API và giới hạn hợp đồng + +Lớp API duy nhất của khu này là `src/api/business.js`; sử dụng đúng `/api/operations/*` +trong file `operations-api(3).md` và JWT của store đăng nhập chung. + +- Chính sách đang ACTIVE: tạo DRAFT mới, kích hoạt; gặp 409 phải xác nhận rồi mới gửi `replaceExisting=true`. + Nếu huỷ, bản nháp còn trên server, chính sách cũ không bị thay thế. +- API chỉ cho một chính sách cùng type/phạm vi có hiệu lực tại một thời điểm. Vì vậy các thông tin phụ ở B02 + (số lần gia hạn, thời gian kiểm tra sau trả, ân hạn) được lưu thành các dòng có nhãn trong `ruleDescription` + của cùng chính sách RENEWAL/RETURN/OVERDUE. Không tự thay đổi quy tắc xung đột của backend. +- Các dòng chữ là hướng dẫn; frontend không tự thi hành khoá truy cập hay tính phạt ở các role khác. +- Nếu API chưa có chính sách tương ứng, ô hiện “Chưa thiết lập”. Không bịa số liệu trong chế độ API thật. +- Tài liệu chưa đảm bảo `managerName`; nếu không có trường này, cột Quản lý hiện “Chưa có thông tin”. + Nếu backend trả tên quản lý, giao diện sử dụng trực tiếp. +- API báo cáo cung cấp `overdueContracts`, không có số ô kho quá hạn riêng. Giao diện ghi rõ “Hợp đồng quá hạn”, + thay vì đổi nhãn rồi đánh đồng hai chỉ tiêu. +- Xuất theo cơ sở/loại kho/doanh thu: gọi endpoint CSV rồi chuyển thành XLSX OOXML thật tại trình duyệt. + Tab tình trạng thuê xuất snapshot vừa tải; không gọi một endpoint xuất trạng thái không có trong tài liệu. +- Khi tải lỗi có nút Thử lại. 401 kết thúc phiên và về đăng nhập; 403 hiện lỗi phân quyền, không tự vượt quyền. + +## Kiểm tra + +```powershell +npm test +npm run test:business +npm run test:render +npm run build +``` + +Các lệnh này không cần .NET hoặc SQL Server. Xem `BUSINESS_FRONTEND_REVIEW.md` để đọc kết quả kiểm chứng. diff --git a/BUSINESS_FRONTEND_REVIEW.md b/BUSINESS_FRONTEND_REVIEW.md new file mode 100644 index 0000000..d1529df --- /dev/null +++ b/BUSINESS_FRONTEND_REVIEW.md @@ -0,0 +1,77 @@ +# Kết quả triển khai frontend Quản lý vận hành KD + +Nguồn mới: `SSFRMS(1).zip` và `operations-api(3).md` do người dùng cung cấp. +Thiết kế: Figma SafeSpace - Modern UI, section 436:13803, B01–B05. + +## Phạm vi + +Chỉ frontend: 5 màn KD trong `src/business/`, lớp API, assets riêng, mock HTTP dùng khi phát triển, +kiểm thử và phần nối role/route/session tối thiểu để OPERATIONS đăng nhập vào đúng khu. +Không sửa source .NET, database, migrations, seeder, DTO, API endpoint hay cấu hình backend. + +`src/ops`, `src/admin`, `src/components`, `src/styles/ss.css` và các trang nghiệp vụ khác giữ nguyên byte. +Các file chung được sửa giới hạn: CustomerApp.jsx (route/guard KD), roles.js (home OPERATIONS), +store.jsx (chấp nhận role và tránh tải dữ liệu CUSTOMER cho OPERATIONS), Auth.jsx (điều hướng role KD). +Điều kiện cũ cho CUSTOMER, STAFF, MANAGER, ADMIN được giữ nguyên. + +## Các màn đã triển khai + +| Màn | Kết quả | +|---|---| +| B01 | Header, logo/chuông gốc, 5 tab, 4 thẻ số liệu, bảng cơ sở và các nút điều hướng | +| B02 | 8 ô chính sách trong 4 nhóm, xác thực đầu vào, lưu qua API, xác nhận 409 và tải lại | +| B03 | Bảng sửa khung giá/phí theo loại kho, danh sách quy tắc, thêm quy tắc giảm giá/miễn phí, lưu | +| B04 | 4 tab báo cáo, biểu đồ/bảng, tải XLSX OOXML hợp lệ | +| B05 | Chọn cơ sở, xem thông tin, xem báo cáo cơ sở tương ứng | +| Chung | Tên tài khoản, đăng xuất, thông báo, trạng thái tải/rỗng/lỗi, thử lại, 401/403, mobile | + +Giữ bố cục theo Figma, không cố định tên, ngày, giá hoặc số lượng cơ sở khi gọi API thật. +Các hình minh hoạ Figma và dữ liệu API có thể khác nhau. Không chèn ảnh chụp Figma vào giao diện. +Hai SVG logo/chuông giữ đúng kích thước 36x36 và 44x44; font Manrope cục bộ có kèm giấy phép. +CSS mới chỉ tác động dưới `.business-app`. + +## Theo đúng hợp đồng API, không sửa backend để phục vụ frontend + +1. Gọi `/api/operations/*` qua `src/api/business.js`, dùng JWT của phiên đăng nhập chung. +2. 8 ô B02 được ánh xạ thành 5 policy type. Những quy định phụ lưu thành các dòng có nhãn trong + ruleDescription của cùng policy, không tạo nhiều policy cùng type/scope rồi tự ghi đè. +3. API trả 409 thì phải có xác nhận trước khi replaceExisting=true. Huỷ thì giữ chính sách cũ, + bản mới là DRAFT; không báo đã áp dụng. +4. Tài liệu chưa đảm bảo managerName: không có thì hiện Chưa có thông tin. Không bịa người quản lý. +5. API chỉ trả overdueContracts: ghi rõ Hợp đồng quá hạn, không đánh đồng với số ô kho quá hạn riêng. + Đây là điều chỉnh nhãn có chủ đích theo dữ liệu API, thay cho nhãn Kho quá hạn trong Figma. +6. Backend xuất CSV; frontend đóng gói thành XLSX thật. Tab tình trạng dùng snapshot hiện đang xem, + vì tài liệu không có endpoint xuất CSV trạng thái. +7. Không tự thi hành các quy định chữ như khoá truy cập, ân hạn, giới hạn gia hạn ở role khác. + +## Kiểm chứng + +| Kiểm tra | Kết quả | +|---|---| +| Bộ test gốc `npm test` | 38/38 PASS | +| Test mới `npm run test:business` | 8/8 PASS: role, phạm vi/hiệu lực, 8 ô/5 policy type, tiền/tháng/ngày, giữ giá trị khác trong cùng policy, XLSX/CSV, JWT/query/body, 401/403/409, huỷ/xác nhận thay thế | +| `npm run test:render` | 76 route PASS (giữ nguyên bộ render cũ) | +| `npm run build` | PASS | +| init.sh --fe-only | PASS qua bản tạm bỏ CRLF trên Linux; không sửa init.sh gốc | +| Trình duyệt Chromium | 13 nhóm kiểm tra PASS; không có pageerror | +| Assets | Đã kiểm tra file cục bộ, callsite, kích thước thực tế 36/44 px | +| Tệp XLSX | 4 tệp tải từ trình duyệt đọc được bằng openpyxl; tiếng Việt và cấu trúc workbook hợp lệ | +| Hồi quy 14 màn role khác | Nội dung và ảnh từng pixel giống bản ZIP gốc sau khi dữ liệu tải xong | +| Backend/database | Đối chiếu byte source/config với ZIP gốc, không thay đổi | + +13 nhóm trình duyệt gồm: hồi quy role khác; 5 tab KD; assets; lưu/tải lại 8 ô và từ chối đầu vào sai; +sửa giá/phí và từ chối khoảng giá sai; quy tắc mới và xác nhận 409; chọn cơ sở/drilldown; +4 view và tải XLSX; đăng xuất/xoá session; chặn CUSTOMER; 5 màn mobile không tràn ngang; +lỗi API/thử lại; JWT hết hạn về đăng nhập. + +14 route so sánh: CUSTOMER overview/units/reservations/payments/support; +STAFF staff/reconcile/support; MANAGER manager/units/report; ADMIN admin/users/logs. +So sánh dùng cùng dữ liệu HTTP ở hai bản frontend trước/sau để tránh nhầm khác biệt dữ liệu thành lỗi CSS. + +## Cách chạy + +Đọc `BUSINESS_FRONTEND_README.md`. Dùng `npm run dev:business` để kiểm tra ngay mà không cần .NET/SQL Server. +Khi backend sẵn sàng, đổi VITE_API_URL và dùng `npm run dev` để gọi server thật. + +Các kiểm tra tích hợp hiện dùng mock HTTP ở frontend theo tài liệu, không xác nhận backend hoặc DB thật. +Không thay đổi hay sửa lỗi build .NET trong phạm vi công việc này. 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..a16af20 --- /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/Overview.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/Pricing.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/BusinessShell.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/mock/mock-api.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs index 0e19256..cc20f11 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs @@ -2,6 +2,7 @@ // 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 { handleBusiness, seedBusiness } from "./mock-business.mjs"; import { createOpsData } from "../src/ops/data.js"; import { reduceOps } from "../src/ops/reducer.js"; @@ -127,8 +128,15 @@ const OPS_ROUTES = [ ["POST", /^\/api\/ops\/contracts\/([^/]+)\/refund$/, "MANAGER", "CONFIRM_REFUND", (b, id) => ({ id })], ]; -export function startMockApi(port = 5199, { verbose = false, ops = process.env.MOCK_OPS === "1" } = {}) { +export function startMockApi(port = 5199, { verbose = false, ops = process.env.MOCK_OPS === "1", business = false } = {}) { 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ở @@ -239,6 +247,10 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M 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) 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..cf8f346 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs @@ -0,0 +1,260 @@ +// 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", + }; + }; + 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" }; + 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") { + Object.assign(f, { name: body.name, address: body.address, contactPhone: body.contactPhone, openingTime: body.openingTime, closingTime: body.closingTime }); + 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.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json index 47e7587..34365a1 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json @@ -4,6 +4,8 @@ "private": true, "type": "module", "scripts": { + "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", 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 0000000000000000000000000000000000000000..84f7af5467eeeb99fdfb08ff0c8c78b5c10bbf75 GIT binary patch literal 14212 zcmV-~H+#r;Pew8T0RR9105^mH4*&oF0E{F605>E60RR9100000000000000000000 z0000RvS=KW3I3KnIFf3UfKMiFcrKtS}mC`veKEXn_$66hG?L_26&klD_NwtDDRi>)@S7Awi@ zj948XoEY5b?i8nxPCYUiuj4$r$d!&?I&6?uZ?$yIo+^054xSP>qu`AE6)QbLW1r;m zAgz7%QkCkSojnE?hFJlyL}89C3JZkp)cy?5&#m`Ygp@GojZu;kIoW`%slk8^MsI8| zBFBi58X+xZ!w926u^D)Z(I`eESOtn`-{rL2RdLz1tSf*$O9ku+x?*3eUz;rvoBAd& zEP(+uG=%&g3eP`({I|8w=iLFx$0!OY>yO$123i7%1e(>{0I-K~{t&uSbzOD~bBa)d zdGFo!LBHBh=lj6vC^X`Xh>kuZz7aPO2HKse`!3Th@++Y1Y=Hu}MfQ8Ay8e?q&hcr* z=Mgz$3|1Dx%UA)TB|6++R3NpmUCeE!XoJva5|KvZ=syw7ji2RSq4n@Hm741VYLe7t znVo+Rm#IkzQ~CdG+S|@ptIg=6<&YgM@>lEP2{jX$9rK&%+b4`s@ffE5;H%I(S!6m^rp^Z#?7Z{L2WDe!4o zMvm%=a7lsGOkJzgZHgynrND1eq7+auDq`6R3G_OJ4+_;+nw6?BUl{TIF_zzh%(ivd z7%3_F&z+cwlI@)Ix_dijqM%n0-WTkNFPjJ4XGVRxKleA7RGlnJ5clQz;GzsSTPLfD9Lq0qR`50dS_xm;qYHc9=HXsK;&j zHV*dlVE|BB=GR|Q5=$nx$eV`;Ps(ivd8rRO_Exu*L4PN zwXO(tOVvwny5fsOr)@`^iDLXu}Z zM*y|EpQDcY2ic7BEwkQd?T|aiExMEH_;#%qRhyiL#cc;;-Gy9(ua7yd!_00s5avec zRa&Ai*QX_$A$*u@ck@?GaYPFpd5fdJO&l>(ZTai?IStbFs&m_J&UNShe%HaZYcxP~ z0P7#BL%&8dfi-@*Ia>zoMZ)2U6)avcwgx0KopD8$M_ObqS?s+}N-VUm07C;&fv{pw zEH#Je2n=L^u43luYAqNCD2$`(aQZ$?&fF>S;7NAZ-605CL)sv>$GQJNZ zQ!cnX5-a2nNi?ZKYKoFL#Yz|}Q)3O^hj7pcYoiV^2R$*Uxic!xYHdozIjx;naY1Vr zRb0~AWffP7+JOQ6k-gXd3-6!{?{(sXetlHuQxW~?S5RtYxC#`ZdZfk*HBI%*EOey< z;g}c;)UttL)qzb~GG_y3s|fqj%tKp^VwIBv=%-c1AZ?C`k;y53j!W~FGvGj?WRT;~~^J(D^y!=AvQ^+Q>F8-H3&v+Hh=vM0ld++BMTBpmBu;E!1U2xVv(SauvZ zdF@^ zlNJY!7&UIf8B@-?=(6jk-E-dqk393<0v)shdI6(=S>Rs~QV?H|P>@)_FAx+Y6$lGN z1>%CVf`f}VBT~OFfZ~zN3RDIL;2=PPLJ4J59&S=r-&qzW4_h%&LRqq*%)!M*Bk}0s zjYCZ2_AZJsH3W$G;ENw5BNLQMTD2+z(QFPaEH!1if;kpgV#O+~vB4IH*r^;3JkKz4 zqy7d+v%FrDuzkS6Y9Oj$01g5qD3nk}rIyuOgKpPU_t2mcFaQSu5)?`(qq5k5ukXQ%`fRBJAgow&y$h8k2U%UYs9|~DB z%!$75LFM6^>hoZ|jYvl=P%#*A5FkOJgfc3%4Df)?O9;IbKF7}0u8zppFo(*)Y^LMb4t1hXl|sh{ z*x0Uke73xET;LK{4oA3N&i$qe;F-gZ+E9Ux6xN_pFaiz&Bq)?n zMkO!E2pvWweDK8&5@aYbt?KA7@V9`4K!OOic-s<)MED3uLWs!4O=LQe3gqwGMXwiQ zaJbSw*D~^a@MJg|{?2a5quq4i1P;Ez~#=avnJ!gFi1k$jzULX+~qg!1JDR zwH28OD@_yKpIK5 zq)O5ean}@NNkHUvp&PJo0uPjS6%b`X3QQmY0vCj+ijtuAub{VtJ^Lvrr5|Vf44>Y| zzvwwmf;gldOGtG;)Slh1#J3G&K*dFuTz17(*UWqF5r~R2&YE)0c^5qP#2m9Lj(RyW zzWo0Hv^s#O3zXN#=fC?AxX{1lK*xkhr~N1Rpxf? zk&PH>M)P}Lcl(Cp0L!*M)v!RDj~GdyuSdoRgrI$08O;Edu}!u21sEfWtRt^U3sr3q zY*U#!YN>#=r5lHiu@8(M=_qS?9#44;=op@W=WAk55^!+gf-w@gwiwA89!-f|Iaoz_ zgp<|XKay0DO1x%*JFejQ#mZ_D<8xT(6Z`e6zAB#Yf`O@_JvyJ#fCKGvb8!Lq&1_Vk zu4h`I>@01t0#;{4yfn|RW8|CmmE&06s|^ftZ2W4?Bhzn7jP8Ub3}RqVB>9>$jZcFj zq*#MEwm(i}R>H+>f*wsuwuZrMwsxd2+evwPtpUph{cF=xkMq*B-5*)bdq%oa(*5FA zP=Y4a5<_B7E3XQ26Z!#p;h*S54>iLQ0?$<0E_9Dd%_ z8S}!E3ls7kKIQU^&0{X-CZs&*h2 z5Z3VrbW;Im$Vqv<3Bp&U%cw`W3+7FA_nqLqSSD+a?- z0*)mb1cfET8P~n`Bk@YnW35@k-1n_*U+grM}N5hpn)g4n;!29jolUM;j zPJNp<%AEhZfTi<__Y9yH0rH@g1Ga(ysV0H7^V6y8r)! z)!{hvCg+92Z?A(hz?mHNnqM;f2b>E~L8Zas-D1rG|J?`xzI)+W>$C08#LpGFOx=9yDI`WFP4yA4x1>5Gvmf6(}2l(`?4Nj>_( zgQ!|TohCG0di0sVz%qqn&W?lC9651*{O9t#ou_cYAGbmaVNe9Q`K%n}!0I?B3+Y5*ffeqgU zVEg|8i2s222*B!K;Act1j1YyujJUV{J5dVCu@oCkKCi^EF$)6&HnVgBCS)v-Z`i<* zjx5iVaiq&ewiqIcnleg|k?NGBLR8l~v7~ow%uhqLoDWeMoyIhyFLW1%*vzn=4G)_J zwxkm(q)-(#fjOCmrBYgj8N?u9pu!lP#aqBviOEVvg%xeSTtl3MOECy!^DKsF3^-03 z*KB9Yz;R7J0;*gUnPkj}Tq}W^LS4>;5{z>5N(7?C!drDgDbj52@l-U}qy{}8aiO5G znSvFM!ieWmONe+2{VQuA_9>zO>;Z%vR#{QP?OXs>wZNJ};4c=ecsza1h5h{-GzG4e zQ3I!);eY@F^%5pb^tFgfPgRYzx}TM+imhV=1tpN-3E6>>os{#Fqq__6D>|!7Y@{zF zehg<2mmM0Q@ASnYNvz;}A+@PEsFYS_=F6O+9Y(y?xfHbM4X`T>EP4X(Yn8sq&pB+i z{^C6k(jsAoM;?6pWD}c3;9zljwyqo-(j2bw-ph4JS+iS|G2=sMjbHw#sX@Dx3o?BP>waO75$=J<jrHSz$;Fk})X_HQwENflb4g=fe#vtufS zwK2i7iVE4Yq(e+Ikf@tREs|ILP>w3fQo*n?1Wj`o(J8{TC1vBi8BUZeb=NH@SDj!)G7N~;4f?Uv`hA_*im_f}{ z5sGWz2NPm47$Kzkf-~6gRT(V$+aUXX;J$Szj(I5!(a}fn(Vtm1+vVjfec{gaeD01kW-51SGni<0KS(Mz$WZv*1K+v zM&mLr5j=3#`o#5wj-zU|8Wl@un>A=5zy0AWq)S!f1iOYLx@rC_9A<%o3}cvv_#rQu z<4jHx6_bzD2IV4i+*O_aiQ=cl-(G8S1-ZIZcW3JPh3)cO)y`a8sf8lZtS*evr`RYU4-@k0l`C3qtRU!t`d;Ir2ohSKWyhV^dCOcP7mxs0+s> zaBJ}t0JoTwIuxwuWUy{J$RW1s`x(m;{6R7^_E(|7`CDc=uAg@1ed#9*9h}Hrh=*Vm zIvcIsW%8X2 zhUF_3mf7ZL1d2;`B#f3(J{|j17fk@|EX50X40SEU8d34qf`viYhI3`ZOK4vf7wvWB zYK~caZ!q=xV?sRoi=rnDC>0~E!WbW)jeUe11gx^C8WG*={u?FWKQIcMo)J%Z)E1zC z;@-8ZrI*c=J?-Z%G)EE|`OYH2cZE*{C7f)DW|bJ@gK6C4j-<_79*UWQe8o2M8{Ei4 zv1q-c@Mk|TnZSCji(LfPAupkvzfqf#sOrA6} zpVT$_I5~Q21_;7WQyHKC>g_qm1pE$^K{Z0cZjdum^VowoD>vHxg+K<4VP%Vv7f)Ol zp-X#5UQ--=b4t2eLU?ZoDQSRQgwxe{DK}wBhTn8^bE-t-$AT842{~Sf>y4vZKPHam zT46gB)pGMOMQ;itS?oqHv3G9f;1?6d5*LCro94X7z~)J!Rp{0b0^d2*x0wWyl@Xz~ z3X_JUT*1pMo%@(^u)wo_o@~Kd8OD^gd8oq`sv}v*j|*#BMvB*}p@sg51graTf>(Ub zI3b{YaAB-2CWytVko5A1Q%^_izi~AjJKS;Nm4wwlW$*cw;x_ZTZW-Gs!`q{4^e?be zl%c0WIp*a8*V)TH?^OMXtWiI#2Mn@{7wMr$7CvmV#_=CJ!E-X5)r>t)Sv#}-tlfb( zC+J9ov4_8Q0CCrd15aGvtT+LbOBQc0JL=41Qq>KhDr38!&Z(it=|SEBFP7pSN5AUR zkN2Uci6?^Ona5ddJhRUBGk(NUM*10riLA5HmYGbtCY*DZ=_mb3IZY^EkjyUv21~`! zuyOs2R`zgw`^2sH&zzdi4GYx$XG z?fw)?ld}jJ0wmaM?agK4{b_@!(&3`09>hhs?tM-iGkoOrSwMG@N*&j9?U)1LEuzjY zHsnotzdb&P8Qh5h&p?D%CqcRvDTX!|Q(?>LA_y+ynlQv(5Cfut1I;kM!1WgJgv z6J#Whqr!mWE-xf~eJTypD4od!BS_IeB0A-thG4Y#nlzB8K*g}2oo?I{MTQ96n;D-< z*;-{+Y#O*_Y@7U<4qci$^z`IGGR|zsIv7ewaellV4m;7!b96S)OuX7a@;$tq0&4=2 zg2?}A4mz5i1#zypQy0=#mg6XFB-k#c`TQ3Dhb3VA-2=K$u01}n4xZw<&#kyA-q7a= zyN>T-^LfmIkDh|{Eolh#KJSAyl*3*i?*iD|Ch+nhuxq$$unXw71mBcVS86mtTi~f& zc1?NiG5;ZAEBDj)ar;kN*)6OuEjuvnHBC`s=a$F#@rF4-H0TwVdpJ~W9wqt)Eg+tWsVvO)iWhg)ggiHqs?E( zc+I;rG9#JOSfrZJ0;wy7qliiiR}Km(`c5)O15=AjFf3BBxHK|fsf!uXCnVh9b?#2% zpOT?#^_+YYVebF`XI#Ji`=vBLJ~A)vgQ^EF=PpX{5^7Zk8_!mq(m;G*r-XrLbV(_A zN;?rxgf>V(orTVL=Pro@-XUj)w=<)bc*`6Pk8{@=;f;WeNwQoZ*Z3cX=hQq63)B!^ zb4zo;#glMsQ{FLr)c!7)VTUr}tP5i|a>ku06lX9z&IxNY_wI1isLu~vJB6U-eR-w# zT+e9tC}x?^ao8Efe4KcR?A@%82~}o(l(0GP*fVS4Nw~}ml*Swp6yCj*iqq{ z`869xzYeQC2}d{O9doqaf9(6B-b+~NeOb$Uu6wj+RQnYHB4?IDxCxJ~S?V1`44);! zMTz*=!Y>|pf@xVwIzB1Z8~boD#O2UwRnKM5r{7lDRG!$_(E&|X^WXRNCB8Xb-2r8S zA+~sUW!XQ)KT{0qs+?$lc(~GH!k&Z$U9rI5!w2$4U21`TA>r8Oykq+R+h}!BdhVcT zsog^`6ahNbYXgH&J+sQJ=%rwuI_&#kFJ}A0z4q%r;`gORk?i6f1hWVp;nLD2DiCS& zCcKjs33Ix@t-f1q(*Nsz;+oJeUuP!DDIa-YYVqgIADqu;Zj15I7QS)UmMurmv1EJp z`}d{oSpfbh$(d^tYnbVhCN>%$By|QejRkx5Vvx}5X>IR)_d4jYd-EOOG*3hP%{l;w zGr+_5G+j&S$_Sh5Glbi8mHOy$`rKbBqUk79^8VYr^?AakyrY}*5Gf>FZ~tkyyLb4+ zA6NL=sZ%$1Z@l^<*Hx$bN6h~5P^p&`p-YC1m1_@HhMXxX3_YV;EYm(rfuobY-{+xq z=o7RclSD^H6TUuUg079`X~Iv?e@6xS>yy#a(8k~HJs=ng^5}Z!6LC%`iTXRsbrd?A zR2m2BufTAg&d08HVH{p%vf z^!>>iysF#s)5^5+d~*$}!HE+~#kz`5m*r>u&2~%*_pM57ZW;d+zaDgf*GXGWnaW@e znn5w?HC_P_6O=jxM&LdCC<&|7ASSEUse~KSoS7T9Yg^7`FYs#O)_l+WtqE`gvk%eS z`FC%_SEx43vofAnvYJdSc8uqFRI+QA*6r>5i)aR}DY~m@`bAK5X9TSMRq2gJbKUeb zv#oST^^*5Rn?l0oz_G)qyBMtLXjY*=b<_ZTG@)J&7&qd||E^rpTKPib5A?fbt-nTe z`6q2D(B=T(U*CIh!J7Gt_RChk6)*2uhpR@Yf_EX

V@Mp8y|2Y*%;)u3%&wZ`XmOoEPI6jFKm*k% z{1MH%@!9stj)(E?=@(ZNGB(V-v+|do$rMb6=dYnfjIBl#S_SB4YHcyh(c9m*;kkuP zd9VerdoeSM1JPhvILQ)q>5ME7L}0l%)quVGY)Co~;j+K`ys70(ZuLj0vBb!}Sl-@M zoOLlfoqP}d>~tWalB3BeI7{yrbF91@;_i?ZeC_(A8#)d|6U${1{?8o#4BP*){XdklO|)^Bk!AP zvk+nWVdmfUCFxp1D>B8)CpO4&V(iS}mMB_LPGG&A3{6KF2CMMhrKxVT&>Ff4>j4?Z zscJmNE;w+v-D)ignSv|a?i#l)cem@{vSLyJIx&5BdNN=GLmAL?_vTH{y34@uUg-HZ?MS>tMpXb?^p61zK$OC-L&iCEr5Eum8tH8(3;p6{~ zuj>CyGLEd~M+Wr>`dFBbb%=#;M!Hj7 zrpEj)fQadN(o+Hr4wr(t?oFGgyECAnfehH4p5l9gLY`-TTDoUnJ}*vCkwB0q3BBbd z@tG%w=~88j<69A53q!Lg+|XN= z1{1>-UtZU4yHne?ySKM}S2d7<)*Tx+we3*tDyu6XN$U$iA!hh{Yt!%H(FVj~d;hL? zTk|mL|9$3xgCzsC-R(z5hT9J}MOTHG2YzJwtcML~E+2h;6s#Vbi5ffmm2iM1nuwWP zr`f8a#bFdPlBw);Bw~bL3w;-0i%c>WFmI)=5+ke|rYh(Z8ot8tYnftL0mA;q413k4 z+6FwydY6kQ1r@lHQlMZrtjA2IEh;cyKeeI$BDrl=h96l_r0k|%<|+{dL^?)e{Qd3M z3fqWH>9aRv8;iGu#+KPPtCd^F&H<$S-ZEwnP(?g`viL+3{TRQ92l5|zed$a#?yjP@ zY>q?+@O}s}(_UE7JyUMerr){HnVomz1%$D?7XT8}ZtQM^>y1BIcmkS$m3%3;Non<< z@p)svtxC#34v-Uz0677or$I+fR(XPVth+}FGu;>Dr0hAEn0a{O?!jw(62RXH#lGFx znwM3P7?)jJ?;PQ0mkg$`M{=$*`O3xL3&p$zF2nbW^JYP^`{Q0xDrRtTy$tN! z)A0Xdd;d_b)V(dc>cL{iz+6Z35SC))(&k%Y}D+uBY72bmG?tX?7F0!_g;O+~th zvv+DX585Mg>2G!L|GOSQKGz;e?#tlZ)7wr%qA_0Ynlb3_KXiy`X=K2Z%lqYfcJI>C zatQvgZa6a5EJ26vXR<_nviUVW6$hKGC!Ss9VLoNdqhzs--v~^)uN82>T>N?1Xz-hrc4&31Fe-sY zv~no0EirAd=ntpog(au;DA?6&&#;Qx)%oA-m1*grJOl?JCVH7}S!-WmT7}!pp%rk3 zKAZp}7(cFh=!b`a+D?*nSvf_AvfIGS^B70xFmGN-VmLnDe#fO1p$^ZNtZbFZeVD|` z!o6PnwU@<(M++moo1eIHX?}c*LfXvxF94aYa}_bbuno4P!`H{{UD!s32^y0%VOA|rbU@Y|8hYX^Wyjv zZ?7EF?N{i^!*nl8vG>t)u2@Iz4fPLX5hdt=+U|yo? za~P(v*{BzP6ZKmCZY^+Svr(nmZ(O#%b`)L-vs+F_&cR*n4|0havHYz4_J@c z^tPtv?WXBXA8;DowCPPvZ37Tcz{VHBW&X_4;IAwIL~ug~>ud1mIH=#GKCG%fundrL zAcSs-Et!5^c^>{gxtU~Ukc8%!2a$htRNa{`=xKUXT5-Qs?A4rI5XKy*v{ckE*YF8=VzL!6js2Lk*FFydBSfn`8TnMIgu$Rm@+tI)Ou~QH z$o4-q=3ApVrYny~x?JcD)1`$o4Gql?UsQt%OzSgQ?fXqfhieu;)Nac<>mL-le^*?l z8Mm~imVKAuq5*j0qrBU-4G>YV12=167 z#tU8)y}-U02T7RrC;1iE>WZ?iq!AIp;l44$;&SPcE26r(t0MiTmWv~YqR4dtuUoUG>Erei}jU*6aD zW&IZz%-XjrGt-s8sR*I34fuSJ$lTB7H%ylm-fl?a59h1uUvi{G$(K+W`7kY?L9@;& zp@U4!<~NFm(_))JN2$MmyMJjZXB7}2D1uezCdi;%BcLN7I3(nDgi57!RU-llC?EjA zhsr3TH>NE-yi1^+7QV43LPRTBZJL|4j*PW*XF1u1IBt5DmFeQctqlsO=SFhYwS{uK zNHNhA>5L(fqg(Og#eo^5uq&LsIrDoudrKEbScpV~tt2C4b7w@#dUkYL!jI^vtZ-IL z>ggXjHyhxLAMFzF+a>Ck0ikhYCHI&)-IU6XqBzoRt?32>v7vSC0SQs-fB`I!C-~3NZpZGgZ?(cuQZ}(7Fe;*< zl?4`!JKMUj35T%>k6v$k9nlrh2^y5d{beReJ=RlPqN`tYw4c2VgJEOqMzMs;Y>l71 zTi=_n9eBqn7HiL`2@0s=av~c$*x&*b(-sllDWpz%v4hsFnn)O{N6gN0CTiqpo!iNz z7z7{sL1XuY#xBP$*9C9@ifs-Et>OgHt0`6%OuU#}(BE8H+2341_DoslPO)TE2XWX{ zEdeoIWHy7wU^B_&P$pN0GD!Qp$R2n+<-9y88t@DSM%+W{dx^s>sXp7O&FPA{jYo}1 zf8NaTGTXXPW9=bwhS`LOfurGm+Yi;40|*irTU|u<&H@$$~ii+L{Oj1-p3>pJAY*o^Dk2YMAUB z=8JAI)LGnv(HdTtTT>vbTMx?mATjjeod&5 zy#Lgz{8a&`N9cxC%iSYgqGhIWl)Kp*N$2$+t5qn0ig3Hf>VkoUHgD{`r^Nyy>rSrw_1>)sjF&V_U zbia3}&!>y)-b48oyghZv_uV&OS||TvfRrN8+b;jDLj#&7ub$uzXhS9g>dK`J+atL} zuoK5Hw|G0(XmzxrL`192gEC*~8k=#TE2cH$E@IG-CYYJ%V@d_F%;Y6e^46!GoQR^T)aZ z;yhR#!SVj?^TuA;Xzjz_kR>vRA8+WSUUW@w576HUl=mFDI}1?%X72*eoqwO!BLGgC z-R2Ku_>c@~u$iX}!)TGdf~WWu@}C-B1r)$Bc}PQ(SHyJuy-rqkQY*^=)YIL~31m>!&t`#= z44=A~dgGX&YxVUN5_NTnWHtf)21r8#_*Y>=OB3<}*)9`ir&6~L#iynV2-T^E4yi*4 zY1?q8TonPKad}N)6A3vUE9;!fgrQUyv8TT{M?_BwTV1YGrw!EC9Bb7+zgfHhdO%P5 z!ugF&+NTtXcKve)aE(`=TCr6uZ4Ww==U~ceDdEkloQi z0gl}M{;yx<{c>*wBXHJMXByaCmQ)?x5f!;C8y(fLo*TvM;6|?JZ4m4W>K*u83lQf& zE`HS1BdI?(N*)_Fe$Lr=1>OA7%DD7+M|F9>G{!F|B*HKz!!cgFs&ryDWdmpdkAK(IZ@0105*edg7>GZ+dwlcE4X4R%uTkkcxZ?Cqpzikc>9e`n?(Set02grj z``NmnU#@))BOK%l21QB2p& zrtwyjNKaYy zcTL!jzaesqJN?o1vD4!)Z5t8_<;cRj1|87xJCPOwchViXjr2r{styfp9&W02Dj__+ z9EQTZFiqYV$nq~%#3-hn1Ep7SZcjEW{1gZd&ySH5bRK0S zB_9bWZBlS_ z+&1C3?ZFw&ug!g%e{#UkM;l0uJ@Qa>NfWK2&JHra802ecL<5WqgY_CVpPWM% z0Csv@A`h%CxFfq1sJ(NuH3*oWpv9EZXi_FqK+j{=>pvj$v;xQbN&f_T$v|`J_@#Ra zl-%BE@L!uU;J2OQQ2Y_xvQ3UIoSrV!?e8l@Ysh=#ef+5#q5I^)eRJ2un=~~ye!X^W zqnI@DcP(Y3w&|O;DJA!tQ(gdU0+m49fjM9fv=e~cE}Dr$@~TLx8|)tK$iI66Ch-hm zRjf9U_p&%3&8pa4J0TfWMtg^q%qjA+x(#<)za!9wjlr14Z2@fAx_^knn~2&q&j2=q z0btc1js~NlXgJy)?TB_pyPCV(uy&A*8cOIj^Vnmg+aAdldumUdxDp_EB%dMsJOztRG;cw9Wx~qV0xpHmSGAiz!lXR{B^? z-0q_uFFs~w@Z>=L=>k~snE2*Wtv~_RTub(=VM)e)a?Wakas;&Uoti)Y7+k{!)JryMs*M#Iey{baD8wnYEdFFZoH!IETnf z@)y4xIy<$1qVJ63K4s|S=0XmUJEEM|Fzs)Fv4*!~Pd**+C%58*^$1a0I^^WvzT}6% zZSeKBz)A)5kZTE-1p(E$pZ+j~&I`c&NE&+*WfitFv-NGKHDx7&dQ07XG-D%e3DFOE z;kl*~S*hVsOr6!Vk*|(BtvI7V6Nk(X>Nd9J9y0SgD~M=gjgHllgs=CKrk(_y&lSUM z!r4r8Cpn&>MEY>|_H0HE;u0b^3Rr8J2{$S1{i+4NEOOQ*rJj%4QG$ zPxEdOk30h_cS&)6dPd$SW-V?JWonUHp*EX=mtE9kqmv=PM}PtZDvlq?z4n1=ZG`+RVg^kq$Dz;21gVvE~;kK4g}8ZG4QriGhLIMF3EUB#m^!##jF zGxJPO0^}jpqz(6`=yHtkUK0adtD*ZAswUU(uNbw&Ym>o~3>zSY)=us9EPuzq&FX#>SAm&BiSwLa$KV_xj}8FceC;T9%c?b(89s>l25WG&Qi$!1C1tWm zKhwX3;&^O9gJ|&)E5Fgr&>v>TZ$AI7Nh$7th1ot9^cIgbM5C7=2@97#<~$4)psKq$?QgPK)QnlcWMpp&85aB27F5F05|S{{l`|J>GR`s8iA1ujxR3$xUQY{51+Ia=39 zZ1l<5&ZU5X3zF<7bU+6ytB6>8%SN(`F1x~(9eWP0y5_nYYsbCuE>gIfc9YnQ^$r^0 z<|Fr2{ucWs##}$ieiEzuZcs^R^qfxO=1u6$Km=tVH+z z3{xyzi8AF%4X7|G!Y3SDk=BXAvsRUAl`GcqxOF8b#RmdHg46yB6p*}4UvyL}rL#t! zvA*1xF_Yx)koxzyjb&Jl7YtQIt>qWM zHot6a?d-EcEy1rJq^x#ya&~czRswKy$YGRlk4HRBIcLlfM;)`<9up=ZsfJhZSrhLN zz=If{_>xgj3O{vvgG9q;3y#AvW2%e5FmjM72PM?dLT5omqk7Gnw5XNnO)$dLhN{(l zPdxC@)9^o*dIUqf#B45AZCL%jA3TACluD?W2_|VJ>uL1dL*a zri5yn_=7vG3BjDqRgV_E$twvx`9kR!^Nnm~i(ko!Y4K}ElQ$@Ril#V999F|xSPvUv zGi-(Ju(Qe)w&W>_@^m4r84$L^cGy;J0%2zhm;2wj;op{Bd5pKP^6M>QNh)>b@-1`}LnX+0tYA~z`y)65+D=1dJdMfo!5Mp6+_cA=&-N~h zf0{V2p{eVB=00(`xFmeR)<|9t8(STdkLmm6TM8k3!n|Q@ zOu=5?`w4k1IOVT^RuOQJoYx}$ygX9x0Zlc1>NABOgmx^JOE0bM5B`(ZxnpDe#e->7 a3TYn0gLbW&i;;0we>2NCY4Sgg^&~Eer=62S7ze zg^dFM(fiRL`~Q%@jUiZPT3xY(?io#vwXlfkA_PYhaVgOA{3%+;+OtH~2WR7aoml&? zP*8Wo8mzP9>Q&j$&w9s{BP5w6z?N6c4#d{I?6@e1WCu?P>!GiZo^yxm`$ zC0Kw#V2P(u0)Yjldz)i6jMD{_N!s3~2qXZ#c0Ww-xRXaVF#!qw|Npsq?YlF%dorK6 z03;kLBwb&fm(0wYyeyG`Y*rSUlmy)D{Dln zeXZ4YRpugN)gpfvbJ~=4h(0Puu@wWw;nug;;cFrQ$|Mlz_07yeK)+3TEucRNLo1+z z0fvT4o$l*ffdjCz3K;4IqLP)Ipuz2=B5LF3T^b9FhFPKS>Iw#Eg}sU z2M*u}PJjmj5P<~bY?3baiV$300Ej5be@p!UeFpDR0SGs z!{KphQ=o19IYr_PdIB^D`*33z3j4!9Mce=X%Yms;?Ci}AVKD3s2hTp_l$8^?mUvGa zeO`n72h>K##Ky%Z1dxHCO2(HfL_K$<{3(zmB1__E47@l5@rV*Qi3N**6$K}ngBTc* zSTe9>;>bcHN0*8r4O2R2DR^>lWph=`O$mWKE((Yg5-TE<&qEn66}(mQQN>d^Up4&H z3ZNvV7DOXhoj@vKnuKa3(=4181d6)>oB{YFARGYgoxtD+%)S~D56}R+0!Lr06<4;6 za$=m^6%a6`l)KM24u4k!B>4Rt<2Y&uh;*PhA>u=2XTwM?*ER(5sbPOdasjq8Z9jqH(f z-aDuQO!g+H%L2~=E+aI;rja+4>E*&)@gT3D1dSw}sZp0q$8{7IS5Q!*M2UieY7A(c z{c0B25E_sg1E7&S#0ieH&qyyYQV4`JV!@X~J8Du3jSh$tn|7eFI)Nhu;3h{`Ha%u+ zcT*jFH`g2>v3Rd@dpour`s%y2XUSF07^~7AW%2F}(S-zcSUMGwZE;@3%t2<02c_T9 z5gekLGNW{MyVrsbsOYh+=@HF5OL!>=8LpBe^Wa~o-b2q|(T=*jn)6rUg(+8zYQ?OO z?R~?R5ZbAr)W}nkVxIUSG6Za!6BzggRzeJ1C0EU_Itnax7NTU(b}j8Tn(pG}4qx2# z+ToltJAZGm_5NS+UuPcnqj4vmS1?9!e$7oeg5}sk6uccPR7t?uVpUr^XM&e2h0q0^ zc_HOaw7|)Ap=>(?c)$NeH4cxS{zic46?)iyKd~cI=MoUq1DoqgtE>ptvY(iF@Aha# zEiqB5ep_#PVm08NljEreoJ66LF^zXNnYkxHm3BvupY}QD<8CN4+6b^5 z>ZFb5p@87n9}=nfJRuxvHj;!HklZK}q6Y0W;C_!02}{EeCNxro=BaiWR%bbBQbmZ9 zZ)zW}7AmM14Q5g2>V1CdKhmJD%Y>~^KpCX@-G{ESpLvLrW*}D55pZ$vKHdGTlr4 z7>bbJgI>1+SeK)zpm17{0;3hwy8^Lw+wQSrP(}OATiv4m79$Xgr|3~FG^ve-2}mYa zw3#IXud#^j<_pwnB4`pvK(MjpP7N85B-S7}&fUC+fanva%*#b`hh>IzBz>7)j>uOr zBp?a%qLJujdIUk18KsDH6}=zgSCk-?6T;R>u3@Ye5{|DzRLB{DI zz~L``y#PV7D9du41u5CS?@=UJZsGL2+=0R)(u4#l9C@TLZ$J<4H^Rm40w24DACR#3 z;f{<)lxw$j)Qa1*rk**0iRPXGLt}h?@78Je+yAR4#yE8`uP;KB$Bn19CKOf%V||sn z;CFMAFlmdH{!0Jyo z{WF4877@4Yx=X)hj4@7I%_#*V|h99hyQ(uE!OY?;7VWR6&BHm`eI_wEx!_w!;DQzMoxfOZ1+ zgf4=o@2oqz?x>dzU;uAs;(pE z>Xex(T6iT&cn^^JqNqk$i*GjRuTTD9GQbQDzuc{gcp0&D_e=1i+iJJEj2Y<5?p%^08LM%~7dh0+cd;ErB=1`$2YQ8p=Ie)moaI*`(yS&7_QL;M9A6c2{u6W?U1xx^x4<3YmSLC?&U(N$3rq+I1v!?bv%z4lz zeH>~A0+yWQ5eVHsZXLCb*DSS$K~^Yz{3465n6_Ecj$>!On?~M|c`k{&kZS|&?fBTK z=g-x`Tbe`LcRI7@-j*Sv@8M3X|38tR%ij-3TIt*bv31yCxbgAtBVMFxHa1F-#Sx_9 zeonz%=Dp5JG->png64OD`5PHop@Zwn=>E)Jgam7}&KlEj`n17y!8Um2f`7O6|Ae~p zWRt5(P5$wTT>&_A*yP;qU(>gq9}Uk09YN~tDh=vvp5b{hM!ipND$e7?QwCnG{f-tB zK21QW2wUKSpD-Z7TyK1(8QqJ%8U&5I39lE~|R{iTcI71QU~ zVDFVxUwOZT`_+bI)ycHUBp;!O5qIo}qK$^Ww1E|O{h${7o$sF0ukLK&x_nN0Oj-;_ zxG+B(h(@B0ABH0KMeVc%_nXT;SiZOrX!mcDZHo{;GV+2RW;Tm)~I>7D`m|sniED?y9@z<8| zyN2Ct4#qOB?uGh>F)fL|VlyNOzMZorHl#Bw{RRl%mgE;n1nxFDM-cbj&Li?CDv6XN zpO&jo0Uv|g4hs%Q~wCv68_Ld<+9(t3SDYr2^i6cQS*L1INGw3 z9+d2w{43ojl+=d}+vfLxO3tFAK46FF6}9kt$D)_ok&XSH|Tx!%N8uMmCV{?y=gfZ!31&!ou4g80mR*Z8=yF_Z-ACy-v+P%eH&nK zX*a;~6SqD|D8d$)Kou|w-Bdb_M)evPUKO`ayGVg&9ZN;8al4MeSOLXGTD)Fu^y&r5 zA(ttOLMy#C?KF~gG0;=UBz!D?3EF6>71PjD=xzL>NT@1?k-~+bdC_H==*m2wWl;*G z%918Z3&w+r78X8jSOcze2H?4@0= z@nEroQt2udZ;1dcwt}9xsHTw77AX}zgUKC~ReYZQmA!y17oikY(+!K&W_LJU`GD*J zKnO-q3@1p6W>`)j6p1BLnLLO>sZwjSI=#Wjo6Hug&F*lz+#avbFCOHTC`mH86sgjr z%aAEcwj8cWhzTWO`|Sop9YP2*yE>OW7Oa}{zfR7 zF|*m^P@s}b86u;@fQaHU3exg%oxem#xt1NEKqZ;k6c8nz&3N7b?brUa(!4eaz<>%( zzAohR=4NMieOwMmSeZGHrCgf@Lo>iNN1U^As4NJ?3Wk9hMrvNY7?}O%|M?#)TrnuX zJQP^aqeP7sEhh9Bkx=IErBchDp+qg&*%XnaG@EHqgnbN9VnmG=J*GXD<`oGwCM+n? m?$I~j7*Qf&+Ean|o-F*K*R*~%LZGN|zp=Vrw*O*p+8qEvL!V~= literal 0 HcmV?d00001 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/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/src/CustomerApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx index bfc7018..a3989a7 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx @@ -24,7 +24,8 @@ 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 BusinessApp from "./business/BusinessApp"; +import { homeFor, isBusinessRoles, isManagerRoles, isOpsRoles, isStaffRoles } from "./lib/roles"; import OpsApp from "./ops/OpsApp"; import { OpsProvider } from "./ops/store"; import Reservations from "./pages/Reservations"; @@ -46,6 +47,7 @@ const TITLES = { reservations: "Đơn đặt chỗ", payments: "Thanh toán & lịch hẹn", sent: "Đã gửi yêu cầu", + business: "Quản lý vận hành kinh doanh", admin: "Quản trị hệ thống", staff: "Nhân viên cơ sở", manager: "Quản lý cơ sở", @@ -94,9 +96,11 @@ function Shell() { const isAdminPage = route.page === "admin"; const isOpsPage = route.page === "staff" || route.page === "manager"; const opsRole = route.page === "staff" ? "STAFF" : "MANAGER"; + const isBusinessPage = route.page === "business"; + const businessAllowed = isBusinessRoles(roles); 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; + const needsLogin = (PRIVATE.includes(route.page) || isOpsPage || ((isAdminPage || isBusinessPage) && mode === "api")) && !authed; useEffect(() => { document.title = `${TITLES[route.page] || "SafeSpace"} · SafeSpace`; @@ -105,14 +109,20 @@ function Shell() { 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; + if (!PRIVATE.includes(current.page) && !["admin", "staff", "manager", "business"].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]); + if ((isAdmin || isOps || businessAllowed) && (PRIVATE.includes(route.page) || route.page === "login" || route.page === "register")) go(homeFor(roles), { replace: true }); + }, [isAdmin, isOps, businessAllowed, roles, route.page]); + + const businessBody = mode !== "api" ? ( +

+ ) : authed && !businessAllowed ? ( +
Về trang của tôi
+ ) : null; const adminBody = mode !== "api" ? ( @@ -132,7 +142,7 @@ function Shell() { return (
{ e.preventDefault(); document.getElementById("main")?.focus(); }}>Chuyển đến nội dung - {!(isAdminPage && !adminBody && authed) && !(isOpsPage && authed && opsAllowed) &&
} + {!(isAdminPage && !adminBody && authed) && !(isOpsPage && authed && opsAllowed) && !(isBusinessPage && !businessBody && authed) &&
}
{needsLogin ? null : loadError && !ready ? (
@@ -147,6 +157,8 @@ function Shell() {
) : isAdminPage ? ( adminBody || + ) : isBusinessPage ? ( + businessBody || ) : isOpsPage ? ( opsAllowed ? ( diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/business.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/business.js new file mode 100644 index 0000000..781fbbb --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/business.js @@ -0,0 +1,51 @@ +// Endpoint khu Quản lý vận hành kinh doanh (StorageProject.Api/Endpoints/OperationsEndpoints.cs), role OPERATIONS. +// Hợp đồng chi tiết: docs/operations-api.md. +import { request, ApiError } from "./http.js"; +import { API_URL } from "../config/api.js"; +async function requestFile(path, { fallbackName = "bao-cao.csv" } = {}) { + let token; + try { token = JSON.parse(localStorage.getItem('safespace.customer.session'))?.token; } catch { /* absent session */ } + let res; + try { res = await fetch(`${API_URL}${path}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} }); } + catch { throw new ApiError('Không kết nối được máy chủ. Vui lòng kiểm tra địa chỉ API.', 0); } + if (!res.ok) { const data = await res.json().catch(() => ({})); throw new ApiError(data.error || data.message || `Không xuất được báo cáo (HTTP ${res.status}).`, res.status, data); } + return { blob: await res.blob(), fileName: fallbackName }; +} + +const q = (params = {}) => { + const s = new URLSearchParams(); + for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null && v !== "") s.set(k, v); + const str = s.toString(); + return str ? `?${str}` : ""; +}; + +export const businessApi = { + // B05 · Cơ sở (UC19) + facilities: (filter) => request(`/api/operations/facilities${q(filter)}`), + createFacility: (body) => request("/api/operations/facilities", { method: "POST", body }), + updateFacility: (id, body) => request(`/api/operations/facilities/${id}`, { method: "PUT", body }), + setFacilityStatus: (id, status, reason) => request(`/api/operations/facilities/${id}/status`, { method: "PUT", body: { status, reason } }), + + // B02, B03 · Chính sách, khung giá, phí, giảm giá (UC20, UC21) + policies: (filter) => request(`/api/operations/policies${q(filter)}`), + createPolicy: (body) => request("/api/operations/policies", { method: "POST", body }), + updatePolicy: (id, body) => request(`/api/operations/policies/${id}`, { method: "PUT", body }), + activatePolicy: (id, replaceExisting = false) => + request(`/api/operations/policies/${id}/activate${replaceExisting ? "?replaceExisting=true" : ""}`, { method: "POST" }), + deactivatePolicy: (id) => request(`/api/operations/policies/${id}/deactivate`, { method: "POST" }), + deletePolicy: (id) => request(`/api/operations/policies/${id}`, { method: "DELETE" }), + + // B03 · Bảng giá thuê + rates: (filter) => request(`/api/operations/rates${q(filter)}`), + setRate: (body) => request("/api/operations/rates", { method: "POST", body }), + + // B01, B04 · Báo cáo (UC22, UC23) + facilityReport: (filter) => request(`/api/operations/reports/facilities${q(filter)}`), + unitTypeReport: (filter) => request(`/api/operations/reports/unit-types${q(filter)}`), + revenueTrend: (filter) => request(`/api/operations/reports/revenue-trend${q(filter)}`), + rentalStatus: (filter) => request(`/api/operations/reports/rental-status${q(filter)}`), + exportReport: (filter, fallbackName) => requestFile(`/api/operations/reports/export${q(filter)}`, { fallbackName }), + + // Danh mục loại kho (công khai) + unitTypes: () => request("/api/unit-types", { auth: false }), +}; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessApp.jsx new file mode 100644 index 0000000..49c477c --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessApp.jsx @@ -0,0 +1,40 @@ +import React from "react"; +import { Empty, LinkButton } from "../components/UI"; +import BusinessShell from "./BusinessShell"; +import BusinessFacilities from "./Facilities"; +import BusinessOverview from "./Overview"; +import BusinessPolicies from "./Policies"; +import BusinessPricing from "./Pricing"; +import BusinessReports from "./Reports"; + +// Khu Quản lý vận hành KD (Figma B01–B05), role OPERATIONS: +// #/business · #/business/facilities · #/business/policies · #/business/pricing · #/business/reports +export default function BusinessApp({ parts, query }) { + const [a] = parts; + let active = "business"; + let body; + if (!a) body = ; + else if (a === "facilities") { + active = "business/facilities"; + body = ; + } else if (a === "policies") { + active = "business/policies"; + body = ; + } else if (a === "pricing") { + active = "business/pricing"; + body = ; + } else if (a === "reports") { + active = "business/reports"; + body = ; + } else { + active = ""; + body = ( +
+ + Về tổng quan hệ thống + +
+ ); + } + return {body}; +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessShell.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessShell.jsx new file mode 100644 index 0000000..61c70a6 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessShell.jsx @@ -0,0 +1,187 @@ +import "./design.css"; +import React, { useEffect, useRef, useState } from "react"; +import { businessApi } from "../api/business"; +import { go, href } from "../lib/router"; +import { useApp } from "../state/store"; + +function useOutside(open, setOpen, ref) { + 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, setOpen, ref]); +} + + +function UserMenu({ roleLabel, tone }) { + const { user, logout } = useApp(); + const [open, setOpen] = useState(false); + const ref = useRef(null); + useOutside(open, setOpen, ref); + return ( +
+ + {open && ( +
+

+ {user?.username || user?.full_name} +
+ {user?.email} +

+ +
+ )} +
+ ); +} + + +// Khung khu Quản lý vận hành KD (Figma B01–B05): logo, tên + "Vận hành KD", chuông, 5 tab. +export const BUSINESS_TABS = [ + ["business", "Tổng quan hệ thống"], + ["business/facilities", "Các cơ sở"], + ["business/policies", "Chính sách"], + ["business/pricing", "Giá & phí"], + ["business/reports", "Báo cáo"], +]; + +const READ_KEY = "safespace.business.notices.read"; +const readSaved = () => { + try { + const saved = JSON.parse(localStorage.getItem(READ_KEY)); + return Array.isArray(saved) ? saved : []; + } catch { + return []; + } +}; + +// Việc cần để ý trên toàn hệ thống, lấy từ API (không có bảng thông báo riêng) +function useNotices() { + const { onApiError } = useApp(); + const [items, setItems] = useState([]); + const [read, setRead] = useState(readSaved); + useEffect(() => { + let alive = true; + (async () => { + try { + const [facilities, report, drafts] = await Promise.all([ + businessApi.facilities(), + businessApi.facilityReport({}), + businessApi.policies({ status: "DRAFT" }), + ]); + if (!alive) return; + const list = []; + const overdue = report?.totals?.overdueContracts || 0; + if (overdue) list.push({ id: `overdue-${overdue}`, title: `${overdue} hợp đồng quá hạn toàn hệ thống`, to: "business/reports" }); + const missing = facilities.filter((f) => f.status === "ACTIVE" && (f.pricedUnitTypes === 0 || f.totalUnits === 0 || f.assignedStaff === 0)); + if (missing.length) list.push({ id: `setup-${missing.map((f) => f.facilityId).join("-")}`, title: `${missing.length} cơ sở đang hoạt động còn thiếu giá, ô kho hoặc nhân sự`, to: "business/facilities" }); + const closed = facilities.filter((f) => f.status === "TEMPORARILY_CLOSED"); + if (closed.length) list.push({ id: `closed-${closed.map((f) => f.facilityId).join("-")}`, title: `${closed.length} cơ sở đang tạm đóng`, to: "business/facilities" }); + if (drafts.length) list.push({ id: `drafts-${drafts.map((p) => p.policyId).join("-")}`, title: `${drafts.length} chính sách ở bản nháp, chưa áp dụng`, to: "business/policies" }); + 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 { + /* trình duyệt chặn lưu: chỉ giữ trong phiên */ + } + }; + return { items: items.map((n) => ({ ...n, read: read.includes(n.id) })), mark }; +} + +function Bell() { + const { items, mark } = useNotices(); + const [open, setOpen] = useState(false); + const ref = useRef(null); + useOutside(open, setOpen, ref); + const unread = items.filter((n) => !n.read).length; + return ( +
+ + {open && ( +
+
+

Cần để ý

+ +
+

{unread ? `${unread} thông báo mới` : "Đã đọc tất cả"}

+
    + {items.map((n) => ( +
  • + +
  • + ))} +
+ {items.length === 0 &&

Hệ thống chưa có việc cần để ý.

} + {unread > 0 && ( + + )} +
+ )} +
+ ); +} + +export default function BusinessShell({ active, children }) { + return ( +
+
+
+ + + SafeSpace + +
+
+ + {children} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx new file mode 100644 index 0000000..aa2f358 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx @@ -0,0 +1,44 @@ +import React from "react"; +import { businessApi } from "../api/business"; +import { Button } from "../components/UI"; +import { useLoad } from "../admin/util"; +import { go, href, qs } from "../lib/router"; +import { useApp } from "../state/store"; +import { FACILITY_STATUS, areaOf, rateLabel, shortFacility } from "./format"; +import { LoadState } from "./parts"; + +// B05: select a facility and open its business report; no unrelated CRUD controls. +export default function BusinessFacilities({ query }) { + const { onApiError } = useApp(); + const load = useLoad(async () => { + const [facilities, rates] = await Promise.all([businessApi.facilities(), businessApi.rates()]); + return { facilities, rates }; + }, [], onApiError); + const selectedId = Number(query.get("id")); + return
+
+

Mạng lưới cơ sở

+

Theo dõi trạng thái hoạt động, sức chứa và người phụ trách toàn hệ thống.

+
+ {({ facilities, rates }) => { + const current = facilities.find(f => f.facilityId === selectedId) || facilities[0]; + const typeNames = [...new Set(rates.filter(r => r.facilityId === current?.facilityId && r.isCurrent).map(r => r.unitTypeName).filter(Boolean))]; + return <> +
+ + + {facilities.map(f => go(`business/facilities${qs({ id: f.facilityId })}`, { replace: true })}> + + + )}{!facilities.length && } +
Cơ sởQuản lýSố kho / tỷ lệ thuêTrạng thái
{[areaOf(f.address).district, shortFacility(f.name)].filter(Boolean).join(' · ')}{f.managerName || ('managerName' in f ? 'Chưa phân công' : 'Chưa có thông tin')}{f.totalUnits} kho · {rateLabel(f.occupancyRate)}{FACILITY_STATUS[f.status]?.[0] || f.status}
Chưa có cơ sở nào.
+ {current &&
+

{current.name}

+

{[areaOf(current.address).district, areaOf(current.address).city].filter(Boolean).join(', ')}{current.openingTime && ` · Giờ ra vào ${current.openingTime}–${current.closingTime}`}

+

{typeNames.length ? `${typeNames.join(' & ')} · ` : ''}Quản lý: {current.managerName || ('managerName' in current ? 'Chưa phân công' : 'Chưa có thông tin')}

+
+
} + ; + }}
+
; +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Overview.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Overview.jsx new file mode 100644 index 0000000..c7c53de --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Overview.jsx @@ -0,0 +1,88 @@ +import React from "react"; +import { businessApi } from "../api/business"; +import { LinkButton } from "../components/UI"; +import { useLoad, dateTime } from "../admin/util"; +import { useApp } from "../state/store"; +import { areaOf, growthLabel, rateLabel, shortMoney } from "./format"; +import { LoadState } from "./parts"; + +// B01 · Tổng quan toàn hệ thống — số liệu tháng này từ /reports/facilities + /reports/revenue-trend +export default function BusinessOverview() { + const { onApiError } = useApp(); + const load = useLoad( + async () => { + const [facilities, report, trend] = await Promise.all([ + businessApi.facilities(), + businessApi.facilityReport({}), + businessApi.revenueTrend({ months: 2 }), + ]); + return { facilities, report, trend }; + }, + [], + onApiError, + ); + + return ( +
+ + {({ facilities, report, trend }) => { + const t = report.totals; + const active = facilities.filter((f) => f.status === "ACTIVE").length; + const [prev, cur] = trend.months.length >= 2 ? trend.months.slice(-2) : [null, trend.months.at(-1)]; + const growth = prev && cur ? growthLabel(prev.rentalAndFeeRevenue, cur.rentalAndFeeRevenue) : null; + const byId = new Map(facilities.map((f) => [f.facilityId, f])); + return ( + <> +
+
+

Tổng quan toàn hệ thống

+

{active} cơ sở đang hoạt động · Cập nhật đến {dateTime(report.snapshotAt)}

+
+
+
+
{facilities.length}Tổng số cơ sở
+
+ {shortMoney(t.rentalAndFeeRevenue)} + Tổng doanh thu tháng + {growth && {growth} so với tháng trước} +
+
{rateLabel(t.occupancyRate)}Tỷ lệ lấp đầy trung bình
+
{t.overdueContracts}Hợp đồng quá hạn toàn hệ thống
+
+ +

Danh sách cơ sở

+
+ + + + + + {report.facilities.length === 0 && } + {report.facilities.map((row) => { + const f = byId.get(row.facilityId); + const { district, city } = areaOf(f?.address); + return ( + + + + + + + + ); + })} + +
Cơ sởKhu vựcSố khoTỷ lệ lấp đầyDoanh thu tháng
Chưa có cơ sở nào.
{row.facilityName}{city || "—"}{row.metrics.totalUnits}{rateLabel(row.metrics.occupancyRate)}{shortMoney(row.metrics.rentalAndFeeRevenue)}
+
+
+ Quản lý chính sách + Quản lý giá & phí + Xem báo cáo hệ thống +
+ + ); + }} +
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Policies.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Policies.jsx new file mode 100644 index 0000000..1b4beb9 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Policies.jsx @@ -0,0 +1,48 @@ +import React, { useState } from 'react'; +import { businessApi } from '../api/business'; +import { Button, Field } from '../components/UI'; +import { useLoad } from '../admin/util'; +import { today } from '../lib/format'; +import { useApp } from '../state/store'; +import { createPolicy, replacePolicy } from './actions'; +import { LoadState, useConfirm } from './parts'; +import { POLICY_SECTIONS, fieldPolicy, fieldValue, policyJobs } from './policy-fields'; + +export default function BusinessPolicies() { + const { notify, onApiError } = useApp(); + const load = useLoad(() => businessApi.policies({}), [], onApiError); + const [drafts, setDrafts] = useState({}); + const [busy, setBusy] = useState(false); + const [confirmEl, ask] = useConfirm(); + const save = async policies => { + let jobs; + try { + // Validate every edited field before the first network mutation. + jobs = policyJobs(policies, drafts, today()); + } catch (e) { return notify(e.message, 'error'); } + if (!jobs.length) return notify('Chưa có thay đổi nào.'); + setBusy(true); + try { + for (const { keys, p, body } of jobs) { + const applied = p ? await replacePolicy(p, body, ask) : (await createPolicy(body, true, ask)).active; + if (!applied) { notify('Đã giữ bản nháp; các ô chưa áp dụng vẫn được giữ lại.'); return; } + setDrafts(d => { const next = { ...d }; for (const key of keys) delete next[key]; return next; }); + } + notify('Đã lưu thay đổi chính sách.'); + } catch (e) { onApiError(e); notify(e.message, 'error'); } + finally { setBusy(false); load.reload(); } + }; + return
+

Chính sách cho thuê chung

Áp dụng cho toàn bộ cơ sở trong hệ thống, trừ khi có quy định riêng cho từng cơ sở.

+ {policies => <> + {POLICY_SECTIONS.map(section =>
+

{section.title}

{section.fields.map(field => { + const p = fieldPolicy(policies, field, today()); + return setDrafts({ ...drafts, [field.key]: e.target.value })}/>; + })}
+
)} +
+ }
+ {confirmEl} +
; +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Pricing.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Pricing.jsx new file mode 100644 index 0000000..ce5caf7 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Pricing.jsx @@ -0,0 +1,188 @@ +import React, { useCallback, useState } from "react"; +import { businessApi } from "../api/business"; +import { Button, Tag } from "../components/UI"; +import { useLoad } from "../admin/util"; +import { money, today } from "../lib/format"; +import { useApp } from "../state/store"; +import { createPolicy, replacePolicy } from "./actions"; +import { POLICY_STATUS, parseMoney, policyFor, policyValueLabel, replacementOf } from "./format"; +import { LoadState, PolicyForm, useConfirm } from "./parts"; + +// Ba cột chính sách theo loại kho (Figma B03): khung giá, phí dịch vụ / tháng, phí quá hạn / ngày +const COLUMNS = [ + { type: "PRICE_RANGE", calc: "RANGE", unit: "", name: (t) => `Khung giá ${t.typeName}`, rule: "Giá thuê theo tháng của loại kho này tại mọi cơ sở phải nằm trong khung." }, + { type: "EXTRA_FEE", calc: "FIXED", unit: "/ tháng", name: (t) => `Phí dịch vụ ${t.typeName}`, rule: "Phí dịch vụ cộng thêm mỗi tháng thuê." }, + { type: "OVERDUE", calc: "FIXED", unit: "/ ngày", name: (t) => `Phí quá hạn ${t.typeName}`, rule: "Phí cho mỗi ngày quá hạn trả kho hoặc thanh toán." }, +]; + +const cellKey = (unitTypeId, type) => `${unitTypeId}:${type}`; + +function cellDraft(policy, col) { + if (!policy) return col.calc === "RANGE" ? { minValue: "", maxValue: "" } : { value: "" }; + return col.calc === "RANGE" ? { minValue: policy.minValue == null ? "" : money(policy.minValue), maxValue: policy.maxValue == null ? "" : money(policy.maxValue) } : { value: policy.value == null ? "" : money(policy.value) }; +} + +// B03 · Quản lý giá & phí (UC21): khung giá / phí theo loại kho, giảm giá / miễn phí +export default function BusinessPricing() { + const { notify, onApiError } = useApp(); + const load = useLoad( + async () => { + const [policies, facilities, unitTypes] = await Promise.all([businessApi.policies({}), businessApi.facilities(), businessApi.unitTypes()]); + return { policies, facilities, unitTypes: unitTypes.filter((t) => t.status !== "INACTIVE") }; + }, + [], + onApiError, + ); + const [edit, setEdit] = useState({}); // Only edited cells are sent to the backend. + const [adding, setAdding] = useState(false); + const [busy, setBusy] = useState(false); + const [confirmEl, ask] = useConfirm(); + const close = useCallback(() => setAdding(false), []); + + const saveTable = async ({ policies, unitTypes }) => { + const jobs = []; + for (const t of unitTypes) + for (const col of COLUMNS) { + const d = edit[cellKey(t.unitTypeId, col.type)]; + if (!d) continue; + const current = policyFor(policies, col.type, t.unitTypeId); + const own = current && current.unitTypeId === t.unitTypeId ? current : null; + const blank = col.calc === "RANGE" ? !d.minValue && !d.maxValue : !String(d.value).trim(); + if (blank) continue; + const values = + col.calc === "RANGE" ? { minValue: parseMoney(d.minValue), maxValue: parseMoney(d.maxValue) } : { value: parseMoney(d.value) }; + if (Object.values(values).some((v) => !Number.isFinite(v) || v < 0)) return notify(`${t.typeName}: giá trị không hợp lệ.`, "error"); + if (col.calc === "RANGE" && values.minValue > values.maxValue) return notify(`${t.typeName}: giá thấp nhất phải nhỏ hơn hoặc bằng giá cao nhất.`, "error"); + const same = own && (col.calc === "RANGE" ? own.minValue === values.minValue && own.maxValue === values.maxValue : Number(own.value) === values.value); + if (same) continue; + jobs.push(own + ? () => replacePolicy(own, replacementOf(own, values, today()), ask) + : () => createPolicy({ policyName: col.name(t), policyType: col.type, calculationType: col.calc, value: null, minValue: null, maxValue: null, ruleDescription: col.rule, facilityId: null, unitTypeId: t.unitTypeId, effectiveFrom: today(), effectiveTo: null, ...values }, true, ask)); + } + if (!jobs.length) { + setEdit({}); + return notify("Chưa có thay đổi nào."); + } + setBusy(true); + try { + for (const job of jobs) { const result = await job(); if (result === false || result?.active === false) return; } + notify(`Đã lưu ${jobs.length} thay đổi khung giá / phí. Áp dụng từ hôm nay.`); + setEdit({}); + load.reload(); + } catch (e) { + onApiError(e); + notify(e.message, "error"); + load.reload(); + } finally { setBusy(false); } + }; + + return ( +
+

Quản lý giá & phí

+ + {(data) => { + const { policies, facilities, unitTypes } = data; + const discounts = policies.filter((p) => ["DISCOUNT", "FEE_WAIVER"].includes(p.policyType) && ["ACTIVE", "DRAFT"].includes(p.status)); + + return ( + <> +
+
+

Khoảng giá theo loại kho

+ +
+
+ + + + {unitTypes.length === 0 && } + {unitTypes.map((t) => ( + + + {COLUMNS.map((col) => { + const p = policyFor(policies, col.type, t.unitTypeId); + const key = cellKey(t.unitTypeId, col.type); + const d = edit[key] ?? cellDraft(p, col); + const put = (patch) => setEdit({ ...edit, [key]: { ...d, ...patch } }); + return ( + + ); + })} + + ))} + +
Loại khoKhoảng giá (theo tháng)Phí dịch vụPhí quá hạn / ngày
Chưa có loại kho.
{t.typeName} + {col.calc === "RANGE" ? ( +
+ put({ minValue: e.target.value })} placeholder="Từ" /> + – + put({ maxValue: e.target.value })} placeholder="Đến" /> +
+ ) : ( + put({ value: e.target.value })} placeholder="Chưa đặt" /> + )} + {col.type === "EXTRA_FEE" && / tháng} +
+
+
+ +
+

Chính sách giảm giá / miễn phí

+ {discounts.length === 0 &&

Chưa có chính sách giảm giá hoặc miễn phí.

} +
    + {discounts.map((p) => { + const [label, tone] = POLICY_STATUS[p.status] || [p.status, "gray"]; + const scope = [p.facilityName, p.unitTypeName].filter(Boolean).join(" · "); + return ( +
  • +
    + {p.policyName} + + {p.ruleDescription || policyValueLabel(p)} + {scope ? ` · ${scope}` : ""} + +
    +
    + {label} + +
    +
  • + ); + })} +
+
+ +
+ + +
+ + {adding && ( + { + try { + const { active } = await createPolicy(body, activate, ask); + notify(activate && active ? `Đã áp dụng “${body.policyName}”.` : `Đã lưu bản nháp “${body.policyName}”.`); + load.reload(); + return true; + } catch (e) { + onApiError(e); + notify(e.message, "error"); + return false; + } + }} + /> + )} + {confirmEl} + + ); + }} +
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Reports.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Reports.jsx new file mode 100644 index 0000000..12439ef --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Reports.jsx @@ -0,0 +1,226 @@ +import React, { useState } from "react"; +import { businessApi } from "../api/business"; +import { Button } from "../components/UI"; +import { useLoad } from "../admin/util"; +import { go, qs } from "../lib/router"; +import { today } from "../lib/format"; +import { useApp } from "../state/store"; +import { + CONTRACT_STATUS_LABELS, + RESERVATION_STATUS_LABELS, + UNIT_STATUS_LABELS, + monthPeriod, + rateLabel, + shortFacility, + shortMoney, +} from "./format"; +import { parseCsv, downloadWorkbook } from "./export"; +import { BarChart, LoadState } from "./parts"; + +const VIEWS = [ + ["facilities", "Theo cơ sở"], + ["unit-types", "Theo loại kho"], + ["revenue", "Theo doanh thu"], + ["status", "Theo tình trạng thuê"], +]; + +function FacilityView({ data }) { + const rows = data.facilities; + return ( + <> + ({ key: r.facilityId, label: shortFacility(r.facilityName), value: r.metrics.rentalAndFeeRevenue, text: shortMoney(r.metrics.rentalAndFeeRevenue) }))} + /> +

Chi tiết theo cơ sở

+
+ + + + {rows.length === 0 && } + {rows.map((r) => ( + + + + + + + ))} + + +
Cơ sởDoanh thuTỷ lệ lấp đầyHợp đồng quá hạn
Không có cơ sở phù hợp bộ lọc.
{r.facilityName}{shortMoney(r.metrics.rentalAndFeeRevenue)}{rateLabel(r.metrics.occupancyRate)}{r.metrics.overdueContracts}
+
+ + ); +} + +function UnitTypeView({ data }) { + const rows = data.unitTypes; + return ( + <> + ({ key: r.unitTypeId, label: r.unitTypeName, value: r.metrics.rentalAndFeeRevenue, text: shortMoney(r.metrics.rentalAndFeeRevenue) }))} + /> +

Chi tiết theo loại kho

+
+ + + + {rows.length === 0 && } + {rows.map((r) => ( + + + + + + + + ))} + +
Loại khoDoanh thuKho đang thuê / khai thác đượcTỷ lệ lấp đầyHợp đồng quá hạn
Không có loại kho phù hợp bộ lọc.
{r.unitTypeName}{shortMoney(r.metrics.rentalAndFeeRevenue)}{r.metrics.unitsInUse} / {r.metrics.operableUnits}{rateLabel(r.metrics.occupancyRate)}{r.metrics.overdueContracts}
+
+ + ); +} + +function RevenueView({ data }) { + const months = data.months; + return ( + <> + ({ key: `${m.year}-${m.month}`, label: `${m.month}/${m.year}`, value: m.rentalAndFeeRevenue, text: shortMoney(m.rentalAndFeeRevenue) }))} + /> +

Chi tiết theo tháng

+
+ + + + {[...months].reverse().map((m) => ( + + + + + + + + ))} + +
ThángDoanh thu thuê và phíCọc thuTổng tiền thuHoàn tiền
Tháng {m.month}/{m.year}{shortMoney(m.rentalAndFeeRevenue)}{shortMoney(m.depositCollected)}{shortMoney(m.collected)}{shortMoney(m.refunded)}
+
+ + ); +} + +function StatusGroup({ title, rows, labels }) { + const total = rows.reduce((s, r) => s + r.count, 0); + return ( +
+

{title} · {total}

+ {rows.length === 0 ? ( +

Chưa có dữ liệu.

+ ) : ( + rows.map((r) => ( +
+
{labels[r.status] || r.status}{r.count}
+
+
+ )) + )} +
+ ); +} + +function StatusView({ data }) { + return ( +
+ + + +
+ ); +} + +// B04 · Báo cáo toàn hệ thống (UC22, UC23): theo cơ sở / loại kho / doanh thu / tình trạng thuê, xuất XLSX (CSV từ API được chuyển thành workbook; trạng thái dùng snapshot đang xem) +export default function BusinessReports({ query }) { + const { notify, onApiError } = useApp(); + const now = today(); + const view = VIEWS.some(([k]) => k === query.get("view")) ? query.get("view") : "facilities"; + const month = /^(?:19|20)\d{2}-(?:0[1-9]|1[0-2])$/.test(query.get("month") || "") ? query.get("month") : now.slice(0, 7); + const facility = query.get("facility") || ""; + const set = (patch) => go(`business/reports${qs({ view, month: month === now.slice(0, 7) ? "" : month, facility, ...patch })}`, { replace: true }); + const period = monthPeriod(month, now); + const filter = { ...period, facilityId: facility }; + const [exporting, setExporting] = useState(false); + + // Giữ kèm tên view để không vẽ số liệu cũ của view khác trong lúc đang tải view mới + const load = useLoad( + async () => { + if (view === "unit-types") return { view, data: await businessApi.unitTypeReport(filter) }; + if (view === "revenue") return { view, data: await businessApi.revenueTrend({ months: 6 }) }; + if (view === "status") return { view, data: await businessApi.rentalStatus({}) }; + return { view, data: await businessApi.facilityReport(filter) }; + }, + [view, month, facility], + onApiError, + ); + + const exportView = view === "unit-types" ? "unit-types" : view === "revenue" ? "revenue-trend" : view === "facilities" ? "facilities" : null; + const doExport = async () => { + setExporting(true); + try { + if (view === "status") { + const data = load.data.data; + const rows = [['SafeSpace — Báo cáo tình trạng thuê'], ['Cập nhật (UTC)', data.snapshotAt], ['Nhóm', 'Tình trạng', 'Số lượng']]; + for (const [key, title, labels] of [['contracts', 'Hợp đồng', CONTRACT_STATUS_LABELS], ['reservations', 'Đơn đặt chỗ', RESERVATION_STATUS_LABELS], ['units', 'Ô kho', UNIT_STATUS_LABELS]]) + for (const r of data[key]) rows.push([title, labels[r.status] || r.status, r.count]); + downloadWorkbook(rows, `bao-cao-tinh-trang-thue-${now}.xlsx`); + notify("Đã xuất báo cáo."); + return; + } + const params = exportView === "revenue-trend" ? { view: exportView, from: new Date(Date.UTC(Number(now.slice(0, 4)), Number(now.slice(5, 7)) - 6, 1)).toISOString().slice(0, 10), to: now } : { view: exportView, ...filter }; + const { blob } = await businessApi.exportReport(params, `bao-cao-${exportView}-${month}.csv`); + downloadWorkbook(parseCsv(await blob.text()), `bao-cao-${exportView}-${month}.xlsx`); + notify("Đã xuất báo cáo."); + } catch (e) { + onApiError(e); + notify(e.message, "error"); + } finally { setExporting(false); } + }; + + const [y, m] = month.split("-"); + return ( +
+
+
+

Báo cáo toàn hệ thống{view === "revenue" || view === "status" ? "" : ` — Tháng ${Number(m)}/${y}`}

+ +
+
+
+
+ {VIEWS.map(([k, label]) => ( + + ))} +
+
+ + {({ data }) => ( + <> + {view === "facilities" && } + {view === "unit-types" && } + {view === "revenue" && } + {view === "status" && } + + + )} + +
+ +
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/actions.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/actions.js new file mode 100644 index 0000000..4ed266f --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/actions.js @@ -0,0 +1,23 @@ +import { businessApi } from '../api/business.js'; +import { ApiError } from '../api/http.js'; +import { POLICY_TYPES } from './format.js'; +export async function activateWithConfirm(policy,ask){ + try{await businessApi.activatePolicy(policy.policyId);return true;} + catch(e){ + if(!(e instanceof ApiError && e.status===409))throw e; + const ids=e.data?.details?.conflictingPolicyIds || []; + const ok=await ask({title:'Thay chính sách đang áp dụng?',message:`API báo xung đột chính sách ${POLICY_TYPES[policy.policyType]?.toLowerCase()||''} cùng loại và phạm vi${ids.length?` (mã ${ids.join(', ')})`:''}. Nếu xác nhận, các bản xung đột sẽ được thay thế theo quy tắc backend.`,actionLabel:'Thay chính sách'}); + if(!ok)return false; + await businessApi.activatePolicy(policy.policyId,true);return true; + } +} +export async function createPolicy(body,activate,ask){ + const created=await businessApi.createPolicy(body); + if(!activate)return {created,active:false}; + return {created,active:await activateWithConfirm(created,ask)}; +} +export async function replacePolicy(policy,body,ask){ + if(policy.status==='DRAFT'){await businessApi.updatePolicy(policy.policyId,body);return true;} + const created=await businessApi.createPolicy(body); + return activateWithConfirm(created,ask); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css new file mode 100644 index 0000000..1d15886 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css @@ -0,0 +1,146 @@ + +.business-app .usermenu__btn--business small { color: #7c3aed; } +.business-app .stat strong.danger { color: var(--red); } +.business-app .stat small.warn { color: #b45309; } +.business-app .table--hover tbody tr.is-selected td { background: var(--soft); } +.business-app .table tfoot .biz-total td { border-top: 1px solid var(--line); font-weight: 700; color: var(--ink); background: #f8fafe; } +.business-app .biz-block { display: grid; gap: 14px; margin-top: 28px; } +.business-app .biz-block .section-title { margin: 0 !important; } +.business-app .biz-link { color: inherit; } +.business-app .biz-link:hover { color: var(--blue); } +.business-app .biz-section { padding: 22px 28px; display: grid; gap: 16px; margin-top: 20px; } +.business-app .biz-section__head { display: flex; justify-content: space-between; align-items: center; gap: 16px; flex-wrap: wrap; } +.business-app .biz-section__head h2 { font-size: 18px; font-weight: 700; color: var(--ink); } +.business-app .biz-policies { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px 20px; } +.business-app .biz-policy { display: grid; gap: 8px; align-content: start; } +.business-app .biz-policy__head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.business-app .biz-policy__name { font-size: 14.5px; font-weight: 600; color: var(--text); } +.business-app .biz-policy__field > label { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } +.business-app .biz-policy__meta { font-size: 13px; color: var(--muted); } +.business-app .biz-policy__actions { display: flex; gap: 8px; flex-wrap: wrap; } +.business-app .biz-input { position: relative; display: block; } +.business-app .biz-input input { padding-right: 64px; } +.business-app .biz-input em { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); font-style: normal; color: var(--muted); font-size: 14px; } +.business-app .biz-form { display: grid; gap: 14px; } +.business-app .biz-form__pair { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; } +.business-app .biz-detail { padding: 22px 24px; display: grid; gap: 8px; margin-top: 22px; } +.business-app .biz-detail h2 { font-size: 18px; font-weight: 700; color: var(--ink); } +.business-app .biz-detail .ops-actions { margin-top: 8px; } +.business-app .biz-cell { min-width: 150px; gap: 4px; } +.business-app .biz-cell input { padding: 9px 12px; } +.business-app .biz-cell-input { width: 100%; min-width: 96px; border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; font-size: 14.5px; background: #fff; } +.business-app .biz-range { display: flex; align-items: center; gap: 6px; } +.business-app .biz-note { color: var(--muted); font-size: 12.5px; } +.business-app .biz-inline-select { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--muted); } +.business-app .biz-inline-select .select { min-width: 260px; } +.business-app .biz-inline-select .select select { padding: 9px 32px 9px 12px; border-radius: 10px; } +.business-app .biz-list { display: grid; gap: 12px; } +.business-app .biz-list__item { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 14px 20px; } +.business-app .biz-list__item > div:first-child { display: grid; gap: 2px; } +.business-app .biz-list__item strong { color: var(--ink); font-weight: 600; } +.business-app .biz-list__item .muted { font-size: 14.5px; } +.business-app .biz-list__side { display: flex; align-items: center; gap: 10px; flex-shrink: 0; } +.business-app .biz-toolbar { align-items: center; } +.business-app .biz-filters { display: flex; gap: 10px; flex-wrap: wrap; } +.business-app .biz-filters .select select { padding: 9px 32px 9px 12px; border-radius: 10px; min-width: 200px; } +.business-app .biz-chart { padding: 22px 28px; display: grid; gap: 18px; margin-top: 20px; } +.business-app .biz-chart h2 { font-size: 17px; font-weight: 700; color: var(--ink); } +.business-app .biz-chart__empty { padding: 30px 0; text-align: center; } +.business-app .biz-bars { display: flex; align-items: flex-end; gap: 18px; height: 220px; padding-top: 24px; overflow-x: auto; } +.business-app .biz-bars__col { flex: 1 0 64px; height: 100%; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 6px; min-width: 64px; } +.business-app .biz-bars__col b { font-size: 12.5px; font-weight: 600; color: var(--text); white-space: nowrap; } +.business-app .biz-bars__col i { display: block; width: 100%; max-width: 120px; background: #7c3aed; border-radius: 6px 6px 2px 2px; } +.business-app .biz-bars__col span { font-size: 12.5px; color: var(--muted); text-align: center; max-width: 110px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.business-app .biz-status-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; margin-top: 20px; } +.business-app .biz-status { padding: 20px 22px; display: grid; gap: 12px; align-content: start; } +.business-app .biz-status h2 { font-size: 17px; font-weight: 700; color: var(--ink); } +@media (max-width: 900px) { + .business-app .biz-policies, .business-app .biz-status-grid { grid-template-columns: 1fr; } +} +@media (max-width: 720px) { + .business-app .biz-form__pair { grid-template-columns: 1fr; } + .business-app .biz-section, .business-app .biz-chart { padding: 18px; } + .business-app .biz-list__item { flex-direction: column; align-items: flex-start; } + .business-app .biz-inline-select { width: 100%; flex-wrap: wrap; } + .business-app .biz-inline-select .select { min-width: 0; width: 100%; } +} + +/* Overrides are scoped to the business shell; other roles retain ss.css verbatim. */ +@font-face { font-family: 'Manrope'; font-style: normal; font-weight: 700; font-display: swap; src: url('../../public/fonts/manrope/manrope-latin-700-normal.woff2') format('woff2'); unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; } +@font-face { font-family: 'Manrope'; font-style: normal; font-weight: 700; font-display: swap; src: url('../../public/fonts/manrope/manrope-vietnamese-700-normal.woff2') format('woff2'); unicode-range: U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB; } +.business-app { --bg: #f6f7f8; --purple: #7c3aed; background: var(--bg); min-height: 100vh; } +.business-app .header__inner { padding-inline: 72px; } +.business-app .brand { font-family: 'Manrope', sans-serif; letter-spacing: -.48px; } +.business-app .brand img { flex: none; } +.business-app .subnav { border: 0; } +.business-app .subnav__inner { padding-inline: 72px; } +.business-app .page > * + * { margin-top: 20px; } +.business-app .page-header h1 { font-family: 'Manrope', sans-serif; font-size: 26px; line-height: 35px; letter-spacing: -.52px; font-weight: 700; } +.business-app .page-header p { margin-top: 20px; line-height: 24px; font-size: 16px; } +.business-app .stats { align-items: start; margin-top: 28px; } +.business-app .stat { padding: 18px 20px; box-shadow: none; border: 0; border-radius: 8px; gap: 6px; } +.business-app .stat strong { font-family: 'Manrope', sans-serif; font-size: 24px; line-height: 33px; } +.business-app .stat span { font-size: 15px; line-height: 18px; } +.business-app .stat small { font-size: 13px; line-height: 16px; } +.business-app .section-title { font-size: 18px; font-weight: 600; line-height: 22px; } +.business-app .stats + .section-title { margin-top: 28px; font-family: 'Manrope', sans-serif; font-size: 20px; line-height: 30px; } +.business-app .panel { border-radius: 8px; box-shadow: none; } +.business-app .table { font-size: 15px; table-layout: fixed; } +.business-app .table th { background: var(--bg); font-size: 14px; line-height: 17px; padding: 12px 20px; font-weight: 500; } +.business-app .table td { padding: 15px 20px; line-height: 18px; } +.business-app .table .cell-strong { font-weight: 400; } +.business-app .table th:first-child { width: 27%; } +.business-app .btn { border-radius: 6px; font-size: 17px; line-height: 21px; padding: 13px 26px; min-height: 47px; font-weight: 600; } +.business-app .ops-actions { gap: 12px; } +.business-app .biz-section { padding: 24px 28px; gap: 16px; } +.business-app .biz-section h2 { font-size: 18px; line-height: 27px; font-weight: 600; color: var(--ink); } +.business-app .biz-policies { gap: 16px; } +.business-app .field { gap: 6px; } +.business-app .field label { font-size: 15px; font-weight: 500; line-height: 18px; } +.business-app .field input { padding: 12px 14px; border-radius: 6px; line-height: 20px; background: var(--white); color: var(--muted); } +.business-app .field input::placeholder { color: var(--muted); } +.business-app .business-facilities { padding-top: 40px; padding-bottom: 40px; } +.business-app .business-facilities h1 { font-size: 30px; line-height: 45px; } +.business-app .business-facilities .table { background: var(--white); } +.business-app .business-facilities .table th { padding: 16px; background: var(--soft); line-height: 21px; } +.business-app .business-facilities .table th:first-child { width: auto; } +.business-app .business-facilities .table td { padding: 16px; font-size: 16px; line-height: 24px; border: 0; } +.business-app .biz-detail { padding: 24px; gap: 16px; } +.business-app .biz-detail h2 { font-size: 18px; line-height: 26px; font-weight: 600; } +.business-app .biz-detail .ops-actions { margin: 0; } +.business-app .biz-detail .btn { padding: 12px; font-size: 16px; line-height: 24px; } +.business-app .biz-block { gap: 24px; margin-top: 24px; } +.business-app .biz-list { gap: 12px; } +.business-app .biz-list__item { padding: 14px 20px; min-height: 70px; } +.business-app .biz-list__item strong { font-size: 16px; line-height: 19px; } +.business-app .biz-list__item .muted { font-size: 15px; line-height: 18px; } +.business-app .biz-list__item .tag { font-size: 13px; line-height: 16px; padding: 4px 10px; } +.business-app .business-pricing .table th:first-child { width: 22.2%; } +.business-app .business-pricing .table th:nth-child(2) { width: 25.4%; } +.business-app .business-pricing .table th:nth-child(3) { width: 20.6%; } +.business-app .business-pricing .table th:nth-child(4) { width: 31.8%; } +.business-app .biz-cell-input { font-size: 15px; line-height: 18px; min-width: 0; padding: 0; border: 0; border-radius: 0; background: transparent; } +.business-app .biz-cell-input:focus { background: var(--soft); } +.business-app .biz-range { gap: 4px; } +.business-app .business-price-cell > input { width: 90px; } +.business-app .business-fee-unit { white-space: nowrap; } +.business-app .business-price-cell { white-space: nowrap; } +.business-app .biz-range input { width: 112px; } +.business-app .biz-toolbar { margin-top: 20px; margin-bottom: 20px; } +.business-app .biz-chart { padding: 24px 28px; gap: 16px; border: 0; margin-top: 20px; } +.business-app .biz-chart h2 { font-size: 17px; line-height: 21px; font-weight: 600; } +.business-app .biz-bars { align-items: flex-start; gap: 20px; height: 184px; padding-top: 10px; } +.business-app .biz-bars__col { justify-content: flex-start; gap: 8px; } +.business-app .biz-bars__col b { display: none; } +.business-app .biz-bars__col i { max-width: none; flex: none; background: var(--purple); border-radius: 6px; } +.business-app .biz-bars__col span { font-size: 13px; line-height: 16px; } +.business-app .business-reports .table th:first-child { width: 27%; } + +.business-app .usermenu__btn--business small { color: #6d28d9; } +@media (max-width: 1000px) { .business-app .header__inner, .business-app .subnav__inner { padding-inline: 24px; } .business-app .table { min-width: 800px; } } +@media (max-width: 720px) { .business-app .header__inner, .business-app .subnav__inner { padding-inline: 16px; } .business-app .biz-policies { grid-template-columns: 1fr; } .business-app .page-header h1 { font-size: 24px; line-height: 32px; } .business-app .btn { white-space: normal; } } + +.business-app .table th:first-child { width: auto; } +.business-app .btn--outline { color: var(--text); } +.business-app .bell { padding: 0; } +.business-app .business-facilities .table tbody tr { background: var(--white); } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/export.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/export.js new file mode 100644 index 0000000..ca655e8 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/export.js @@ -0,0 +1,60 @@ +// A minimal OOXML workbook (ZIP STORE) without a runtime dependency. +// All text is inlineStr, so user-controlled cells cannot become Excel formulas. +const encode = s => new TextEncoder().encode(s); +const xml = v => String(v ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +function crc32(bytes) { + let crc = -1; + for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); } + return (crc ^ -1) >>> 0; +} +const header = (size, fields) => { + const out = new Uint8Array(size), view = new DataView(out.buffer); + for (const [offset, value, width] of fields) width === 4 ? view.setUint32(offset, value, true) : view.setUint16(offset, value, true); + return out; +}; +export function workbookBytes(rows) { + const cell = (v, i) => { + let col = '', n = i + 1; + while (n) { col = String.fromCharCode(65 + (n - 1) % 26) + col; n = Math.floor((n - 1) / 26); } + return typeof v === 'number' && Number.isFinite(v) ? `${v}` : `${xml(v)}`; + }; + const files = { + '[Content_Types].xml': '', + '_rels/.rels': '', + 'xl/workbook.xml': '', + 'xl/_rels/workbook.xml.rels': '', + 'xl/worksheets/sheet1.xml': '' + rows.map((row, r) => `${row.map((v, i) => cell(v, i).replace('ROW', String(r + 1))).join('')}`).join('') + '', + }; + const local = [], central = []; let offset = 0, centralSize = 0; + for (const [path, content] of Object.entries(files)) { + const name = encode(path), data = encode(content), crc = crc32(data); + const entry = header(30, [[0, 0x04034b50, 4], [4, 20, 2], [10, 0, 2], [12, 33, 2], [14, crc, 4], [18, data.length, 4], [22, data.length, 4], [26, name.length, 2]]); + const dir = header(46, [[0, 0x02014b50, 4], [4, 20, 2], [6, 20, 2], [14, 33, 2], [16, crc, 4], [20, data.length, 4], [24, data.length, 4], [28, name.length, 2], [42, offset, 4]]); + local.push(entry, name, data); central.push(dir, name); offset += entry.length + name.length + data.length; centralSize += dir.length + name.length; + } + const count = Object.keys(files).length; + const end = header(22, [[0, 0x06054b50, 4], [8, count, 2], [10, count, 2], [12, centralSize, 4], [16, offset, 4]]); + const out = new Uint8Array(offset + centralSize + end.length); let pos = 0; + for (const part of [...local, ...central, end]) { out.set(part, pos); pos += part.length; } + return out; +} +export function parseCsv(text) { + const rows = []; let row = [], field = '', quoted = false; + text = text.replace(/^\ufeff/, ''); + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (c === '"') { if (quoted && text[i + 1] === '"') { field += '"'; i++; } else quoted = !quoted; } + else if (c === ',' && !quoted) { row.push(field); field = ''; } + else if ((c === '\n' || c === '\r') && !quoted) { if (c === '\r' && text[i + 1] === '\n') i++; row.push(field); rows.push(row); row = []; field = ''; } + else field += c; + } + if (quoted) throw new Error('Tệp báo cáo từ máy chủ không hợp lệ.'); + if (field || row.length) { row.push(field); rows.push(row); } + return rows; +} +export function downloadWorkbook(rows, fileName) { + const blob = new Blob([workbookBytes(rows)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); + const url = URL.createObjectURL(blob), a = document.createElement('a'); + a.href = url; a.download = fileName; document.body.append(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js new file mode 100644 index 0000000..ba7e1ac --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js @@ -0,0 +1,181 @@ +// Hàm thuần cho khu Quản lý vận hành KD (B01–B05) — có test ở tests/business.test.js. +import { money, today } from "../lib/format.js"; + +const comma = (n, digits = 1) => Number(n).toFixed(digits).replace(".", ","); + +/** Tiền rút gọn cho thẻ số liệu / bảng: 1.080.000.000 → "1,08 tỷ đ", 92.400.000 → "92,4 triệu đ". */ +export function shortMoney(n) { + const v = Number(n) || 0; + if (Math.abs(v) >= 1e9) return `${comma(v / 1e9, 2)} tỷ đ`; + if (Math.abs(v) >= 1e6) return `${comma(v / 1e6, 1)} triệu đ`; + return money(v); +} + +/** Tỷ lệ sử dụng: null = "Không áp dụng" (cơ sở không có kho khai thác được — docs/operations-api.md). */ +export const rateLabel = (rate) => (rate === null || rate === undefined ? "Không áp dụng" : `${Number.isInteger(+rate) ? rate : comma(rate)}%`); + +/** Tăng trưởng so với kỳ trước: "+4,8%" / "−2,0%"; kỳ trước bằng 0 thì không so được. */ +export function growthLabel(prev, cur) { + if (!prev) return null; + const g = ((cur - prev) / prev) * 100; + return `${g >= 0 ? "+" : "−"}${comma(Math.abs(g))}%`; +} + +/** Địa chỉ "…, Quận 7, TP. Hồ Chí Minh" → { district: "Quận 7", city: "TP. Hồ Chí Minh" } (cùng cách với giao diện khách). */ +export function areaOf(address = "") { + const parts = String(address).split(",").map((s) => s.trim()).filter(Boolean); + return { district: parts.length >= 2 ? parts[parts.length - 2] : "", city: parts[parts.length - 1] || "" }; +} + +export const shortFacility = (name = "") => name.replace(/^SafeSpace\s+/, ""); + +export const FACILITY_STATUS = { + ACTIVE: ["Đang hoạt động", "green"], + TEMPORARILY_CLOSED: ["Tạm đóng", "amber"], + INACTIVE: ["Ngừng hoạt động", "gray"], +}; + +export const POLICY_STATUS = { + ACTIVE: ["Đang áp dụng", "green"], + DRAFT: ["Bản nháp", "amber"], + INACTIVE: ["Đã ngừng", "gray"], + EXPIRED: ["Hết hiệu lực", "gray"], +}; + +export const POLICY_TYPES = { + DEPOSIT: "Đặt cọc", + RENEWAL: "Gia hạn", + CANCELLATION: "Huỷ đặt chỗ", + RETURN: "Trả kho", + OVERDUE: "Quá hạn", + EXTRA_FEE: "Phí dịch vụ", + DISCOUNT: "Giảm giá", + FEE_WAIVER: "Miễn phí", + PRICE_RANGE: "Khung giá", +}; + +// Loại chính sách mà giá trị FIXED là số tiền (đ). Loại khác (gia hạn, trả kho…) là số ngày / giờ ghi trong mô tả. +export const MONEY_TYPES = ["DEPOSIT", "OVERDUE", "EXTRA_FEE", "CANCELLATION", "FEE_WAIVER", "DISCOUNT"]; +export const isMoneyFixed = (p) => + p?.calculationType === "FIXED" && MONEY_TYPES.includes(p.policyType) && !(p.policyType === "DEPOSIT" && Number(p.value) < 1000); + +export const CALC_TYPES = { + FIXED: "Số tiền cố định", + PERCENTAGE: "Phần trăm", + RANGE: "Khoảng giá", + RULE: "Quy định (mô tả)", +}; + +/** + * Giá trị chính sách dạng chữ. Cọc FIXED < 1.000 là số tháng tiền thuê (cách ghi của chính sách seed, D16). + * @param {object} p PolicyDto + * @param {string} [unit] đuôi cho số tiền cố định, vd "/ ngày" + */ +export function policyValueLabel(p, unit = "") { + if (!p) return "—"; + const v = p.value === null || p.value === undefined ? null : Number(p.value); + const tail = unit ? ` ${unit}` : ""; + switch (p.calculationType) { + case "PERCENTAGE": + return v === null ? "—" : `${comma(v, Number.isInteger(v) ? 0 : 1)}%`; + case "RANGE": + return `${money(p.minValue ?? 0)} – ${money(p.maxValue ?? 0)}`; + case "RULE": + return p.ruleDescription || "—"; + case "FIXED": + if (v === null) return "—"; + if (p.policyType === "DEPOSIT" && v < 1000) return `${comma(v, Number.isInteger(v) ? 0 : 1)} tháng tiền thuê`; + if (!MONEY_TYPES.includes(p.policyType)) return comma(v, Number.isInteger(v) ? 0 : 1); + return `${money(v)}${tail}`; + default: + return v === null ? p.ruleDescription || "—" : String(v); + } +} + +/** + * Chính sách đang có hiệu lực cho một phạm vi: ưu tiên đúng loại kho rồi mới đến toàn hệ thống (BR20, phần dùng ở B03). + * Chỉ xét chính sách toàn hệ thống về cơ sở (facilityId = null). + */ +export function policyFor(policies, type, unitTypeId = null) { + const pool = policies.filter((p) => p.policyType === type && p.status === "ACTIVE" && p.facilityId == null + && (!p.effectiveFrom || p.effectiveFrom <= today()) && (!p.effectiveTo || p.effectiveTo >= today()) + && !(type === "OVERDUE" && p.calculationType === "RULE")); + return pool.find((p) => p.unitTypeId === unitTypeId) || (unitTypeId != null ? pool.find((p) => p.unitTypeId == null) : null) || null; +} + +/** Thân request tạo bản thay thế của một chính sách (giữ phạm vi, đổi giá trị, hiệu lực từ hôm nay). */ +export function replacementOf(p, changes, today) { + return { + policyName: p.policyName, + policyType: p.policyType, + calculationType: p.calculationType, + value: p.value, + minValue: p.minValue, + maxValue: p.maxValue, + ruleDescription: p.ruleDescription, + facilityId: p.facilityId ?? null, + unitTypeId: p.unitTypeId ?? null, + effectiveFrom: today, + effectiveTo: null, + ...changes, + }; +} + +/** Kỳ báo cáo của một tháng "yyyy-MM": từ ngày 1 đến cuối tháng (tháng hiện tại thì đến hôm nay). */ +export function monthPeriod(month, today) { + const [y, m] = month.split("-").map(Number); + const last = new Date(Date.UTC(y, m, 0)).getUTCDate(); + const end = `${month}-${String(last).padStart(2, "0")}`; + return { from: `${month}-01`, to: end > today ? today : end }; +} + +/** 12 tháng gần nhất, mới nhất trước: [{ value: "2026-10", label: "Tháng 10/2026" }]. */ +export function recentMonths(today, count = 12) { + const [y, m] = today.split("-").map(Number); + return Array.from({ length: count }, (_, i) => { + const d = new Date(Date.UTC(y, m - 1 - i, 1)); + const mm = d.getUTCMonth() + 1; + return { value: `${d.getUTCFullYear()}-${String(mm).padStart(2, "0")}`, label: `Tháng ${mm}/${d.getUTCFullYear()}` }; + }); +} + +/** Giá thuê hợp lệ: số nguyên dương, bội số 1.000 đ (docs/operations-api.md mục 3). */ +export function rateError(value) { + const n = Number(String(value).replace(/[.\sđ₫]/g, "")); + if (!String(value).trim()) return "Nhập giá mới."; + if (!Number.isFinite(n) || n <= 0) return "Giá phải lớn hơn 0."; + if (n % 1000 !== 0) return "Giá là bội số của 1.000 đ."; + return null; +} +export const parseMoney = (value) => Number(String(value).replace(/[.\sđ₫]/g, "")); + +export const CONTRACT_STATUS_LABELS = { + DRAFT: "Chờ bàn giao", + ACTIVE: "Đang thuê", + EXPIRING: "Sắp hết hạn", + OVERDUE: "Quá hạn", + RETURN_PENDING: "Chờ trả kho", + COMPLETED: "Đã kết thúc", + TERMINATED: "Chấm dứt", + CANCELLED: "Đã huỷ", +}; +export const RESERVATION_STATUS_LABELS = { + PENDING_PAYMENT: "Chờ chuyển khoản", + PENDING_VERIFICATION: "Chờ đối soát", + CONFIRMED: "Đã xác nhận, chờ phân bổ", + UNIT_ASSIGNED: "Đã phân bổ ô", + CHECKED_IN: "Đã nhận kho", + CANCELLED: "Đã huỷ", + EXPIRED: "Hết hạn giữ chỗ", + NO_SHOW: "Không đến nhận", +}; +export const UNIT_STATUS_LABELS = { + AVAILABLE: "Trống", + RESERVED: "Đã giữ cho khách", + ASSIGNED: "Đã phân bổ", + OCCUPIED: "Đang thuê", + RETURN_PENDING: "Chờ trả kho", + INSPECTION: "Chờ kiểm tra", + MAINTENANCE: "Bảo trì", + OUT_OF_SERVICE: "Ngừng sử dụng", +}; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/parts.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/parts.jsx new file mode 100644 index 0000000..2f22da0 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/parts.jsx @@ -0,0 +1,199 @@ +import React, { useState } from "react"; +import { Select } from "../components/Pickers"; +import { Button, Empty, Field, Modal } from "../components/UI"; +import { today } from "../lib/format"; +import { CALC_TYPES, POLICY_TYPES, parseMoney } from "./format"; + +// Trạng thái tải chung cho các màn B01–B05 +export function LoadState({ load, children }) { + if (load.error) + return ( + + + + ); + if (load.loading || !load.data) + return ( +
+
+ ); + return children(load.data); +} + +/** Biểu đồ cột đơn giản (B04): items = [{ key, label, value, text }] — chiều cao theo giá trị lớn nhất. */ +export function BarChart({ title, items, empty = "Chưa có số liệu trong kỳ." }) { + const max = Math.max(0, ...items.map((i) => i.value)); + return ( +
+

{title}

+ {max <= 0 ? ( +

{empty}

+ ) : ( +
+ {items.map((it) => ( +
+ {it.text} + + {it.label} +
+ ))} +
+ )} +
+ ); +} + +const NUMBER_HINT = { + FIXED: "Số tiền VND. Riêng đặt cọc: số nhỏ hơn 1.000 là số tháng tiền thuê.", + PERCENTAGE: "Từ 0 đến 100.", + RANGE: "Giá thấp nhất – cao nhất (VND / tháng).", + RULE: "Chỉ là quy định bằng chữ, hệ thống không tự tính.", +}; + +/** + * Tạo chính sách mới (UC20, UC21). Luôn tạo bản nháp; "Lưu và áp dụng" kích hoạt ngay (thay chính sách cùng phạm vi). + * @param {{ types: string[], unitTypes?: object[], facilities?: object[], onSubmit: (body, activate) => Promise, onClose: () => void }} props + */ +export function PolicyForm({ title = "Thêm chính sách", types, unitTypes = [], facilities = [], defaults = {}, onSubmit, onClose }) { + const [f, setF] = useState({ + policyType: types[0], + calculationType: types[0] === "PRICE_RANGE" ? "RANGE" : types[0] === "DISCOUNT" ? "PERCENTAGE" : "FIXED", + policyName: "", + value: "", + minValue: "", + maxValue: "", + ruleDescription: "", + facilityId: "", + unitTypeId: "", + effectiveFrom: today(), + ...defaults, + }); + const [errors, setErrors] = useState({}); + const [busy, setBusy] = useState(false); + const set = (k) => (e) => setF({ ...f, [k]: e.target.value }); + + const submit = async (activate) => { + const e = {}; + if (!f.policyName.trim()) e.policyName = "Nhập tên chính sách."; + if (!f.ruleDescription.trim()) e.ruleDescription = "Mô tả cách áp dụng để nhân viên và khách hiểu đúng."; + if (f.calculationType === "RANGE") { + if (!f.minValue || !f.maxValue) e.range = "Nhập đủ giá thấp nhất và cao nhất."; + else if (parseMoney(f.minValue) > parseMoney(f.maxValue)) e.range = "Giá thấp nhất phải nhỏ hơn hoặc bằng giá cao nhất."; + } else if (f.calculationType !== "RULE") { + const v = Number(String(f.value).replace(",", ".")); + if (String(f.value).trim() === "" || !Number.isFinite(v) || v < 0) e.value = "Nhập giá trị không âm."; + else if (f.calculationType === "PERCENTAGE" && v > 100) e.value = "Phần trăm từ 0 đến 100."; + } + if (!f.effectiveFrom) e.effectiveFrom = "Chọn ngày áp dụng."; + setErrors(e); + if (Object.keys(e).length) return; + setBusy(true); + const range = f.calculationType === "RANGE"; + const ok = await onSubmit( + { + policyName: f.policyName.trim(), + policyType: f.policyType, + calculationType: f.calculationType, + value: range || f.calculationType === "RULE" ? null : Number(String(f.value).replace(",", ".")), + minValue: range ? parseMoney(f.minValue) : null, + maxValue: range ? parseMoney(f.maxValue) : null, + ruleDescription: f.ruleDescription.trim(), + facilityId: f.facilityId ? Number(f.facilityId) : null, + unitTypeId: f.unitTypeId ? Number(f.unitTypeId) : null, + effectiveFrom: f.effectiveFrom, + effectiveTo: null, + }, + activate, + ); + setBusy(false); + if (ok) onClose(); + }; + + return ( + +
+ {types.length > 1 && ( + + + + )} + + + + + + + {f.calculationType === "RANGE" ? ( +
+ + + + + + +
+ ) : ( + f.calculationType !== "RULE" && ( + + + + ) + )} + +