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] 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..84f7af5467eeeb99fdfb08ff0c8c78b5c10bbf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D=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" && ( + + + + ) + )} + +