diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env deleted file mode 100644 index 9131cab..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env +++ /dev/null @@ -1 +0,0 @@ -VITE_API_URL=http://localhost:5151 diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example index 9dfa00e..2e2b527 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example @@ -1,2 +1,14 @@ -# Backend API URL (SSFRMS ASP.NET Core Minimal API) +# Chép thành .env.local rồi chỉnh. + +# Nối backend SSFRMS (StorageProject.Api). false = chạy bằng dữ liệu lưu trong trình duyệt. +VITE_USE_API=true VITE_API_URL=http://localhost:5151 + +# Thời gian giữ đơn chờ chuyển khoản (giây). Figma: 01:00 → 60. Dùng 900 cho 15 phút. +VITE_PAYMENT_TIMEOUT_SECONDS=60 + +# Tài khoản nhận chuyển khoản, dùng để tạo mã VietQR ở màn thanh toán (C04) +VITE_BANK_BIN=970422 +VITE_BANK_NAME=MB Bank +VITE_BANK_ACCOUNT=0901234567890 +VITE_BANK_HOLDER=CONG TY TNHH SAFESPACE diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md new file mode 100644 index 0000000..402ce5a --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -0,0 +1,79 @@ +# BE-CONTRACT — những gì giao diện khách hàng cần từ backend + +Giao diện bám Figma nên **khác luồng backend cũ (v3)** ở vài điểm. Tài liệu này là danh sách để sửa BE cho khớp. +Toàn bộ nghiệp vụ hiện nằm ở `src/state/reducer.js`; mỗi lệnh (`CREATE_RESERVATION`, `CONFIRM_TRANSFER`, ...) +tương ứng một endpoint dưới đây, nên thay bằng lời gọi API là đủ. + +## 0. Hiện trạng nối API (VITE_USE_API=true) + +Giao diện đã gọi thật các endpoint backend đang có: auth, facilities / unit-types / rates / availability, +reservations, contracts (+ payments, renewals, handover), tickets. Những luồng dưới đây backend **chưa có** +nên giao diện tạm lưu trong trình duyệt theo từng tài khoản (mất khi đổi máy / xoá dữ liệu trình duyệt): +báo đã chuyển khoản, đăng ký trả kho + lịch trả kho, thông báo, đổi tên hiển thị, ảnh đính kèm hỗ trợ. +Đổi / quên mật khẩu đang khoá trên giao diện. + +Cách giao diện xử lý các điểm lệch hiện tại của backend: +- **Đăng nhập chỉ bằng Username** → khi khách đăng ký trên giao diện, `username` được đặt bằng email, nên khách + đăng nhập được bằng email như Figma. Tài khoản seed (`customer01`…) vẫn đăng nhập bằng username. +- **DateTime trả về không kèm múi giờ** (đọc từ DB) → giao diện coi là UTC. Nên cấu hình JSON trả kèm `Z`. +- **Giữ chỗ 24 giờ** ở backend, Figma là 01:00 → đơn tạo trên giao diện đếm ngược theo `VITE_PAYMENT_TIMEOUT_SECONDS`, + hết giờ thì gọi `POST /api/reservations/{id}/cancel`. Đơn tạo nơi khác theo `ExpiresAt` của backend. +- **Không có API báo đã chuyển khoản** → đơn vẫn `PENDING_PAYMENT` trên backend dù khách đã bấm. +- **Yêu cầu hỗ trợ bắt buộc ContractId** → khách chưa có hợp đồng không gửi được. `IssueType` = mã chủ đề + (`ACCESS`, `LOCK`, `UNIT`, `PAYMENT`, `ITEMS`, `SCHEDULE`, `OTHER`), `Title` theo chủ đề, `Priority` = `HIGH` / `NORMAL`. +- **Loại kho thật** (Mini S 1 m², M 4 m², L 9 m², XL 16 m²) hiển thị thành "Kho thường / Kiểm soát nhiệt độ" + + diện tích thật, lấy giá từ `/api/rates`. + +## 1. Luồng khác v3 (cần quyết định phía BE) + +| Điểm | Figma / giao diện hiện tại | Backend cũ (v3) | +|---|---|---| +| Thanh toán đặt chỗ | Khách chuyển khoản QR **ngay lúc đặt** (C04), bấm "Tôi đã chuyển khoản" → đơn "Chờ đối soát" | Đặt chỗ trước, thanh toán sau khi có hợp đồng | +| Giữ chỗ | Đơn chờ chuyển khoản **tự huỷ sau N giây** (Figma: 60 giây) → C04b | Không có | +| Số tiền chuyển | Tổng ban đầu = tiền thuê + cọc (cọc = 1 tháng) | — | +| Gói thuê | 1 / 3 / 6 tháng | 1–24 tháng tuỳ nhập | +| Đăng ký | Họ tên, email, SĐT, mật khẩu, xác nhận; **không có username** | Có `username` | +| Đăng nhập | "Tên đăng nhập **hoặc** email" | `username` | +| Hồ sơ | Khách chỉ sửa **tên**; email / SĐT chỉ đọc | Sửa cả email, SĐT | +| Hỗ trợ | Chủ đề + mô tả + ảnh đính kèm (không có tiêu đề) | Có `title` | +| Thanh toán & lịch hẹn | Một màn: lịch hẹn + **sổ khoản thu** (chỉ xem) | Danh sách thanh toán có nút báo chuyển khoản | + +## 2. Trạng thái UI dùng (khoá → nhãn) + +- **Reservation**: `PENDING_PAYMENT` Chờ chuyển khoản · `PENDING_VERIFICATION` Chờ đối soát · `CONFIRMED` Đã xác nhận · `CHECKED_IN` Đã nhận kho · `CANCELLED` Đã huỷ đặt chỗ (kèm `cancel_reason`) +- **Contract**: `ACTIVE`, `ENDED` lưu ở BE; `EXPIRING` (≤ 30 ngày) và `OVERDUE` UI tự suy ra từ `end_date` +- **Ledger (khoản thu)**: `RECONCILED` Đã đối soát · `PENDING_VERIFICATION` Chờ đối soát · `DEPOSIT_HELD` Đang giữ cọc · `RENEWAL_PENDING` Chờ duyệt yêu cầu · `UNPAID` Chưa thanh toán · `REFUNDED` +- **Appointment**: `kind` = `CHECK_IN` | `MOVE_OUT`; `status` = `CONFIRMED` | `PENDING` | `DONE` | `CANCELLED` +- **Ticket**: `OPEN` · `IN_PROGRESS` · `RESOLVED` · `CANCELLED`; `topic` = `ACCESS|LOCK|UNIT|PAYMENT|ITEMS|SCHEDULE|OTHER` +- **Renewal**: `PENDING` | `APPROVED` | `REJECTED` — **Return**: `PENDING` | `SCHEDULED` | `COMPLETED` + +## 3. Endpoint cần có + +| Màn | Endpoint đề xuất | Ghi chú | +|---|---|---| +| A01 | `POST /api/auth/login` `{identifier, password}` | Sai mật khẩu nên trả **400/422**, không phải 401 (UI coi 401 là hết phiên) | +| A02 | `POST /api/auth/register` `{fullName, email, phone, password}` | Tự gán role Customer; trả token + user | +| A01 | `POST /api/auth/forgot-password` `{email}` | Luôn trả 200 | +| C13 | `GET/PUT /api/auth/profile` | PUT chỉ nhận `fullName` | +| C13 | `POST /api/auth/change-password` `{currentPassword, newPassword}` | Sai mật khẩu hiện tại → 400 | +| C02, C03 | `GET /api/facilities?type=&band=&area=&camera=&sort=&page=` | Trả: `id, name, district, city, address, distanceKm, hours, camera, hasClimate, basePrice`. `distanceKm` cần vị trí khách hoặc tạm tính | +| C03b | `POST /api/quotes` `{facilityId, type, band, months, startDate}` | → `monthlyRate, rentTotal, deposit, initialTotal, endDate, available` | +| C03c | `GET /api/facilities/{id}/photos` | 4+ ảnh kèm chú thích (mặt tiền, sơ đồ, ...) | +| C04 | `POST /api/reservations` | Tạo đơn `PENDING_PAYMENT`, trả `reservationId, expiresAt, timeoutSeconds, transferAmount, transferContent` (UI tự tạo VietQR từ tài khoản nhận) | +| C04 | `POST /api/reservations/{id}/confirm-transfer` | → `PENDING_VERIFICATION`; sau `expiresAt` trả lỗi mã `EXPIRED` | +| C04b | (job nền) | Tự chuyển `PENDING_PAYMENT` quá hạn sang `CANCELLED`, `cancelReason` kiểu "Quá 1 phút chưa xác nhận" | +| C14, C05 | `GET /api/reservations`, `GET /api/reservations/{id}` | | +| C06, C07 | `GET /api/contracts`, `GET /api/contracts/{id}` | Thêm `unitNumber, sizeM2, location, handedOver, depositAmount` | +| C08 | `POST /api/contracts/{id}/renewals` `{months}` (1/3/6) | Trả 409 nếu đã có yêu cầu chờ | +| C09 | `POST /api/contracts/{id}/move-out` `{date, slot, note}` | Tạo `Appointment MOVE_OUT` trạng thái `PENDING` | +| C11 | `GET /api/appointments`, `GET /api/ledger` | Sổ khoản thu: `ref, label, amount, status, contractId?, reservationId?` | +| C12 | `GET/POST /api/tickets`, `POST /api/tickets/{id}/cancel` | POST là multipart: `contractId?, topic, description, files[≤3, ≤5MB, image/*]`; chỉ huỷ được khi `OPEN` | +| Popup | `GET /api/notifications`, `POST /api/notifications/read` `{ids?}` | `id, title, detail, to, createdAt, read` | + +## 4. Việc còn lại phía backend + +- Tài khoản nhận chuyển khoản đang cấu hình ở `.env` (`VITE_BANK_*`); nếu mỗi cơ sở nhận tiền riêng thì trả kèm theo đơn. +- Khoảng cách "Cách bạn X km" cần vị trí khách; hiện lấy từ dữ liệu cơ sở. +- Ảnh cơ sở đang là file tĩnh trong `public/images/`; khi có API ảnh (`GET /api/facilities/{id}/photos`), thay các hàm trong `src/config/media.js`. +- Đăng nhập nhân viên / quản lý / admin (Figma A01) thuộc các giao diện vai trò khác, chưa nằm trong gói này. +- Kho dữ liệu cục bộ lưu cả mật khẩu để đăng nhập được khi chưa có server; khi nối API, bỏ trường này. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md new file mode 100644 index 0000000..6f2e8d8 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md @@ -0,0 +1,36 @@ +# Đối chiếu Figma ↔ code + +Nguồn: file Figma "SafeSpace - Modern UI" (section Khách hàng + Trang chủ & tài khoản + các section tương tác). + +| Figma | Route | Component | Ghi chú | +|---|---|---|---| +| START Trang chủ | `#/home` | `pages/Home.jsx` | Hero tối, 3 điểm nổi bật, 12 cơ sở phân trang 9/trang, CTA đăng ký / đăng nhập | +| A01 Đăng nhập | `#/login` | `pages/Auth.jsx` | Trang riêng; "Quên mật khẩu?" mở hộp thoại; giữ `?next=` để quay lại | +| A02 Đăng ký | `#/register` | `pages/Auth.jsx` | Họ tên, email, SĐT, mật khẩu, xác nhận mật khẩu; tự vào vai trò Khách hàng | +| P01 Bảng giá | `#/pricing` | `pages/Public.jsx` | Giá "Từ" tính từ dữ liệu cơ sở | +| P02 Hướng dẫn | `#/guide` | `pages/Public.jsx` | Accordion +/− | +| C01 Dashboard | `#/overview` | `pages/Overview.jsx` | 3 số liệu, kho đang thuê, hành động nhanh, mốc sắp tới, hoạt động | +| C02 Tìm & đặt kho | `#/find` | `pages/FindList.jsx` | Hiện tất cả cơ sở; lọc loại kho / diện tích / khu vực; chip; sắp xếp; phân trang | +| C02a–f, C03 | `#/find?type=&band=&area=` | `pages/FindList.jsx` | Các trạng thái chọn + kết quả lọc + trail 01→04 | +| C03b, C03b-1..3 | `#/find/:id` | `pages/FacilityDetail.jsx` | Loại kho, diện tích, gói 1/3/6 tháng, lịch chọn ngày, chi phí | +| C03c-1..4 | (lightbox) | `components/Photo.jsx` | 6 ảnh: ảnh cơ sở, 4 ảnh bên trong kho, sơ đồ mặt bằng ở cuối; ← → / Esc | +| C04 Đặt chỗ & Thanh toán | `#/checkout/:id` | `pages/Checkout.jsx` | Mã VietQR thật, số tiền, nội dung CK, đếm ngược, "Tôi đã chuyển khoản" | +| C04b Không thành công | `#/checkout/:id/failed` | `pages/Checkout.jsx` | Hết giờ → đơn tự huỷ, kể cả khi đã đóng tab | +| C05 Xác nhận | `#/confirmation/:id` | `pages/Checkout.jsx` | "Chờ đối soát thanh toán" | +| C06 Kho của tôi | `#/units` | `pages/Units.jsx` | | +| C07 / C07b Hợp đồng | `#/units/:id` | `pages/Units.jsx` | Nút gia hạn / trả kho bị khoá khi đang có yêu cầu chờ | +| C08 / C08b Gia hạn | `#/units/:id/renew` | `pages/Units.jsx` | Chọn 1/3/6 tháng | +| C09 / C09b Trả kho | `#/units/:id/return` | `pages/Units.jsx` | Ngày (lịch), khung giờ, ghi chú, đối chiếu cọc | +| C10 Yêu cầu đã gửi | `#/sent?type=&contract=` | `pages/Units.jsx` | | +| C11 Thanh toán & lịch hẹn | `#/payments` | `pages/Payments.jsx` | Thẻ lịch hẹn + bảng khoản thu; "Cần đổi lịch?" mở form hỗ trợ đúng chủ đề | +| C12 Hỗ trợ | `#/support` | `pages/Support.jsx` | Có ảnh đính kèm (tối đa 3, 5 MB); danh sách yêu cầu bên phải | +| C13, C13a–d, toast | `#/profile` | `pages/Profile.jsx` | Chỉ sửa tên; email / SĐT chỉ đọc (SĐT che bớt); hộp thoại "Đã hiểu" | +| C14 Đơn đặt chỗ | `#/reservations`, `#/reservations/:id` | `pages/Reservations.jsx`, `pages/Checkout.jsx` | | +| Popup thông báo (public / customer, đã đọc) | (header) | `components/Header.jsx` | | + +## Chỗ Figma tự mâu thuẫn, code chọn như sau +- C04 ghi cần chuyển 3.450.000 đ nhưng C03b/C14 ghi "Tổng ban đầu" 4.600.000 đ → chuyển **4.600.000 đ** (tiền thuê + cọc). +- C03c ghi "x trên 4" → thư viện hiện **6 ảnh** (ảnh cơ sở + 4 ảnh bên trong + sơ đồ). +- C01 nói đã gửi gia hạn B-015 nhưng vẫn có nút "Gửi yêu cầu gia hạn" → dữ liệu khởi tạo chưa có yêu cầu gia hạn. +- Figma không có màn cho: chi tiết đơn, huỷ yêu cầu hỗ trợ, trạng thái rỗng → dựng theo cùng phong cách. +- Figma có 12 cơ sở nhưng chỉ vẽ 9 thẻ; 3 cơ sở trang 2 (Gò Vấp, Tân Bình, Bình Tân) dùng lại ảnh Bình Thạnh, Tân Thuận, Bình Chánh. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md index 35f12fd..0668555 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md @@ -1,178 +1,74 @@ -# SafeSpace — Frontend Customer (React + Vite) +# SafeSpace — Giao diện khách hàng -Module Customer có giao diện và thao tác frontend, xây theo ảnh SafeSpace và video bạn cung cấp. Chưa có source đăng nhập của nhóm để merge trực tiếp. Bản này chạy độc lập và có thể đưa vào project React hiện tại; không thay thế trang đăng nhập đã làm. +React + Vite, bám theo file Figma **SafeSpace - Modern UI**: Trang chủ, Đăng nhập, Đăng ký, Bảng giá, +Hướng dẫn và toàn bộ luồng khách hàng C01–C14 (kèm C03b/C03c/C04b, popup thông báo, các trạng thái C13). -## Chạy ngay +## Chạy cùng backend (khuyến nghị) -**Xem nhanh, không cài đặt:** mở `SafeSpace-Customer-Preview.html` bằng Chrome/Edge. Toàn bộ mã và font đã nhúng trong file. Đây là bản demo tương tác, không chỉ là ảnh. Nếu trình xem file của ứng dụng chặn JavaScript, tải file về máy rồi mở bằng trình duyệt. - -**Code và chạy dev:** dùng Node.js 22.12+ (khuyến nghị Node 24). +1. Chạy backend ở thư mục gốc repo: `dotnet run --project StorageProject.Api --launch-profile http` → `http://localhost:5151` +2. Chạy giao diện: ```bash +cd SafeSpace-Customer-UI/SafeSpace-Customer-UI npm ci -npm run dev +copy .env.example .env.local # macOS/Linux: cp .env.example .env.local +npm run dev # http://127.0.0.1:5173 ``` -Mở URL localhost do Vite in ra. Đường dẫn mặc định: `#/customer/overview`. - -```bash -npm run build -npm run preview -npm test -``` - -`dist/` là bản build sẵn. Không mở trực tiếp `dist/index.html` bằng `file://` vì đây là build có ES module; dùng `npm run preview`. Muốn mở file trực tiếp, dùng bản Preview ở trên. - -## Phạm vi đã code - -| Trang / luồng | URL trong module | Thao tác có thể demo | -| ----------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------ | -| Tổng quan Customer | `#/customer/overview` | Số kho, khoản cần trả, lịch hẹn, nhắc gia hạn, liên kết nhanh | -| Tìm cơ sở / loại kho | `#/customer/find` | Lọc cơ sở, kích thước, giá; kiểm tra ngày và kỳ thuê; empty state | -| Chi tiết cơ sở | `#/customer/find/1` | Địa chỉ, giờ hỗ trợ, bảng giá, diện tích, kích thước, chọn loại kho | -| Đặt kho | Modal từ trang tìm / chi tiết | Ngày thuê, số tháng, dự toán tiền thuê và cọc; xác nhận; tạo đơn | -| Danh sách đơn đặt | `#/customer/reservations` | Lọc trạng thái, xem đơn | -| Chi tiết đơn đặt | `#/customer/reservations/DC-2026-004` | Tiến độ phân bổ, kỳ thuê, dự toán; hủy đơn chưa phân bổ có lý do | -| Kho của tôi | `#/customer/units` | Nhiều kho / hợp đồng; lọc đang sử dụng, chờ nhận, hoàn tất | -| Chi tiết kho / hợp đồng | `#/customer/units/HD-2026-001` | Giá thuê, ngày kết thúc, cọc, lịch sử gia hạn, thanh toán liên quan | -| Gia hạn | Modal trong chi tiết kho | Chọn số tháng, tính dự kiến, gửi yêu cầu chờ duyệt, chống gửi trùng | -| Trả kho | Modal trong chi tiết kho | Chọn ngày, ghi chú, xác nhận; chuyển sang chờ kiểm tra | -| Thanh toán | `#/customer/payments` | Khoản cần trả, đã trả, chờ xác minh; lọc theo hợp đồng | -| Chi tiết / gửi thông báo thanh toán | `#/customer/payments/TT-2026-008` | Chuyển khoản hoặc tiền mặt; gửi thông báo mẫu; chặn gửi trùng | -| Lịch nhận kho / bàn giao | `#/customer/appointments` | Xem lịch, điều kiện nhận, biên bản; chỉ xác nhận sau khi nhân viên đã kiểm tra | -| Yêu cầu hỗ trợ | `#/customer/support` | Danh sách, lọc đang xử lý / đã giải quyết | -| Tạo yêu cầu hỗ trợ | `#/customer/support/new` | Chọn hợp đồng, loại vấn đề, nhập nội dung và gửi | -| Chi tiết hỗ trợ | `#/customer/support/HT-2026-012` | Nội dung, loại vấn đề, hợp đồng và tiến độ xử lý | -| Hồ sơ cá nhân | `#/customer/profile` | Sửa họ tên, điện thoại; kiểm tra dữ liệu; email chỉ đọc | +`.env.local` mặc định đã bật `VITE_USE_API=true`. Tài khoản có sẵn trong backend: `customer01` / `Customer@123` +(đăng nhập bằng **tên đăng nhập**). Khách đăng ký mới trên giao diện đăng nhập bằng **email**. -Các trang có bố cục responsive. Menu bên trái đổi thành drawer trên điện thoại; bảng có vùng cuộn ngang riêng. Có trạng thái chưa có dữ liệu, thông báo thành công/lỗi, label cho input, focus modal và phím Escape. +## Chạy không cần backend -## Nhận xét từ video và ảnh +Đặt `VITE_USE_API=false` (hoặc không tạo `.env.local`): dữ liệu lưu trong trình duyệt, tài khoản có sẵn +`mai.nguyen@example.com` / `SafeSpace@123`. Dùng khi chỉ cần xem giao diện. -- Đầu video thấy terminal **Vite v8.3.0**, các file `src/App.jsx`, `src/index.css`; cách dùng state là React. Vì vậy module dùng React + CSS, không thêm UI framework hay React Router. -- Khoảng giây 20–30: form đăng ký dạng modal trắng, nút xanh, label trên input; lỗi viền đỏ và thông báo bên dưới. Module đặt kho / gia hạn / hỗ trợ giữ cách phản hồi này. -- Khoảng giây 40–100: bộ tìm kiếm có cơ sở, loại kho, ngày bắt đầu, số tháng; video minh họa kiểm tra ngày và kỳ thuê. Module kiểm tra hai trường này trước khi tạo yêu cầu. -- Ảnh cung cấp chốt nhận diện **SafeSpace**: trắng, navy, xanh dương, card bo góc, search panel nổi ở chân hero. Các trang Customer kế thừa cùng hệ màu, khoảng cách và loại nút. -- Font chính xác không thể xác định chỉ qua video. Bản code chọn **Inter**, nhúng font tiếng Việt để hiển thị ổn định. Icon và minh họa kho là SVG cục bộ, không phụ thuộc ảnh mạng hoặc ảnh lỗi trong mẫu. -- Kích thước Small/Medium/Large theo video lần lượt **5 / 12 / 20 m²**, giá mẫu **500.000 / 1.200.000 / 2.000.000 đ/tháng** tại hai cơ sở đầu. Ảnh tĩnh có thông số khác, nên `src/data.js` gom tất cả để nhóm sửa theo dữ liệu cuối cùng. -- Header SafeSpace giữ nhận diện ảnh; sidebar là phần bổ sung cho khu vực đã đăng nhập. Video không cho thấy bộ trang Customer hoàn chỉnh, nên cách tổ chức các trang này được thiết kế từ chức năng giáo viên giao. +## Luồng nào gọi backend -## Ghép vào phần đăng nhập của nhóm +| Luồng | Chế độ API | +|---|---| +| Đăng ký, đăng nhập, đăng xuất | `POST /api/auth/register · login · logout` | +| Cơ sở, loại kho, bảng giá, kiểm tra kho trống | `GET /api/facilities · unit-types · rates`, `POST /api/availability/check` | +| Tạo / xem / huỷ đơn đặt chỗ, hết giờ giữ chỗ tự huỷ | `/api/reservations` | +| Hợp đồng, khoản thu, lịch nhận kho, xác nhận bàn giao | `/api/contracts`, `/api/handovers/{id}/confirm` | +| Gia hạn | `POST /api/contracts/{id}/renewals` | +| Yêu cầu hỗ trợ (gửi, xem, huỷ) | `/api/tickets` | +| Báo "Tôi đã chuyển khoản", đăng ký trả kho, thông báo, đổi tên hiển thị, ảnh đính kèm hỗ trợ | Backend **chưa có API** → lưu trong trình duyệt theo từng tài khoản | +| Đổi mật khẩu, quên mật khẩu | Backend chưa có API → giao diện hướng dẫn liên hệ quản trị viên | -### 1. Chép module +Khi backend bổ sung API cho các dòng cuối, chỉ cần sửa `src/state/store.jsx` (nhánh `ApiProvider`), xem `BE-CONTRACT.md`. -Chép các file sau từ `src/` của gói này vào `src/customer/` trong project nhóm, giữ cấu trúc tương đối: - -- `CustomerApp.jsx`, `customer.css`, `context.js`, `data.js`, `domain.js` -- thư mục `components/`, `pages/` - -Không ghi đè `App.jsx`, `main.jsx`, `index.css`, `package.json` hoặc `package-lock.json` của project nhóm. - -Nếu nhóm đã có React/ReactDOM, chỉ thêm font: +## Kiểm tra ```bash -npm install @fontsource/inter +npm test # 25 test: nghiệp vụ, VietQR, chuyển đổi dữ liệu backend (theo seed thật) +npm run test:render # render 38 route, bắt lỗi runtime, NaN, undefined +npm run build # xuất bản dist/ (đường dẫn tương đối, đặt được ở thư mục con) ``` -Module dùng các React hook thông thường và `useId` (React 18+). Bản chạy độc lập đã được build với phiên bản khóa trong `package-lock.json` của gói này. Không cần nâng phiên bản project nhóm chỉ để copy UI. - -### 2. Hiển thị Customer sau đăng nhập thành công +## Ảnh -Ví dụ cách đặt vào `App.jsx` hiện tại — đây là đoạn minh họa tích hợp, không phải thay toàn bộ component của nhóm: +Toàn bộ ảnh nằm sẵn trong `public/images/` (đã nén JPG, tổng ~3,9 MB): ảnh hero trang chủ, ảnh mặt tiền +9 cơ sở, 4 ảnh bên trong kho và 3 sơ đồ mặt bằng. Khi bấm xem một cơ sở, thư viện ảnh gồm ảnh cơ sở, +4 ảnh bên trong kho và 1 sơ đồ ở cuối (mỗi cơ sở được gán một trong 3 sơ đồ). Chi tiết ở +`public/images/README.md`; đổi cách gán ảnh ở `src/config/media.js`. -```jsx -import { useState } from "react"; -import CustomerApp from "./customer/CustomerApp"; +## Thanh toán -function App() { - const [showCustomer, setShowCustomer] = useState(false); +Màn C04 tạo mã **VietQR** (chuẩn NAPAS 247) từ tài khoản trong `.env`, số tiền và mã đặt chỗ làm nội dung +chuyển khoản; ứng dụng ngân hàng quét là điền sẵn cả ba. Đơn tự huỷ khi hết thời gian giữ chỗ +(`VITE_PAYMENT_TIMEOUT_SECONDS`), kể cả khi khách đã đóng trang. - // Giữ TOÀN BỘ hook khác của nhóm trước mọi conditional return. - // Trong nhánh xử lý đăng nhập thành công đang có: - // setShowCustomer(true); - // window.location.hash = '/customer/overview'; - // Chỉ làm điều này sau khi xác thực xong nếu đã có backend. +## Cấu trúc - if (showCustomer) { - return ( - { - // Gọi logic đăng xuất hiện tại của nhóm nếu đã có. - setShowCustomer(false); - window.location.hash = ""; - }} - /> - ); - } - - // return JSX trang chủ / modal đăng nhập hiện có của nhóm; -} ``` - -- `showCustomer` chỉ là cờ chuyển màn hình để demo. Không coi cờ React hoặc hash URL là xác thực/phân quyền. -- Không tạo thêm `createRoot()` khi ghép; chỉ import component như trên. -- Không truyền thông tin đăng nhập thật vào dữ liệu demo. Hồ sơ Nguyễn Minh Anh là nhân vật mẫu, chưa phải người dùng lấy từ login/API. -- CSS được scope dưới `.ss-app` để hạn chế ảnh hưởng form đăng nhập. Module có header riêng; khi hiển thị Customer, không render thêm header công khai ở bên ngoài. -- Module hiện tự đọc hash `#/customer/...`. Nếu project đang dùng `HashRouter`, cần chuyển các đường dẫn sang router của nhóm trước khi ghép; không mount hai hash router cùng lúc. -- Khi chưa truyền `onLogout`, nút Đăng xuất hiển thị thông báo chưa nối phần đăng nhập. Khi ghép, callback phải gọi logic logout thực tế của nhóm. - -## Cấu trúc source - -| File | Vai trò | -| -------------------------------- | ------------------------------------------------------------------------------- | -| `src/CustomerApp.jsx` | Layout, header/sidebar, điều hướng hash, state demo, thông báo, callback logout | -| `src/customer.css` | Toàn bộ style Customer, design tokens, responsive | -| `src/components/UI.jsx` | Button, Field, Badge, Modal, card primitives, SVG icon/minh họa | -| `src/components/ActionModal.jsx` | Form đặt kho, hủy, thanh toán, gia hạn, trả kho, xác nhận bàn giao | -| `src/pages/Overview.jsx` | Dashboard và card kho dùng chung | -| `src/pages/FindStorage.jsx` | Tìm kho và chi tiết cơ sở | -| `src/pages/Records.jsx` | Đơn đặt, kho/hợp đồng, thanh toán, lịch nhận | -| `src/pages/Support.jsx` | Hỗ trợ và hồ sơ | -| `src/data.js` | Toàn bộ dữ liệu mẫu | -| `src/domain.js` | Format tiền/ngày, tính tháng, kiểm tra và lệnh Customer | -| `tests/domain.test.js` | Kiểm tra các quy tắc quan trọng | -| `preview/` | Ảnh chụp thật từ trình duyệt và kết quả kiểm tra UI | - -Đổi màu: các biến `--ss-primary`, `--ss-navy`, `--ss-bg` ở đầu `customer.css`. Đổi tên thương hiệu: phần `.ss-brand` trong `CustomerApp.jsx`. Đổi giá, diện tích, cơ sở: `data.js`. - -## Ranh giới demo và phần backend cần nối - -Bản này là **frontend UI có tương tác**, không phải hệ thống cho thuê hoàn chỉnh. State được lưu bằng `localStorage`, chỉ trên trình duyệt đang dùng. Có nút “Đặt lại dữ liệu mẫu” và hộp thoại xác nhận. Ngày của dữ liệu mới được tạo tương đối theo ngày mở demo, không cố định ngày quá khứ. Khi dữ liệu đã lưu, ngày trong mẫu giữ nguyên cho đến khi reset. - -Tên trường chính bám Data Dictionary: `reservation_id`, `facility_id`, `unit_type_id`, `start_date`, `rental_period_months`, `contract_id`, `payment_id`, `issue_type`… Các quy tắc: - -1. Đặt theo cơ sở + loại kho. Tạo reservation `PENDING_PAYMENT` và hiển thị “Chờ phân bổ” trong giai đoạn chưa có assignment/hợp đồng. Không tự tạo số kho, hợp đồng hoặc nghĩa vụ thanh toán từ browser. -2. Mức cọc 1 tháng và giới hạn 1–24 tháng là **giả định cho demo**, không phải chính sách đã xác nhận. Giá trên màn hình là dự toán. -3. Filter giá/cơ sở/kích thước hoạt động thực. Số lượng khả dụng là fixture, **chưa kiểm tra chồng lấn ngày thuê**. Khi nối API phải kiểm tra cả khoảng `[start_date, expected_end_date)` và giữ chỗ có thời hạn tại server. -4. Gia hạn tạo `PENDING`; không đổi `end_date` khi khách gửi. Cần manager duyệt, áp dụng giá, tạo khoản phí và xác nhận `PAID` trước khi cập nhật hợp đồng. -5. Khách gửi thông báo chuyển khoản/tiền mặt chỉ giữ payment `PENDING`. Bản demo không có tài khoản ngân hàng nhận tiền, QR thanh toán, hay kết nối cổng thanh toán. -6. `paymentNotices` là state UI riêng, không phải enum thanh toán mới trong database. “Chờ xác minh” là nhãn hiển thị, không gửi thành giá trị `payments.status`. -7. `returnRequests` là state UI cho yêu cầu trả kho, chưa có bảng riêng trong Data Dictionary. Khi nối backend, thống nhất API cập nhật hợp đồng/audit và để nhân viên tạo `return_inspections`. Không ghi `PENDING` của view này vào enum `return_inspections.status` (bảng đó dùng `SCHEDULED`, `IN_PROGRESS`, `COMPLETED`, `CANCELLED`). Không tự hoàn tiền cọc hoặc đánh dấu kho AVAILABLE. -8. Chỉ khách xác nhận phần `customer_confirmed` sau khi nhân viên đã kiểm tra; không tự đặt `staff_confirmed`, kích hoạt hợp đồng hay bàn giao khóa. Dữ liệu mẫu có một lịch chưa kiểm tra và một biên bản đã hoàn tất. -9. Đơn chưa phân bổ có thể hủy trực tiếp trong demo. Đơn đã phân bổ/xác nhận chuyển sang hỗ trợ để cơ sở xử lý theo chính sách, tránh tự hủy khoản phí hoặc hợp đồng liên quan. -10. Support chọn hợp đồng thuộc khách hàng và suy ra unit tương ứng. Không có file đính kèm, chat thread hoặc feedback rating vì Data Dictionary hiện tại chưa có cấu trúc cho các phần đó. -11. Hồ sơ chỉ thay họ tên và điện thoại trong demo. Đổi email, mật khẩu, xác thực, quyền truy cập, phân trang, cập nhật thời gian thực và quyền theo customer phải nối hệ thống thật. -12. Kiểm tra trong `domain.js` giúp UI phản hồi; **mọi kiểm tra quan trọng phải lặp lại ở server**, đặc biệt ownership, khả dụng, tiền và trạng thái. - -Điểm thay mock: `command()` trong `CustomerApp.jsx` hiện gọi `reduceCustomer()`. Khi nối API, chuyển command thành async service, lấy dữ liệu mới từ server; thêm trạng thái loading/disabled và xử lý lỗi request. Không đồng bộ nguyên object localStorage vào database. Các collections `facilities`, `unitTypes`, `rates`, `units`, `contracts`, `payments`, `handovers`, `tickets`, `renewals` sẽ nhận dữ liệu API thay cho `createDemoData()`. - -## Kịch bản demo ngắn - -1. Tổng quan → Tìm & đặt kho → lọc cơ sở/loại/giá → Đặt chỗ → nhập kỳ thuê → đồng ý → gửi. Xem đơn “Chờ phân bổ”. -2. Tại chi tiết đơn mới → Hủy đơn → nhập lý do → xác nhận. -3. Thanh toán → khoản TT-2026-008 → Thanh toán → chọn phương thức → gửi thông báo mẫu. Trạng thái chuyển sang nhãn “Chờ xác minh”, không phải “Đã thanh toán”. -4. Kho A-102 → gia hạn 3 tháng → gửi → xem lịch sử chờ duyệt; ngày kết thúc chưa thay đổi. -5. Kho B-015 → yêu cầu trả kho → chọn ngày → xác nhận → xem trạng thái “Chờ trả kho”. -6. Yêu cầu hỗ trợ → tạo yêu cầu → chọn hợp đồng, nhập nội dung → xem tiến độ mới gửi. -7. Hồ sơ → thử số điện thoại sai rồi sửa đúng → lưu. Reload để kiểm tra dữ liệu được giữ lại. -8. Thu nhỏ trình duyệt về điện thoại → mở menu → kiểm tra điều hướng, form, bảng cuộn ngang. - -## Kiểm tra đã thực hiện - -- `npm run build`: build production thành công. -- `npm test`: 9 bài kiểm tra về tháng lịch, ngày thuê, đặt kho, thanh toán, gia hạn, trả kho, bàn giao, support và hủy đơn. -- Kết quả chạy trình duyệt và phạm vi viewport được ghi trong `preview/browser-checks.json`. -- Ảnh trong `preview/` là ảnh render thật của frontend, không phải bản vẽ wireframe. - -Chưa kiểm thử trên Safari/iOS thật và chưa thể kiểm tra ghép với source nhóm vì source đó chưa được cung cấp. +src/ + CustomerApp.jsx router + chặn trang cần đăng nhập + pages/ mỗi màn Figma một component (xem CUSTOMER-FLOW-COVERAGE.md) + components/ Header + thông báo, lịch chọn ngày, thư viện ảnh, mã QR, UI dùng chung + state/reducer.js nghiệp vụ (thuần, có test) + state/store.jsx phiên đăng nhập; 2 chế độ: dữ liệu trong trình duyệt / API backend + api/ gọi API (http.js, endpoints.js) + chuyển dữ liệu backend → giao diện (mappers.js) + data/seed.js dữ liệu khởi tạo: 12 cơ sở, khách hàng Nguyễn Thị Mai + config/ địa chỉ API, ảnh, tài khoản nhận chuyển khoản +``` diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/SafeSpace-Customer-Preview.html b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/SafeSpace-Customer-Preview.html deleted file mode 100644 index 2cfd006..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/SafeSpace-Customer-Preview.html +++ /dev/null @@ -1,160 +0,0 @@ - -SafeSpace · Khách hàng - -
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/THIRD-PARTY-NOTICES.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/THIRD-PARTY-NOTICES.md index 406fe6e..edd45d7 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/THIRD-PARTY-NOTICES.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/THIRD-PARTY-NOTICES.md @@ -145,3 +145,22 @@ 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. + +## qrcode + +Version: 1.5.4 +License: MIT +Repository: https://github.com/soldair/node-qrcode + +``` +The MIT License (MIT) + +Copyright (c) 2012 Ryan Day + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +``` diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package-lock.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package-lock.json index 0452deb..881f486 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package-lock.json +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package-lock.json @@ -9,6 +9,7 @@ "version": "1.0.0", "dependencies": { "@fontsource/inter": "^5.3.0", + "qrcode": "^1.5.4", "react": "^19.3.0", "react-dom": "^19.3.0" }, @@ -300,6 +301,77 @@ "dev": true, "license": "MIT" }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -310,6 +382,18 @@ "node": ">=8" } }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -328,6 +412,19 @@ } } }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -343,6 +440,24 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", @@ -604,6 +719,18 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/nanoid": { "version": "3.3.19", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", @@ -623,6 +750,51 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -643,6 +815,15 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/postcss": { "version": "8.5.28", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", @@ -672,6 +853,23 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/react": { "version": "19.3.0", "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", @@ -693,6 +891,21 @@ "react": "^19.3.0" } }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/rolldown": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz", @@ -733,6 +946,12 @@ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", "license": "MIT" }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -743,6 +962,32 @@ "node": ">=0.10.0" } }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -837,6 +1082,67 @@ "optional": true } } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } } } } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json index 2f6f2c5..c2c0135 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json @@ -7,10 +7,12 @@ "dev": "vite --host 127.0.0.1", "build": "vite build --base=./", "preview": "vite preview --host 127.0.0.1", - "test": "node --test tests/domain.test.js" + "test": "node --test tests/reducer.test.js tests/api-mappers.test.js", + "test:render": "node tests/render.test.mjs" }, "dependencies": { "@fontsource/inter": "^5.3.0", + "qrcode": "^1.5.4", "react": "^19.3.0", "react-dom": "^19.3.0" }, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/booking.png b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/booking.png deleted file mode 100644 index a963de8..0000000 Binary files a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/booking.png and /dev/null differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/browser-checks.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/browser-checks.json deleted file mode 100644 index 64b43e2..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/browser-checks.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "passed": [ - "14 routes at 1440px: render + no page overflow", - "14 routes at 390px: render + no page overflow", - "14 routes at 768px: render + no page overflow", - "Combined search filters + empty result", - "Booking validation, submit, awaiting assignment, reload persistence", - "Cancel unassigned reservation", - "Payment notice stays PENDING and disables duplicate submission", - "Renewal pending, unchanged contract end, duplicate guard", - "Return request pending inspection", - "Support creation, contract binding, escaped user content", - "Customer handover gated by staff verification", - "Profile validation and saved update", - "Mobile menu navigation + modal + Escape", - "No browser console errors or uncaught runtime exceptions", - "Offline HTML: file://, zero external network requests, desktop/mobile booking, field errors clear on edit" - ], - "errors": [] -} \ No newline at end of file diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/find.png b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/find.png deleted file mode 100644 index 55ee134..0000000 Binary files a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/find.png and /dev/null differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-booking.png b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-booking.png deleted file mode 100644 index 396e936..0000000 Binary files a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-booking.png and /dev/null differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-find.png b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-find.png deleted file mode 100644 index a72ec72..0000000 Binary files a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-find.png and /dev/null differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-overview.png b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-overview.png deleted file mode 100644 index f211e27..0000000 Binary files a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/mobile-overview.png and /dev/null differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/overview.png b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/overview.png deleted file mode 100644 index 63f0842..0000000 Binary files a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/overview.png and /dev/null differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/units-HD-2026-001.png b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/units-HD-2026-001.png deleted file mode 100644 index 8d953f9..0000000 Binary files a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/preview/units-HD-2026-001.png and /dev/null differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/README.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/README.md new file mode 100644 index 0000000..768f66f --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/README.md @@ -0,0 +1,10 @@ +# Ảnh giao diện + +| File | Dùng ở | +|---|---| +| `hero.jpg` | Ảnh lớn trang chủ (hành lang bên trong cơ sở) | +| `facilities/kho-1.jpg` … `kho-9.jpg` | Ảnh mặt tiền từng cơ sở theo thứ tự: Nguyễn Lương Bằng, Him Lam, Phú Xuân, Tân Thuận, Phú Mỹ Hưng, Bình Thạnh, Nhà Bè, Bình Chánh, Thủ Đức | +| `inside/ben-trong-1.jpg` … `4.jpg` | 4 ảnh bên trong kho, dùng chung trong thư viện ảnh mọi cơ sở | +| `plans/so-do-1.jpg` … `3.jpg` | 3 sơ đồ mặt bằng; mỗi cơ sở được gán một sơ đồ (ảnh cuối trong thư viện) | + +Đổi ảnh: thay file cùng tên (JPG, rộng ~1400 px, dưới 350 KB). Thêm cơ sở / đổi cách gán ảnh: `src/config/media.js`. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-1.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-1.jpg new file mode 100644 index 0000000..bac3bec Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-1.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-2.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-2.jpg new file mode 100644 index 0000000..45cf815 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-2.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-3.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-3.jpg new file mode 100644 index 0000000..ecac406 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-3.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-4.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-4.jpg new file mode 100644 index 0000000..d3895ee Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-4.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-5.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-5.jpg new file mode 100644 index 0000000..68959c4 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-5.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-6.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-6.jpg new file mode 100644 index 0000000..7bcc177 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-6.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-7.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-7.jpg new file mode 100644 index 0000000..0e4e743 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-7.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-8.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-8.jpg new file mode 100644 index 0000000..d7fbe96 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-8.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-9.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-9.jpg new file mode 100644 index 0000000..a32c6e0 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/facilities/kho-9.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/hero.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/hero.jpg new file mode 100644 index 0000000..b38522d Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/hero.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-1.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-1.jpg new file mode 100644 index 0000000..76af829 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-1.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-2.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-2.jpg new file mode 100644 index 0000000..1f5840e Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-2.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-3.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-3.jpg new file mode 100644 index 0000000..c3904c7 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-3.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-4.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-4.jpg new file mode 100644 index 0000000..fea83d4 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/inside/ben-trong-4.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-1.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-1.jpg new file mode 100644 index 0000000..4e6c491 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-1.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-2.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-2.jpg new file mode 100644 index 0000000..5b29202 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-2.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-3.jpg b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-3.jpg new file mode 100644 index 0000000..b295fb3 Binary files /dev/null and b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/public/images/plans/so-do-3.jpg differ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/build-preview.py b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/build-preview.py deleted file mode 100644 index 853d6c5..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/build-preview.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Create an offline, single-file preview from an already-built Vite dist folder. -Run: npm run build && python3 scripts/build-preview.py -""" -from pathlib import Path -import re, base64 -root = Path(__file__).resolve().parents[1] -dist = root / 'dist' -page = (dist / 'index.html').read_text() -css_ref = re.search(r']+href="([^"]+\.css)"[^>]*>', page) -js_ref = re.search(r']+src="([^"]+\.js)"[^>]*>', page) -css_path = dist / css_ref.group(1).removeprefix('./') -css = css_path.read_text() -def font_data(match): - relative = match.group(1).strip('"\'') - if relative.startswith('data:'): - return match.group(0) - path = (css_path.parent / relative).resolve() - encoded = base64.b64encode(path.read_bytes()).decode() - mime = 'font/woff2' if path.suffix == '.woff2' else 'font/woff' - return f'url("data:{mime};base64,{encoded}")' -css = re.sub(r'url\(([^)]+)\)', font_data, css) -js = (dist / js_ref.group(1).removeprefix('./')).read_text() -js = re.sub(r'' + css + '') -page = page.replace(js_ref.group(0), '') -page = page.replace('', '') -licenses = [] -for pkg in ['react', 'react-dom', '@fontsource/inter']: - path = root / 'node_modules' / pkg / 'LICENSE' - if path.exists(): - licenses.append(f'## {pkg}\n\n' + path.read_text()) -if licenses: - notice = '# Third-party licenses\n\n' + '\n\n'.join(licenses) - (root / 'THIRD-PARTY-NOTICES.md').write_text(notice) - page = page.replace('', '') -output = root / 'SafeSpace-Customer-Preview.html' -output.write_text(page) -print(f'Created {output.name} ({output.stat().st_size:,} bytes)') diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx index 0c3f385..b2386f4 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx @@ -8,658 +8,139 @@ import "@fontsource/inter/latin-700.css"; import "@fontsource/inter/vietnamese-700.css"; import "@fontsource/inter/latin-800.css"; import "@fontsource/inter/vietnamese-800.css"; -import React, { useState, useEffect, useCallback, useRef } from "react"; -import { CustomerContext } from "./context"; -import { createDemoData } from "./data"; -import { reduceCustomer } from "./domain"; -import { Icon, Empty, LinkButton, Button, Modal } from "./components/UI"; -import ActionModal from "./components/ActionModal"; -import AuthModal from "./components/AuthModal"; +import "./styles/ss.css"; +import React, { useEffect } from "react"; +import Header from "./components/Header"; +import { Button, Empty, Icon, LinkButton } from "./components/UI"; +import { go, href, parseRoute, useRoute } from "./lib/router"; +import { Login, Register } from "./pages/Auth"; +import { Checkout, CheckoutFailed, ReservationSummary } from "./pages/Checkout"; +import FacilityDetail from "./pages/FacilityDetail"; +import FindList from "./pages/FindList"; +import Home from "./pages/Home"; import Overview from "./pages/Overview"; -import FindStorage from "./pages/FindStorage"; -import { Reservations, Units, Payments, Appointments } from "./pages/Records"; -import Support, { Profile } from "./pages/Support"; -import { - authService, - authStorage, - facilityService, - reservationService, - contractService, - renewalService, - supportService, -} from "./services"; -import { - mapFacilityFromApi, - mapUnitTypeFromApi, - mapRateFromApi, - mapReservationFromApi, - mapContractFromApi, - mapTicketFromApi, - mapHandoverFromApi, - mapPaymentFromApi, -} from "./services/adapters"; -import "./customer.css"; - -const NAV = [ - ["overview", "grid", "Tổng quan"], - ["find", "search", "Tìm & đặt kho"], - ["units", "box", "Kho của tôi"], - ["reservations", "file", "Đơn đặt kho"], - ["payments", "card", "Thanh toán"], - ["appointments", "calendar", "Lịch nhận kho"], - ["support", "help", "Yêu cầu hỗ trợ"], -]; - -const VERSION = 1; - -function readData(storageKey) { - try { - const saved = JSON.parse(localStorage.getItem(storageKey)); - if ( - saved?.version === VERSION && - saved.data?.user && - Array.isArray(saved.data?.contracts) && - saved.data?.paymentNotices - ) - return saved.data; - } catch { - /* Storage unavailable: keep demo in memory. */ - } - return createDemoData(); -} - -export default function CustomerApp({ - onLogout, - storageKey = "safespace.customer.demo.v1", -}) { - const [data, setData] = useState(() => readData(storageKey)); - const dataRef = useRef(data); - dataRef.current = data; - - const [authUser, setAuthUser] = useState(() => authService.getCurrentUser()); - const [authModalOpen, setAuthModalOpen] = useState(false); - const [isLiveApi, setIsLiveApi] = useState(false); - const [loading, setLoading] = useState(false); - - const [route, setRoute] = useState( - window.location.hash || "#/customer/overview", - ); - const [mobile, setMobile] = useState(false); - const [modal, setModal] = useState(null); - const [toast, setToast] = useState(null); - const [storageError, setStorageError] = useState(false); - const [resetOpen, setResetOpen] = useState(false); - - const timer = useRef(); - const notify = useCallback((message, error = false) => { - clearTimeout(timer.current); - setToast({ message, error }); - timer.current = setTimeout(() => setToast(null), 5000); - }, []); - - useEffect(() => () => clearTimeout(timer.current), []); - - // Listen for unauthorized events to prompt login - useEffect(() => { - authStorage.onUnauthorized(() => { - setAuthUser(null); - notify("Phiên làm việc hết hạn. Vui lòng đăng nhập lại.", true); - setAuthModalOpen(true); - }); - }, [notify]); - - // Handle hash route changes - useEffect(() => { - const change = () => { - setRoute(window.location.hash || "#/customer/overview"); - setMobile(false); - window.scrollTo(0, 0); - }; - window.addEventListener("hashchange", change); - return () => window.removeEventListener("hashchange", change); - }, []); - - // Save demo data to localStorage if not using live API - useEffect(() => { - if (!isLiveApi) { - try { - localStorage.setItem( - storageKey, - JSON.stringify({ version: VERSION, data }), - ); - setStorageError(false); - } catch { - setStorageError(true); - } - } - }, [data, storageKey, isLiveApi]); - - // Fetch Live Data from .NET Backend API - const loadServerData = useCallback(async () => { - try { - setLoading(true); - const [facilitiesRes, unitTypesRes, ratesRes] = await Promise.all([ - facilityService.getFacilities().catch(() => null), - facilityService.getUnitTypes().catch(() => null), - facilityService.getRates().catch(() => null), - ]); - - if (!facilitiesRes || !unitTypesRes) { - // Backend offline or unreachable, retain demo state - setIsLiveApi(false); - return; - } - - const facilities = facilitiesRes.map((f, idx) => mapFacilityFromApi(f, idx)); - const unitTypes = unitTypesRes.map((t) => mapUnitTypeFromApi(t)); - const rates = ratesRes ? ratesRes.map((r) => mapRateFromApi(r)) : []; - - let reservations = []; - let contracts = []; - let tickets = []; - let handovers = []; - let payments = []; - - // If user is authenticated, fetch personalized customer records - if (authService.isAuthenticated()) { - try { - const [resList, contractsList, ticketsList] = await Promise.all([ - reservationService.getMyReservations().catch(() => []), - contractService.getMyContracts().catch(() => []), - supportService.getMyTickets().catch(() => []), - ]); - - reservations = resList.map((r) => mapReservationFromApi(r)); - contracts = contractsList.map((c) => mapContractFromApi(c)); - tickets = ticketsList.map((t) => mapTicketFromApi(t)); - - // Load detailed contracts to collect handovers and payments - if (contracts.length > 0) { - const detailPromises = contracts.map(async (c) => { - try { - const detail = await contractService.getContract(c.contract_id); - if (detail?.handover) { - handovers.push(mapHandoverFromApi(detail.handover, c.contract_id)); - } - if (Array.isArray(detail?.payments)) { - payments.push(...detail.payments.map((p) => mapPaymentFromApi(p))); - } - } catch { - /* Ignore single contract error */ - } - }); - await Promise.all(detailPromises); - } - } catch { - // Keep empty lists on auth fetch error - } - } - - const currentStoredUser = authService.getCurrentUser(); - const nextUser = currentStoredUser - ? { - user_id: currentStoredUser.userId || 101, - full_name: currentStoredUser.fullName || currentStoredUser.username, - email: currentStoredUser.email, - phone: currentStoredUser.phone || "", - } - : dataRef.current.user; - - const nextData = { - user: nextUser, - facilities, - unitTypes, - rates: rates.length ? rates : dataRef.current.rates, - units: dataRef.current.units, - contracts: contracts.length > 0 ? contracts : (authService.isAuthenticated() ? [] : dataRef.current.contracts), - reservations: reservations.length > 0 ? reservations : (authService.isAuthenticated() ? [] : dataRef.current.reservations), - payments: payments.length > 0 ? payments : (authService.isAuthenticated() ? [] : dataRef.current.payments), - handovers: handovers.length > 0 ? handovers : (authService.isAuthenticated() ? [] : dataRef.current.handovers), - tickets: tickets.length > 0 ? tickets : (authService.isAuthenticated() ? [] : dataRef.current.tickets), - renewals: [], - returnRequests: [], - paymentNotices: dataRef.current.paymentNotices || {}, - }; - - dataRef.current = nextData; - setData(nextData); - setIsLiveApi(true); - } catch (err) { - console.warn("Backend API not reachable. Using fallback local demo data.", err); - setIsLiveApi(false); - } finally { - setLoading(false); - } - }, []); - - useEffect(() => { - loadServerData(); - }, [loadServerData]); - - // Central command handler (API or Mock fallback) - const command = useCallback( - async (type, payload) => { - if (isLiveApi && authService.isAuthenticated()) { - try { - switch (type) { - case "BOOK": { - const res = await reservationService.createReservation({ - facilityId: payload.facility_id, - unitTypeId: payload.unit_type_id, - startDate: payload.start_date, - rentalPeriodMonths: payload.rental_period_months, - }); - await loadServerData(); - return mapReservationFromApi(res); - } - case "CANCEL_RESERVATION": { - await reservationService.cancelReservation(payload.id, payload.reason); - await loadServerData(); - return true; - } - case "RENEW": { - await renewalService.requestRenewal(payload.contract_id, payload.months); - await loadServerData(); - return true; - } - case "CONFIRM_HANDOVER": { - await contractService.confirmHandover(payload.id); - await loadServerData(); - return true; - } - case "TICKET": { - const res = await supportService.createTicket({ - contractId: payload.contract_id, - issueType: payload.issue_type, - title: payload.title, - description: payload.description, - priority: "NORMAL", - }); - await loadServerData(); - return mapTicketFromApi(res); - } - case "CANCEL_TICKET": { - await supportService.cancelTicket(payload.id); - await loadServerData(); - return true; - } - case "PROFILE": { - setData((prev) => ({ - ...prev, - user: { ...prev.user, full_name: payload.full_name, phone: payload.phone }, - })); - return true; - } - case "PAYMENT_NOTICE": { - setData((prev) => ({ - ...prev, - paymentNotices: { - ...prev.paymentNotices, - [payload.id]: { method: payload.method, sent_at: new Date().toISOString() }, - }, - })); - return true; - } - default: - break; - } - } catch (e) { - notify(e.message || "Lỗi xử lý yêu cầu phía máy chủ.", true); - return false; - } - } - - // Check if action requires auth when live API is available - if (isLiveApi && !authService.isAuthenticated()) { - if (["BOOK", "CANCEL_RESERVATION", "RENEW", "CONFIRM_HANDOVER", "TICKET"].includes(type)) { - notify("Vui lòng đăng nhập để thực hiện thao tác này.", true); - setAuthModalOpen(true); - return false; - } - } - - // Fallback local reducer execution - try { - const next = reduceCustomer(dataRef.current, { type, payload }); - dataRef.current = next; - setData(next); - return true; - } catch (e) { - notify(e.message, true); - return false; - } - }, - [isLiveApi, loadServerData, notify], - ); - - const closeModal = useCallback(() => setModal(null), []); - const closeReset = useCallback(() => setResetOpen(false), []); - const navigate = (to) => { - window.location.hash = `/customer/${to}`; - }; - const openModal = (type, payload) => { - if (isLiveApi && !authService.isAuthenticated() && ["book", "renew", "cancel", "handover"].includes(type)) { - notify("Vui lòng đăng nhập tài khoản trước.", true); - setAuthModalOpen(true); - return; - } - setModal({ type, payload }); - }; - - const handleLogout = async () => { - await authService.logout(); - setAuthUser(null); - notify("Đã đăng xuất thành công."); - await loadServerData(); - navigate("overview"); - if (onLogout) onLogout(); - }; - - const handleAuthSuccess = (user) => { - setAuthUser(user); - notify(`Xin chào, ${user.fullName || user.username}!`); - loadServerData(); - }; - - const [path, search = ""] = route.replace(/^#\/?/, "").split("?"); - const parts = path.split("/"); - const page = parts[0] === "customer" ? parts[1] || "overview" : "overview", - id = parts[2], - query = new URLSearchParams(search); - - useEffect(() => { - document.title = `${NAV.find((n) => n[0] === page)?.[2] || "Tài khoản"} · SafeSpace`; - }, [page]); - - const value = { - data, - user: authUser, - isAuthenticated: !!authUser, - isLiveApi, - loading, - openAuthModal: () => setAuthModalOpen(true), - command, - refreshData: loadServerData, - notify, - navigate, - openModal, - }; - - const pending = data.payments.filter((p) => - ["PENDING", "FAILED"].includes(p.status), - ).length; - - let content; +import Payments from "./pages/Payments"; +import Profile from "./pages/Profile"; +import { Guide, Pricing } from "./pages/Public"; +import Reservations from "./pages/Reservations"; +import Support from "./pages/Support"; +import { Renew, Return, Sent, UnitDetail, Units } from "./pages/Units"; +import { AppProvider, useApp } from "./state/store"; + +const TITLES = { + home: "Trang chủ", + login: "Đăng nhập", + register: "Đăng ký", + pricing: "Bảng giá", + guide: "Hướng dẫn & hỗ trợ", + find: "Tìm & đặt kho", + checkout: "Đặt chỗ & thanh toán", + confirmation: "Xác nhận đặt chỗ", + overview: "Tổng quan", + units: "Kho của tôi", + reservations: "Đơn đặt chỗ", + payments: "Thanh toán & lịch hẹn", + sent: "Đã gửi yêu cầu", + support: "Hỗ trợ", + profile: "Tài khoản", +}; + +// Trang cần đăng nhập. Các trang công khai: home, login, register, pricing, guide, find (xem cơ sở). +const PRIVATE = ["overview", "units", "reservations", "payments", "support", "profile", "checkout", "confirmation", "sent"]; + +function renderPage({ page, parts, query }) { + const [a, b] = parts; switch (page) { - case "overview": - content = ; - break; - case "find": - content = ; - break; - case "reservations": - content = ; - break; + case "home": return ; + case "login": return ; + case "register": return ; + case "pricing": return ; + case "guide": return ; + case "find": return a ? : ; + case "checkout": return b === "failed" ? : ; + case "confirmation": return ; + case "overview": return ; + case "reservations": return a ? : ; case "units": - content = ; - break; - case "payments": - content = ; - break; - case "appointments": - content = ; - break; - case "support": - content = ; - break; - case "profile": - content = ; - break; + if (a && b === "renew") return ; + if (a && b === "return") return ; + return a ? : ; + case "sent": return ; + case "payments": return ; + case "support": return ; + case "profile": return ; default: - content = ( - - Về tổng quan - + return ( +
+ + Về trang chủ + +
); } +} - const userDisplayName = authUser - ? authUser.fullName || authUser.username - : data.user.full_name; +function Shell() { + const route = useRoute(); + const { authed, toast, dismissToast, storageError, ready, loadError, retry } = useApp(); + const needsLogin = PRIVATE.includes(route.page) && !authed; - const initials = userDisplayName - .split(" ") - .slice(-2) - .map((s) => s[0] || "") - .join("") || "KH"; + useEffect(() => { + document.title = `${TITLES[route.page] || "SafeSpace"} · SafeSpace`; + }, [route.page]); + useEffect(() => { + if (!needsLogin) return; + // Đăng xuất rồi chuyển trang: hash có thể đã đổi sang trang công khai, khi đó không ép quay lại đăng nhập + const current = parseRoute(window.location.hash); + if (!PRIVATE.includes(current.page)) return; + go(`login?next=${encodeURIComponent(current.raw)}`, { replace: true }); + }, [needsLogin, route.raw]); return ( - -
- { - e.preventDefault(); - document.getElementById("ss-main")?.focus(); - }} - > - Chuyển đến nội dung - - -
-
- - - - - - SafeSpace - -
- - - -
- Khu vực khách hàng - - - {pending > 0 && } - - - {authUser ? ( - - {initials} - - {userDisplayName} - Khách hàng - - - ) : ( - - )} -
-
- - {mobile && ( - - - ) : ( - - )} -
- - -
-
- SafeSpace - - {NAV.find((n) => n[0] === page)?.[2] || "Tài khoản"} - - {isLiveApi ? "● KẾT NỐI API .NET" : "BẢN DEMO UI"} - -
- -
- {loading && !data.facilities.length ? ( -
-
-

Đang đồng bộ dữ liệu từ máy chủ...

-
- ) : ( - content - )} +
+ { e.preventDefault(); document.getElementById("main")?.focus(); }}>Chuyển đến nội dung +
+
+ {needsLogin ? null : loadError && !ready ? ( +
+ + +
- -
- © 2026 SafeSpace. Không gian cho cuộc sống của bạn. - {!isLiveApi && ( - - )} - {isLiveApi && ( - - )} -
- - {storageError && ( -

- Trình duyệt không cho lưu dữ liệu. Thao tác hiện tại chỉ được giữ - trong phiên này. -

- )} -
- - {modal && } - {authModalOpen && ( - setAuthModalOpen(false)} - onAuthSuccess={handleAuthSuccess} - /> - )} - - {resetOpen && ( - -
-

- Các đơn đặt kho, thông báo thanh toán và yêu cầu bạn vừa tạo - trong bản demo sẽ bị xóa. Dữ liệu ví dụ ban đầu sẽ được khôi - phục. -

-
- - -
-
-
- )} - - {toast && ( -
- - {toast.message} - -
+ ) : !ready ? ( +
+
+ ) : ( + renderPage(route) )}
- + + {storageError &&

Trình duyệt không cho lưu dữ liệu, thao tác chỉ giữ trong phiên này.

} + {toast && ( +
+ + {toast.message} + +
+ )} +
+ ); +} + +export default function CustomerApp() { + return ( + + + ); } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js new file mode 100644 index 0000000..4b6ef08 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js @@ -0,0 +1,34 @@ +// Toàn bộ endpoint backend mà giao diện khách hàng dùng (StorageProject.Api/Endpoints). +import { request } from "./http.js"; + +export const api = { + // Auth + login: (username, password) => request("/api/auth/login", { method: "POST", body: { username, password }, auth: false }), + register: (body) => request("/api/auth/register", { method: "POST", body, auth: false }), + logout: () => request("/api/auth/logout", { method: "POST" }), + + // Cơ sở, loại kho, bảng giá (công khai) + facilities: () => request("/api/facilities", { auth: false }), + unitTypes: () => request("/api/unit-types", { auth: false }), + rates: () => request("/api/rates", { auth: false }), + availability: (body) => request("/api/availability/check", { method: "POST", body, auth: false }), + + // Đặt chỗ + reservations: () => request("/api/reservations"), + reservation: (id) => request(`/api/reservations/${id}`), + createReservation: (body) => request("/api/reservations", { method: "POST", body }), + cancelReservation: (id, reason) => request(`/api/reservations/${id}/cancel`, { method: "POST", body: { reason } }), + + // Hợp đồng, thanh toán, gia hạn, bàn giao + contracts: () => request("/api/contracts"), + contract: (id) => request(`/api/contracts/${id}`), + requestRenewal: (contractId, months) => + request(`/api/contracts/${contractId}/renewals`, { method: "POST", body: { renewalPeriodMonths: months } }), + confirmHandover: (handoverId) => request(`/api/handovers/${handoverId}/confirm`, { method: "POST" }), + + // Hỗ trợ + tickets: () => request("/api/tickets"), + ticket: (id) => request(`/api/tickets/${id}`), + createTicket: (body) => request("/api/tickets", { method: "POST", body }), + cancelTicket: (id) => request(`/api/tickets/${id}/cancel`, { method: "POST" }), +}; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/http.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/http.js new file mode 100644 index 0000000..37fb9ad --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/http.js @@ -0,0 +1,65 @@ +import { API_URL } from "../config/api.js"; + +export class ApiError extends Error { + constructor(message, status = 0, data = null) { + super(message); + this.status = status; + this.data = data; + } +} + +let token = null; +export const setToken = (t) => { + token = t || null; +}; + +const DEFAULT_MESSAGES = { + 0: "Không kết nối được máy chủ. Vui lòng kiểm tra backend đang chạy.", + 401: "Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.", + 403: "Tài khoản không có quyền thực hiện thao tác này.", + 404: "Không tìm thấy dữ liệu.", + 500: "Máy chủ gặp lỗi. Vui lòng thử lại sau.", +}; + +// Lấy câu báo lỗi từ phản hồi ASP.NET: { error } | { message } | ProblemDetails { title, errors } +function messageOf(data, status) { + if (data && typeof data === "object") { + if (data.error) return data.error; + if (data.message) return data.message; + if (data.errors) { + const first = Object.values(data.errors).flat()[0]; + if (first) return first; + } + if (data.title && status !== 401) return data.title; + } + if (typeof data === "string" && data && data.length < 300 && !data.startsWith("<")) return data; + return DEFAULT_MESSAGES[status] || (status >= 500 ? DEFAULT_MESSAGES[500] : `Yêu cầu không thành công (mã ${status}).`); +} + +export async function request(path, { method = "GET", body, auth = true, fetchImpl = globalThis.fetch } = {}) { + let res; + try { + res = await fetchImpl(`${API_URL}${path}`, { + method, + headers: { + Accept: "application/json", + ...(body !== undefined ? { "Content-Type": "application/json" } : {}), + ...(auth && token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + } catch { + throw new ApiError(DEFAULT_MESSAGES[0], 0); + } + const text = await res.text(); + let data = null; + if (text) { + try { + data = JSON.parse(text); + } catch { + data = text; + } + } + if (!res.ok) throw new ApiError(messageOf(data, res.status), res.status, data); + return data; +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js new file mode 100644 index 0000000..45e73f1 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js @@ -0,0 +1,366 @@ +// Chuyển dữ liệu backend (DTO camelCase, id số, trạng thái BE) sang dạng dữ liệu các trang đang dùng, +// rồi ghép với phần lưu trong trình duyệt ("overlay") cho những luồng backend chưa có API. +import { bandOfArea, SIZE_BANDS } from "../lib/catalog.js"; +import { localDate, timeoutLabel } from "../lib/format.js"; +import { TICKET_TOPICS } from "../lib/status.js"; + +const TICKET_TOPIC_KEYS = Object.keys(TICKET_TOPICS); + +// ASP.NET trả DateTime đọc từ DB không kèm múi giờ nhưng thực chất là UTC → thêm "Z" +export function parseUtc(value) { + if (!value) return null; + const s = String(value); + const hasZone = /(Z|[+-]\d{2}:?\d{2})$/i.test(s); + const d = new Date(hasZone ? s : `${s}Z`); + return Number.isNaN(d.getTime()) ? null : d; +} +const isoOf = (value) => parseUtc(value)?.toISOString() ?? null; +const pad = (n, w = 4) => String(n).padStart(w, "0"); +const dateOnly = (v) => (v ? String(v).slice(0, 10) : null); + +export const reservationCode = (dto) => { + const d = parseUtc(dto.createdAt) || new Date(); + return `SS-${localDate(d).replaceAll("-", "")}-${pad(dto.reservationId)}`; +}; +export const contractCode = (dto) => `HĐ-${String(dto.startDate || "").slice(0, 4) || "0000"}-${pad(dto.contractId)}`; +export const ticketCode = (id) => `HT-${pad(id)}`; + +function monthsBetween(start, end) { + if (!start || !end) return 0; + const [y1, m1, d1] = start.split("-").map(Number); + const [y2, m2, d2] = end.split("-").map(Number); + return Math.max(1, (y2 - y1) * 12 + (m2 - m1) - (d2 < d1 ? 1 : 0)); +} + +const areaText = (n) => `${Number(n).toLocaleString("vi-VN", { maximumFractionDigits: 1 })} m²`; + +// "123 Hoàng Hoa Thám, Phường 13, Quận Tân Bình, TP. Hồ Chí Minh" → quận + thành phố +function splitAddress(address = "") { + const parts = address.split(",").map((s) => s.trim()).filter(Boolean); + return { district: parts.length >= 2 ? parts[parts.length - 2] : "", city: parts[parts.length - 1] || "" }; +} +const hhmm = (t) => (t ? String(t).slice(0, 5) : null); + +// ---------- Danh mục (công khai) ---------- +export function mapCatalog({ facilities = [], unitTypes = [], rates = [] }) { + const typeById = new Map(unitTypes.map((t) => [t.unitTypeId, t])); + const mapped = facilities + .filter((f) => !f.status || f.status === "ACTIVE") + .map((f) => { + const offers = rates + .filter((r) => r.facilityId === f.facilityId && typeById.has(r.unitTypeId)) + .map((r) => { + const t = typeById.get(r.unitTypeId); + return { + key: `ut-${t.unitTypeId}`, + unit_type_id: t.unitTypeId, + name: t.typeName, + type: t.climateControlled ? "climate" : "normal", + band: bandOfArea(Number(t.area)), + area: Number(t.area), + size_label: areaText(t.area), + monthly_rate: Number(r.monthlyRate), + description: t.description || "", + }; + }) + .sort((a, b) => a.area - b.area || a.monthly_rate - b.monthly_rate); + const { district, city } = splitAddress(f.address); + const open = hhmm(f.openingTime); + const close = hhmm(f.closingTime); + return { + facility_id: f.facilityId, + name: f.name, + address: f.address, + district, + city, + phone: f.contactPhone || "", + hours: open && close ? `${open}–${close}` : "06:00–22:00", + distance_km: null, + camera: true, + has_climate: offers.some((o) => o.type === "climate"), + offers, + }; + }) + .sort((a, b) => a.facility_id - b.facility_id); + return { facilities: mapped, unitTypes }; +} + +// ---------- Trạng thái ---------- +const RESERVATION = { + PENDING_PAYMENT: "PENDING_PAYMENT", + UNIT_ASSIGNED: "CONFIRMED", + CONFIRMED: "CONFIRMED", + CHECKED_IN: "CHECKED_IN", + COMPLETED: "CHECKED_IN", + CANCELLED: "CANCELLED", + EXPIRED: "CANCELLED", +}; +const CONTRACT = { ACTIVE: "ACTIVE", ENDED: "ENDED", COMPLETED: "ENDED", TERMINATED: "ENDED", CANCELLED: "ENDED" }; +const TICKET = { OPEN: "OPEN", ASSIGNED: "IN_PROGRESS", IN_PROGRESS: "IN_PROGRESS", RESOLVED: "RESOLVED", CLOSED: "RESOLVED", CANCELLED: "CANCELLED" }; +const TICKET_NOTE = { + OPEN: "Cơ sở sẽ tiếp nhận và phản hồi qua thông báo.", + IN_PROGRESS: "Nhân viên cơ sở đang xử lý.", + RESOLVED: "Yêu cầu đã được xử lý.", + CANCELLED: "Bạn đã huỷ yêu cầu này.", +}; +const RENEWAL = { PENDING_PAYMENT: "PENDING", PENDING_APPROVAL: "PENDING", APPROVED: "APPROVED", COMPLETED: "APPROVED", REJECTED: "REJECTED", CANCELLED: "REJECTED" }; + +function offerOfType(unitTypes, id, name) { + const t = unitTypes.find((x) => x.unitTypeId === id) || unitTypes.find((x) => x.typeName === name); + if (!t) return { type: "normal", band: "M", size_label: SIZE_BANDS[1].label, area: null, key: null }; + return { + type: t.climateControlled ? "climate" : "normal", + band: bandOfArea(Number(t.area)), + size_label: areaText(t.area), + area: Number(t.area), + key: `ut-${t.unitTypeId}`, + unit_type_id: t.unitTypeId, + }; +} + +const EMPTY_OVERLAY = { + holds: {}, // reservationId → thời điểm tạo trong trình duyệt này (ms), dùng cho đồng hồ giữ chỗ + transfers: {}, // reservationId → thời điểm khách bấm "Tôi đã chuyển khoản" + expired: {}, // reservationId → hết thời gian giữ chỗ, đang huỷ trên máy chủ + attachments: {}, // ticketId → tên file ảnh đính kèm + returns: [], + appointments: [], + notifications: [], + activities: [], + name: null, + phone: null, +}; +export const emptyOverlay = () => JSON.parse(JSON.stringify(EMPTY_OVERLAY)); + +// ---------- Ghép dữ liệu khách hàng ---------- +export function composeData({ catalog, remote, overlay: ov, session, timeoutSeconds, now = new Date() }) { + const overlay = { ...EMPTY_OVERLAY, ...(ov || {}) }; + const facilities = catalog?.facilities || []; + const unitTypes = catalog?.unitTypes || []; + const facilityByName = (name) => facilities.find((f) => f.name === name); + const user = session + ? { + user_id: session.user.userId, + username: session.user.username, + full_name: overlay.name || session.user.fullName, + email: session.user.email, + phone: overlay.phone || "", + } + : null; + const base = { + user, + facilities, + reservations: [], + contracts: [], + ledger: [], + appointments: [...overlay.appointments], + renewals: [], + returns: [...overlay.returns], + tickets: [], + notifications: [...overlay.notifications], + activities: [...overlay.activities], + }; + if (!remote) return base; + + // Đặt chỗ + const codeByReservation = new Map(); + const reservations = remote.reservations.map((r) => { + const id = r.reservationId; + const code = reservationCode(r); + codeByReservation.set(id, code); + const created = parseUtc(r.createdAt) || now; + const hold = overlay.holds[id]; + let status = RESERVATION[r.status] || "PENDING_VERIFICATION"; + let cancel_reason = r.cancellationReason || null; + let expires_at = null; + let timeout_seconds = null; + if (status === "PENDING_PAYMENT") { + if (overlay.transfers[id]) status = "PENDING_VERIFICATION"; + else { + const expires = hold ? new Date(hold + timeoutSeconds * 1000) : parseUtc(r.expiresAt); + timeout_seconds = hold ? timeoutSeconds : expires ? Math.round((expires - created) / 1000) : null; + expires_at = expires ? expires.toISOString() : null; + if (overlay.expired[id] || (expires && expires <= now)) { + status = "CANCELLED"; + cancel_reason = `Quá ${timeoutLabel(timeout_seconds || timeoutSeconds)} chưa xác nhận`; + } + } + } + const offer = offerOfType(unitTypes, r.unitTypeId, r.unitTypeName); + const rent = Number(r.estimatedAmount); + const deposit = Number(r.requiredDeposit); + return { + reservation_id: code, + api_id: id, + facility_id: r.facilityId, + facility_name: r.facilityName, + type: offer.type, + band: offer.band, + offer_key: offer.key, + size_label: offer.size_label, + months: r.rentalPeriodMonths, + start_date: dateOnly(r.startDate), + end_date: dateOnly(r.expectedEndDate), + monthly_rate: Number(r.quotedMonthlyRate), + rent_total: rent, + deposit, + initial_total: rent + deposit, + status, + cancel_reason, + created_at: created.toISOString(), + expires_at, + timeout_seconds, + transfer_confirmed_at: overlay.transfers[id] ? new Date(overlay.transfers[id]).toISOString() : null, + contract_api_id: remote.reservationDetails?.[id]?.contractId ?? null, + }; + }); + + // Hợp đồng + thanh toán + gia hạn + const contracts = []; + const ledger = []; + const renewals = []; + const contractCodeById = new Map(); + for (const c of remote.contracts) { + const code = contractCode(c); + contractCodeById.set(c.contractId, code); + const facility = facilityByName(c.facilityName); + const offer = offerOfType(unitTypes, null, c.unitTypeName); + const start = dateOnly(c.startDate); + const end = dateOnly(c.endDate); + const handover = c.handover || null; + contracts.push({ + contract_id: code, + api_id: c.contractId, + reservation_id: codeByReservation.get(c.reservationId) || null, + facility_id: facility?.facility_id ?? null, + facility_name: c.facilityName, + unit_number: c.unitNumber, + type: offer.type, + band: offer.band, + size_m2: offer.area, + unit_type_name: c.unitTypeName, + location: null, + months: monthsBetween(start, end), + start_date: start, + end_date: end, + monthly_rate: Number(c.agreedMonthlyRate), + deposit: Number(c.depositAmount), + status: CONTRACT[c.status] || "ACTIVE", + handed_over: Boolean(handover && (["HANDED_OVER", "COMPLETED"].includes(handover.status) || (handover.customerConfirmed && handover.staffConfirmed))), + handover_api_id: handover?.handoverId ?? null, + handover_pending_customer: Boolean(handover && !handover.customerConfirmed && handover.staffConfirmed), + }); + const paidRenewals = new Set(); + for (const p of c.payments || []) { + if (p.renewalId) paidRenewals.add(p.renewalId); + const kind = p.paymentType || "OTHER"; + const label = + kind === "RENT" ? `Thuê kho ${c.unitNumber}` : kind === "DEPOSIT" ? `Cọc hợp đồng ${c.unitNumber}` : kind === "RENEWAL" ? `Gia hạn kho ${c.unitNumber}` : `Khoản thu kho ${c.unitNumber}`; + const paid = p.status === "PAID"; + ledger.push({ + ref: p.transactionReference || `TT-${pad(p.paymentId)}`, + kind, + label, + contract_id: code, + amount: Number(p.amount), + status: paid ? (kind === "DEPOSIT" ? "DEPOSIT_HELD" : "RECONCILED") : p.status === "REFUNDED" ? "REFUNDED" : "UNPAID", + }); + } + for (const r of c.renewals || []) { + const status = RENEWAL[r.status] || "PENDING"; + renewals.push({ + renewal_id: `GH-${pad(r.renewalId)}`, + api_id: r.renewalId, + contract_id: code, + months: r.renewalPeriodMonths, + old_end: dateOnly(r.oldEndDate), + new_end: dateOnly(r.newEndDate), + amount: Number(r.renewalAmount), + status, + requested_at: isoOf(r.requestedAt), + }); + if (status === "PENDING" && !paidRenewals.has(r.renewalId)) { + ledger.push({ ref: `GH-${pad(r.renewalId)}`, kind: "RENEWAL", label: "Gia hạn đề xuất", contract_id: code, amount: Number(r.renewalAmount), status: "RENEWAL_PENDING" }); + } + } + } + for (const r of reservations) r.contract_id = r.contract_api_id ? contractCodeById.get(r.contract_api_id) || null : null; + + // Khoản đã báo chuyển khoản, chờ nhân viên đối soát + for (const r of reservations.filter((x) => x.status === "PENDING_VERIFICATION")) { + const refBase = `SS-${pad(r.api_id)}`; + ledger.unshift( + { ref: `${refBase}-DEP`, kind: "DEPOSIT", label: "Cọc hợp đồng", reservation_id: r.reservation_id, amount: r.deposit, status: "PENDING_VERIFICATION" }, + { ref: `${refBase}-RENT`, kind: "RENT", label: `Thuê kho · ${r.months} tháng`, reservation_id: r.reservation_id, amount: r.rent_total, status: "PENDING_VERIFICATION" }, + ); + } + + // Lịch hẹn nhận kho từ backend (chi tiết đơn) + lịch trả kho lưu cục bộ + const appointments = []; + for (const r of reservations) { + const d = remote.reservationDetails?.[r.api_id]; + const at = parseUtc(d?.checkInAppointmentAt); + if (!at || r.status === "CANCELLED") continue; + const end = new Date(at.getTime() + 30 * 60000); + const t = (x) => `${String(x.getHours()).padStart(2, "0")}:${String(x.getMinutes()).padStart(2, "0")}`; + appointments.push({ + appointment_id: `LH-${pad(r.api_id)}`, + kind: "CHECK_IN", + contract_id: r.contract_id, + reservation_id: r.reservation_id, + facility_id: r.facility_id, + unit_number: d.assignedUnitNumber || "đang phân bổ", + date: localDate(at), + slot: `${t(at)}–${t(end)}`, + status: r.status === "CHECKED_IN" ? "DONE" : "CONFIRMED", + note: "Mang giấy tờ đã đăng ký và mã đặt chỗ. Nhân viên xác minh, hướng dẫn và bàn giao kho.", + }); + } + + // Yêu cầu hỗ trợ + const tickets = remote.tickets.map((t) => { + const status = TICKET[t.status] || "OPEN"; + return { + ticket_id: ticketCode(t.ticketId), + api_id: t.ticketId, + contract_id: contractCodeById.get(t.contractId) || null, + topic: TICKET_TOPIC_KEYS.includes(t.issueType) ? t.issueType : "OTHER", + title: t.title, + description: t.description || "", + attachments: overlay.attachments[t.ticketId] || [], + status, + staff_note: TICKET_NOTE[status], + created_at: isoOf(t.createdAt), + updated_at: isoOf(t.closedAt || t.resolvedAt || t.assignedAt || t.createdAt), + }; + }); + + return { + ...base, + reservations, + contracts, + ledger, + renewals, + tickets, + appointments: [...appointments, ...base.appointments], + }; +} + +// Đơn đã hết giờ giữ chỗ nhưng máy chủ còn để "chờ thanh toán" → cần gọi huỷ +export function reservationsToExpire({ remote, overlay, timeoutSeconds, now = new Date() }) { + if (!remote) return []; + return remote.reservations.filter((r) => { + if (r.status !== "PENDING_PAYMENT" || overlay.transfers[r.reservationId]) return false; + const hold = overlay.holds[r.reservationId]; + const expires = hold ? new Date(hold + timeoutSeconds * 1000) : parseUtc(r.expiresAt); + return expires && expires <= now; + }); +} + +// Tên đăng nhập backend (≤ 50 ký tự) sinh từ email để khách đăng nhập được bằng email như Figma +export function usernameFromEmail(email) { + const e = String(email || "").trim().toLowerCase(); + if (e.length <= 50) return e; + return `${e.split("@")[0].slice(0, 40)}${Date.now().toString(36).slice(-6)}`; +} + diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/ActionModal.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/ActionModal.jsx deleted file mode 100644 index 6e42be8..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/ActionModal.jsx +++ /dev/null @@ -1,441 +0,0 @@ -import React, { useState } from "react"; -import { useCustomer } from "../context"; -import { Modal, Field, Button, Notice, Details, Icon } from "./UI"; -import { - today, - addMonths, - dateLabel, - money, - validateBooking, - uid, -} from "../domain"; -export default function ActionModal({ modal, onClose }) { - const { data, command, notify, navigate } = useCustomer(); - const { type, payload: p } = modal; - const [form, setForm] = useState({ - facility_id: p.facility_id || data.facilities[0].facility_id, - unit_type_id: p.unit_type_id || 1, - start_date: p.start_date || today(), - rental_period_months: p.rental_period_months || "1", - months: "1", - date: today(), - reason: "", - notes: "", - method: "BANK_TRANSFER", - agree: false, - }); - const [errors, setErrors] = useState({}); - const [submitting, setSubmitting] = useState(false); - const set = (k, v) => { - setForm({ ...form, [k]: v }); - setErrors((previous) => { - const next = { ...previous }; - delete next[k]; - return next; - }); - }; - const finish = async (type, payload, msg, to) => { - setSubmitting(true); - try { - const result = await command(type, payload); - if (result) { - onClose(); - notify(msg); - if (to) { - const targetTo = - typeof result === "object" && result?.reservation_id - ? `reservations/${result.reservation_id}` - : to; - navigate(targetTo); - } - } - } finally { - setSubmitting(false); - } - }; - const titles = { - book: "Đặt không gian của bạn", - renew: "Yêu cầu gia hạn", - return: "Yêu cầu trả kho", - pay: "Thanh toán khoản phí", - cancel: "Hủy đơn đặt kho", - handover: "Xác nhận nhận kho", - }; - const submit = (e) => { - e.preventDefault(); - const err = {}; - if (type === "book") { - Object.assign(err, validateBooking(form)); - if (!form.agree) - err.agree = "Vui lòng xác nhận thông tin và điều kiện đặt kho."; - setErrors(err); - if (Object.keys(err).length) return; - const id = uid("DC"); - finish( - "BOOK", - { - reservation_id: id, - facility_id: Number(form.facility_id), - unit_type_id: Number(form.unit_type_id), - start_date: form.start_date, - rental_period_months: Number(form.rental_period_months), - }, - "Đã gửi yêu cầu đặt kho.", - `reservations/${id}`, - ); - } - if (type === "renew") { - if ( - !Number.isInteger(Number(form.months)) || - Number(form.months) < 1 || - Number(form.months) > 24 - ) - err.months = "Chọn số tháng từ 1 đến 24."; - if (!form.agree) err.agree = "Vui lòng xác nhận gửi yêu cầu gia hạn."; - setErrors(err); - if (!Object.keys(err).length) - finish( - "RENEW", - { contract_id: p.contract_id, months: Number(form.months) }, - "Đã gửi yêu cầu gia hạn. Chờ quản lý phê duyệt.", - ); - } - if (type === "return") { - if (!form.date || form.date < today()) - err.date = "Ngày trả kho không được ở quá khứ."; - if (!form.agree) err.agree = "Vui lòng xác nhận điều kiện trả kho."; - setErrors(err); - if (!Object.keys(err).length) - finish( - "RETURN", - { contract_id: p.contract_id, date: form.date, notes: form.notes }, - "Đã gửi yêu cầu trả kho. Cơ sở sẽ xác nhận lịch kiểm tra.", - ); - } - if (type === "cancel") { - if (!form.reason.trim()) err.reason = "Vui lòng cho biết lý do hủy."; - setErrors(err); - if (!Object.keys(err).length) - finish( - "CANCEL_RESERVATION", - { id: p.reservation_id, reason: form.reason.trim() }, - "Đã hủy đơn đặt kho.", - ); - } - if (type === "pay") { - if (!form.agree) - err.agree = "Vui lòng xác nhận thông tin thanh toán mẫu."; - setErrors(err); - if (!Object.keys(err).length) - finish( - "PAYMENT_NOTICE", - { id: p.payment_id, method: form.method }, - "Đã gửi thông báo. Chờ nhân viên xác minh.", - ); - } - if (type === "handover") { - if (!form.agree) err.agree = "Vui lòng xác nhận đã kiểm tra và nhận đủ."; - setErrors(err); - if (!Object.keys(err).length) - finish( - "CONFIRM_HANDOVER", - { id: p.handover_id }, - "Đã ghi nhận xác nhận nhận kho của bạn.", - ); - } - }; - const agree = (label) => ( -
- - {errors.agree && ( - - {errors.agree} - - )} -
- ); - const rate = data.rates.find( - (r) => - r.facility_id === Number(form.facility_id) && - r.unit_type_id === Number(form.unit_type_id), - ); - return ( - -
- {type === "book" && ( - <> -
-
- - - - - - -
- - set("start_date", e.target.value)} - /> - - - - set("rental_period_months", e.target.value) - } - /> - -
-
-
-

Dự toán thuê kho

-
0 - ? dateLabel( - addMonths( - form.start_date, - form.rental_period_months, - ), - ) - : "—", - ], - ]} - /> -
- Tổng dự kiến - - {money( - rate.monthly_rate * - ((Number(form.rental_period_months) || 0) + 1), - )} - -
-
-
- - {rate.available - ? "Cơ sở sẽ xác nhận khả dụng và phân bổ kho cụ thể. Đây là yêu cầu đặt chỗ; chưa phát sinh thanh toán." - : "Loại kho này hiện đã hết chỗ. Vui lòng chọn loại kho hoặc cơ sở khác."} - - {agree( - "Tôi đã kiểm tra kỳ thuê và chi phí dự kiến; đồng ý để cơ sở xác nhận đơn đặt kho.", - )} - - )} - {type === "renew" && ( - <> -

- Hợp đồng {p.contract_id} · Kết thúc hiện tại{" "} - {dateLabel(p.end_date)} -

- - - -
-
-
- - Quản lý sẽ kiểm tra lịch trống và xác nhận giá. Ngày kết thúc chỉ - được cập nhật sau khi gia hạn được duyệt và thanh toán hoàn tất. - - {agree("Tôi đồng ý gửi yêu cầu gia hạn theo thông tin trên.")} - - )} - {type === "return" && ( - <> -

Hợp đồng {p.contract_id}

- - set("date", e.target.value)} - /> - - -