diff --git a/DECISIONS.md b/DECISIONS.md index cc20e39..5dac273 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -121,4 +121,22 @@ - Mọi dữ liệu hiển thị trên bảng làm việc của Nhân viên (`GET /api/staff/board`) và Quản lý (`GET /api/manager/board`) đều được truy vấn trực tiếp từ các bảng SQL Server (`Reservations`, `StorageUnits`, `RentalContracts`, `UnitAssignments`, `HandoverRecords`, `ReturnInspections`, `SupportTickets`, `UserFacilities`, `Payments`). - Mọi thao tác ghi nhận (đối soát, phân bổ kho, bàn giao, kiểm tra trả kho, gia hạn, hoàn cọc) đều được lưu vĩnh viễn vào SQL Server qua `dbContext.SaveChangesAsync()`. - Các hành động của khách hàng (`REQUEST_RETURN`, `UPDATE_NAME`, `CHANGE_PASSWORD`) được kết nối trực tiếp đến các endpoint backend (`POST /api/contracts/{id}/move-out`, `PUT /api/auth/profile`, `POST /api/auth/change-password`). +## D20 — Toạ độ cơ sở lưu trong database, Vận hành KD sửa ở B05a — Đã chốt (15/10/2026) +- Bảng `facilities` thêm `Latitude`, `Longitude` (decimal(9,6), cùng có hoặc cùng trống). API cơ sở công khai và `/api/operations/facilities` trả / nhận hai trường này. +- Màn B05 thêm nút "Sửa thông tin cơ sở" mở hộp thoại B05a (tên, địa chỉ, điện thoại, giờ ra vào, vĩ độ, kinh độ). Dán cặp toạ độ copy từ Google Maps vào một ô thì tự tách hai ô. +- Bản đồ Tìm kho (C02m) đọc toạ độ từ API; `src/config/geo.js` chỉ còn là toạ độ dự phòng cho cơ sở chưa nhập. +- Toạ độ khởi tạo của 12 cơ sở lấy giống `geo.js` (ước lượng); Vận hành KD nên kiểm tra lại trên Google Maps và sửa ở B05a. + +## D21 — Giao diện thanh toán theo Figma 16/10: PayOS + tại cửa hàng, QR mở cửa mô phỏng — Đã chốt (16/10/2026) +- C04 có hai lựa chọn: **Thanh toán QR** (PayOS, tự xác nhận qua webhook PayOS, giao diện hỏi trạng thái 3 giây/lần rồi tự + sang C05) và **Tại cửa hàng** (C04c → C05c, nhân viên thu ở S09). Bỏ nút "Tôi đã chuyển khoản"; chữ "đối soát" đổi thành + "thanh toán" / "thu tiền" trên mọi màn (S09 "Thu tiền tại kho"). +- Giữ chỗ khi thanh toán QR: **10 phút** (Figma C04; `VITE_PAYMENT_TIMEOUT_SECONDS=600`, trước là 60 giây). Tại cửa hàng: 24 giờ. +- Thanh toán tại cửa hàng dùng lại trạng thái `PENDING_VERIFICATION` (hàng chờ S09 sẵn có). Backend chưa có + `pay-at-facility` thì giao diện gọi `confirm-transfer` — luồng vẫn chạy với backend hiện tại. +- Endpoint mới chưa có trên backend (404/405 không kèm nội dung) → giao diện hiện thông báo thay thế, không báo lỗi + (`src/api/payment-access.js` `isUnsupported`). Hợp đồng JSON: `SafeSpace-Customer-UI/BACKEND-TODO.md` mục "Mới 16/10". +- QR mở cửa: **mô phỏng** máy quét ở `#/door` (không cần đăng nhập, như thiết bị tại cơ sở); mã QR chỉ là mã tham chiếu. +- Huỷ đơn đã thanh toán (C14a) lấy số tiền hoàn từ `cancel-preview`; chế độ trình duyệt tạm tính phí 10% tiền thuê như Figma. +- M02a đổi trạng thái ô chỉ cho Trống ↔ Bảo trì và Chờ kiểm tra → Trống / Bảo trì (SRS 8.1); ô đang có khách không đổi ở đây. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example index 1fe7d33..5b82914 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/.env.example @@ -6,7 +6,7 @@ VITE_API_URL=http://localhost:5151 VITE_USE_API=true # Thời gian giữ đơn chờ chuyển khoản (giây). Figma: 01:00 → 60. Dùng 900 cho 15 phút. -VITE_PAYMENT_TIMEOUT_SECONDS=60 +VITE_PAYMENT_TIMEOUT_SECONDS=600 # Tài khoản nhận chuyển khoản, dùng để tạo mã VietQR ở màn thanh toán (C04) VITE_BANK_BIN=970422 diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index b344726..1048b2c 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -7,6 +7,79 @@ API ngay khi backend có — không cần sửa giao diện nếu làm đúng h Chạy thử hợp đồng không cần .NET: `MOCK_OPS=1 npm run dev:mock` (máy chủ giả lập `mock/mock-api.mjs` đã làm đủ các endpoint mục A–B; `tests/ops-api.test.mjs` kiểm tra từng endpoint). Backend làm đúng như mock là giao diện chạy. +## Mới 16/10/2026 — API cho các màn đồng bộ Figma (PayOS, thanh toán tại kho, QR mở cửa, F12) + +Giao diện **đã gọi sẵn** các endpoint dưới đây (`src/api/endpoints.js`, `src/api/payment-access.js`, `src/ops/api.js`). +Backend chưa có route → giao diện **không báo lỗi**: hiện thông báo thay thế (bảng cột "Khi chưa có") cho tới khi backend +làm xong. Máy chủ giả lập đã làm đủ (`npm run dev:mock`), `tests/payment-api.test.mjs` kiểm tra từng endpoint. Làm đúng +tên route + tên trường JSON là giao diện chạy ngay, không phải sửa giao diện. JSON camelCase như các endpoint đang có. + +| Mục | Endpoint | Người làm | Khi chưa có (404/405) | +|---|---|---|---| +| P1 | ~~`POST /api/reservations/{id}/payos`~~ — **đã nối** vào `POST /api/reservations/create-payos-qr` `{ reservationId }` có sẵn trên main (16/10) | Đạt | — | +| P2 | `POST /api/reservations/{id}/pay-at-facility` → `ReservationDto` | Đạt | Giao diện gọi `confirm-transfer` (đã có) → đơn vẫn vào S09 chờ thu tiền | +| P3 | `POST /api/payments/{id}/payos` → `PayosCheckoutDto`; `GET /api/payments/{id}` (đã có) để hỏi trạng thái | Đạt | Popup C11q báo "đang tạm gián đoạn, thanh toán tại quầy" | +| P4 | Webhook PayOS — **đã có** `POST /api/payments/payos-webhook` (webhook đổi đơn sang `CONFIRMED`) | Đạt | — (giao diện hỏi trạng thái 3 giây/lần) | +| Q1 | `GET /api/contracts/{id}/access-qr` → `AccessQrDto` | Tiến | Popup C07q báo "Mã QR đang được cơ sở kích hoạt" | +| Q2 | `POST /api/access/scan` `{ code }` → `ScanResultDto` (cho phép không đăng nhập — máy quét ở cửa) | Tiến | Màn `#/door` báo "Máy quét chưa kết nối được hệ thống" | +| R1 | `GET /api/tickets/{id}` trả thêm `responses[]` | Ngọc Mai | C12 không hiện dòng phản hồi | +| H1 | `GET /api/reservations/{id}/cancel-preview` → `CancelPreviewDto`; `ReservationDto` thêm `refundAmount`, `refundStatus` | Ngọc Mai | C14a ghi "Theo chính sách hiện hành / Cơ sở xác nhận sau khi huỷ" | +| U1 | **Đã nối** `PUT /api/staff/units/{mã}/status` `{ status, reason }` có sẵn trên main (nhân viên + quản lý). Còn thiếu: kiểm chuyển tiếp hợp lệ, bắt buộc lý do, trạng thái `INSPECTION` | Thắng | — | + +### P · PayOS (D19) và thanh toán tại cửa hàng +```json +// PayosCheckoutDto — P1, P3 (gọi lại khi đơn PayOS còn hạn thì trả lại đúng đơn cũ, không tạo mới) +{ "orderCode": 100001, "amount": 4600000, "description": "SS0142", "status": "PENDING", + "qrCode": "000201010212385700...6304ABCD", "checkoutUrl": "https://pay.payos.vn/web/...", "expiredAt": "2026-10-16T08:10:00Z" } +``` +- `qrCode`, `checkoutUrl` lấy nguyên từ PayOS SDK (`createPaymentLink`). Giao diện vẽ `qrCode` thành ảnh QR, kèm link `checkoutUrl`. +- `amount` của P1 = `estimatedAmount + requiredDeposit` (thuê cả kỳ + cọc 1 tháng). P3 = số tiền khoản `RENEWAL`. +- `expiredAt` = thời gian giữ chỗ. Giao diện đếm ngược theo giá trị nhỏ hơn giữa `expiredAt` và 10 phút (`VITE_PAYMENT_TIMEOUT_SECONDS=600`); + hết giờ giao diện gọi `POST /api/reservations/{id}/cancel` như cũ. **Backend đặt `expiredAt` 10 phút** cho khớp Figma C04. +- Webhook (P4): kiểm chữ ký bằng SDK + Checksum Key, đúng `orderCode`, đúng `amount`, gửi trùng chỉ ghi một lần. Đặt chỗ: đơn + `PENDING_PAYMENT` → `CONFIRMED` (hoặc `PAID`; giao diện coi cả hai là "Đã thanh toán", `UNIT_ASSIGNED` cũng vậy) và ghi khoản + thuê + cọc `PAID`. Gia hạn: payment `RENEWAL` → `PAID`, renewal → `PAID`, `contracts.end_date` = `newEndDate`. +- Giao diện hỏi trạng thái bằng `GET /api/reservations/{id}` (đặt chỗ) và `GET /api/payments/{id}` (gia hạn, `status: "PAID"`). +- Lúc quản lý phân bổ ô (M05) với đơn đã trả qua PayOS: gắn các khoản đã thu vào hợp đồng, **không tạo khoản mới**. +- P2 thanh toán tại cửa hàng: đơn `PENDING_PAYMENT` → trạng thái chờ thu (dùng `PENDING_VERIFICATION` sẵn có, hoặc trạng thái mới + `PENDING_AT_FACILITY` — giao diện hiểu cả hai), ghi `paymentMethod: "AT_FACILITY"` trong `ReservationDto`, giữ chỗ 24 giờ + (job nền tự huỷ khi quá hạn), huỷ link PayOS đang mở của đơn. `GET /api/ops/board` phải đưa đơn này vào `payments[]` để hiện + ở S09; nhân viên xác nhận bằng `POST /api/ops/payments/{id}/confirm` (đã có). Đơn trả PayOS **không** vào `payments[]`. +- Board `payments[]` nên trả thêm `rent`, `deposit`, `months` (S09 dòng "Gồm"); chưa có thì giao diện tự tách từ `amount`. + +### Q · QR mở cửa (Tiến) — mô phỏng, không dùng thiết bị thật +```json +// AccessQrDto — Q1: chỉ chủ hợp đồng, hợp đồng đã bàn giao (HANDED_OVER) và còn hiệu lực; sai → 400 { "error": "..." } +{ "contractId": 86, "code": "SSQR-86-4821", "backupCode": "4821 9037", "unitNumber": "B-015", + "unitType": "Kho lạnh", "location": "Tầng 1 · Dãy B", "validUntil": "2026-12-25" } +// ScanResultDto — Q2: nhận code hoặc backupCode; luôn trả 200, kết quả nằm trong "result"; ghi activity_logs mỗi lần quét +{ "result": "OPEN", "unitNumber": "B-015", "customerName": "Nguyễn Thị Mai", "contractCode": "HĐ-2026-0086", + "scannedAt": "2026-10-16T03:32:00Z", "reason": null } +{ "result": "DENIED", "reason": "Mã đã hết hiệu lực — hợp đồng đã trả kho.", "unitNumber": "B-015", ... } +``` +`code` chỉ là mã tham chiếu (không chứa bí mật). Hết hiệu lực khi biên bản trả kho được lập (S04) hoặc hợp đồng kết thúc. +Hợp đồng quá hạn có khoá QR hay không: nhóm chốt (giao diện chỉ hiện `reason` backend trả về). + +### R · Phản hồi hỗ trợ (Ngọc Mai) +`SupportTicketDetailDto` thêm `"responses": [{ "message": "Thẻ cũ bị lỗi từ…", "staffName": "Trần Văn Long", "createdAt": "2026-09-14T04:02:00" }]` +(lấy từ phản hồi S05, hiện đang nằm trong `activity_logs`). Giao diện cũng đọc `note`/`content` nếu đặt tên khác. + +### H · Huỷ đơn đã thanh toán (Ngọc Mai) +```json +// CancelPreviewDto — theo chính sách CANCELLATION đang hiệu lực ở B02 +{ "paidAmount": 4600000, "cancellationFee": 345000, "refundAmount": 4255000, "policyName": "Huỷ trước ngày nhận kho: phí 10% tiền thuê" } +``` +`POST /api/reservations/{id}/cancel` (đã có, nhận `PENDING_PAYMENT` / `CONFIRMED`) với đơn đã trả: ghi khoản `REFUND`, trả +`refundAmount` + `refundStatus: "PENDING"` trong `ReservationDto` để C14b hiện "Đã huỷ · Đang hoàn tiền". + +### U · Đổi trạng thái ô kho — F12 (Thắng) +`PUT /api/ops/units/{code}/status` `{ "status": "MAINTENANCE", "reason": "Hỏng khoá cửa" }` — chỉ `MANAGER`, đúng cơ sở. +Trạng thái theo từ của board: `EMPTY` (DB `AVAILABLE`), `MAINTENANCE`, `INSPECTION`. Chỉ cho: `EMPTY ↔ MAINTENANCE`, +`INSPECTION → EMPTY | MAINTENANCE`; ô đang có khách → 400. Thiếu lý do → 400. Ghi `unit_status_history` (dùng lại +`FacilityOpsService.SetUnitStatus`). Board `units[]` nên trả thêm `history[]` `{ from, to, reason, by, at }` (không bắt buộc). + +--- + ## Đã nối API (không cần làm thêm) `/api/auth/register · login · logout`, `/api/facilities`, `/api/unit-types`, `/api/rates`, `/api/availability/check`, `/api/reservations` (tạo, xem, huỷ), `/api/contracts` (+ payments, renewals), `/api/handovers/{id}/confirm`, @@ -77,7 +150,7 @@ Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái) ## C. Ưu tiên 3 — chỉnh nhỏ - [ ] JSON `DateTime` trả kèm `Z` (UTC); hiện đọc từ DB không có múi giờ, giao diện phải tự coi là UTC. -- [ ] Giữ chỗ đơn chờ chuyển khoản: backend 24 giờ, Figma 1 phút → thống nhất một con số (giao diện đọc `VITE_PAYMENT_TIMEOUT_SECONDS`). +- [ ] Giữ chỗ: thanh toán QR 10 phút (Figma C04, `VITE_PAYMENT_TIMEOUT_SECONDS=600`), thanh toán tại cửa hàng 24 giờ (C04c) — backend đặt `ExpiresAt` / `expiredAt` PayOS theo hai con số này. - [ ] Khu quản trị: ~~role `OPERATIONS` (Vận hành KD)~~ (đã có), ghi lịch sử đăng nhập thất bại, lọc nhật ký nhiều `action`. - [x] API khu Vận hành KD (Figma B01–B05): `/api/operations/*`, role `OPERATIONS`, tài khoản `ops01` / `Ops@123` — hợp đồng ở `docs/operations-api.md`. Giao diện B01–B05 chưa có. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md index 90a2443..21e2e7e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -47,8 +47,8 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: | Điểm | Figma / giao diện hiện tại | Backend cũ (v3) | |---|---|---| -| Thanh toán đặt chỗ | Khách chuyển khoản QR **ngay lúc đặt** (C04), bấm "Tôi đã chuyển khoản" → đơn "Chờ đối soát" | Đặt chỗ trước, thanh toán sau khi có hợp đồng | -| Giữ chỗ | Đơn chờ chuyển khoản **tự huỷ sau N giây** (Figma: 60 giây) → C04b | Không có | +| Thanh toán đặt chỗ | **QR PayOS** ngay lúc đặt (C04), tự xác nhận qua webhook, trang tự chuyển (D19); hoặc **thanh toán tại cửa hàng** (C04c) → nhân viên thu ở S09 | Đặt chỗ trước, thanh toán sau khi có hợp đồng | +| Giữ chỗ | QR: **10 phút** (Figma C04) rồi tự huỷ → C04b; tại cửa hàng: 24 giờ (C04c) | Không có | | Số tiền chuyển | Tổng ban đầu = tiền thuê + cọc (cọc = 1 tháng) | — | | Gói thuê | 1 / 3 / 6 tháng | 1–24 tháng tuỳ nhập | | Đăng ký | Họ tên, email, SĐT, mật khẩu, xác nhận; **không có username** | Có `username` | @@ -59,9 +59,9 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: ## 2. Trạng thái UI dùng (khoá → nhãn) -- **Reservation**: `PENDING_PAYMENT` Chờ chuyển khoản · `PENDING_VERIFICATION` Chờ đối soát · `CONFIRMED` Đã xác nhận · `CHECKED_IN` Đã nhận kho · `CANCELLED` Đã huỷ đặt chỗ (kèm `cancel_reason`) +- **Reservation**: `PENDING_PAYMENT` Chờ thanh toán · `PENDING_VERIFICATION` Chờ thanh toán tại cửa hàng (BE `PENDING_VERIFICATION` hoặc `PENDING_AT_FACILITY`) · `CONFIRMED` Đã xác nhận (BE `CONFIRMED` / `PAID` / `UNIT_ASSIGNED`) · `CHECKED_IN` Đã nhận kho · `CANCELLED` Đã huỷ đặt chỗ (kèm `cancel_reason`) - **Contract**: `ACTIVE`, `ENDED` lưu ở BE; `EXPIRING` (≤ 30 ngày) và `OVERDUE` UI tự suy ra từ `end_date` -- **Ledger (khoản thu)**: `RECONCILED` Đã đối soát · `PENDING_VERIFICATION` Chờ đối soát · `DEPOSIT_HELD` Đang giữ cọc · `RENEWAL_PENDING` Chờ duyệt yêu cầu · `UNPAID` Chưa thanh toán · `REFUNDED` +- **Ledger (khoản thu)**: `RECONCILED` Đã thanh toán · `PENDING_VERIFICATION` Chờ thanh toán tại cửa hàng · `DEPOSIT_HELD` Đang giữ cọc · `RENEWAL_PENDING` Chờ duyệt yêu cầu · `UNPAID` Chờ thanh toán (khoản `RENEWAL` chưa trả có nút "Thanh toán" → C11q) · `REFUNDED` - **Appointment**: `kind` = `CHECK_IN` | `MOVE_OUT`; `status` = `CONFIRMED` | `PENDING` | `DONE` | `CANCELLED` - **Ticket**: `OPEN` · `IN_PROGRESS` · `RESOLVED` · `CANCELLED`; `topic` = `ACCESS|LOCK|UNIT|PAYMENT|ITEMS|SCHEDULE|OTHER` - **Renewal**: `PENDING` | `APPROVED` | `REJECTED` — **Return**: `PENDING` | `SCHEDULED` | `COMPLETED` @@ -79,7 +79,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: | C03b | `POST /api/quotes` `{facilityId, type, band, months, startDate}` | → `monthlyRate, rentTotal, deposit, initialTotal, endDate, available` | | C03c | `GET /api/facilities/{id}/photos` | 4+ ảnh kèm chú thích (mặt tiền, sơ đồ, ...) | | C04 | `POST /api/reservations` | Tạo đơn `PENDING_PAYMENT`, trả `reservationId, expiresAt, timeoutSeconds, transferAmount, transferContent` (UI tự tạo VietQR từ tài khoản nhận) | -| C04 | `POST /api/reservations/{id}/confirm-transfer` | → `PENDING_VERIFICATION`; sau `expiresAt` trả lỗi mã `EXPIRED` — **đã có** (D18) | +| C04 | `POST /api/reservations/{id}/payos`, `POST /api/reservations/{id}/pay-at-facility` | PayOS + thanh toán tại cửa hàng — hợp đồng JSON ở `BACKEND-TODO.md` mục "Mới 16/10". `confirm-transfer` (đã có) chỉ còn là dự phòng khi chưa có `pay-at-facility` | | C04b | (job nền) | Tự chuyển `PENDING_PAYMENT` quá hạn sang `CANCELLED`, `cancelReason` kiểu "Quá 1 phút chưa xác nhận" | | C14, C05 | `GET /api/reservations`, `GET /api/reservations/{id}` | | | C06, C07 | `GET /api/contracts`, `GET /api/contracts/{id}` | Thêm `unitNumber, sizeM2, location, handedOver, depositAmount` | diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md index 031c372..b1842de 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md @@ -14,22 +14,25 @@ Nguồn: file Figma "SafeSpace - Modern UI" (section Khách hàng + Trang chủ | C02a–f, C03 | `#/find?type=&band=&area=` | `pages/FindList.jsx` | Các trạng thái chọn + kết quả lọc + trail 01→04 | | Nút Danh sách · Bản đồ | `#/find` ↔ `#/find/map` | `components/Inline.jsx` (`ViewToggle`) | Góc trên phải của C02 và C02m, giữ bộ lọc khi chuyển | | C01/C06/C14-trống | `#/overview`, `#/units`, `#/reservations` | `components/Inline.jsx` (`EmptyInline`) | Khách chưa có kho / đơn: một dòng thông báo + nút "Tìm & đặt kho" | -| C02m, C02m-1, C02m-2 | `#/find/map` | `pages/FindMap.jsx` | Chỉ có thanh tìm kho + bản đồ Leaflet/OSM (không có danh sách thẻ, Figma 01/10); bấm logo mở "Thông tin cơ sở" + "Xem chi tiết cơ sở" | -| C03b, C03b-1..3 | `#/find/:id` | `pages/FacilityDetail.jsx` | Loại kho, diện tích, gói 1/3/6 tháng, lịch chọn ngày, chi phí | +| C02m, C02m-1, C02m-2 | `#/find/map` | `pages/FindMap.jsx` | Chỉ có thanh tìm kho + bản đồ Leaflet/OSM (không có danh sách thẻ, Figma 01/10); bấm logo mở "Thông tin cơ sở" + "Xem chi tiết cơ sở" + "Chỉ đường" | +| 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í; khối "Chỉ đường đến cơ sở" mở Google Maps (toạ độ D20, chưa có thì theo địa chỉ) | | C03b-sđ (13 cơ sở) | `#/find/:id?view=map&unit=K01` | `pages/FacilityDetail.jsx`, `components/UnitMap.jsx` | Nút "Xem sơ đồ & tình trạng kho" ↔ "← Xem ảnh & tiện ích"; 10 ô; tóm tắt đổi theo ô; ô không trống → nút xám "Ô này hiện không khả dụng" | | C03c-1..4 | (lightbox) | `components/Photo.jsx` | 5 ảnh: ảnh cơ sở + 4 ảnh bên trong kho (đã bỏ sơ đồ mặt bằng); ← → / Esc | -| C04 Đặt chỗ & Thanh toán | `#/checkout/:id` | `pages/Checkout.jsx` | Mã VietQR thật, số tiền, nội dung CK, đếm ngược, "Tôi đã chuyển khoản" | +| C04 Đặt chỗ & Thanh toán | `#/checkout/:id` | `pages/Checkout.jsx` | Chọn "Thanh toán QR" / "Tại cửa hàng". QR PayOS từ `POST /api/reservations/{id}/payos`, tiền thuê + cọc, đếm ngược 10:00, hỏi trạng thái 3 giây/lần rồi tự sang C05 (D19). Đã bỏ "Tôi đã chuyển khoản" | +| C04c Thanh toán tại cửa hàng | `#/checkout/:id` (chọn "Tại cửa hàng") | `pages/Checkout.jsx` | Giữ chỗ 24 giờ, "Xác nhận đặt chỗ" → `pay-at-facility` (chưa có thì `confirm-transfer`) → C05c | | C04b Không thành công | `#/checkout/:id/failed` | `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" | +| C05 / C05c Xác nhận | `#/confirmation/:id` | `pages/Checkout.jsx` | QR: "Đã thanh toán"; tại cửa hàng: "Đã giữ chỗ cho bạn", số tiền, hạn 24 giờ, "Chờ thanh toán tại cửa hàng" | | C06 Kho của tôi | `#/units` | `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 | +| C07 / C07b Hợp đồng | `#/units/:id` | `pages/Units.jsx` | Chưa bàn giao (F29): "Xem / Đổi lịch nhận kho", khoá gia hạn, trả kho, mở cửa. Đã bàn giao: "Mở cửa kho" mở C07q. Gia hạn / trả kho khoá khi đang có yêu cầu chờ | +| C07q QR mở cửa | (popup ở `#/units/:id`) | `pages/Units.jsx` (`AccessQrModal`) | `GET /api/contracts/{id}/access-qr`: QR, mã dự phòng, ô kho, hiệu lực; link "Mô phỏng quét ở cửa kho" | +| C07r1 / C07r2 Máy quét | `#/door?unit=&code=` | `pages/Door.jsx` | Mô phỏng máy quét (không cần đăng nhập): `POST /api/access/scan` → "Mở cửa" / "Từ chối" kèm lý do | +| C08 / C08b Gia hạn | `#/units/:id/renew` | `pages/Units.jsx` | Chọn 1/3/6 tháng; chỉ trả tiền thuê kỳ mới, cọc chuyển sang kỳ mới | | C09 / C09b Trả kho | `#/units/:id/return` | `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 | +| C11 / C11b Thanh toán & lịch hẹn | `#/payments` | `pages/Payments.jsx` | Thẻ lịch hẹn + bảng khoản thu; khoản gia hạn đã duyệt có nút "Thanh toán" → C11q (`components/PayosModal.jsx`, `POST /api/payments/{id}/payos`); trả xong hiện thông báo C11b | +| 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; khối "Phản hồi của nhân viên" từ `responses[]` của `GET /api/tickets/{id}` | | 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` | | +| C14 / C14a / C14b Đơn đặt chỗ | `#/reservations`, `#/reservations/:id` | `pages/Reservations.jsx`, `pages/Checkout.jsx` | Nút "Huỷ đơn" (đơn chưa nhận kho) → hộp thoại C14a: đã trả, phí huỷ, số tiền hoàn (`cancel-preview`); huỷ xong "Đã huỷ · Đang hoàn tiền" | | Popup thông báo (public / customer, đã đọc) | (header) | `components/Header.jsx` | | ## Chỗ Figma tự mâu thuẫn, code chọn như sau diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md index b7a281b..c8db328 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md @@ -7,9 +7,9 @@ Dữ liệu: `src/ops/data.js` (khởi tạo) · nghiệp vụ: `src/ops/reducer | Figma | Route | Làm được gì | |---|---|---| -| S01 Công việc trong ngày | `#/staff` | 3 số liệu + thẻ việc dạng **lưới 3x3** (9 thẻ / trang, phân trang); không có việc → S01-trống | +| S01 Công việc trong ngày | `#/staff` | 3 số liệu (có "Chờ thu tiền tại kho") + thẻ việc dạng **lưới 3x3** (9 thẻ / trang, phân trang); không có việc → S01-trống | | S09a / S02a / S03a / S04a / S05a | `#/staff/reconcile` … `#/staff/support` (không có `?id`) | Mỗi tab là lưới 3x3 thẻ việc của tab đó; bấm thẻ mở màn xử lý; không có việc → thông báo trống (S09a-trống) | -| S09 Đối soát thanh toán | `#/staff/reconcile?id=` (có `?id`) | Xác nhận đã thu / Báo sai lệch (bắt buộc ghi rõ) | +| S09 Thu tiền tại kho | `#/staff/reconcile?id=` (có `?id`) | Đơn khách chọn "Thanh toán tại cửa hàng": số tiền, giữ chỗ đến, gồm thuê + cọc; "Xác nhận đã thu" (`POST /api/ops/payments/{id}/confirm`) / "Để sau". Đơn trả PayOS không vào đây | | S02 Xác minh khách hàng | `#/staff/verify?id=` | Loại + số giấy tờ (chỉ giữ 4 số cuối), 2 ô đối chiếu; xong chuyển sang bàn giao | | S03 Bàn giao kho | `#/staff/handover?id=` | Thẻ từ / Mã PIN / Vân tay; chặn khi chưa xác minh; kho → Đang hoạt động | | S04 Kiểm tra trả kho | `#/staff/return?id=` | 4 mục biên bản, gửi quản lý; kho → Chờ kiểm tra | @@ -21,7 +21,7 @@ Dữ liệu: `src/ops/data.js` (khởi tạo) · nghiệp vụ: `src/ops/reducer | Figma | Route | Làm được gì | |---|---|---| | M01 Tổng quan | `#/manager` | 86 kho, tỷ lệ lấp đầy tính từ dữ liệu, doanh thu, "Cần xử lý" gom mọi việc tồn | -| M02 Danh sách kho | `#/manager/units?tab=` | Lọc theo trạng thái, tìm mã kho / khách, phân trang 12 | +| M02 / M02a Danh sách kho | `#/manager/units?tab=` | Lọc theo trạng thái (thêm "Bảo trì"), tìm mã kho / khách, phân trang 12; cột "Thao tác": "Đổi trạng thái" → hộp thoại M02a (Trống ↔ Bảo trì, Chờ kiểm tra → Trống / Bảo trì, bắt buộc lý do) — `PUT /api/ops/units/{code}/status` (F12) | | M05 Phân bổ kho | `#/manager/allocate?id=` | Chỉ hiện kho trống đúng loại + diện tích; phân bổ xong tạo lịch xác minh & bàn giao cho nhân viên | | M06 Phân công | `#/manager/assign` | Giao việc cho nhân viên (ca làm, số việc đang nhận) | | M03 Gia hạn | `#/manager/renewals` | Duyệt (cập nhật ngày hết hạn) / Từ chối (bắt buộc lý do) | diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md index ad53d3e..8001a44 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md @@ -62,7 +62,8 @@ Muốn làm lại từ đầu: xoá `safespace.ops.v1` và `safespace.customer.v | Hợp đồng, khoản thu, lịch nhận kho, xác nhận bàn giao | `/api/contracts`, `/api/handovers/{id}/confirm` | | Gia hạn | `POST /api/contracts/{id}/renewals` | | Yêu cầu hỗ trợ (gửi, xem, huỷ) | `/api/tickets` | -| Báo "Tôi đã chuyển khoản", đăng ký trả kho, thông báo, đổi tên hiển thị, ảnh đính kèm hỗ trợ | Backend **chưa có API** → lưu trong trình duyệt theo từng tài khoản | +| Thanh toán QR PayOS (C04, C11q), thanh toán tại cửa hàng (C04c), QR mở cửa + máy quét `#/door` (C07q/C07r), phản hồi hỗ trợ (C12), xem trước hoàn tiền (C14a), đổi trạng thái ô (M02a) | Giao diện **gọi sẵn** endpoint theo `BACKEND-TODO.md` mục "Mới 16/10"; backend chưa có (404/405) → hiện thông báo thay thế, thanh toán tại cửa hàng tự dùng `confirm-transfer`. Thử đủ luồng: `MOCK_OPS=1 npm run dev:mock`; thử như backend chưa cập nhật: thêm `MOCK_LEGACY=1` | +| Đăng ký trả kho, thông báo, đổi tên hiển thị, ảnh đính kèm hỗ trợ | Backend **chưa có API** → lưu trong trình duyệt theo từng tài khoản | | Đổi mật khẩu, quên mật khẩu | Backend chưa có API → giao diện hướng dẫn liên hệ quản trị viên | | Sơ đồ tình trạng 10 ô kho, toạ độ cơ sở trên bản đồ | Backend chưa có API → sinh cố định theo cơ sở (`src/lib/units.js`, `src/config/geo.js`) | | Toàn bộ khu Nhân viên / Quản lý cơ sở | Đăng nhập qua API (vai trò `STAFF` / `MANAGER` trong JWT); dữ liệu vận hành lưu trong trình duyệt (`src/ops/`) cho đến khi backend có API (xem mục 5 của `BE-CONTRACT.md`) | diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs index 9e8ded3..363bbb5 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs @@ -94,6 +94,10 @@ export function createState() { ]; const tickets = [ { ticketId: 1, customerId: 3, contractId: 1, unitId: 3, issueType: "UNIT", title: "Kiểm tra nhiệt độ phòng kho", description: "Nhờ nhân viên kiểm tra lại nhiệt độ kho TB-M-103 vào buổi trưa", priority: "NORMAL", status: "OPEN", createdAt: days(-2), assignedAt: null, resolvedAt: null, closedAt: null }, + { + ticketId: 2, customerId: 3, contractId: 1, unitId: 3, issueType: "ACCESS", title: "Lỗi thẻ ra vào", description: "Thẻ ra vào chưa mở được cổng cơ sở.", priority: "HIGH", status: "RESOLVED", createdAt: days(-6), assignedAt: days(-6), resolvedAt: days(-6), closedAt: null, + responses: [{ message: "Thẻ cũ bị lỗi từ. Bạn qua quầy lễ tân nhận thẻ mới, mang theo CCCD giúp mình nhé.", staffName: "Trần Nhân Viên", createdAt: days(-6) }], + }, ]; const roles = [ { roleId: 1, roleName: "ADMIN", description: "Quản trị viên toàn quyền hệ thống" }, @@ -109,7 +113,11 @@ export function createState() { const rolePermissions = permissions.map((p) => ({ roleId: 1, permissionId: p.permissionId })); const userRoles = [{ userId: 1, roleId: 1 }, { userId: 2, roleId: 3 }, { userId: 3, roleId: 4 }, { userId: 4, roleId: 4 }]; for (const u of users) Object.assign(u, { phone: null, createdAt: days(-30 + u.userId), updatedAt: days(-30 + u.userId) }); - return { users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals: [], tickets, tokens: new Map(), down: false, roles, permissions, rolePermissions, userRoles, userFacilities: [], loginHistory: [], activityLogs: [] }; + // Gia hạn đã được quản lý duyệt (M03) → khoản RENEWAL chờ khách trả qua PayOS ở C11 (BACKEND-TODO.md mục P3) + const renewEnd = addMonths(contracts[0].endDate, 3); + const renewals = [{ renewalId: 1, contractId: 1, oldEndDate: contracts[0].endDate, newEndDate: renewEnd, renewalPeriodMonths: 3, oldMonthlyRate: 1500000, newMonthlyRate: 1500000, renewalAmount: 4500000, status: "APPROVED", requestedAt: days(-2) }]; + payments.push({ paymentId: 3, contractId: 1, renewalId: 1, paymentType: "RENEWAL", amount: 4500000, currency: "VND", paymentMethod: "PAYOS", transactionReference: "SS-0001-REN", dueDate: contracts[0].endDate, paidAt: null, status: "PENDING", createdAt: days(-1) }); + return { users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals, tickets, payos: new Map(), accessLogs: [], tokens: new Map(), down: false, roles, permissions, rolePermissions, userRoles, userFacilities: [], loginHistory: [], activityLogs: [] }; } // ---- Khu vận hành (Nhân viên / Quản lý cơ sở): chỉ bật khi { ops: true } hoặc MOCK_OPS=1. @@ -127,7 +135,7 @@ const OPS_ROUTES = [ ["POST", /^\/api\/(?:ops|staff)\/handovers\/([^/]+)\/complete$/, "STAFF", "HANDOVER", (b, id) => ({ id, method: b?.unlockMethod })], ["POST", /^\/api\/(?:ops|staff)\/returns\/([^/]+)\/inspection$/, "STAFF", "SUBMIT_RETURN", (b, id) => ({ id, report: mapKeys(b || {}, snake) })], ["POST", /^\/api\/(?:ops|staff)\/tickets\/([^/]+)\/responses$/, "STAFF", "TICKET_RESPONSE", (b, id, me) => ({ id, note: b?.note, next: b?.nextStatus, staff: me })], - ["PUT", /^\/api\/(?:ops|staff)\/units\/([^/]+)\/status$/, "STAFF", "UPDATE_UNIT_STATUS", (b, id) => ({ id, status: b?.status, reason: b?.reason })], + ["PUT", /^\/api\/(?:ops|staff)\/units\/([^/]+)\/status$/, "STAFF", "UPDATE_UNIT_STATUS", (b, id) => ({ id, code: id, status: b?.status, reason: b?.reason })], ["POST", /^\/api\/(?:ops|staff)\/credentials\/([^/]+)\/revoke$/, "STAFF", "REVOKE_CREDENTIAL", (b, id) => ({ id })], ["POST", /^\/api\/(?:ops|staff)\/credentials\/reissue$/, "STAFF", "REISSUE_CREDENTIAL", (b) => ({ unit: b?.unitCode, type: b?.credentialType, reason: b?.reason })], ["POST", /^\/api\/(?:ops|manager)\/renewals\/([^/]+)\/approve$/, "MANAGER", "DECIDE_RENEWAL", (b, id) => ({ id, approve: true })], @@ -141,7 +149,26 @@ const OPS_ROUTES = [ ["POST", /^\/api\/(?:ops|manager)\/units\/([^/]+)\/lock$/, "MANAGER", "LOCK_UNIT", (b, id) => ({ id, reason: b?.reason })], ]; -export function startMockApi(port = 5199, { verbose = false, ops = process.env.MOCK_OPS === "1", business = false } = {}) { +// Endpoint mới (BACKEND-TODO.md mục "Mới 16/10") — tắt hết khi chạy legacy để thử giao diện với backend chưa cập nhật +const LEGACY_MISSING = [ + /^\/api\/reservations\/\d+\/(payos|pay-at-facility|cancel-preview)$/, + /^\/api\/payments\/\d+\/payos$/, + /^\/api\/contracts\/\d+\/access-qr$/, + /^\/api\/access\/scan$/, + /^\/api\/ops\/units\/[^/]+\/status$/, +]; + +export function startMockApi( + port = 5199, + { + verbose = false, + ops = process.env.MOCK_OPS === "1", + business = false, + payosAutoPaySeconds = Number(process.env.MOCK_PAYOS_AUTOPAY ?? 0), + // legacy: giống backend hiện tại trên main — chưa có các endpoint mới 16/10 (trả 404 rỗng như ASP.NET) + legacy = process.env.MOCK_LEGACY === "1", + } = {}, +) { const S = createState(); if (business) { S.roles.push({ roleId: 5, roleName: 'OPERATIONS', description: 'Quản lý vận hành kinh doanh' }); @@ -168,6 +195,7 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M startDate: r.startDate, expectedEndDate: r.expectedEndDate, rentalPeriodMonths: r.rentalPeriodMonths, quotedMonthlyRate: r.quotedMonthlyRate, estimatedAmount: r.estimatedAmount, requiredDeposit: r.requiredDeposit, status: r.status, expiresAt: r.expiresAt ? dbTime(r.expiresAt) : null, cancelledAt: r.cancelledAt ? dbTime(r.cancelledAt) : null, cancellationReason: r.cancellationReason, createdAt: dbTime(r.createdAt), + paymentMethod: r.paymentMethod || null, refundAmount: r.refundAmount ?? null, refundStatus: r.refundStatus || null, }); const payDto = (p) => ({ ...p, paidAt: p.paidAt ? dbTime(p.paidAt) : null, createdAt: dbTime(p.createdAt) }); const renDto = (r) => ({ ...r, requestedAt: dbTime(r.requestedAt), approvedAt: null }); @@ -175,6 +203,42 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M const u = unit(c.unitId); return { contractId: c.contractId, reservationId: c.reservationId, unitId: c.unitId, unitNumber: u.unitNumber, facilityName: fac(u.facilityId).name, unitTypeName: ut(u.unitTypeId).typeName, startDate: c.startDate, endDate: c.endDate, agreedMonthlyRate: c.agreedMonthlyRate, depositAmount: c.depositAmount, status: c.status, activatedAt: c.activatedAt ? dbTime(c.activatedAt) : null }; }; + // ---- PayOS giả lập (D19): tạo đơn → QR → "webhook" (tự báo đã trả sau payosAutoPaySeconds hoặc gọi /__payos/paid?order=) + const payosPaid = (order) => { + const o = S.payos.get(order); + if (!o || o.status === "PAID") return; + o.status = "PAID"; + if (o.kind === "reservation") { + const r = S.reservations.find((x) => x.reservationId === o.id); + if (r && r.status === "PENDING_PAYMENT") Object.assign(r, { status: "CONFIRMED", paymentMethod: "PAYOS" }); + } else { + const p = S.payments.find((x) => x.paymentId === o.id); + if (p && p.status !== "PAID") { + Object.assign(p, { status: "PAID", paidAt: new Date(), transactionReference: p.transactionReference || `PAYOS-${order}` }); + const ren = S.renewals.find((x) => x.renewalId === p.renewalId); + const c = S.contracts.find((x) => x.contractId === p.contractId); + if (ren && c && ren.status !== "PAID") { + ren.status = "PAID"; + c.endDate = ren.newEndDate; + } + } + } + }; + const payosOrder = (kind, id, amount, description) => { + const existing = [...S.payos.values()].find((o) => o.kind === kind && o.id === id && o.status === "PENDING" && o.expiredAt > new Date()); + const o = existing || { orderCode: 100000 + S.payos.size + 1, kind, id, amount, description, status: "PENDING", expiredAt: new Date(Date.now() + 10 * 60000) }; + if (!existing) { + S.payos.set(o.orderCode, o); + if (payosAutoPaySeconds > 0) setTimeout(() => payosPaid(o.orderCode), payosAutoPaySeconds * 1000).unref?.(); + } + const qr = `00020101021238570010A000000727012700069704220113SAFESPACE${o.orderCode}0208QRIBFTTA530370454${String(o.amount).length.toString().padStart(2, "0")}${o.amount}5802VN62${String(o.description.length + 4).padStart(2, "0")}08${String(o.description.length).padStart(2, "0")}${o.description}6304ABCD`; + return { orderCode: o.orderCode, amount: o.amount, description: o.description, qrCode: qr, checkoutUrl: `https://pay.payos.vn/web/mock-${o.orderCode}`, expiredAt: iso(o.expiredAt), status: o.status }; + }; + const accessCode = (c) => { + const n = String((c.contractId * 7919 + 4821) % 100000000).padStart(8, "0"); + return { code: `SSQR-${c.contractId}-${n.slice(0, 4)}`, backup: `${n.slice(0, 4)} ${n.slice(4)}` }; + }; + const ticketDto = (t) => ({ ticketId: t.ticketId, contractId: t.contractId, unitId: t.unitId, issueType: t.issueType, title: t.title, priority: t.priority, status: t.status, createdAt: dbTime(t.createdAt), resolvedAt: null, closedAt: null }); const availability = (facilityId, unitTypeId, startDate, months) => { @@ -201,7 +265,14 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M if (path === "/__down") { S.down = true; return send(200, {}); } if (path === "/__up") { S.down = false; return send(200, {}); } if (path === "/__revoke") { S.tokens.clear(); return send(200, {}); } + // Giả lập webhook PayOS: /__payos/paid?order= (bỏ trống order = trả mọi đơn đang chờ) + if (path === "/__payos/paid") { + const order = Number(url.searchParams.get("order")); + for (const o of S.payos.values()) if (!order || o.orderCode === order) payosPaid(o.orderCode); + return send(200, {}); + } if (S.down) { req.socket.destroy(); return; } + if (legacy && LEGACY_MISSING.some((re) => re.test(path))) return send(404); let body = null; if (req.method === "POST" || req.method === "PUT") { const chunks = []; @@ -279,6 +350,26 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M return send(200, { facilityId: body.facilityId, facilityName: fac(body.facilityId)?.name, unitTypeId: body.unitTypeId, unitTypeName: t?.typeName, area: t?.area, climateControlled: t?.climateControlled, monthlyRate: rate?.monthlyRate || 0, estimatedTotalRent: (rate?.monthlyRate || 0) * body.rentalPeriodMonths, requiredDeposit: rate?.monthlyRate || 0, startDate: body.startDate, expectedEndDate: addMonths(body.startDate, body.rentalPeriodMonths), availableUnitCount: count, isAvailable: count > 0 }); } + // C07r · máy quét cửa kho (thiết bị tại cơ sở, không cần đăng nhập khách) + if (req.method === "POST" && path === "/api/access/scan") { + const code = String(body?.code || "").trim(); + const clean = code.replace(/\s/g, ""); + const c = S.contracts.find((x) => { const a = accessCode(x); return a.code === code || a.backup.replace(/\s/g, "") === clean; }); + const now = new Date(); + const out = (result, reason, cc) => { + S.accessLogs.push({ code, result, at: now }); + const u = cc && unit(cc.unitId); + const cust = cc && S.users.find((x) => x.userId === cc.customerId); + return send(200, { result, unitNumber: u?.unitNumber || null, customerName: cust?.fullName || null, contractCode: cc ? `HĐ-${cc.startDate.slice(0, 4)}-${String(cc.contractId).padStart(4, "0")}` : null, scannedAt: iso(now), reason }); + }; + if (!c) return out("DENIED", "Mã không đúng. Kiểm tra lại mã trên ứng dụng hoặc mã dự phòng.", null); + const h = S.handovers.find((x) => x.contractId === c.contractId); + if (c.status !== "ACTIVE") return out("DENIED", "Mã đã hết hiệu lực — hợp đồng đã trả kho.", c); + if (!h || h.status !== "HANDED_OVER") return out("DENIED", "Kho chưa được bàn giao cho khách.", c); + if (c.endDate < dateOnly(now)) return out("DENIED", "Hợp đồng đã quá hạn. Vui lòng gia hạn hoặc liên hệ cơ sở.", c); + return out("OPEN", null, c); + } + const user = auth(); if (path.startsWith("/api/") && !user) return send(401); const me = user?.userId; @@ -486,16 +577,44 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M r.status = "PENDING_VERIFICATION"; return send(200, resDto(r)); } + if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/payos$/))) { + const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); + if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." }); + if (r.status !== "PENDING_PAYMENT") return bad("Đơn đặt chỗ này không còn chờ thanh toán."); + return send(200, payosOrder("reservation", r.reservationId, r.estimatedAmount + r.requiredDeposit, `SS${String(r.reservationId).padStart(4, "0")}`)); + } + if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/pay-at-facility$/))) { + const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); + if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." }); + if (r.status === "PENDING_VERIFICATION") return send(200, resDto(r)); + if (r.status !== "PENDING_PAYMENT") return bad("Đơn đặt chỗ này không còn chờ thanh toán."); + Object.assign(r, { status: "PENDING_VERIFICATION", paymentMethod: "AT_FACILITY", expiresAt: new Date(Date.now() + 24 * 3600000) }); + for (const o of S.payos.values()) if (o.kind === "reservation" && o.id === r.reservationId && o.status === "PENDING") o.status = "CANCELLED"; + return send(200, resDto(r)); + } + if (req.method === "GET" && (m = path.match(/^\/api\/reservations\/(\d+)\/cancel-preview$/))) { + const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); + if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." }); + const paid = r.status === "CONFIRMED" ? r.estimatedAmount + r.requiredDeposit : 0; + const fee = paid ? Math.round(r.estimatedAmount * 0.1) : 0; + return send(200, { paidAmount: paid, cancellationFee: fee, refundAmount: paid - fee, policyName: "Huỷ trước ngày nhận kho: phí 10% tiền thuê" }); + } if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/cancel$/))) { const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); if (!r) return bad("Không tìm thấy đơn đặt chỗ hợp lệ."); if (!["PENDING_PAYMENT", "CONFIRMED"].includes(r.status)) return bad(`Không thể hủy đơn đặt chỗ ở trạng thái '${r.status}'.`); - Object.assign(r, { status: "CANCELLED", cancelledAt: new Date(), cancellationReason: body?.reason }); + const paid = r.status === "CONFIRMED" && r.paymentMethod === "PAYOS"; + Object.assign(r, { status: "CANCELLED", cancelledAt: new Date(), cancellationReason: body?.reason, ...(paid ? { refundAmount: r.estimatedAmount + r.requiredDeposit - Math.round(r.estimatedAmount * 0.1), refundStatus: "PENDING" } : {}) }); return send(200, { message: "Đã hủy đơn đặt chỗ thành công." }); } if (req.method === "POST" && (path === "/api/v1/reservations/create-payos-qr" || path === "/api/reservations/create-payos-qr")) { const resId = body?.reservationId; const r = S.reservations.find((x) => x.reservationId === resId); + // Đơn của khách đang chờ thanh toán → dùng chung PayOS giả lập (QR + webhook /__payos/paid) như /api/reservations/{id}/payos + if (r && r.customerId === me) { + if (r.status !== "PENDING_PAYMENT") return bad("Đơn đặt chỗ này không còn chờ thanh toán."); + return send(200, { reservationId: r.reservationId, ...payosOrder("reservation", r.reservationId, r.estimatedAmount + r.requiredDeposit, `SS${String(r.reservationId).padStart(4, "0")}`) }); + } const amount = body?.amount || (r ? (r.requiredDeposit > 0 ? r.requiredDeposit : r.estimatedAmount) : 1000000); const orderCode = Date.now() % 1000000000; const checkoutUrl = `https://pay.payos.vn/web/mock-${resId || orderCode}`; @@ -533,6 +652,26 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M return send(201, { ...r, requestedAt: iso(r.requestedAt), approvedAt: null }); } if (req.method === "GET" && (m = path.match(/^\/api\/contracts\/(\d+)\/payments$/))) return send(200, S.payments.filter((p) => p.contractId === +m[1]).map(payDto)); + const myPayment = (id) => S.payments.find((p) => p.paymentId === id && S.contracts.some((c) => c.contractId === p.contractId && c.customerId === me)); + if (req.method === "GET" && (m = path.match(/^\/api\/payments\/(\d+)$/))) { + const p = myPayment(+m[1]); + return p ? send(200, payDto(p)) : send(404, { error: "Không tìm thấy khoản thanh toán." }); + } + if (req.method === "POST" && (m = path.match(/^\/api\/payments\/(\d+)\/payos$/))) { + const p = myPayment(+m[1]); + if (!p) return send(404, { error: "Không tìm thấy khoản thanh toán." }); + if (p.status === "PAID") return bad("Khoản này đã được thanh toán."); + return send(200, payosOrder("payment", p.paymentId, p.amount, (p.transactionReference || `TT${p.paymentId}`).replaceAll("-", ""))); + } + if (req.method === "GET" && (m = path.match(/^\/api\/contracts\/(\d+)\/access-qr$/))) { + const c = S.contracts.find((x) => x.contractId === +m[1] && x.customerId === me); + if (!c) return send(404, { error: "Không tìm thấy hợp đồng." }); + const h = S.handovers.find((x) => x.contractId === c.contractId); + if (c.status !== "ACTIVE" || !h || h.status !== "HANDED_OVER") return bad("QR mở cửa chỉ dùng được sau khi nhận kho và khi hợp đồng còn hiệu lực."); + const u = unit(c.unitId); + const a = accessCode(c); + return send(200, { contractId: c.contractId, code: a.code, backupCode: a.backup, unitNumber: u.unitNumber, unitType: ut(u.unitTypeId).climateControlled ? "Kho lạnh" : "Kho thường", location: null, validUntil: c.endDate }); + } if (req.method === "POST" && (m = path.match(/^\/api\/handovers\/(\d+)\/confirm$/))) { const h = S.handovers.find((x) => x.handoverId === +m[1]); if (!h) return bad("Không tìm thấy biên bản bàn giao phù hợp."); @@ -551,7 +690,7 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M if (req.method === "GET" && (m = path.match(/^\/api\/tickets\/(\d+)$/))) { const t = S.tickets.find((x) => x.ticketId === +m[1] && x.customerId === me); if (!t) return send(404, { error: "Không tìm thấy yêu cầu hỗ trợ." }); - return send(200, { ...ticketDto(t), contractUnitNumber: unit(S.contracts.find((c) => c.contractId === t.contractId).unitId).unitNumber, description: t.description, assignedAt: null }); + return send(200, { ...ticketDto(t), contractUnitNumber: unit(S.contracts.find((c) => c.contractId === t.contractId).unitId).unitNumber, description: t.description, assignedAt: null, responses: (t.responses || []).map((x) => ({ ...x, createdAt: dbTime(x.createdAt) })) }); } if (req.method === "POST" && path === "/api/tickets") { const c = S.contracts.find((x) => x.contractId === body.contractId && x.customerId === me); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json index 34365a1..27daabb 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json @@ -9,7 +9,7 @@ "dev": "vite --host 127.0.0.1", "build": "vite build --base=./", "preview": "vite preview --host 127.0.0.1", - "test": "node --test tests/reducer.test.js tests/api-mappers.test.js tests/admin.test.js tests/ops.test.js tests/units.test.js tests/ops-api.test.mjs", + "test": "node --test tests/reducer.test.js tests/api-mappers.test.js tests/admin.test.js tests/ops.test.js tests/units.test.js tests/ops-api.test.mjs tests/payment-access.test.js tests/payment-api.test.mjs tests/access.test.js", "test:render": "node tests/render.test.mjs", "dev:mock": "node scripts/dev-mock.mjs" }, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs index 42232fc..2a0abfa 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs @@ -5,13 +5,15 @@ import { createServer } from "vite"; import { startMockApi } from "../mock/mock-api.mjs"; const API_PORT = Number(process.env.MOCK_API_PORT) || 5151; +const AUTOPAY = Number(process.env.MOCK_PAYOS_AUTOPAY ?? 10); // Biến VITE_* có sẵn trong môi trường được Vite ưu tiên hơn file .env process.env.VITE_USE_API = "true"; process.env.VITE_API_URL = `http://localhost:${API_PORT}`; try { - await startMockApi(API_PORT, { verbose: true, ops: process.env.MOCK_OPS === "1" }); + // PayOS giả lập tự báo "đã thanh toán" sau 10 giây (đổi bằng MOCK_PAYOS_AUTOPAY, 0 = chỉ khi gọi /__payos/paid) + await startMockApi(API_PORT, { verbose: true, ops: process.env.MOCK_OPS === "1", payosAutoPaySeconds: AUTOPAY }); } catch (e) { console.error(`Không mở được cổng ${API_PORT} (có thể backend thật đang chạy). Đặt MOCK_API_PORT=5199 rồi chạy lại.`); process.exit(1); @@ -28,5 +30,7 @@ console.log(` manager01 / Manager@123 → Quản lý cơ sở (#/manager) — chỉ khi chạy với MOCK_OPS=1 MOCK_OPS=1 bật các endpoint /api/ops/* (giống backend thật, xem docs/facility-ops-api.md). Không bật: khu vận hành dùng dữ liệu cục bộ trong trình duyệt. + PayOS giả lập: mã QR tự được "thanh toán" sau ${AUTOPAY} giây (MOCK_PAYOS_AUTOPAY=0 để tắt; gọi + http://localhost:${API_PORT}/__payos/paid để báo đã trả ngay). Máy quét cửa kho: #/door. Mỗi lời gọi API sẽ hiện bên dưới (xanh = thành công, đỏ = lỗi từ máy chủ). `); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx index 3edd028..f528eb0 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx @@ -20,6 +20,7 @@ import FindList from "./pages/FindList"; import FindMap from "./pages/FindMap"; import Home from "./pages/Home"; import Overview from "./pages/Overview"; +import Door from "./pages/Door"; import Payments from "./pages/Payments"; import Profile from "./pages/Profile"; import { Guide, Pricing } from "./pages/Public"; @@ -53,6 +54,7 @@ const TITLES = { manager: "Quản lý cơ sở", support: "Hỗ trợ", profile: "Tài khoản", + door: "Máy quét cửa kho", }; // Trang cần đăng nhập. Các trang công khai: home, login, register, pricing, guide, find (xem cơ sở). @@ -79,6 +81,8 @@ function renderPage({ page, parts, query }) { case "payments": return ; case "support": return ; case "profile": return ; + // C07r: máy quét ở cửa kho (mô phỏng), không cần đăng nhập như thiết bị gắn tại cơ sở + case "door": return ; default: 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 index 09307e9..add9ffe 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js @@ -18,8 +18,16 @@ export const api = { reservation: (id) => request(`/api/reservations/${id}`), createReservation: (body) => request("/api/reservations", { method: "POST", body }), cancelReservation: (id, reason) => request(`/api/reservations/${id}/cancel`, { method: "POST", body: { reason } }), - // C04: khách báo đã chuyển khoản → PENDING_VERIFICATION (nhân viên đối soát ở S09) + // Bản cũ "Tôi đã chuyển khoản" → PENDING_VERIFICATION. Giờ chỉ dùng làm dự phòng cho "Thanh toán tại cửa hàng" + // khi backend chưa có pay-at-facility (đơn vẫn vào hàng chờ S09 để nhân viên thu tiền). confirmTransfer: (id) => request(`/api/reservations/${id}/confirm-transfer`, { method: "POST" }), + // C04 · PayOS: tạo / lấy lại link + mã QR PayOS của đơn qua endpoint backend đang có + // (POST /api/reservations/create-payos-qr → { reservationId, orderCode, checkoutUrl, qrCode, amount }). + reservationPayos: (id) => request("/api/reservations/create-payos-qr", { method: "POST", body: { reservationId: Number(id) } }), + // C04c · Khách chọn thanh toán tại cửa hàng → chờ nhân viên thu tiền ở S09 + payAtFacility: (id) => request(`/api/reservations/${id}/pay-at-facility`, { method: "POST" }), + // C14a · Xem trước số tiền hoàn khi huỷ đơn đã thanh toán (chính sách CANCELLATION ở B02) + cancelPreview: (id) => request(`/api/reservations/${id}/cancel-preview`), // Hợp đồng, thanh toán, gia hạn, bàn giao, trả kho contracts: () => request("/api/contracts"), @@ -33,6 +41,14 @@ export const api = { getProfile: () => request("/api/auth/profile"), updateProfile: (body) => request("/api/auth/profile", { method: "PUT", body }), changePassword: (body) => request("/api/auth/change-password", { method: "POST", body }), + // C11 · Khoản gia hạn đã duyệt: tạo QR PayOS cho khoản thanh toán, hỏi trạng thái bằng GET /api/payments/{id} + payment: (paymentId) => request(`/api/payments/${paymentId}`), + paymentPayos: (paymentId) => request(`/api/payments/${paymentId}/payos`, { method: "POST" }), + + // C07q · QR mở cửa (chỉ chủ hợp đồng, hợp đồng đã bàn giao và còn hiệu lực) + accessQr: (contractId) => request(`/api/contracts/${contractId}/access-qr`), + // C07r · Máy quét ở cửa kho (mô phỏng): kiểm mã → OPEN / DENIED, backend ghi activity_logs + scanAccess: (body) => request("/api/access/scan", { method: "POST", body }), // Hỗ trợ tickets: () => request("/api/tickets"), diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js index 492440c..b529cee 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js @@ -98,6 +98,10 @@ export function mapCatalog({ facilities = [], unitTypes = [], rates = [] }) { const RESERVATION = { PENDING_PAYMENT: "PENDING_PAYMENT", PENDING_VERIFICATION: "PENDING_VERIFICATION", + // Trạng thái backend sẽ thêm cho thanh toán tại cửa hàng (BACKEND-TODO.md mục P2); giao diện coi như chờ thu tiền + PENDING_AT_FACILITY: "PENDING_VERIFICATION", + // PayOS webhook xác nhận đã trả (D19): backend có thể ghi PAID hoặc CONFIRMED + PAID: "CONFIRMED", UNIT_ASSIGNED: "CONFIRMED", CONFIRMED: "CONFIRMED", CHECKED_IN: "CHECKED_IN", @@ -130,7 +134,8 @@ function offerOfType(unitTypes, id, name) { 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" + transfers: {}, // reservationId → thời điểm khách gửi đơn chờ thu tiền (bản cũ: "Tôi đã chuyển khoản") + atFacility: {}, // reservationId → khách chọn "Thanh toán tại cửa hàng" (khi backend chưa trả paymentMethod) 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: [], @@ -197,6 +202,7 @@ export function composeData({ catalog, remote, overlay: ov, session, timeoutSeco } } const offer = offerOfType(unitTypes, r.unitTypeId, r.unitTypeName); + const atFacility = r.paymentMethod === "AT_FACILITY" || r.status === "PENDING_AT_FACILITY" || Boolean(overlay.atFacility?.[id]); const rent = Number(r.estimatedAmount); const deposit = Number(r.requiredDeposit); return { @@ -216,7 +222,12 @@ export function composeData({ catalog, remote, overlay: ov, session, timeoutSeco deposit, initial_total: rent + deposit, status, + api_status: r.status, + pay_at_facility: atFacility, cancel_reason, + // C14b: backend trả khi huỷ đơn đã thanh toán (BACKEND-TODO.md mục H) + refund_amount: r.refundAmount != null ? Number(r.refundAmount) : null, + refund_status: r.refundStatus || null, created_at: created.toISOString(), expires_at, timeout_seconds, @@ -261,19 +272,35 @@ export function composeData({ catalog, remote, overlay: ov, session, timeoutSeco handover_pending_customer: Boolean(handover && !handover.customerConfirmed && handover.staffConfirmed), }); const paidRenewals = new Set(); + const renewalById = new Map((c.renewals || []).map((r) => [r.renewalId, r])); for (const p of c.payments || []) { if (p.renewalId) paidRenewals.add(p.renewalId); const kind = p.paymentType || "OTHER"; + const ren = p.renewalId ? renewalById.get(p.renewalId) : null; 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}`; + kind === "RENT" + ? `Thuê kho ${c.unitNumber}` + : kind === "DEPOSIT" + ? `Cọc hợp đồng ${c.unitNumber}` + : kind === "RENEWAL" + ? `Gia hạn ${c.unitNumber}${ren?.renewalPeriodMonths ? ` · ${ren.renewalPeriodMonths} tháng` : ""}` + : kind === "REFUND" + ? `Hoàn cọc ${c.unitNumber}` + : `Khoản thu kho ${c.unitNumber}`; const paid = p.status === "PAID"; + const status = paid ? (kind === "DEPOSIT" ? "DEPOSIT_HELD" : "RECONCILED") : p.status === "REFUNDED" || kind === "REFUND" ? "REFUNDED" : "UNPAID"; ledger.push({ ref: p.transactionReference || `TT-${pad(p.paymentId)}`, + api_id: p.paymentId, kind, label, contract_id: code, + unit_number: c.unitNumber, amount: Number(p.amount), - status: paid ? (kind === "DEPOSIT" ? "DEPOSIT_HELD" : "RECONCILED") : p.status === "REFUNDED" ? "REFUNDED" : "UNPAID", + status, + // C11: khoản gia hạn đã duyệt nhưng chưa trả → nút "Thanh toán" (QR PayOS) + payable: !paid && kind === "RENEWAL" && !["CANCELLED", "REFUNDED", "FAILED"].includes(p.status), + period: ren ? { from: dateOnly(ren.oldEndDate), to: dateOnly(ren.newEndDate), months: ren.renewalPeriodMonths } : null, }); } for (const r of c.renewals || []) { @@ -296,7 +323,7 @@ export function composeData({ catalog, remote, overlay: ov, session, timeoutSeco } 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 + // Đơn chọn thanh toán tại cửa hàng (hoặc bản cũ báo chuyển khoản), chờ nhân viên thu tiền ở S09 for (const r of reservations.filter((x) => x.status === "PENDING_VERIFICATION")) { const refBase = `SS-${pad(r.api_id)}`; ledger.unshift( @@ -340,6 +367,11 @@ export function composeData({ catalog, remote, overlay: ov, session, timeoutSeco attachments: overlay.attachments[t.ticketId] || [], status, staff_note: TICKET_NOTE[status], + // C12: phản hồi của nhân viên (S05). Backend trả mảng responses trong GET /api/tickets/{id} (BACKEND-TODO.md mục R) + responses: (t.responses || []) + .map((x) => ({ text: x.message ?? x.note ?? x.content ?? "", by: x.staffName ?? x.responderName ?? null, at: isoOf(x.createdAt ?? x.respondedAt) })) + .filter((x) => x.text), + unit_number: t.contractUnitNumber || null, created_at: isoOf(t.createdAt), updated_at: isoOf(t.closedAt || t.resolvedAt || t.assignedAt || t.createdAt), }; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/payment-access.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/payment-access.js new file mode 100644 index 0000000..3b40d51 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/payment-access.js @@ -0,0 +1,88 @@ +// Chuẩn hoá dữ liệu backend cho các màn mới: PayOS (C04, C11q), QR mở cửa (C07q), máy quét cửa kho (C07r), +// xem trước hoàn tiền khi huỷ (C14a). Hàm thuần, có test (tests/payment-access.test.js). +// Hợp đồng JSON đầy đủ ở BACKEND-TODO.md mục P (PayOS), Q (QR mở cửa), H (huỷ đơn). +import { ApiError } from "./http.js"; +import { parseUtc } from "./mappers.js"; + +// Backend chưa có endpoint (bản cũ) → giao diện hiện thông báo thay vì báo lỗi +export const isUnsupported = (e) => e instanceof ApiError && (e.status === 404 || e.status === 405 || e.status === 501); + +const num = (v) => (v === null || v === undefined || v === "" ? null : Number(v)); +const iso = (v) => parseUtc(v)?.toISOString() ?? null; + +// PayosCheckoutDto: { orderCode, amount, qrCode, checkoutUrl, expiredAt, description, status } +// qrCode là chuỗi VietQR PayOS trả về (vẽ thành ảnh QR ở giao diện), checkoutUrl là trang thanh toán của PayOS. +export function normPayos(dto) { + if (!dto || typeof dto !== "object") return null; + const qr = dto.qrCode ?? dto.qr_code ?? null; + const url = dto.checkoutUrl ?? dto.checkout_url ?? null; + if (!qr && !url) return null; + const status = String(dto.status || "PENDING").toUpperCase(); + return { + order_code: dto.orderCode ?? dto.order_code ?? null, + amount: num(dto.amount), + qr, + url, + expires_at: iso(dto.expiredAt ?? dto.expiresAt ?? null), + description: dto.description || null, + paid: status === "PAID", + status, + }; +} + +// AccessQrDto: { code, backupCode, unitNumber, unitType, location, validUntil, contractId } +export function normAccess(dto) { + if (!dto?.code) return null; + return { + code: String(dto.code), + backup: dto.backupCode ? String(dto.backupCode) : null, + unit: dto.unitNumber || null, + unit_type: dto.unitType || null, + location: dto.location || null, + valid_until: dto.validUntil ? String(dto.validUntil).slice(0, 10) : null, + }; +} + +// ScanResultDto: { result: "OPEN" | "DENIED", unitNumber, customerName, contractCode, scannedAt, reason } +export function normScan(dto) { + const result = String(dto?.result || "").toUpperCase() === "OPEN" ? "OPEN" : "DENIED"; + return { + result, + unit: dto?.unitNumber || null, + customer: dto?.customerName || null, + contract: dto?.contractCode || null, + at: iso(dto?.scannedAt) || new Date().toISOString(), + reason: dto?.reason || (result === "OPEN" ? null : "Mã không hợp lệ hoặc đã hết hiệu lực."), + }; +} + +// CancelPreviewDto: { paidAmount, cancellationFee, refundAmount, policyName } +export function normCancelPreview(dto) { + if (!dto) return null; + const paid = num(dto.paidAmount); + const fee = num(dto.cancellationFee); + const refund = num(dto.refundAmount); + if (paid === null && refund === null) return null; + return { paid: paid ?? 0, fee: fee ?? Math.max(0, (paid ?? 0) - (refund ?? 0)), refund: refund ?? Math.max(0, (paid ?? 0) - (fee ?? 0)), policy: dto.policyName || null }; +} + +// Link chỉ đường Google Maps theo toạ độ (ưu tiên) hoặc địa chỉ +export function directionsUrl({ lat, lng, address, name } = {}) { + const hasCoords = lat != null && lng != null && lat !== "" && lng !== "" && Number.isFinite(Number(lat)) && Number.isFinite(Number(lng)); + const dest = hasCoords ? `${Number(lat)},${Number(lng)}` : [name, address].filter(Boolean).join(", "); + return `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(dest)}`; +} + +// Mã QR mở cửa khi chạy không có backend (chế độ trình duyệt): mã tham chiếu cố định theo hợp đồng, không chứa bí mật +export function localAccessCode(contract) { + const digits = [...String(contract.contract_id)].reduce((h, ch) => (h * 31 + ch.charCodeAt(0)) % 100000000, 7); + const backup = String(digits).padStart(8, "0"); + return { + code: `SSQR-${String(contract.contract_id).replace(/[^A-Za-z0-9]/g, "")}-${backup.slice(0, 4)}`, + backup: `${backup.slice(0, 4)} ${backup.slice(4)}`, + unit: contract.unit_number, + unit_type: null, + location: contract.location || null, + valid_until: contract.end_date, + }; +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js index ba7e1ac..32f78e9 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js @@ -160,8 +160,8 @@ export const CONTRACT_STATUS_LABELS = { CANCELLED: "Đã huỷ", }; export const RESERVATION_STATUS_LABELS = { - PENDING_PAYMENT: "Chờ chuyển khoản", - PENDING_VERIFICATION: "Chờ đối soát", + PENDING_PAYMENT: "Chờ thanh toán", + PENDING_VERIFICATION: "Chờ thu tại kho", CONFIRMED: "Đã xác nhận, chờ phân bổ", UNIT_ASSIGNED: "Đã phân bổ ô", CHECKED_IN: "Đã nhận kho", diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/PayosModal.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/PayosModal.jsx new file mode 100644 index 0000000..90c23dd --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/PayosModal.jsx @@ -0,0 +1,83 @@ +import React, { useCallback, useEffect, useState } from "react"; +import { money } from "../lib/format"; +import { useApp } from "../state/store"; +import QrCode from "./QrCode"; +import { Button, Modal, Notice } from "./UI"; + +const POLL_MS = 3000; + +// C11q — Popup thanh toán QR PayOS cho một khoản (gia hạn đã duyệt). Hỏi backend định kỳ, tự đóng khi đã trả. +export default function PayosModal({ target, title, subtitle, onPaid, onClose }) { + const { services } = useApp(); + const [checkout, setCheckout] = useState(null); + const [state, setState] = useState("loading"); // loading | ready | unsupported | error | paid + const [error, setError] = useState(""); + + const load = useCallback(async () => { + setState("loading"); + const res = await services.startPayos(target); + if (res.ok) { + setCheckout(res.checkout); + setState(res.checkout.paid ? "paid" : "ready"); + } else if (res.unsupported) setState("unsupported"); + else { + setError(res.error); + setState("error"); + } + }, [services, target]); + + useEffect(() => { + load(); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + if (state !== "ready") return undefined; + let alive = true; + const timer = setInterval(async () => { + const res = await services.checkPaid(target); + if (alive && res.ok && res.paid) setState("paid"); + }, POLL_MS); + return () => { + alive = false; + clearInterval(timer); + }; + }, [state]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + if (state === "paid") onPaid?.(); + }, [state]); // eslint-disable-line react-hooks/exhaustive-deps + + const amount = checkout?.amount ?? target.item.amount; + return ( + + {subtitle &&

{subtitle}

} + {state === "unsupported" ? ( + Thanh toán QR cho khoản này đang tạm gián đoạn. Bạn có thể thanh toán tại quầy của cơ sở hoặc thử lại sau. + ) : state === "error" ? ( + + {error}{" "} + + + ) : ( + Mở trang thanh toán PayOS ↗ : "Quét bằng ứng dụng ngân hàng"} + /> + )} +
+
Số tiền
{money(amount)}
+ {checkout?.description &&
Nội dung chuyển
{checkout.description}
} +
+
Trạng thái
+
{state === "paid" ? "Đã thanh toán" : "Đang chờ thanh toán…"}
+
+
+

Hệ thống tự xác nhận khi nhận được tiền, bạn không cần bấm gì thêm. Đóng cửa sổ này thì khoản vẫn chờ thanh toán.

+
+ +
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/QrCode.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/QrCode.jsx new file mode 100644 index 0000000..054e2df --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/QrCode.jsx @@ -0,0 +1,34 @@ +import React, { useEffect, useState } from "react"; +import QRCode from "qrcode"; +import { Icon } from "./UI"; + +// Vẽ một chuỗi (VietQR của PayOS, mã mở cửa…) thành ảnh QR SVG. Chưa có chuỗi → ô chờ như Figma C04 / C07q. +export default function QrCode({ value, label, title, caption, size = 200 }) { + const [svg, setSvg] = useState(""); + useEffect(() => { + let alive = true; + if (!value) { + setSvg(""); + return undefined; + } + QRCode.toString(String(value), { type: "svg", margin: 1, errorCorrectionLevel: "M", color: { dark: "#10152a", light: "#ffffff" } }) + .then((s) => alive && setSvg(s)) + .catch(() => alive && setSvg("")); + return () => { + alive = false; + }; + }, [value]); + return ( +
+ {svg ? ( +
+ ) : ( +
+ + {title && {title}} +
+ )} + {caption &&
{caption}
} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js index 0c27dfb..095ac13 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js @@ -57,5 +57,6 @@ export function galleryImage(facility, index) { return { ...item, src }; } -// Thời gian giữ đơn chờ chuyển khoản (Figma: 01:00). Đổi bằng VITE_PAYMENT_TIMEOUT_SECONDS. -export const paymentTimeoutSeconds = Number(import.meta.env?.VITE_PAYMENT_TIMEOUT_SECONDS) || 60; +// Thời gian giữ chỗ khi thanh toán QR PayOS (Figma C04: 10:00). Đổi bằng VITE_PAYMENT_TIMEOUT_SECONDS. +// Backend nên đặt hạn link PayOS (expiredAt) bằng đúng con số này; giao diện ưu tiên expiredAt backend trả về. +export const paymentTimeoutSeconds = Number(import.meta.env?.VITE_PAYMENT_TIMEOUT_SECONDS) || 600; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js index c04c3b3..3c2e0b8 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js @@ -67,7 +67,7 @@ export function createSeedData(t = today()) { deposit: 1150000, rent_total: 3450000, initial_total: 4600000, - status: "PENDING_VERIFICATION", + status: "CONFIRMED", // đã thanh toán qua QR PayOS, chờ nhận kho (Figma C14) created_at: at(addDays(t, -6), "09:12"), }, { @@ -157,6 +157,18 @@ export function createSeedData(t = today()) { amount: 1380000, status: "DEPOSIT_HELD", }, + { + // C11: gia hạn đã được cơ sở duyệt, chờ khách thanh toán qua QR PayOS (C11q) + ref: "SS-0086-REN", + kind: "RENEWAL", + label: "Gia hạn B-015 · 3 tháng", + contract_id: "HĐ-2026-0086", + unit_number: "B-015", + amount: 4140000, + status: "UNPAID", + payable: true, + period: { from: b015End, to: addMonths(b015End, 3), months: 3 }, + }, ], appointments: [ { @@ -172,7 +184,18 @@ export function createSeedData(t = today()) { note: "Mang giấy đăng ký và mã đặt chỗ. Nhân viên xác minh, hướng dẫn và bàn giao kho.", }, ], - renewals: [], + renewals: [ + { + renewal_id: "GH-0012", + contract_id: "HĐ-2026-0086", + months: 3, + old_end: b015End, + new_end: addMonths(b015End, 3), + amount: 4140000, + status: "APPROVED", + requested_at: at(addDays(t, -2), "10:20"), + }, + ], returns: [], tickets: [ { @@ -182,7 +205,14 @@ export function createSeedData(t = today()) { description: "Thẻ ra vào chưa mở được cổng cơ sở.", attachments: [], status: "IN_PROGRESS", - staff_note: "Nhân viên Trần Minh đang kiểm tra.", + staff_note: "Nhân viên Trần Văn Long đang kiểm tra.", + responses: [ + { + text: "Thẻ cũ bị lỗi từ. Bạn qua quầy lễ tân nhận thẻ mới, mang theo CCCD giúp mình nhé.", + by: "Trần Văn Long", + at: at(addDays(t, -6), "11:02"), + }, + ], created_at: at(addDays(t, -6), "09:40"), updated_at: at(addDays(t, -6), "10:15"), }, @@ -222,7 +252,7 @@ export function createSeedData(t = today()) { }, { id: "A-2", - text: "Thanh toán thuê kho 3 tháng đã đối soát", + text: "Thanh toán thuê kho 3 tháng qua QR thành công", tone: "green", at: addDays(t, -6), }, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/status.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/status.js index 68b0c2d..7c6be73 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/status.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/status.js @@ -2,8 +2,9 @@ // Xem BE-CONTRACT.md để đối chiếu với trạng thái backend. export const RESERVATION_STATUS = { - PENDING_PAYMENT: ["Chờ chuyển khoản", "amber"], - PENDING_VERIFICATION: ["Chờ đối soát", "amber"], + PENDING_PAYMENT: ["Chờ thanh toán", "amber"], + // Từ khi có PayOS (D19), đơn chờ xác nhận chỉ còn là đơn khách chọn trả tại cửa hàng (C04c/C05c) + PENDING_VERIFICATION: ["Chờ thanh toán tại cửa hàng", "amber"], CONFIRMED: ["Đã xác nhận", "green"], CHECKED_IN: ["Đã nhận kho", "green"], CANCELLED: ["Đã huỷ đặt chỗ", "gray"], @@ -17,11 +18,11 @@ export const CONTRACT_STATUS = { }; export const LEDGER_STATUS = { - RECONCILED: ["Đã đối soát", "green"], - PENDING_VERIFICATION: ["Chờ đối soát", "amber"], + RECONCILED: ["Đã thanh toán", "green"], + PENDING_VERIFICATION: ["Chờ thanh toán tại cửa hàng", "amber"], DEPOSIT_HELD: ["Đang giữ cọc", "blue"], RENEWAL_PENDING: ["Chờ duyệt yêu cầu", "amber"], - UNPAID: ["Chưa thanh toán", "red"], + UNPAID: ["Chờ thanh toán", "red"], REFUNDED: ["Đã hoàn", "gray"], }; @@ -40,10 +41,10 @@ export const TICKET_STATUS = { }; export const TICKET_TOPICS = { - ACCESS: { label: "Thẻ ra vào / mã truy cập", title: "Lỗi mã truy cập" }, + ACCESS: { label: "Thẻ ra vào / mã truy cập", title: "Lỗi thẻ ra vào" }, LOCK: { label: "Khóa / chìa khóa", title: "Khóa / chìa khóa" }, UNIT: { label: "Tình trạng kho", title: "Tình trạng kho" }, - PAYMENT: { label: "Thanh toán / đối soát", title: "Thanh toán / đối soát" }, + PAYMENT: { label: "Thanh toán", title: "Thanh toán" }, ITEMS: { label: "Đồ đạc lưu trữ", title: "Đồ đạc lưu trữ" }, SCHEDULE: { label: "Đổi lịch hẹn", title: "Đổi lịch hẹn" }, OTHER: { label: "Vấn đề khác", title: "Yêu cầu hỗ trợ" }, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/ManagerPages.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/ManagerPages.jsx index 81eefa5..646dde1 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/ManagerPages.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/ManagerPages.jsx @@ -5,7 +5,7 @@ import { typeLabel } from "../lib/catalog"; import { dateLabel, dateTimeLabel, daysBetween, rangeLabel, today } from "../lib/format"; import { go, href, qs } from "../lib/router"; import { UNIT_STATE } from "./data"; -import { ASSIGN_STATE, candidateUnits } from "./reducer"; +import { ASSIGN_STATE, UNIT_TRANSITIONS, candidateUnits } from "./reducer"; import { useOps } from "./store"; import { QueuePicker, millions, slotLabel } from "./util"; @@ -31,7 +31,7 @@ export function ManagerOverview() { const g = growth(ops.revenue.months); const items = [ renewals.length && { key: "r", title: `${renewals.length} yêu cầu gia hạn đang chờ duyệt`, sub: "Cần phản hồi trong vòng 24 giờ", to: "manager/renewals", label: "Xem yêu cầu", primary: true }, - allocations.length && { key: "a", title: `${allocations.length} đơn đã đối soát chờ phân bổ kho`, sub: allocations.map((a) => a.id).join(", "), to: "manager/allocate", label: "Phân bổ kho", primary: true }, + allocations.length && { key: "a", title: `${allocations.length} đơn đã thanh toán chờ phân bổ kho`, sub: allocations.map((a) => a.id).join(", "), to: "manager/allocate", label: "Phân bổ kho", primary: true }, unassigned.length && { key: "u", title: `${unassigned.length} công việc chưa phân công`, sub: unassigned.map((a) => a.title).join(" · "), to: "manager/assign", label: "Phân công" }, overdue.length && { key: "o", title: `${overdue.length} kho quá hạn thanh toán`, sub: `Kho ${overdue.map((u) => `#${u.code}`).join(", ")}`, to: "manager/units?tab=OVERDUE", label: "Xem danh sách kho" }, returned.length && { key: "t", title: `${returned.length} biên bản trả kho chờ xác nhận hoàn cọc`, sub: returned.map((c) => `${c.unit} · ${c.customer}`).join(", "), to: "manager/contracts", label: "Xem hợp đồng" }, @@ -80,12 +80,61 @@ const UNIT_TABS = [ ["EXPIRING", "Sắp hết hạn"], ["OVERDUE", "Quá hạn"], ["WAITING_HANDOVER", "Chờ bàn giao"], + ["MAINTENANCE", "Bảo trì"], ]; + +const STATUS_HELP = { + MAINTENANCE: "Tạm khoá ô, khách không đặt được", + EMPTY: "Mở lại ô, khách đặt được và quản lý phân bổ được", +}; + +// M02a — Hộp thoại đổi trạng thái ô kho (F12) +function UnitStatusDialog({ unit, onClose }) { + const { run } = useOps(); + const options = UNIT_TRANSITIONS[unit.status] || []; + const [status, setStatus] = useState(options[0]); + const [reason, setReason] = useState(""); + const [err, setErr] = useState(""); + const [busy, setBusy] = useState(false); + const [label] = UNIT_STATE[unit.status] || [unit.status]; + const submit = async () => { + if (!reason.trim()) return setErr("Nhập lý do đổi trạng thái."); + setBusy(true); + const r = await run("UPDATE_UNIT_STATUS", { code: unit.code, status, reason }, `Đã đổi ô ${unit.code} sang ${UNIT_STATE[status][0].toLowerCase()}`); + setBusy(false); + if (r.ok) onClose(); + else setErr(r.error); + }; + return ( + +

Hiện tại: {label} · {unit.area} m² · {typeLabel(unit.type)}

+
+ Trạng thái mới + {options.map((s) => ( + + ))} +
+

Chỉ hiện các trạng thái được phép chuyển: Trống ↔ Bảo trì. Ô đang có khách thuê không đổi được ở đây.

+ +