From e2c11cf9829bcab0f5821f4b0625a850d862a710 Mon Sep 17 00:00:00 2001 From: Vector Date: Tue, 22 Sep 2026 20:44:24 +0700 Subject: [PATCH] =?UTF-8?q?Admin=20UI=20(A01-A04)=20g=E1=BA=AFn=20API=20/a?= =?UTF-8?q?pi/admin;=201=20file=20=C4=91=C3=A8=20d=E1=BB=AF=20li=E1=BB=87u?= =?UTF-8?q?=2012=20c=C6=A1=20s=E1=BB=9F=20SafeSpace=20v=C3=A0o=20databas?= =?UTF-8?q?=20m=E1=BB=97i=20l=E1=BA=A7n=20backend=20kh=E1=BB=9Fi=20=C4=91?= =?UTF-8?q?=E1=BB=99ng=20=C4=91=E1=BA=A3m=20b=E1=BA=A3o=20=C4=91=E1=BB=A7?= =?UTF-8?q?=2012=20cs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SafeSpace-Customer-UI/.env.example | 5 +- .../ADMIN-FLOW-COVERAGE.md | 33 ++ .../SafeSpace-Customer-UI/BE-CONTRACT.md | 19 +- .../SafeSpace-Customer-UI/README.md | 25 +- .../SafeSpace-Customer-UI/mock/mock-api.mjs | 459 ++++++++++++++++++ .../SafeSpace-Customer-UI/package.json | 2 +- .../scripts/dev-mock.mjs | 28 ++ .../SafeSpace-Customer-UI/src/CustomerApp.jsx | 33 +- .../src/admin/AdminApp.jsx | 35 ++ .../src/admin/AdminCreateUser.jsx | 183 +++++++ .../src/admin/AdminLogs.jsx | 143 ++++++ .../src/admin/AdminPermissions.jsx | 173 +++++++ .../src/admin/AdminShell.jsx | 183 +++++++ .../src/admin/AdminUserDetail.jsx | 314 ++++++++++++ .../src/admin/AdminUsers.jsx | 178 +++++++ .../SafeSpace-Customer-UI/src/admin/util.js | 109 +++++ .../SafeSpace-Customer-UI/src/api/admin.js | 35 ++ .../SafeSpace-Customer-UI/src/api/mappers.js | 9 +- .../src/components/Photo.jsx | 4 +- .../SafeSpace-Customer-UI/src/config/api.js | 8 +- .../SafeSpace-Customer-UI/src/config/media.js | 37 +- .../SafeSpace-Customer-UI/src/lib/catalog.js | 6 +- .../SafeSpace-Customer-UI/src/lib/roles.js | 86 ++++ .../SafeSpace-Customer-UI/src/pages/Auth.jsx | 8 +- .../SafeSpace-Customer-UI/src/state/store.jsx | 39 +- .../SafeSpace-Customer-UI/src/styles/ss.css | 84 ++++ .../SafeSpace-Customer-UI/tests/admin.test.js | 41 ++ .../tests/render.test.mjs | 1 + .../Data/DbSeeder.cs | 114 +++++ 29 files changed, 2351 insertions(+), 43 deletions(-) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUserDetail.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUsers.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/util.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/admin.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/roles.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/admin.test.js diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example index 2e2b527..1fe7d33 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example @@ -1,8 +1,9 @@ # Chép thành .env.local rồi chỉnh. -# Nối backend SSFRMS (StorageProject.Api). false = chạy bằng dữ liệu lưu trong trình duyệt. -VITE_USE_API=true +# Backend SSFRMS (StorageProject.Api). Mặc định giao diện gọi API ở địa chỉ này. VITE_API_URL=http://localhost:5151 +# Đặt false để tắt API và dùng dữ liệu lưu trong trình duyệt (chỉ xem giao diện khách hàng) +VITE_USE_API=true # Thời gian giữ đơn chờ chuyển khoản (giây). Figma: 01:00 → 60. Dùng 900 cho 15 phút. VITE_PAYMENT_TIMEOUT_SECONDS=60 diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md new file mode 100644 index 0000000..f4ab795 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md @@ -0,0 +1,33 @@ +# Quản trị hệ thống — đối chiếu Figma ↔ code ↔ API + +Nguồn: Figma "SafeSpace - Modern UI", section **Quản trị hệ thống** (A01–A04) + popup "Thông báo / admin". +Backend: `StorageProject.Api/Endpoints/AdminEndpoints.cs` (UC24–UC27), yêu cầu vai trò `ADMIN`. + +Đăng nhập chung trang `#/login`. Giao diện đọc vai trò trong JWT: tài khoản `ADMIN` vào thẳng `#/admin`, +tài khoản khác mở `#/admin` sẽ thấy "Không có quyền truy cập". Tài khoản seed: `admin` / `Admin@123`. + +| Figma | Route | Component | API | +|---|---|---|---| +| A01 Quản lý tài khoản | `#/admin` | `admin/AdminUsers.jsx` | `GET dashboard/stats`, `GET users?page&pageSize&searchTerm&status&roleId`, `GET roles`, `GET users/{id}/facilities` (cột Cơ sở phụ trách) | +| (thêm) Chi tiết tài khoản | `#/admin/users/:id` | `admin/AdminUserDetail.jsx` | `GET/PUT users/{id}`, `POST users/{id}/reset-password`, `POST/DELETE users/{id}/roles`, `GET users/{id}/facilities`, `POST user-facilities`, `PUT user-facilities/{id}/status` | +| A02 Thêm & phân quyền tài khoản | `#/admin/new` | `admin/AdminCreateUser.jsx` | `POST users` (+ `POST user-facilities` khi là Nhân viên / Quản lý) | +| A03 Cấu hình quyền truy cập | `#/admin/permissions` | `admin/AdminPermissions.jsx` | `GET roles`, `GET permissions`, `POST/DELETE roles/{id}/permissions` | +| A04 Nhật ký hoạt động | `#/admin/logs` | `admin/AdminLogs.jsx` | `GET logs/login-history`, `GET logs/activity-logs` | +| Thông báo / admin | (chuông) | `admin/AdminShell.jsx` | `GET dashboard/stats`, `GET logs/login-history` | + +## Khác Figma vì backend +- **A02**: Figma "Gửi lời mời qua email" nhưng backend chưa gửi email → form có thêm **Tên đăng nhập** (gợi ý từ email) + và **Mật khẩu tạm thời** (tự sinh 12 ký tự); sau khi tạo hiện hộp thoại để admin chép gửi người dùng. +- **A03**: Figma vẽ Xem / Chỉnh sửa / Xoá theo vai trò; backend quản lý **13 mã quyền** gán cho vai trò → giữ bảng + "Vai trò / Phạm vi dữ liệu" như Figma, bên dưới là ma trận quyền × vai trò; lưu theo thay đổi, có bước xác nhận. +- **Vai trò "Vận hành KD"** có trong Figma nhưng backend chỉ có `ADMIN`, `MANAGER`, `STAFF`, `CUSTOMER`. + Danh sách vai trò lấy từ `GET /api/admin/roles`, nên khi backend thêm vai trò mới (vd. `OPERATIONS`) giao diện tự hiện. +- **Chi tiết tài khoản** Figma chưa vẽ; dựng cùng phong cách để dùng các API sửa / khoá / đặt lại mật khẩu / vai trò / phân công. +- **Nhật ký**: backend chỉ ghi lịch sử đăng nhập **thành công** (sai mật khẩu không được ghi) và nhật ký hoạt động + không lưu IP → cột IP là "—". Tab "Tất cả / Thay đổi dữ liệu / Phân quyền" gộp 100 bản ghi mới nhất mỗi loại. + +## Luật backend được giao diện phản ánh +- Không khoá / thu hồi vai trò `ADMIN` của quản trị viên hoạt động cuối cùng → hiện đúng thông báo lỗi từ backend. +- Chỉ Nhân viên / Quản lý được phân công cơ sở; mỗi người tối đa 1 phân công đang hoạt động (phân công mới tự kết thúc cái cũ). +- Tài khoản không ở trạng thái "Đang hoạt động" không đăng nhập được (backend trả lỗi, trang đăng nhập hiện nguyên văn). +- Tài khoản chỉ có vai trò Nhân viên / Quản lý: chưa có giao diện riêng → trang đăng nhập báo và không mở phiên. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md index 402ce5a..19425ef 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -4,7 +4,7 @@ Giao diện bám Figma nên **khác luồng backend cũ (v3)** ở vài điểm. Toàn bộ nghiệp vụ hiện nằm ở `src/state/reducer.js`; mỗi lệnh (`CREATE_RESERVATION`, `CONFIRM_TRANSFER`, ...) tương ứng một endpoint dưới đây, nên thay bằng lời gọi API là đủ. -## 0. Hiện trạng nối API (VITE_USE_API=true) +## 0. Hiện trạng nối API Giao diện đã gọi thật các endpoint backend đang có: auth, facilities / unit-types / rates / availability, reservations, contracts (+ payments, renewals, handover), tickets. Những luồng dưới đây backend **chưa có** @@ -24,6 +24,23 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: - **Loại kho thật** (Mini S 1 m², M 4 m², L 9 m², XL 16 m²) hiển thị thành "Kho thường / Kiểm soát nhiệt độ" + diện tích thật, lấy giá từ `/api/rates`. +## 0a. Dữ liệu 12 cơ sở theo Figma + +`StorageProject.Infrastructure/Data/DbSeeder.cs` được bổ sung bước **7b** (`SeedSafeSpaceNetworkAsync`): +- Đổi tên 2 cơ sở seed cũ: "SSFRMS Chi nhánh Tân Bình / Quận 7" → "SafeSpace Tân Bình / Quận 7". +- Thêm 10 cơ sở Figma (Nguyễn Lương Bằng, Him Lam, Phú Xuân, Tân Thuận, Phú Mỹ Hưng, Bình Thạnh, Nhà Bè, Bình Chánh, + Thủ Đức, Gò Vấp), mỗi cơ sở có bảng giá S / M / L (một số có XL) và 5–6 phòng kho `AVAILABLE`. +- Chạy lại được: chỉ thêm phần còn thiếu, nên database đã tạo từ trước cũng tự có đủ 12 cơ sở khi khởi động lại API. + +## 0b. Khu quản trị + +Đã gọi toàn bộ `/api/admin/*` hiện có (xem `ADMIN-FLOW-COVERAGE.md`). Đề xuất bổ sung phía backend: +- Gửi email mời / đặt mật khẩu lần đầu khi tạo tài khoản (Figma A02 "Gửi lời mời"). +- Vai trò `OPERATIONS` (Vận hành KD) như Figma. +- Ghi lịch sử đăng nhập **thất bại** (hiện chỉ ghi khi thành công) và lưu IP vào nhật ký hoạt động. +- Cho lọc nhật ký theo nhiều `action` một lúc (để tab "Thay đổi dữ liệu" / "Phân quyền" phân trang ở máy chủ). +- Trả kèm cơ sở phụ trách trong `GET /api/admin/users` để khỏi gọi thêm từng người. + ## 1. Luồng khác v3 (cần quyết định phía BE) | Điểm | Figma / giao diện hiện tại | Backend cũ (v3) | diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md index 0668555..70ae52e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md @@ -1,9 +1,10 @@ -# SafeSpace — Giao diện khách hàng +# SafeSpace — Giao diện khách hàng & quản trị hệ thống React + Vite, bám theo file Figma **SafeSpace - Modern UI**: Trang chủ, Đăng nhập, Đăng ký, Bảng giá, -Hướng dẫn và toàn bộ luồng khách hàng C01–C14 (kèm C03b/C03c/C04b, popup thông báo, các trạng thái C13). +Hướng dẫn, toàn bộ luồng khách hàng C01–C14 (kèm C03b/C03c/C04b, popup thông báo, các trạng thái C13) +và khu **Quản trị hệ thống** A01–A04 (xem `ADMIN-FLOW-COVERAGE.md`). -## Chạy cùng backend (khuyến nghị) +## Chạy cùng backend 1. Chạy backend ở thư mục gốc repo: `dotnet run --project StorageProject.Api --launch-profile http` → `http://localhost:5151` 2. Chạy giao diện: @@ -11,16 +12,21 @@ Hướng dẫn và toàn bộ luồng khách hàng C01–C14 (kèm C03b/C03c/C04 ```bash cd SafeSpace-Customer-UI/SafeSpace-Customer-UI npm ci -copy .env.example .env.local # macOS/Linux: cp .env.example .env.local npm run dev # http://127.0.0.1:5173 ``` -`.env.local` mặc định đã bật `VITE_USE_API=true`. Tài khoản có sẵn trong backend: `customer01` / `Customer@123` -(đăng nhập bằng **tên đăng nhập**). Khách đăng ký mới trên giao diện đăng nhập bằng **email**. +Giao diện mặc định gọi API ở `http://localhost:5151`; đổi địa chỉ bằng `VITE_API_URL` trong `.env.local` (xem `.env.example`). Tài khoản có sẵn trong backend (đăng nhập bằng **tên đăng nhập**): + +| Tài khoản | Mật khẩu | Vào | +|---|---|---| +| `customer01`, `customer02` | `Customer@123` | Giao diện khách hàng `#/overview` | +| `admin` | `Admin@123` | Quản trị hệ thống `#/admin` | + +Khách đăng ký mới trên giao diện đăng nhập bằng **email**. Khu quản trị chỉ chạy ở chế độ API. ## Chạy không cần backend -Đặt `VITE_USE_API=false` (hoặc không tạo `.env.local`): dữ liệu lưu trong trình duyệt, tài khoản có sẵn +Tạo `.env.local` với dòng `VITE_USE_API=false`: dữ liệu lưu trong trình duyệt, tài khoản có sẵn `mai.nguyen@example.com` / `SafeSpace@123`. Dùng khi chỉ cần xem giao diện. ## Luồng nào gọi backend @@ -41,7 +47,7 @@ Khi backend bổ sung API cho các dòng cuối, chỉ cần sửa `src/state/st ## Kiểm tra ```bash -npm test # 25 test: nghiệp vụ, VietQR, chuyển đổi dữ liệu backend (theo seed thật) +npm test # 28 test: nghiệp vụ, VietQR, chuyển đổi dữ liệu backend, vai trò JWT, nhật ký quản trị npm run test:render # render 38 route, bắt lỗi runtime, NaN, undefined npm run build # xuất bản dist/ (đường dẫn tương đối, đặt được ở thư mục con) ``` @@ -68,7 +74,8 @@ src/ components/ Header + thông báo, lịch chọn ngày, thư viện ảnh, mã QR, UI dùng chung state/reducer.js nghiệp vụ (thuần, có test) state/store.jsx phiên đăng nhập; 2 chế độ: dữ liệu trong trình duyệt / API backend - api/ gọi API (http.js, endpoints.js) + chuyển dữ liệu backend → giao diện (mappers.js) + api/ gọi API (http.js, endpoints.js, admin.js) + chuyển dữ liệu backend → giao diện (mappers.js) + admin/ khu quản trị: AdminShell, AdminUsers, AdminUserDetail, AdminCreateUser, AdminPermissions, AdminLogs data/seed.js dữ liệu khởi tạo: 12 cơ sở, khách hàng Nguyễn Thị Mai config/ địa chỉ API, ảnh, tài khoản nhận chuyển khoản ``` diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs new file mode 100644 index 0000000..c67bba9 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs @@ -0,0 +1,459 @@ +// Máy chủ API giả lập theo đúng StorageProject.Api (endpoint, JSON camelCase, luật kiểm tra, dữ liệu DbSeeder). +// 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"; + +const pad = (n) => String(n).padStart(2, "0"); +const iso = (d) => d.toISOString(); // DateTime.UtcNow trả về khi vừa tạo: có "Z" +const dbTime = (d) => d.toISOString().replace("Z", "").replace(/\.\d+$/, ""); // đọc lại từ DB: không có "Z" +const dateOnly = (d) => `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`; +const addMonths = (s, m) => { + const d = new Date(`${s}T00:00:00Z`); + d.setUTCMonth(d.getUTCMonth() + m); + return dateOnly(d); +}; +const days = (n) => new Date(Date.now() + n * 86400000); + +export function createState() { + const users = [ + { userId: 1, username: "admin", email: "admin@storage.vn", password: "Admin@123", fullName: "Hệ Thống Admin", status: "ACTIVE" }, + { userId: 2, username: "staff01", email: "staff01@storage.vn", password: "Staff@123", fullName: "Trần Nhân Viên", status: "ACTIVE" }, + { userId: 3, username: "customer01", email: "an.nguyen@example.com", password: "Customer@123", fullName: "Nguyễn Văn An", status: "ACTIVE" }, + { userId: 4, username: "customer02", email: "mai.tran@example.com", password: "Customer@123", fullName: "Trần Thị Mai", status: "ACTIVE" }, + ]; + // Theo DbSeeder: 2 cơ sở ban đầu (đã đổi tên SafeSpace) + 10 cơ sở mạng lưới SafeSpace (bước 7b) + const NETWORK = [ + ["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", 1150000, true], + ["HL", "SafeSpace Him Lam", "Khu dân cư Him Lam, Phường Tân Hưng, Quận 7, TP. Hồ Chí Minh", "02837001013", 1050000, false], + ["PX", "SafeSpace Phú Xuân", "Đường Nguyễn Hữu Thọ, Xã Phú Xuân, Huyện Nhà Bè, TP. Hồ Chí Minh", "02837001014", 890000, false], + ["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", 1100000, true], + ["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", 1250000, true], + ["BT", "SafeSpace Bình Thạnh", "Đường Nguyễn Xí, Phường 26, Quận Bình Thạnh, TP. Hồ Chí Minh", "02837001017", 980000, false], + ["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", 850000, false], + ["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", 790000, true], + ["TD", "SafeSpace Thủ Đức", "Đường Võ Văn Ngân, Phường Linh Chiểu, TP. Thủ Đức, TP. Hồ Chí Minh", "02837001020", 920000, false], + ["GV", "SafeSpace Gò Vấp", "Đường Quang Trung, Phường 10, Quận Gò Vấp, TP. Hồ Chí Minh", "02837001021", 930000, false], + ]; + const facilities = [ + { facilityId: 1, name: "SafeSpace 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: "07:00", closingTime: "22:00", status: "ACTIVE" }, + { facilityId: 2, name: "SafeSpace 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: "06:00", closingTime: "23:00", status: "ACTIVE" }, + ...NETWORK.map(([, name, address, contactPhone], i) => ({ facilityId: i + 3, name, address, contactPhone, openingTime: "06:00", closingTime: "22:00", status: "ACTIVE" })), + ]; + const unitTypes = [ + { unitTypeId: 1, typeName: "Kho Mini S (1m x 1m)", length: 1, width: 1, height: 2.5, area: 1, 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" }, + { unitTypeId: 2, typeName: "Kho Tiêu Chuẩn M (2m x 2m)", length: 2, width: 2, height: 2.8, area: 4, 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" }, + { unitTypeId: 3, typeName: "Kho Lớn L (3m x 3m)", length: 3, width: 3, height: 3, area: 9, 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" }, + { unitTypeId: 4, typeName: "Kho Doanh Nghiệp XL (4m x 4m)", length: 4, width: 4, height: 3.2, area: 16, climateControlled: true, description: "Kho chuyên biệt cho doanh nghiệp", status: "ACTIVE" }, + ]; + const eff = dateOnly(days(-30)); + const round10k = (v) => Math.round(v / 10000) * 10000; + const rateRows = [ + [1, 1, 500000], [1, 2, 1500000], [1, 3, 3000000], + [2, 1, 550000], [2, 2, 1600000], [2, 3, 3200000], [2, 4, 5500000], + ]; + NETWORK.forEach(([, , , , rateM, xl], i) => { + const fid = i + 3; + rateRows.push([fid, 1, round10k(rateM * 0.4)], [fid, 2, rateM], [fid, 3, round10k(rateM * 2)]); + if (xl) rateRows.push([fid, 4, round10k(rateM * 3.5)]); + }); + const rates = rateRows.map(([facilityId, unitTypeId, monthlyRate], i) => ({ rateId: i + 1, facilityId, facilityName: facilities[facilityId - 1].name, unitTypeId, unitTypeName: unitTypes[unitTypeId - 1].typeName, monthlyRate, effectiveFrom: eff, effectiveTo: null })); + const units = [ + [1, 1, 1, "TB-S-101", "AVAILABLE"], [2, 1, 1, "TB-S-102", "AVAILABLE"], [3, 1, 2, "TB-M-103", "OCCUPIED"], [4, 1, 2, "TB-M-104", "AVAILABLE"], + [5, 1, 3, "TB-L-201", "AVAILABLE"], [6, 1, 3, "TB-L-202", "AVAILABLE"], [7, 2, 1, "Q7-S-101", "AVAILABLE"], [8, 2, 1, "Q7-S-102", "AVAILABLE"], + [9, 2, 2, "Q7-M-103", "AVAILABLE"], [10, 2, 2, "Q7-M-104", "AVAILABLE"], [11, 2, 3, "Q7-L-201", "AVAILABLE"], [12, 2, 4, "Q7-XL-301", "AVAILABLE"], + ].map(([unitId, facilityId, unitTypeId, unitNumber, status]) => ({ unitId, facilityId, unitTypeId, unitNumber, status })); + NETWORK.forEach(([code, , , , , xl], i) => { + const fid = i + 3; + const plan = [[1, "S", 101, 2], [2, "M", 111, 2], [3, "L", 201, 1], ...(xl ? [[4, "XL", 301, 1]] : [])]; + for (const [unitTypeId, size, first, count] of plan) + for (let k = 0; k < count; k++) units.push({ unitId: units.length + 1, facilityId: fid, unitTypeId, unitNumber: `${code}-${size}-${first + k}`, status: "AVAILABLE" }); + }); + const start1 = dateOnly(days(-15)); + const start2 = dateOnly(days(5)); + const reservations = [ + { reservationId: 1, customerId: 3, facilityId: 1, unitTypeId: 2, startDate: start1, expectedEndDate: addMonths(start1, 3), rentalPeriodMonths: 3, quotedMonthlyRate: 1500000, estimatedAmount: 4500000, requiredDeposit: 1500000, status: "CHECKED_IN", createdAt: days(-16), expiresAt: days(-15), cancelledAt: null, cancellationReason: null }, + { reservationId: 2, customerId: 3, facilityId: 1, unitTypeId: 1, startDate: start2, expectedEndDate: addMonths(start2, 1), rentalPeriodMonths: 1, quotedMonthlyRate: 500000, estimatedAmount: 500000, requiredDeposit: 500000, status: "PENDING_PAYMENT", createdAt: new Date(), expiresAt: new Date(Date.now() + 24 * 3600000), cancelledAt: null, cancellationReason: null }, + ]; + const contracts = [ + { contractId: 1, reservationId: 1, customerId: 3, unitId: 3, startDate: start1, endDate: addMonths(start1, 3), agreedMonthlyRate: 1500000, depositAmount: 1500000, status: "ACTIVE", createdAt: days(-15), activatedAt: days(-15) }, + ]; + const handovers = [{ handoverId: 1, contractId: 1, status: "HANDED_OVER", scheduledAt: days(-15), handoverAt: days(-15), customerConfirmed: true, staffConfirmed: true }]; + const payments = [ + { paymentId: 1, contractId: 1, renewalId: null, paymentType: "DEPOSIT", amount: 1500000, currency: "VND", paymentMethod: "BANK_TRANSFER", transactionReference: "VNPAY-DEP-10001", dueDate: start1, paidAt: days(-15), status: "PAID", createdAt: days(-15) }, + { paymentId: 2, contractId: 1, renewalId: null, paymentType: "RENT", amount: 1500000, currency: "VND", paymentMethod: "BANK_TRANSFER", transactionReference: "VNPAY-RENT-10002", dueDate: start1, paidAt: days(-15), status: "PAID", createdAt: days(-15) }, + ]; + const tickets = [ + { ticketId: 1, customerId: 3, contractId: 1, unitId: 3, issueType: "UNIT", title: "Kiểm tra nhiệt độ phòng kho", description: "Nhờ nhân viên kiểm tra lại nhiệt độ kho TB-M-103 vào buổi trưa", priority: "NORMAL", status: "OPEN", createdAt: days(-2), assignedAt: null, resolvedAt: null, closedAt: null }, + ]; + const roles = [ + { roleId: 1, roleName: "ADMIN", description: "Quản trị viên toàn quyền hệ thống" }, + { roleId: 2, roleName: "MANAGER", description: "Quản lý cơ sở kho" }, + { roleId: 3, roleName: "STAFF", description: "Nhân viên vận hành, bàn giao và kiểm tra kho" }, + { roleId: 4, roleName: "CUSTOMER", description: "Khách hàng thuê kho tự quản" }, + ]; + const permissions = [ + ["USER_MANAGE", "Quản lý tài khoản"], ["ROLE_MANAGE", "Quản lý vai trò"], ["FACILITY_SCOPE_MANAGE", "Quản lý phạm vi cơ sở"], ["AUDIT_LOG_VIEW", "Xem nhật ký kiểm toán"], + ["FACILITY_MANAGE", "Quản lý cơ sở"], ["UNIT_MANAGE", "Quản lý kho"], ["ASSIGNMENT_MANAGE", "Phân bổ kho"], ["HANDOVER_MANAGE", "Bàn giao kho"], ["RETURN_MANAGE", "Kiểm tra trả kho"], + ["RENEWAL_MANAGE", "Duyệt gia hạn"], ["TICKET_MANAGE", "Xử lý hỗ trợ"], ["PAYMENT_CONFIRM", "Xác nhận thanh toán"], ["REPORT_VIEW", "Xem báo cáo"], + ].map(([permissionCode, permissionName], i) => ({ permissionId: i + 1, permissionCode, permissionName, description: `Mô tả ${permissionName.toLowerCase()}` })); + const rolePermissions = permissions.map((p) => ({ roleId: 1, permissionId: p.permissionId })); + const userRoles = [{ userId: 1, roleId: 1 }, { userId: 2, roleId: 3 }, { userId: 3, roleId: 4 }, { userId: 4, roleId: 4 }]; + for (const u of users) Object.assign(u, { phone: null, createdAt: days(-30 + u.userId), updatedAt: days(-30 + u.userId) }); + return { users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals: [], tickets, tokens: new Map(), down: false, roles, permissions, rolePermissions, userRoles, userFacilities: [], loginHistory: [], activityLogs: [] }; +} + +export function startMockApi(port = 5199, { verbose = false } = {}) { + const S = createState(); + const log = []; + const fac = (id) => S.facilities.find((f) => f.facilityId === id); + const ut = (id) => S.unitTypes.find((t) => t.unitTypeId === id); + const unit = (id) => S.units.find((u) => u.unitId === id); + + const resDto = (r) => ({ + reservationId: r.reservationId, facilityId: r.facilityId, facilityName: fac(r.facilityId).name, unitTypeId: r.unitTypeId, unitTypeName: ut(r.unitTypeId).typeName, + startDate: r.startDate, expectedEndDate: r.expectedEndDate, rentalPeriodMonths: r.rentalPeriodMonths, quotedMonthlyRate: r.quotedMonthlyRate, + estimatedAmount: r.estimatedAmount, requiredDeposit: r.requiredDeposit, status: r.status, expiresAt: r.expiresAt ? dbTime(r.expiresAt) : null, + cancelledAt: r.cancelledAt ? dbTime(r.cancelledAt) : null, cancellationReason: r.cancellationReason, createdAt: dbTime(r.createdAt), + }); + const payDto = (p) => ({ ...p, paidAt: p.paidAt ? dbTime(p.paidAt) : null, createdAt: dbTime(p.createdAt) }); + const renDto = (r) => ({ ...r, requestedAt: dbTime(r.requestedAt), approvedAt: null }); + const contractSummary = (c) => { + const u = unit(c.unitId); + return { contractId: c.contractId, reservationId: c.reservationId, unitId: c.unitId, unitNumber: u.unitNumber, facilityName: fac(u.facilityId).name, unitTypeName: ut(u.unitTypeId).typeName, startDate: c.startDate, endDate: c.endDate, agreedMonthlyRate: c.agreedMonthlyRate, depositAmount: c.depositAmount, status: c.status, activatedAt: c.activatedAt ? dbTime(c.activatedAt) : null }; + }; + const ticketDto = (t) => ({ ticketId: t.ticketId, contractId: t.contractId, unitId: t.unitId, issueType: t.issueType, title: t.title, priority: t.priority, status: t.status, createdAt: dbTime(t.createdAt), resolvedAt: null, closedAt: null }); + + const availability = (facilityId, unitTypeId, startDate, months) => { + const end = addMonths(startDate, months); + const free = S.units.filter((u) => u.facilityId === facilityId && u.unitTypeId === unitTypeId && u.status === "AVAILABLE").length; + const held = S.reservations.filter((r) => r.facilityId === facilityId && r.unitTypeId === unitTypeId && ["PENDING_PAYMENT", "CONFIRMED"].includes(r.status) && r.startDate < end && r.expectedEndDate > startDate).length; + return Math.max(0, free - held); + }; + + const server = http.createServer(async (req, res) => { + const cors = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*", "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS" }; + const send = (status, body) => { + res.writeHead(status, { ...cors, ...(body !== undefined ? { "Content-Type": "application/json; charset=utf-8" } : {}) }); + res.end(body !== undefined ? JSON.stringify(body) : ""); + if (verbose && req.method !== "OPTIONS" && !req.url.startsWith("/__")) { + const color = status >= 400 ? "\x1b[31m" : "\x1b[32m"; + console.log(`${color}${status}\x1b[0m ${req.method.padEnd(6)} ${req.url}${status >= 400 && body ? ` → ${body.error || body.message || ""}` : ""}`); + } + }; + if (req.method === "OPTIONS") return send(204); + const url = new URL(req.url, "http://x"); + const path = url.pathname.replace(/\/+$/, "") || "/"; + if (path === "/__state") return send(200, { reservations: S.reservations, renewals: S.renewals, tickets: S.tickets, users: S.users.map(({ password, ...u }) => u) }); + if (path === "/__down") { S.down = true; return send(200, {}); } + if (path === "/__up") { S.down = false; return send(200, {}); } + if (path === "/__revoke") { S.tokens.clear(); return send(200, {}); } + if (S.down) { req.socket.destroy(); return; } + let body = null; + if (req.method === "POST" || req.method === "PUT") { + const chunks = []; + for await (const c of req) chunks.push(c); + const raw = Buffer.concat(chunks).toString(); + try { body = raw ? JSON.parse(raw) : null; } catch { return send(400, { title: "Bad JSON" }); } + } + log.push(`${req.method} ${path}`); + const auth = () => { + const t = (req.headers.authorization || "").replace(/^Bearer /, ""); + return S.tokens.get(t) || null; + }; + const bad = (m) => send(400, { error: m }); + let m; + + // ---- Auth + if (req.method === "POST" && path === "/api/auth/register") { + if (S.users.some((u) => u.username === body.username || u.email === body.email)) return bad("Tên đăng nhập hoặc email đã tồn tại trong hệ thống."); + const user = { userId: S.users.length + 1, username: body.username, email: body.email, password: body.password, fullName: body.fullName, phone: body.phone, status: "ACTIVE", createdAt: new Date(), updatedAt: new Date() }; + S.users.push(user); + S.userRoles.push({ userId: user.userId, roleId: 4 }); + return send(201, { userId: user.userId, username: user.username, fullName: user.fullName, email: user.email, status: user.status }); + } + if (req.method === "POST" && path === "/api/auth/login") { + const u = S.users.find((x) => x.username === body.username); + if (!u || u.password !== body.password) return send(401); + if (u.status !== "ACTIVE") return bad("Tài khoản đang bị khóa hoặc ngưng hoạt động."); + const h = { loginHistoryId: S.loginHistory.length + 1, userId: u.userId, loginAt: new Date(), logoutAt: null, ipAddress: "::1", deviceInfo: req.headers["user-agent"] || "", loginStatus: "SUCCESS" }; + S.loginHistory.push(h); + const b64 = (o) => Buffer.from(JSON.stringify(o)).toString("base64url"); + const roleNames = S.userRoles.filter((r) => r.userId === u.userId).map((r) => S.roles.find((x) => x.roleId === r.roleId).roleName); + const claim = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; + const token = `${b64({ alg: "HS256", typ: "JWT" })}.${b64({ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": String(u.userId), fullName: u.fullName, loginHistoryId: String(h.loginHistoryId), ...(roleNames.length ? { [claim]: roleNames.length === 1 ? roleNames[0] : roleNames } : {}) })}.c2ln`; + S.tokens.set(token, u); + return send(200, { token, expiresAt: iso(new Date(Date.now() + 86400000)), user: { userId: u.userId, username: u.username, fullName: u.fullName, email: u.email, status: u.status } }); + } + if (req.method === "POST" && path === "/api/auth/logout") { + const u = auth(); + if (!u) return send(401); + const h = [...S.loginHistory].reverse().find((x) => x.userId === u.userId && !x.logoutAt); + if (h) h.logoutAt = new Date(); + return send(200, { message: "Đăng xuất thành công." }); + } + + // ---- Công khai + if (req.method === "GET" && path === "/api/facilities") return send(200, S.facilities); + if (req.method === "GET" && path === "/api/unit-types") return send(200, S.unitTypes); + if (req.method === "GET" && path === "/api/rates") return send(200, S.rates); + if (req.method === "POST" && path === "/api/availability/check") { + const rate = S.rates.find((r) => r.facilityId === body.facilityId && r.unitTypeId === body.unitTypeId); + const t = ut(body.unitTypeId); + const count = availability(body.facilityId, body.unitTypeId, body.startDate, body.rentalPeriodMonths); + return send(200, { facilityId: body.facilityId, facilityName: fac(body.facilityId)?.name, unitTypeId: body.unitTypeId, unitTypeName: t?.typeName, area: t?.area, climateControlled: t?.climateControlled, monthlyRate: rate?.monthlyRate || 0, estimatedTotalRent: (rate?.monthlyRate || 0) * body.rentalPeriodMonths, requiredDeposit: rate?.monthlyRate || 0, startDate: body.startDate, expectedEndDate: addMonths(body.startDate, body.rentalPeriodMonths), availableUnitCount: count, isAvailable: count > 0 }); + } + + const user = auth(); + if (path.startsWith("/api/") && !user) return send(401); + const me = user?.userId; + + + // ---- Quản trị (RequireRole ADMIN) + if (path.startsWith("/api/admin")) { + const isAdmin = S.userRoles.some((r) => r.userId === me && r.roleId === 1); + if (!isAdmin) return send(403); + const msg = (status, m) => send(status, { message: m }); + const roleNamesOf = (uid) => S.userRoles.filter((r) => r.userId === uid).map((r) => S.roles.find((x) => x.roleId === r.roleId).roleName); + const log = (action, entityType, entityId, oldValue, newValue) => + S.activityLogs.push({ logId: S.activityLogs.length + 1, userId: me, action, entityType, entityId, oldValue: oldValue == null ? null : typeof oldValue === "string" ? oldValue : JSON.stringify(oldValue), newValue: newValue == null ? null : typeof newValue === "string" ? newValue : JSON.stringify(newValue), ipAddress: null, loggedAt: new Date() }); + const activeAdmins = (except) => S.users.filter((u) => u.userId !== except && u.status === "ACTIVE" && roleNamesOf(u.userId).includes("ADMIN")).length; + const ufDto = (x) => { + const u = S.users.find((y) => y.userId === x.userId); + const a = S.users.find((y) => y.userId === x.assignedBy); + return { userFacilityId: x.userFacilityId, userId: x.userId, username: u.username, userFullName: u.fullName, facilityId: x.facilityId, facilityName: fac(x.facilityId).name, assignedFrom: x.assignedFrom, assignedTo: x.assignedTo, status: x.status, assignedBy: x.assignedBy, assignerName: a?.fullName || null, createdAt: dbTime(x.createdAt) }; + }; + const logDto = (l) => ({ ...l, username: S.users.find((u) => u.userId === l.userId)?.username || null, loggedAt: dbTime(l.loggedAt) }); + const page = (list) => { + const p = Math.max(1, +url.searchParams.get("page") || 1); + const size = +url.searchParams.get("pageSize") || 20; + return { items: list.slice((p - 1) * size, p * size), totalItems: list.length, page: p, pageSize: size, totalPages: Math.ceil(list.length / size), hasPreviousPage: p > 1, hasNextPage: p * size < list.length }; + }; + const inRange = (d) => { + const f = url.searchParams.get("fromDate"); + const t = url.searchParams.get("toDate"); + return (!f || d >= new Date(f)) && (!t || d <= new Date(t)); + }; + + if (req.method === "GET" && path === "/api/admin/dashboard/stats") { + const active = S.users.filter((u) => u.status === "ACTIVE").length; + const usersByRole = Object.fromEntries(S.roles.map((r) => [r.roleName, S.userRoles.filter((x) => x.roleId === r.roleId).length]).filter(([, n]) => n)); + return send(200, { totalUsers: S.users.length, usersByRole, activeUsersCount: active, inactiveUsersCount: S.users.length - active, totalFacilities: S.facilities.length, totalUnits: S.units.length, occupiedUnits: 1, availableUnits: S.units.length - 1, maintenanceUnits: 0, occupancyRate: 8.33, activeContractsCount: S.contracts.length, pendingReservationsCount: S.reservations.filter((r) => r.status === "PENDING_PAYMENT").length, openTicketsCount: S.tickets.filter((t) => t.status === "OPEN").length, recentActivities: [...S.activityLogs].reverse().slice(0, 5).map(logDto) }); + } + if (req.method === "GET" && path === "/api/admin/users") { + const term = (url.searchParams.get("searchTerm") || "").toLowerCase(); + const st = url.searchParams.get("status"); + const rid = url.searchParams.get("roleId"); + const list = S.users + .filter((u) => !term || [u.username, u.fullName, u.email].some((v) => v.toLowerCase().includes(term)) || (u.phone || "").includes(term)) + .filter((u) => !st || u.status === st.toUpperCase()) + .filter((u) => !rid || S.userRoles.some((r) => r.userId === u.userId && r.roleId === +rid)) + .sort((a, b) => b.createdAt - a.createdAt) + .map((u) => ({ userId: u.userId, username: u.username, fullName: u.fullName, email: u.email, phone: u.phone, status: u.status, createdAt: dbTime(u.createdAt), roles: roleNamesOf(u.userId) })); + return send(200, page(list)); + } + if ((m = path.match(/^\/api\/admin\/users\/(\d+)$/))) { + const u = S.users.find((x) => x.userId === +m[1]); + if (req.method === "GET") { + if (!u) return send(404, { message: `Không tìm thấy người dùng với ID: ${m[1]}` }); + const last = [...S.loginHistory].reverse().find((h) => h.userId === u.userId); + return send(200, { userId: u.userId, username: u.username, fullName: u.fullName, email: u.email, phone: u.phone, status: u.status, createdAt: dbTime(u.createdAt), updatedAt: dbTime(u.updatedAt), roles: S.userRoles.filter((r) => r.userId === u.userId).map((r) => S.roles.find((x) => x.roleId === r.roleId)), facilityAssignments: S.userFacilities.filter((x) => x.userId === u.userId).map(ufDto), activeContractsCount: S.contracts.filter((c) => c.customerId === u.userId && c.status === "ACTIVE").length, openTicketsCount: S.tickets.filter((t) => t.customerId === u.userId && t.status === "OPEN").length, lastLoginAt: last ? dbTime(last.loginAt) : null }); + } + if (req.method === "PUT") { + if (!u) return msg(404, `Không tìm thấy người dùng với ID: ${m[1]}`); + const newStatus = (body.status || "ACTIVE").toUpperCase(); + if (u.status === "ACTIVE" && newStatus !== "ACTIVE" && roleNamesOf(u.userId).includes("ADMIN") && activeAdmins(u.userId) === 0) return msg(400, "Không thể khóa hoặc ngưng hoạt động tài khoản Quản trị viên (ADMIN) đang hoạt động duy nhất của hệ thống."); + if (S.users.some((x) => x.userId !== u.userId && x.email === body.email)) return msg(400, `Email '${body.email}' đã được tài khoản khác sử dụng.`); + const old = { FullName: u.fullName, Email: u.email, Phone: u.phone, Status: u.status }; + Object.assign(u, { fullName: body.fullName, email: body.email, phone: body.phone, status: newStatus, updatedAt: new Date() }); + log("USER_UPDATE", "users", u.userId, old, { FullName: u.fullName, Email: u.email, Phone: u.phone, Status: u.status }); + return send(200, { userId: u.userId, username: u.username, fullName: u.fullName, email: u.email, phone: u.phone, status: u.status, createdAt: dbTime(u.createdAt), roles: roleNamesOf(u.userId) }); + } + } + if (req.method === "POST" && path === "/api/admin/users") { + if (S.users.some((u) => u.username === body.username)) return msg(400, `Tên đăng nhập '${body.username}' đã tồn tại trong hệ thống.`); + if (S.users.some((u) => u.email === body.email)) return msg(400, `Email '${body.email}' đã được sử dụng.`); + const u = { userId: S.users.length + 1, username: body.username, password: body.password, fullName: body.fullName, email: body.email, phone: body.phone, status: body.status || "ACTIVE", createdAt: new Date(), updatedAt: new Date() }; + S.users.push(u); + if (body.initialRoleId) S.userRoles.push({ userId: u.userId, roleId: body.initialRoleId }); + log("USER_CREATE", "users", u.userId, null, { Username: u.username, FullName: u.fullName, Email: u.email, Status: u.status }); + return send(201, { userId: u.userId, username: u.username, fullName: u.fullName, email: u.email, phone: u.phone, status: u.status, createdAt: iso(u.createdAt), roles: roleNamesOf(u.userId) }); + } + if (req.method === "POST" && (m = path.match(/^\/api\/admin\/users\/(\d+)\/reset-password$/))) { + const u = S.users.find((x) => x.userId === +m[1]); + if (!u) return msg(404, `Không tìm thấy người dùng với ID: ${m[1]}`); + if (!body.newPassword || body.newPassword.length < 6) return msg(400, "Mật khẩu mới phải có độ dài tối thiểu 6 ký tự."); + u.password = body.newPassword; + log("USER_RESET_PASSWORD", "users", u.userId, null, "Mật khẩu đã được đặt lại bởi quản trị viên"); + return send(200, { message: "Đặt lại mật khẩu người dùng thành công." }); + } + if (req.method === "GET" && path === "/api/admin/roles") + return send(200, S.roles.map((r) => ({ ...r, permissions: S.rolePermissions.filter((x) => x.roleId === r.roleId).map((x) => S.permissions.find((p) => p.permissionId === x.permissionId)) }))); + if (req.method === "GET" && path === "/api/admin/permissions") return send(200, S.permissions); + if (req.method === "POST" && (m = path.match(/^\/api\/admin\/users\/(\d+)\/roles$/))) { + const u = S.users.find((x) => x.userId === +m[1]); + if (!u) return msg(404, `Không tìm thấy user với ID: ${m[1]}`); + const role = S.roles.find((r) => r.roleId === body.roleId); + if (!role) return msg(404, `Không tìm thấy vai trò với ID: ${body.roleId}`); + if (S.userRoles.some((r) => r.userId === u.userId && r.roleId === role.roleId)) return msg(400, `Người dùng đã có vai trò '${role.roleName}'.`); + S.userRoles.push({ userId: u.userId, roleId: role.roleId }); + log("ROLE_ASSIGN", "user_roles", u.userId, null, { UserId: u.userId, RoleId: role.roleId, RoleName: role.roleName }); + return send(200, { message: "Gán vai trò cho người dùng thành công." }); + } + if (req.method === "DELETE" && (m = path.match(/^\/api\/admin\/users\/(\d+)\/roles\/(\d+)$/))) { + const idx = S.userRoles.findIndex((r) => r.userId === +m[1] && r.roleId === +m[2]); + if (idx < 0) return msg(404, "Liên kết vai trò của người dùng không tồn tại."); + const role = S.roles.find((r) => r.roleId === +m[2]); + const u = S.users.find((x) => x.userId === +m[1]); + if (role.roleName === "ADMIN" && u.status === "ACTIVE" && activeAdmins(u.userId) === 0) return msg(400, "Không thể thu hồi vai trò Quản trị viên (ADMIN) từ tài khoản Admin hoạt động duy nhất của hệ thống."); + S.userRoles.splice(idx, 1); + log("ROLE_REVOKE", "user_roles", u.userId, { UserId: u.userId, RoleId: role.roleId, RoleName: role.roleName }, null); + return send(200, { message: "Thu hồi vai trò của người dùng thành công." }); + } + if (req.method === "POST" && (m = path.match(/^\/api\/admin\/roles\/(\d+)\/permissions$/))) { + const role = S.roles.find((r) => r.roleId === +m[1]); + const perm = S.permissions.find((p) => p.permissionId === body.permissionId); + if (!role) return msg(404, `Không tìm thấy role: ${m[1]}`); + if (!perm) return msg(404, `Không tìm thấy permission: ${body.permissionId}`); + if (S.rolePermissions.some((x) => x.roleId === role.roleId && x.permissionId === perm.permissionId)) return msg(400, "Quyền này đã được gán cho vai trò."); + S.rolePermissions.push({ roleId: role.roleId, permissionId: perm.permissionId }); + log("PERMISSION_ASSIGN", "role_permissions", role.roleId, null, { RoleId: role.roleId, RoleName: role.roleName, PermissionId: perm.permissionId, PermissionCode: perm.permissionCode }); + return send(200, { message: "Gán quyền hạn cho vai trò thành công." }); + } + if (req.method === "DELETE" && (m = path.match(/^\/api\/admin\/roles\/(\d+)\/permissions\/(\d+)$/))) { + const idx = S.rolePermissions.findIndex((x) => x.roleId === +m[1] && x.permissionId === +m[2]); + if (idx < 0) return msg(404, "Liên kết quyền của vai trò không tồn tại."); + const role = S.roles.find((r) => r.roleId === +m[1]); + const perm = S.permissions.find((p) => p.permissionId === +m[2]); + S.rolePermissions.splice(idx, 1); + log("PERMISSION_REVOKE", "role_permissions", role.roleId, { RoleId: role.roleId, RoleName: role.roleName, PermissionId: perm.permissionId, PermissionCode: perm.permissionCode }, null); + return send(200, { message: "Thu hồi quyền hạn khỏi vai trò thành công." }); + } + if (req.method === "GET" && (m = path.match(/^\/api\/admin\/users\/(\d+)\/facilities$/))) + return send(200, S.userFacilities.filter((x) => x.userId === +m[1]).sort((a, b) => b.createdAt - a.createdAt).map(ufDto)); + if (req.method === "POST" && path === "/api/admin/user-facilities") { + const u = S.users.find((x) => x.userId === body.userId); + if (!u) return msg(404, `Không tìm thấy người dùng với ID: ${body.userId}`); + if (!roleNamesOf(u.userId).some((r) => r === "STAFF" || r === "MANAGER")) return msg(400, "Chỉ có thể phân công cơ sở cho tài khoản có vai trò STAFF hoặc MANAGER."); + const f = fac(body.facilityId); + if (!f) return msg(404, `Không tìm thấy cơ sở với ID: ${body.facilityId}`); + if (body.assignedTo && body.assignedTo < body.assignedFrom) return msg(400, "Ngày kết thúc phân công không thể trước ngày bắt đầu."); + for (const old of S.userFacilities.filter((x) => x.userId === u.userId && x.status === "ACTIVE")) { + old.status = "ENDED"; + if (!old.assignedTo || old.assignedTo > body.assignedFrom) old.assignedTo = body.assignedFrom; + } + const x = { userFacilityId: S.userFacilities.length + 1, userId: u.userId, facilityId: f.facilityId, assignedBy: me, assignedFrom: body.assignedFrom, assignedTo: body.assignedTo || null, status: "ACTIVE", createdAt: new Date() }; + S.userFacilities.push(x); + log("FACILITY_SCOPE_ASSIGN", "user_facilities", u.userId, null, { UserId: u.userId, FacilityId: f.facilityId, FacilityName: f.name, AssignedFrom: body.assignedFrom, AssignedTo: body.assignedTo }); + return send(201, ufDto(x)); + } + if (req.method === "PUT" && (m = path.match(/^\/api\/admin\/user-facilities\/(\d+)\/status$/))) { + const x = S.userFacilities.find((y) => y.userFacilityId === +m[1]); + if (!x) return msg(404, `Không tìm thấy bản ghi phân công cơ sở với ID: ${m[1]}`); + const st = (body.status || "").toUpperCase(); + if (!["ACTIVE", "ENDED", "SUSPENDED"].includes(st)) return msg(400, "Trạng thái phân công không hợp lệ (chỉ chấp nhận ACTIVE, ENDED, SUSPENDED)."); + if (st === "ACTIVE" && S.userFacilities.some((y) => y.userId === x.userId && y.userFacilityId !== x.userFacilityId && y.status === "ACTIVE")) return msg(400, "Người dùng đang có phân công ACTIVE khác. Hãy kết thúc phân công hiện tại trước khi kích hoạt phân công này."); + const old = x.status; + x.status = st; + if (st === "ENDED" && !x.assignedTo) x.assignedTo = dateOnly(new Date()); + log("FACILITY_SCOPE_STATUS_CHANGE", "user_facilities", x.userFacilityId, { Status: old }, { Status: st }); + return send(200, { message: "Cập nhật trạng thái phân công cơ sở thành công." }); + } + if (req.method === "GET" && path === "/api/admin/logs/login-history") { + const list = [...S.loginHistory].filter((h) => inRange(h.loginAt)).sort((a, b) => b.loginAt - a.loginAt).map((h) => { + const u = S.users.find((x) => x.userId === h.userId); + return { ...h, username: u.username, fullName: u.fullName, loginAt: dbTime(h.loginAt), logoutAt: h.logoutAt ? dbTime(h.logoutAt) : null }; + }); + return send(200, page(list)); + } + if (req.method === "GET" && path === "/api/admin/logs/activity-logs") { + const action = url.searchParams.get("action"); + const list = [...S.activityLogs].filter((l) => inRange(l.loggedAt) && (!action || l.action === action)).sort((a, b) => b.loggedAt - a.loggedAt).map(logDto); + return send(200, page(list)); + } + return send(404, { message: "Not found" }); + } + + // ---- Đặt chỗ + if (req.method === "GET" && path === "/api/reservations") return send(200, S.reservations.filter((r) => r.customerId === me).sort((a, b) => b.createdAt - a.createdAt).map(resDto)); + if (req.method === "GET" && (m = path.match(/^\/api\/reservations\/(\d+)$/))) { + const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); + if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." }); + const c = S.contracts.find((x) => x.reservationId === r.reservationId); + return send(200, { ...resDto(r), checkInAppointmentAt: null, assignedUnitNumber: c ? unit(c.unitId).unitNumber : null, contractId: c?.contractId ?? null, contractStatus: c?.status ?? null }); + } + if (req.method === "POST" && path === "/api/reservations") { + if (body.rentalPeriodMonths <= 0) return bad("Thời hạn thuê phải lớn hơn 0 tháng."); + if (!fac(body.facilityId)) return bad("Không tìm thấy cơ sở kho."); + if (!ut(body.unitTypeId)) return bad("Không tìm thấy loại phòng kho."); + if (body.startDate < dateOnly(new Date())) return bad("Ngày bắt đầu thuê không thể ở quá khứ."); + const rate = S.rates.find((r) => r.facilityId === body.facilityId && r.unitTypeId === body.unitTypeId); + if (!rate) return bad("Chưa có bảng giá áp dụng cho cơ sở và loại kho này."); + if (availability(body.facilityId, body.unitTypeId, body.startDate, body.rentalPeriodMonths) <= 0) return bad("Hiện tại đã hết kho trống cho loại kho và khoảng thời gian yêu cầu."); + const r = { reservationId: S.reservations.length + 1, customerId: me, facilityId: body.facilityId, unitTypeId: body.unitTypeId, startDate: body.startDate, expectedEndDate: addMonths(body.startDate, body.rentalPeriodMonths), rentalPeriodMonths: body.rentalPeriodMonths, quotedMonthlyRate: rate.monthlyRate, estimatedAmount: rate.monthlyRate * body.rentalPeriodMonths, requiredDeposit: rate.monthlyRate, status: "PENDING_PAYMENT", createdAt: new Date(), expiresAt: new Date(Date.now() + 24 * 3600000), cancelledAt: null, cancellationReason: null }; + 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+)\/cancel$/))) { + const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); + if (!r) return bad("Không tìm thấy đơn đặt chỗ hợp lệ."); + if (!["PENDING_PAYMENT", "CONFIRMED"].includes(r.status)) return bad(`Không thể hủy đơn đặt chỗ ở trạng thái '${r.status}'.`); + Object.assign(r, { status: "CANCELLED", cancelledAt: new Date(), cancellationReason: body?.reason }); + return send(200, { message: "Đã hủy đơn đặt chỗ thành công." }); + } + + // ---- Hợp đồng + if (req.method === "GET" && path === "/api/contracts") return send(200, S.contracts.filter((c) => c.customerId === me).map(contractSummary)); + if (req.method === "GET" && (m = path.match(/^\/api\/contracts\/(\d+)$/))) { + const c = S.contracts.find((x) => x.contractId === +m[1] && x.customerId === me); + if (!c) return send(404, { error: "Không tìm thấy hợp đồng." }); + const h = S.handovers.find((x) => x.contractId === c.contractId); + return send(200, { ...contractSummary(c), terminationReason: null, createdAt: dbTime(c.createdAt), completedAt: null, handover: h ? { handoverId: h.handoverId, status: h.status, scheduledAt: dbTime(h.scheduledAt), handoverAt: dbTime(h.handoverAt), customerConfirmed: h.customerConfirmed, staffConfirmed: h.staffConfirmed } : null, payments: S.payments.filter((p) => p.contractId === c.contractId).map(payDto), renewals: S.renewals.filter((r) => r.contractId === c.contractId).map(renDto) }); + } + if (req.method === "POST" && (m = path.match(/^\/api\/contracts\/(\d+)\/renewals$/))) { + if (!(body.renewalPeriodMonths > 0)) return bad("Thời gian gia hạn phải lớn hơn 0 tháng."); + const c = S.contracts.find((x) => x.contractId === +m[1] && x.customerId === me); + if (!c) return bad("Không tìm thấy hợp đồng hợp lệ."); + if (c.status !== "ACTIVE") return bad(`Chỉ hợp đồng ở trạng thái 'ACTIVE' mới có thể gia hạn. Trạng thái hiện tại: ${c.status}`); + if (S.renewals.some((r) => r.contractId === c.contractId && ["PENDING_PAYMENT", "PENDING_APPROVAL"].includes(r.status))) return bad("Hợp đồng đã có yêu cầu gia hạn đang chờ xử lý."); + const r = { renewalId: S.renewals.length + 1, contractId: c.contractId, oldEndDate: c.endDate, newEndDate: addMonths(c.endDate, body.renewalPeriodMonths), renewalPeriodMonths: body.renewalPeriodMonths, oldMonthlyRate: c.agreedMonthlyRate, newMonthlyRate: c.agreedMonthlyRate, renewalAmount: c.agreedMonthlyRate * body.renewalPeriodMonths, status: "PENDING_PAYMENT", requestedAt: new Date() }; + S.renewals.push(r); + return send(201, { ...r, requestedAt: iso(r.requestedAt), approvedAt: null }); + } + if (req.method === "GET" && (m = path.match(/^\/api\/contracts\/(\d+)\/payments$/))) return send(200, S.payments.filter((p) => p.contractId === +m[1]).map(payDto)); + if (req.method === "POST" && (m = path.match(/^\/api\/handovers\/(\d+)\/confirm$/))) { + const h = S.handovers.find((x) => x.handoverId === +m[1]); + if (!h) return bad("Không tìm thấy biên bản bàn giao phù hợp."); + h.customerConfirmed = true; + return send(200, { message: "Đã xác nhận bàn giao." }); + } + + // ---- Hỗ trợ + if (req.method === "GET" && path === "/api/tickets") return send(200, S.tickets.filter((t) => t.customerId === me).map(ticketDto)); + if (req.method === "GET" && (m = path.match(/^\/api\/tickets\/(\d+)$/))) { + const t = S.tickets.find((x) => x.ticketId === +m[1] && x.customerId === me); + if (!t) return send(404, { error: "Không tìm thấy yêu cầu hỗ trợ." }); + return send(200, { ...ticketDto(t), contractUnitNumber: unit(S.contracts.find((c) => c.contractId === t.contractId).unitId).unitNumber, description: t.description, assignedAt: null }); + } + if (req.method === "POST" && path === "/api/tickets") { + const c = S.contracts.find((x) => x.contractId === body.contractId && x.customerId === me); + if (!c) return bad("Hợp đồng liên quan không tồn tại hoặc không thuộc về khách hàng."); + const t = { ticketId: S.tickets.length + 1, customerId: me, contractId: c.contractId, unitId: body.unitId ?? c.unitId, issueType: body.issueType, title: body.title, description: body.description, priority: body.priority || "MEDIUM", status: "OPEN", createdAt: new Date() }; + S.tickets.push(t); + return send(201, { ...ticketDto(t), createdAt: iso(t.createdAt) }); + } + if (req.method === "POST" && (m = path.match(/^\/api\/tickets\/(\d+)\/cancel$/))) { + const t = S.tickets.find((x) => x.ticketId === +m[1] && x.customerId === me); + if (!t) return bad("Yêu cầu hỗ trợ không tồn tại."); + if (t.status !== "OPEN") return bad("Chỉ có thể hủy yêu cầu đang ở trạng thái mở."); + t.status = "CANCELLED"; + return send(200, { message: "Đã hủy yêu cầu hỗ trợ." }); + } + return send(404, { error: "Not found" }); + }); + return new Promise((resolve) => server.listen(port, () => resolve({ server, state: S, log }))); +} + +if (process.argv[1] && process.argv[1].replace(/\\/g, "/").endsWith("mock/mock-api.mjs")) { + const port = Number(process.argv[2]) || 5151; + startMockApi(port, { verbose: true }).then(() => console.log(`API giả lập đang chạy: http://localhost:${port}`)); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json index c2c0135..9a84be7 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json @@ -7,7 +7,7 @@ "dev": "vite --host 127.0.0.1", "build": "vite build --base=./", "preview": "vite preview --host 127.0.0.1", - "test": "node --test tests/reducer.test.js tests/api-mappers.test.js", + "test": "node --test tests/reducer.test.js tests/api-mappers.test.js tests/admin.test.js", "test:render": "node tests/render.test.mjs" }, "dependencies": { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs new file mode 100644 index 0000000..bb50950 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs @@ -0,0 +1,28 @@ +// Chạy giao diện ở chế độ API với máy chủ giả lập (không cần .NET / SQL Server): +// npm run dev:mock +// → API giả lập ở http://localhost:5151 (in ra từng lời gọi API) + giao diện ở http://127.0.0.1:5173 +import { createServer } from "vite"; +import { startMockApi } from "../mock/mock-api.mjs"; + +const API_PORT = Number(process.env.MOCK_API_PORT) || 5151; + +// Biến VITE_* có sẵn trong môi trường được Vite ưu tiên hơn file .env +process.env.VITE_USE_API = "true"; +process.env.VITE_API_URL = `http://localhost:${API_PORT}`; + +try { + await startMockApi(API_PORT, { verbose: true }); +} catch (e) { + console.error(`Không mở được cổng ${API_PORT} (có thể backend thật đang chạy). Đặt MOCK_API_PORT=5199 rồi chạy lại.`); + process.exit(1); +} +const vite = await createServer({ server: { host: "127.0.0.1", port: 5173 } }); +await vite.listen(); +console.log("\n API giả lập (theo StorageProject.Api): http://localhost:" + API_PORT); +vite.printUrls(); +console.log(` + Tài khoản có sẵn: + admin / Admin@123 → Quản trị hệ thống (#/admin) + customer01 / Customer@123 → Khách hàng + Mỗi lời gọi API sẽ hiện bên dưới (xanh = thành công, đỏ = lỗi từ máy chủ). +`); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx index b2386f4..a89f8e4 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx @@ -22,6 +22,7 @@ import Overview from "./pages/Overview"; import Payments from "./pages/Payments"; import Profile from "./pages/Profile"; import { Guide, Pricing } from "./pages/Public"; +import AdminApp from "./admin/AdminApp"; import Reservations from "./pages/Reservations"; import Support from "./pages/Support"; import { Renew, Return, Sent, UnitDetail, Units } from "./pages/Units"; @@ -41,6 +42,7 @@ const TITLES = { reservations: "Đơn đặt chỗ", payments: "Thanh toán & lịch hẹn", sent: "Đã gửi yêu cầu", + admin: "Quản trị hệ thống", support: "Hỗ trợ", profile: "Tài khoản", }; @@ -82,8 +84,9 @@ function renderPage({ page, parts, query }) { function Shell() { const route = useRoute(); - const { authed, toast, dismissToast, storageError, ready, loadError, retry } = useApp(); - const needsLogin = PRIVATE.includes(route.page) && !authed; + const { authed, toast, dismissToast, storageError, ready, loadError, retry, isAdmin, mode } = useApp(); + const isAdminPage = route.page === "admin"; + const needsLogin = (PRIVATE.includes(route.page) || (isAdminPage && mode === "api")) && !authed; useEffect(() => { document.title = `${TITLES[route.page] || "SafeSpace"} · SafeSpace`; @@ -92,14 +95,34 @@ 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)) return; + if (!PRIVATE.includes(current.page) && current.page !== "admin") return; go(`login?next=${encodeURIComponent(current.raw)}`, { replace: true }); }, [needsLogin, route.raw]); + // Tài khoản quản trị không dùng các trang khách hàng + useEffect(() => { + if (isAdmin && (PRIVATE.includes(route.page) || route.page === "login" || route.page === "register")) go("admin", { replace: true }); + }, [isAdmin, route.page]); + + const adminBody = + mode !== "api" ? ( +
+ + Về trang chủ + +
+ ) : authed && !isAdmin ? ( +
+ + Về trang của tôi + +
+ ) : null; + return (
{ e.preventDefault(); document.getElementById("main")?.focus(); }}>Chuyển đến nội dung -
+ {!(isAdminPage && !adminBody && authed) &&
}
{needsLogin ? null : loadError && !ready ? (
@@ -112,6 +135,8 @@ function Shell() {
+ ) : isAdminPage ? ( + adminBody || ) : ( renderPage(route) )} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx new file mode 100644 index 0000000..0906752 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx @@ -0,0 +1,35 @@ +import React from "react"; +import { Empty, LinkButton } from "../components/UI"; +import AdminCreateUser from "./AdminCreateUser"; +import AdminLogs from "./AdminLogs"; +import AdminPermissions from "./AdminPermissions"; +import AdminShell from "./AdminShell"; +import AdminUserDetail from "./AdminUserDetail"; +import AdminUsers from "./AdminUsers"; + +// Định tuyến khu quản trị: #/admin, #/admin/users/:id, #/admin/new, #/admin/permissions, #/admin/logs +export default function AdminApp({ parts }) { + const [a, b] = parts; + let tab = ""; + let body; + if (!a) body = ; + else if (a === "users" && b) body = ; + else if (a === "new") { + tab = "new"; + body = ; + } else if (a === "permissions") { + tab = "permissions"; + body = ; + } else if (a === "logs") { + tab = "logs"; + body = ; + } else + body = ( +
+ + Về quản lý tài khoản + +
+ ); + return {body}; +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx new file mode 100644 index 0000000..e2a5655 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx @@ -0,0 +1,183 @@ +import React, { useState } from "react"; +import { adminApi } from "../api/admin"; +import { Select } from "../components/Pickers"; +import { Button, Field, Modal, Notice } from "../components/UI"; +import { isEmail, isPhone, today } from "../lib/format"; +import { FACILITY_ROLES, roleLabel, sortRoles } from "../lib/roles"; +import { go } from "../lib/router"; +import { useApp } from "../state/store"; +import { tempPassword, useLoad, usernameFrom } from "./util"; + +const EMPTY = { fullName: "", email: "", phone: "", username: "", password: "", roleId: "", facilityId: "" }; + +export default function AdminCreateUser() { + const { onApiError, notify } = useApp(); + const meta = useLoad(async () => { + const [roles, facilities] = await Promise.all([adminApi.roles(), adminApi.facilities()]); + return { roles: sortRoles(roles, (r) => r.roleName), facilities: facilities.filter((f) => f.status === "ACTIVE") }; + }, [], onApiError); + const [form, setForm] = useState(() => ({ ...EMPTY, password: tempPassword() })); + const [userTouched, setUserTouched] = useState(false); + const [errors, setErrors] = useState({}); + const [busy, setBusy] = useState(false); + const [done, setDone] = useState(null); + + const roles = meta.data?.roles || []; + const role = roles.find((r) => String(r.roleId) === String(form.roleId)); + const scoped = role && FACILITY_ROLES.includes(role.roleName); + + const set = (k, v) => { + setForm((f) => { + const next = { ...f, [k]: v }; + if (k === "email" && !userTouched) next.username = usernameFrom(v); + return next; + }); + setErrors((e) => ({ ...e, [k]: undefined, form: undefined })); + }; + + const validate = () => { + const e = {}; + if (!form.fullName.trim()) e.fullName = "Vui lòng nhập họ và tên."; + if (!isEmail(form.email)) e.email = "Nhập email hợp lệ, ví dụ ten@safespace.vn."; + if (form.phone && !isPhone(form.phone)) e.phone = "Số điện thoại chưa đúng định dạng."; + if (!/^[a-zA-Z0-9._@-]{3,50}$/.test(form.username)) e.username = "Tên đăng nhập 3–50 ký tự: chữ, số, dấu . _ - @"; + if (form.password.length < 8) e.password = "Mật khẩu tạm thời cần ít nhất 8 ký tự."; + if (!form.roleId) e.roleId = "Chọn vai trò cho tài khoản."; + if (scoped && !form.facilityId) e.facilityId = "Nhân viên và Quản lý cơ sở cần có cơ sở phụ trách."; + return e; + }; + + const submit = async (ev) => { + ev.preventDefault(); + const e = validate(); + if (Object.keys(e).length) return setErrors(e); + setBusy(true); + let created; + try { + created = await adminApi.createUser({ + username: form.username.trim(), + password: form.password, + fullName: form.fullName.trim(), + email: form.email.trim().toLowerCase(), + phone: form.phone.replace(/[\s.-]/g, "") || null, + initialRoleId: Number(form.roleId), + status: "ACTIVE", + }); + } catch (err) { + onApiError(err); + setBusy(false); + const msg = err.message || "Không tạo được tài khoản."; + if (/Tên đăng nhập/i.test(msg)) return setErrors({ username: msg }); + if (/Email/i.test(msg)) return setErrors({ email: msg }); + return setErrors({ form: msg }); + } + let facilityError = null; + if (scoped && form.facilityId) { + try { + await adminApi.assignFacility({ userId: created.userId, facilityId: Number(form.facilityId), assignedFrom: today(), assignedTo: null }); + } catch (err) { + facilityError = err.message; + } + } + setBusy(false); + setDone({ user: created, password: form.password, facilityError }); + }; + + const copy = async (text) => { + try { + await navigator.clipboard.writeText(text); + notify("Đã sao chép."); + } catch { + notify("Không sao chép được, vui lòng chép thủ công.", "error"); + } + }; + + return ( +
+
+

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

+

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

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

{errors.form}

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

{errors.roleId}

} +
+ + + +

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

+ +

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

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

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

+
+
Tên đăng nhập
{done.user.username}
+
Mật khẩu tạm thời
{done.password}
+
+ {done.facilityError && Chưa phân công được cơ sở: {done.facilityError}. Bạn có thể phân công lại trong trang chi tiết.} +
+ + +
+
+ )} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx new file mode 100644 index 0000000..9dc0387 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx @@ -0,0 +1,143 @@ +import React, { useMemo, useState } from "react"; +import { adminApi } from "../api/admin"; +import { parseUtc } from "../api/mappers"; +import { DatePicker, Pagination } from "../components/Pickers"; +import { Notice } from "../components/UI"; +import { ACTION_GROUPS, roleLabel, sortRoles } from "../lib/roles"; +import { useApp } from "../state/store"; +import { dateTime, describeActivity, useLoad } from "./util"; + +const TABS = [ + ["all", "Tất cả"], + ["login", "Đăng nhập"], + ["data", "Thay đổi dữ liệu"], + ["access", "Phân quyền"], +]; +const PAGE_SIZE = 10; +const FETCH = 100; // số bản ghi mới nhất lấy mỗi loại để gộp / lọc ở trình duyệt + +// Ngày địa phương → mốc UTC để gửi backend +const startOf = (d) => (d ? new Date(`${d}T00:00:00`).toISOString() : undefined); +const endOf = (d) => (d ? new Date(`${d}T23:59:59`).toISOString() : undefined); + +export default function AdminLogs() { + const { onApiError } = useApp(); + const [tab, setTab] = useState("all"); + const [from, setFrom] = useState(""); + const [to, setTo] = useState(""); + const [page, setPage] = useState(1); + + const users = useLoad(async () => { + const res = await adminApi.users({ page: 1, pageSize: 500 }); + return new Map(res.items.map((u) => [u.userId, u])); + }, [], onApiError); + + const logs = useLoad(async () => { + const range = { fromDate: startOf(from), toDate: endOf(to) }; + if (tab === "login") return { login: await adminApi.loginHistory({ page, pageSize: PAGE_SIZE, ...range }) }; + const [login, activity] = await Promise.all([ + tab === "all" ? adminApi.loginHistory({ page: 1, pageSize: FETCH, ...range }) : null, + adminApi.activityLogs({ page: 1, pageSize: FETCH, ...range }), + ]); + return { login, activity }; + }, [tab, from, to, tab === "login" ? page : 0], onApiError); + + const userMap = users.data || new Map(); + const nameOf = (id) => userMap.get(id)?.fullName; + const rolesOf = (id) => sortRoles(userMap.get(id)?.roles || []).map(roleLabel).join(", ") || "—"; + + const rows = useMemo(() => { + const d = logs.data; + if (!d) return []; + const loginRows = (d.login?.items || []).map((h) => ({ + id: `L${h.loginHistoryId}`, + at: h.loginAt, + userId: h.userId, + user: h.fullName || h.username, + action: `${h.loginStatus === "SUCCESS" ? "Đăng nhập thành công" : `Đăng nhập ${h.loginStatus === "FAILED" ? "thất bại" : h.loginStatus.toLowerCase()}`}${h.logoutAt ? ` · đăng xuất ${dateTime(h.logoutAt).slice(11)}` : ""}`, + ip: h.ipAddress || "—", + device: h.deviceInfo, + })); + if (tab === "login") return loginRows; + const group = ACTION_GROUPS[tab]; + const actRows = (d.activity?.items || []) + .filter((a) => !group || group.includes(a.action)) + .map((a) => ({ + id: `A${a.logId}`, + at: a.loggedAt, + userId: a.userId, + user: a.userId ? nameOf(a.userId) || a.username || `#${a.userId}` : "Hệ thống", + action: describeActivity(a, nameOf), + ip: a.ipAddress || "—", + })); + return [...loginRows, ...actRows].sort((x, y) => (parseUtc(y.at)?.getTime() || 0) - (parseUtc(x.at)?.getTime() || 0)); + }, [logs.data, tab, userMap]); // eslint-disable-line react-hooks/exhaustive-deps + + const serverPaged = tab === "login"; + const total = serverPaged ? logs.data?.login?.totalItems || 0 : rows.length; + const pages = Math.max(1, Math.ceil(total / PAGE_SIZE)); + const current = Math.min(page, pages); + const shown = serverPaged ? rows : rows.slice((current - 1) * PAGE_SIZE, current * PAGE_SIZE); + const first = (current - 1) * PAGE_SIZE + 1; + + const pick = (fn) => (v) => { + fn(v); + setPage(1); + }; + + return ( +
+
+
+

Lịch sử đăng nhập & nhật ký hoạt động

+

Theo dõi đăng nhập, thay đổi dữ liệu tài khoản và phân quyền trong hệ thống.

+
+
+ +
+
+ {TABS.map(([k, label]) => ( + + ))} +
+
+ + + {(from || to) && ( + + )} +
+
+ + {logs.error && {logs.error}} +
+ + + + + + {shown.map((r) => ( + + + + + + + + ))} + {!logs.loading && shown.length === 0 && ( + + )} + {logs.loading && !logs.data && ( + + )} + +
Thời gianNgười dùngVai tròHành độngĐịa chỉ IP
{dateTime(r.at)}{r.user}{r.userId ? rolesOf(r.userId) : "—"}{r.action}{r.ip}
Chưa có hoạt động trong khoảng thời gian này.
Đang tải nhật ký…
+
+ + {!serverPaged && total >= FETCH &&

Hiển thị {FETCH} bản ghi mới nhất mỗi loại. Dùng bộ lọc ngày để xem các mốc cũ hơn.

} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx new file mode 100644 index 0000000..a340c21 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx @@ -0,0 +1,173 @@ +import React, { useMemo, useState } from "react"; +import { adminApi } from "../api/admin"; +import { Button, Modal, Notice } from "../components/UI"; +import { ROLE_SCOPE, roleLabel, sortRoles } from "../lib/roles"; +import { useApp } from "../state/store"; +import { useLoad } from "./util"; + +const key = (roleId, permissionId) => `${roleId}:${permissionId}`; + +export default function AdminPermissions() { + const { onApiError, notify } = useApp(); + const res = useLoad(async () => { + const [roles, permissions] = await Promise.all([adminApi.roles(), adminApi.permissions()]); + return { roles: sortRoles(roles, (r) => r.roleName), permissions }; + }, [], onApiError); + const [changes, setChanges] = useState({}); // key → true (gán) | false (thu hồi) + const [confirm, setConfirm] = useState(false); + const [saving, setSaving] = useState(false); + const [errors, setErrors] = useState([]); + + const granted = useMemo(() => { + const s = new Set(); + for (const r of res.data?.roles || []) for (const p of r.permissions) s.add(key(r.roleId, p.permissionId)); + return s; + }, [res.data]); + const isOn = (roleId, pid) => { + const k = key(roleId, pid); + return k in changes ? changes[k] : granted.has(k); + }; + const toggle = (roleId, pid) => { + const k = key(roleId, pid); + const next = !isOn(roleId, pid); + setChanges((c) => { + const copy = { ...c }; + if (next === granted.has(k)) delete copy[k]; + else copy[k] = next; + return copy; + }); + }; + const pending = Object.entries(changes); + const roles = res.data?.roles || []; + const permissions = res.data?.permissions || []; + const roleOf = (id) => roles.find((r) => String(r.roleId) === String(id)); + const permOf = (id) => permissions.find((p) => String(p.permissionId) === String(id)); + const adminLosesAccess = pending.some(([k, on]) => { + const [rid, pid] = k.split(":"); + return !on && roleOf(rid)?.roleName === "ADMIN" && ["USER_MANAGE", "ROLE_MANAGE"].includes(permOf(pid)?.permissionCode); + }); + + const save = async () => { + setConfirm(false); + setSaving(true); + const failed = []; + for (const [k, on] of pending) { + const [rid, pid] = k.split(":").map(Number); + try { + if (on) await adminApi.assignPermission(rid, pid); + else await adminApi.revokePermission(rid, pid); + } catch (e) { + onApiError(e); + failed.push(`${roleLabel(roleOf(rid)?.roleName)} · ${permOf(pid)?.permissionName}: ${e.message}`); + } + } + setSaving(false); + setErrors(failed); + setChanges({}); + await res.reload(); + notify(failed.length ? `Đã lưu, ${failed.length} thay đổi không thành công.` : "Đã lưu cấu hình quyền.", failed.length ? "error" : "success"); + }; + + return ( +
+
+
+

Cấu hình quyền truy cập dữ liệu

+

Thiết lập phạm vi dữ liệu và quyền thao tác mà mỗi vai trò được phép.

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

Quyền thao tác theo vai trò

+
+ + + + + {roles.map((r) => ( + + ))} + + + + {permissions.map((p) => ( + + + {roles.map((r) => { + const k = key(r.roleId, p.permissionId); + const on = isOn(r.roleId, p.permissionId); + return ( + + ); + })} + + ))} + +
Quyền{roleLabel(r.roleName)}
+ {p.permissionName} + {p.permissionCode}{p.description ? ` · ${p.description}` : ""} + + +
+
+ + {errors.length > 0 && ( + + {errors.map((e) => ( +
{e}
+ ))} +
+ )} +
+ + {pending.length > 0 && !saving && ( + + )} +
+ + {confirm && ( + setConfirm(false)} size="md"> +
    + {pending.map(([k, on]) => { + const [rid, pid] = k.split(":"); + return ( +
  • + {on ? "Gán" : "Thu hồi"} {permOf(pid)?.permissionName} {on ? "cho" : "của"} {roleLabel(roleOf(rid)?.roleName)} +
  • + ); + })} +
+ {adminLosesAccess && Bạn đang thu hồi quyền quản lý tài khoản / vai trò của Quản trị. Hãy chắc chắn vẫn còn cách khôi phục.} +
+ + +
+
+ )} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx new file mode 100644 index 0000000..f598204 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx @@ -0,0 +1,183 @@ +import React, { useEffect, useRef, useState } from "react"; +import { Icon } from "../components/UI"; +import { go, href } from "../lib/router"; +import { useApp } from "../state/store"; +import { adminApi } from "../api/admin"; +import { dateTime } from "./util"; + +const TABS = [ + ["", "Tài khoản"], + ["new", "Thêm tài khoản"], + ["permissions", "Quyền truy cập"], + ["logs", "Nhật ký hoạt động"], +]; +const READ_KEY = "safespace.admin.notices.read"; + +function useNotices(onApiError) { + const [items, setItems] = useState([]); + const [read, setRead] = useState(() => { + try { + return JSON.parse(localStorage.getItem(READ_KEY)) || []; + } catch { + return []; + } + }); + useEffect(() => { + let alive = true; + (async () => { + try { + const [stats, logins] = await Promise.all([adminApi.stats(), adminApi.loginHistory({ page: 1, pageSize: 1 })]); + if (!alive) return; + const list = []; + const locked = stats.inactiveUsersCount || 0; + list.push({ + id: `locked-${locked}`, + title: "Tài khoản cần kiểm tra", + detail: locked ? `${locked} tài khoản đang khoá hoặc ngưng hoạt động.` : "Rà soát vai trò và cơ sở phụ trách.", + to: "admin", + }); + const access = (stats.recentActivities || []).find((a) => /^(ROLE|PERMISSION)_/.test(a.action)); + if (access) list.push({ id: `access-${access.logId}`, title: "Quyền truy cập được cập nhật", detail: `Lúc ${dateTime(access.loggedAt)}. Xem cấu hình quyền theo vai trò.`, to: "admin/permissions" }); + const last = logins.items?.[0]; + if (last) list.push({ id: `login-${last.loginHistoryId}`, title: "Nhật ký hoạt động mới", detail: `${last.fullName} đăng nhập lúc ${dateTime(last.loginAt)}.`, to: "admin/logs" }); + setItems(list); + } catch (e) { + onApiError?.(e); + } + })(); + return () => { + alive = false; + }; + }, [onApiError]); + const mark = (ids) => { + const next = [...new Set([...read, ...ids])].slice(-100); + setRead(next); + try { + localStorage.setItem(READ_KEY, JSON.stringify(next)); + } catch { + /* bỏ qua */ + } + }; + return { items: items.map((n) => ({ ...n, read: read.includes(n.id) })), mark }; +} + +function Bell() { + const { onApiError } = useApp(); + const { items, mark } = useNotices(onApiError); + const [open, setOpen] = useState(false); + const ref = useRef(null); + const unread = items.filter((n) => !n.read).length; + useEffect(() => { + if (!open) return undefined; + const onDown = (e) => !ref.current?.contains(e.target) && setOpen(false); + const onKey = (e) => e.key === "Escape" && setOpen(false); + document.addEventListener("pointerdown", onDown); + document.addEventListener("keydown", onKey); + return () => { + document.removeEventListener("pointerdown", onDown); + document.removeEventListener("keydown", onKey); + }; + }, [open]); + return ( +
+