From 015f454da7593cfc01239c957945e3ca169bf379 Mon Sep 17 00:00:00 2001 From: maingocse Date: Sat, 24 Oct 2026 01:16:48 +0700 Subject: [PATCH 1/4] feat(F40): dong bo Figma dot 1 --- DECISIONS.md | 7 + .../SafeSpace-Customer-UI/BACKEND-TODO.md | 15 ++ .../SafeSpace-Customer-UI/FRONTEND-MAP.md | 2 + .../admin/permissions/PermissionListPage.jsx | 43 +++--- .../features/admin/users/CreateUserPage.jsx | 47 +++--- .../features/admin/users/UserDetailPage.jsx | 130 +++++++---------- .../business/policies/PolicySettingsPage.jsx | 25 ++-- .../features/business/pricing/PricingPage.jsx | 20 ++- .../reservations/ReservationListPage.jsx | 67 +++++---- .../FacilityOperationsRoutes.jsx | 2 + .../api/facilityOperationsApi.js | 4 +- .../data/facilityOperationsSeed.js | 7 + .../state/FacilityOperationsProvider.jsx | 82 +++++++---- .../state/facilityOperationsReducer.js | 12 +- .../utils/opsConfirmation.js | 127 ++++++++++++++-- .../utils/pendingTaskCounts.js | 2 +- .../allocations/UnitAllocationPage.jsx | 5 +- .../assignments/StaffAssignmentPage.jsx | 5 +- .../manager/contracts/ContractListPage.jsx | 53 ++++++- .../refunds/CancellationRefundPage.jsx | 136 ++++++++++++++++++ .../manager/renewals/RenewalApprovalPage.jsx | 27 ++-- .../handovers/CustomerVerificationPage.jsx | 2 +- .../features/staff/keys/KeyReceiptPage.jsx | 2 +- .../payments/PaymentConfirmationPage.jsx | 2 +- .../staff/returns/ReturnInspectionPage.jsx | 6 +- .../staff/support/StaffSupportPage.jsx | 6 +- .../shared/components/ChangeFlowDialog.jsx | 78 ++++++++++ .../src/shared/components/ConfirmDialog.jsx | 4 +- .../src/shared/styles/ss.css | 17 +++ .../SafeSpace-Customer-UI/tests/ops.test.js | 20 +++ .../tests/render.test.mjs | 4 +- docs/figma-ui-sync-2026-10-23.md | 31 ++++ feature_list.json | 11 +- progress.md | 8 ++ 34 files changed, 776 insertions(+), 233 deletions(-) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/CancellationRefundPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/components/ChangeFlowDialog.jsx create mode 100644 docs/figma-ui-sync-2026-10-23.md diff --git a/DECISIONS.md b/DECISIONS.md index d475d9a..c51ef32 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -196,3 +196,10 @@ Theo yêu cầu nhóm, dùng src/app, src/features//, src/shared, - Quá hạn: lấy đúng tham số OVERDUE lưu ở màn B02 (mặc định 5% giá thuê tháng mỗi ngày, hoặc 150% giá thuê ngày mỗi ngày trễ). Không đặt số cứng trong code. - Thời hạn hoàn: 3–5 ngày làm việc, chuyển khoản thủ công sau khi trừ phí. Hệ thống ghi trạng thái hoàn khi Quản lý xác nhận ở M07. - Thay thế: quy định "phí hủy 10% tiền thuê" trong BACKEND-TODO (H1) và CANCEL_FEE_RATE (appReducer.js) không còn áp dụng; phải đổi theo D27. Chưa triển khai code. + +## D28 — 2026-10-23: Đồng bộ Figma 23/10 (huỷ/hoàn tiền D27 và hộp thoại kết quả) + +- Figma được cập nhật theo D27: luồng đặt chỗ hiện tiền cọc (thuê + cọc 1 tháng = tổng ban đầu); huỷ trước ngày bắt đầu thuê: phí 10% tiền cọc, hoàn 100% tiền thuê và 90% cọc; B02 phí quá hạn 5% giá thuê tháng mỗi ngày trễ. Code giữ số liệu từ backend, chỉ đổi chữ và bố cục theo Figma. +- C14 đặt nút "Xem đơn / Huỷ đơn" trên từng dòng; C14b/C14c hiện "Đã huỷ · Đang hoàn tiền" (`refundStatus` PENDING) và "Đã huỷ · Đã hoàn tiền" (COMPLETED). +- Mọi thao tác ghi của nhân viên và các thao tác phân bổ, phân công, duyệt/từ chối gia hạn của quản lý đi qua: xác nhận → thành công (03a) hoặc thất bại (03b) theo Figma 779:*, 847:*, 885:*. Admin và Vận hành KD dùng chung `shared/components/ChangeFlowDialog.jsx`. Sau thành công, trang quay về danh sách đúng theo nút trên Figma thay vì trang kết quả `staff/done`. +- M08 hoàn tiền đơn huỷ là trang riêng `#/manager/refunds` nằm dưới tab "Hợp đồng & quá hạn" (Figma đặt cùng tab). Chỉ hoàn bằng chuyển khoản vì khách đã trả qua PayOS; bắt buộc nhập mã giao dịch. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index 6a6bd55..f9f7b8c 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -350,3 +350,18 @@ Trạng thái triển khai D27 (22/10/2026): - Giao diện: `cancelPreviewOf` (appReducer.js) tính 10% tiền cọc; C14a hiển thị phí và số hoàn theo đó. Còn thiếu: nút xác nhận hoàn cho đơn đã huỷ ở màn M07. - Đường cũ `POST /api/manager/contracts/{id}/refund` giờ gọi chung `FacilityOpsService.ConfirmRefundAsync` (D27); đã bỏ `ManagerService.ConfirmRefundAsync` (trước đây đặt trạng thái `ENDED` không hợp lệ). Id phải là mã hiển thị `HĐ-…` như `/api/ops`; tài khoản ADMIN không có cơ sở được phân công nên nhận 403. - F12 · RESERVED → OCCUPIED: `UnitStartActivation` (chạy cùng worker mỗi phút) chuyển ô đang giữ chỗ sang đang thuê khi hợp đồng ACTIVE/EXPIRING đến `StartDate` (giờ Việt Nam), ghi `unit_status_histories`. Nhận chìa khóa vẫn không đổi trạng thái ô (D26). Chuyển RESERVED/OCCUPIED bằng tay vẫn bị chặn ở `UnitStatusRules`. + +## M08 — Hoàn tiền đơn huỷ trên giao diện quản lý (F40, 23/10/2026) + +Giao diện `#/manager/refunds` (Figma M08 828:10212, M08a 828:10262) đọc danh sách từ `GET /api/ops/board` và gọi +`POST /api/ops/reservations/{id}/refund` (đã có, D27). Backend cần bổ sung: + +- `GET /api/ops/board` trả thêm mảng `refunds` cho cơ sở của quản lý (đơn `CANCELLED` có khoản `REFUND`). Khi chưa có, trang hiện "Chưa có đơn huỷ cần hoàn tiền." +- Body của `POST /api/ops/reservations/{id}/refund`: nhận và lưu `method` (`BANK_TRANSFER`) và `transactionRef` (mã giao dịch quản lý nhập). Hiện endpoint bỏ qua body. + +```jsonc +// GET /api/ops/board → refunds[] (camelCase; giao diện tự đổi sang snake_case) +{ "id": "SS-20260918-0151", "customer": "Nguyễn Hoàng Yến", "cancelledAt": "2026-10-22T08:40:00", + "rent": 3450000, "deposit": 1150000, "paid": 4600000, "fee": 115000, "amount": 4485000, + "status": "PENDING", "paidAt": null, "transactionRef": null } // status: PENDING | PAID +``` diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md index c1f2add..6443eb8 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md @@ -58,6 +58,7 @@ | Quản lý cơ sở / Tổng quan — ManagerDashboardPage | `src/features/manager/dashboard/ManagerDashboardPage.jsx` | | Quản lý cơ sở / Gia hạn — RenewalApprovalPage | `src/features/manager/renewals/RenewalApprovalPage.jsx` | | Quản lý cơ sở / Báo cáo — FacilityReportPage | `src/features/manager/reports/FacilityReportPage.jsx` | +| Quản lý cơ sở / Hoàn tiền đơn huỷ — CancellationRefundPage | `src/features/manager/refunds/CancellationRefundPage.jsx` | | Quản lý cơ sở / Kết quả — ManagerResultPage | `src/features/manager/results/ManagerResultPage.jsx` | | Quản lý cơ sở / Quản lý ô kho — UnitManagementPage | `src/features/manager/units/UnitManagementPage.jsx` | | Nhân viên / Tổng quan — StaffDashboardPage | `src/features/staff/dashboard/StaffDashboardPage.jsx` | @@ -77,6 +78,7 @@ | Kho thuê / gia hạn / trả kho | `#/units`, `#/units/:id/renew`, `#/units/:id/return` | | Nhân viên thu tiền / xác minh / nhận chìa khóa | `#/staff/reconcile`, `#/staff/verify`, `#/staff/keys` (alias cũ: `#/staff/handover`) | | Quản lý ô / phân bổ / gia hạn | `#/manager/units`, `#/manager/allocate`, `#/manager/renewals` | +| Hoàn tiền đơn huỷ (M08) | `#/manager/refunds` | | Vận hành kinh doanh / quản trị | `#/business`, `#/admin` | ## Ví dụ lần theo code diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx index a4fa3f2..0d6c87e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx @@ -24,6 +24,7 @@ import React, { useMemo, useState } from "react"; import { adminApi } from "../api/adminApi.js"; import { Button, Modal, Notice } from "../../../shared/components/UI.jsx"; import { ROLE_SCOPE, roleLabel, sortRoles } from "../../../shared/utils/roles.js"; +import { useChangeFlow } from "../../../shared/components/ChangeFlowDialog.jsx"; import { useApp } from "../../../app/state/AppProvider.jsx"; import { useLoad } from "../utils/adminUtils.js"; @@ -51,6 +52,7 @@ export default function PermissionListPage() { const [changes, setChanges] = useState({}); // Trạng thái hiển thị modal xác nhận lưu thay đổi const [confirm, setConfirm] = useState(false); + const [flowEl, runChange] = useChangeFlow(); // Trạng thái đang gửi request lưu lên backend const [saving, setSaving] = useState(false); // Danh sách các lỗi nếu có request gán/thu hồi quyền thất bại @@ -123,27 +125,33 @@ export default function PermissionListPage() { * 4. Thu thập các lỗi (nếu có) để hiển thị cho Admin. * 5. Tải lại dữ liệu mới từ backend và thông báo qua toast. */ + // Figma 885:10589–10613: xác nhận (kèm danh sách thay đổi) → đã lưu / không lưu được const save = async () => { setConfirm(false); setSaving(true); const failed = []; - - for (const [k, on] of pending) { - const [rid, pid] = k.split(":").map(Number); - try { - if (on) await adminApi.assignPermission(rid, pid); - else await adminApi.revokePermission(rid, pid); - } catch (e) { - onApiError(e); - failed.push(`${roleLabel(roleOf(rid)?.roleName)} · ${permOf(pid)?.permissionName}: ${e.message}`); - } - } - + await runChange({ + action: "Lưu cấu hình quyền", scope: "Các vai trò trong hệ thống", confirm: false, + perform: async () => { + for (const [k, on] of pending) { + const [rid, pid] = k.split(":").map(Number); + try { + if (on) await adminApi.assignPermission(rid, pid); + else await adminApi.revokePermission(rid, pid); + } catch (e) { + onApiError(e); + failed.push(`${roleLabel(roleOf(rid)?.roleName)} · ${permOf(pid)?.permissionName}: ${e.message}`); + } + } + if (failed.length === pending.length) throw new Error(failed[0]); + return true; + }, + }); setSaving(false); setErrors(failed); setChanges({}); await res.reload(); - notify(failed.length ? `Đã lưu, ${failed.length} thay đổi không thành công.` : "Đã lưu cấu hình quyền.", failed.length ? "error" : "success"); + if (failed.length && failed.length < pending.length) notify(`Đã lưu, ${failed.length} thay đổi không thành công.`, "error"); }; return ( @@ -254,7 +262,8 @@ export default function PermissionListPage() { {/* MODAL XÁC NHẬN ÁP DỤNG THAY ĐỔI */} {confirm && ( - setConfirm(false)} size="md"> + setConfirm(false)} size="md"> +

Kiểm tra thông tin trước khi xác nhận. Chọn Quay lại để giữ nguyên dữ liệu.

{/* Liệt kê từng thay đổi cụ thể */}
    {pending.map(([k, on]) => { @@ -273,12 +282,14 @@ export default function PermissionListPage() { )} {/* Các nút hành động trong Modal */} +

    Chỉ lưu thay đổi sau khi bạn bấm Xác nhận.

    - - + +
    )} + {flowEl} ); } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx index ba0271b..6793da0 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx @@ -21,6 +21,7 @@ import { Button, Field, Modal, Notice } from "../../../shared/components/UI.jsx" import { isEmail, isPhone, today } from "../../../shared/utils/format.js"; import { FACILITY_ROLES, roleLabel, sortRoles } from "../../../shared/utils/roles.js"; import { go } from "../../../app/router.js"; +import { useChangeFlow } from "../../../shared/components/ChangeFlowDialog.jsx"; import { useApp } from "../../../app/state/AppProvider.jsx"; import { tempPassword, useLoad, usernameFrom } from "../utils/adminUtils.js"; @@ -88,6 +89,7 @@ export default function CreateUserPage() { // null: chưa tạo thành công, chưa hiện Modal. // Có dữ liệu: hiện Modal thông tin đăng nhập. const [done, setDone] = useState(null); + const [flowEl, runChange] = useChangeFlow(); /* @@ -210,31 +212,27 @@ export default function CreateUserPage() { // Biến lưu thông tin tài khoản được backend tạo. let created; - try { - - /* - * GỌI API TẠO TÀI KHOẢN - * - * Dữ liệu gửi đi: - * - username: tên đăng nhập. - * - password: mật khẩu tạm thời. - * - fullName: họ tên. - * - email: chuyển chữ thường. - * - phone: loại bỏ khoảng trắng, dấu . và -. - * - initialRoleId: ID vai trò được chọn. - * - status: tài khoản được tạo ở trạng thái ACTIVE. - */ - - created = await adminApi.createUser({ - username: form.username.trim(), - password: form.password, - fullName: form.fullName.trim(), - email: form.email.trim().toLowerCase(), - phone: form.phone.replace(/[\s.-]/g, "") || null, - initialRoleId: Number(form.roleId), - status: "ACTIVE", - }); + // Figma 885:10555–10579: hỏi xác nhận trước khi tạo; lỗi hiện hộp thoại "Không tạo tài khoản được". + // Thành công vẫn dùng hộp thoại riêng bên dưới để hiện tên đăng nhập và mật khẩu tạm một lần. + const outcome = await runChange({ + action: "Tạo tài khoản", scope: "Tài khoản mới", content: "Thông tin, vai trò và cơ sở đã chọn", showSuccess: false, + perform: async () => { + created = await adminApi.createUser({ + username: form.username.trim(), + password: form.password, + fullName: form.fullName.trim(), + email: form.email.trim().toLowerCase(), + phone: form.phone.replace(/[\s.-]/g, "") || null, + initialRoleId: Number(form.roleId), + status: "ACTIVE", + }); + return created; + }, + }); + if (outcome.cancelled) return setBusy(false); + try { + if (outcome.error) throw outcome.error; } catch (err) { // Xử lý lỗi API, ví dụ phiên đăng nhập hết hạn. @@ -471,6 +469,7 @@ export default function CreateUserPage() { {/* MODAL SAU KHI TẠO TÀI KHOẢN THÀNH CÔNG Chỉ xuất hiện khi done khác null. Khi đóng Modal sẽ chuyển sang trang chi tiết User. */} + {flowEl} {done && ( go(`admin/users/${done.user.userId}`)}> diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx index 8501d51..751adc2 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx @@ -11,10 +11,10 @@ * - Nút "Lưu thay đổi" chỉ bật khi có dữ liệu thay đổi (dirty) và không trong trạng thái đang gửi request. * 3. Thẻ 2: Đặt lại mật khẩu (PasswordCard): * - Cho phép Admin nhập mật khẩu mới hoặc bấm "Tạo ngẫu nhiên" mật khẩu mạnh 12 ký tự. - * - Gọi API resetPassword và mở Modal hiển thị mật khẩu mới để Admin sao chép gửi cho người dùng. + * - Gọi API resetPassword qua hộp thoại xác nhận; hộp thoại thành công hiện mật khẩu mới một lần (Figma 885:10676). * 4. Thẻ 3: Quản lý vai trò (RolesCard): * - Danh sách các vai trò tài khoản đang sở hữu dưới dạng pill. - * - Nút xoá (x) trên từng pill để thu hồi vai trò kèm Modal cảnh báo xác nhận. + * - Nút xoá (x) trên từng pill để thu hồi vai trò qua hộp thoại xác nhận chung (Figma 885:10725). * - Dropdown chọn vai trò để gán thêm vai trò mới (chỉ hiển thị những vai trò tài khoản chưa có). * 5. Thẻ 4: Phân công cơ sở phụ trách (FacilityCard): * - Hiển thị cơ sở đang phụ trách hiện tại (ACTIVE). @@ -26,7 +26,8 @@ import React, { useEffect, useState } from "react"; import { adminApi } from "../api/adminApi.js"; import { DatePicker, Select } from "../../../shared/components/Pickers.jsx"; -import { Button, Empty, Field, LinkButton, Modal, Notice, StatusTag } from "../../../shared/components/UI.jsx"; +import { Button, Empty, Field, LinkButton, Notice, StatusTag } from "../../../shared/components/UI.jsx"; +import { useChangeFlow } from "../../../shared/components/ChangeFlowDialog.jsx"; import { isEmail, isPhone, today } from "../../../shared/utils/format.js"; import { ASSIGNMENT_STATUS, USER_STATUS, needsFacility, roleLabel, sortRoles } from "../../../shared/utils/roles.js"; import { useApp } from "../../../app/state/AppProvider.jsx"; @@ -40,7 +41,8 @@ import { dateOnlyLabel, dateTime, tempPassword, useLoad } from "../utils/adminUt * - onSaved: callback làm mới lại dữ liệu từ server sau khi cập nhật thành công */ function InfoCard({ user, onSaved }) { - const { onApiError, notify } = useApp(); + const { onApiError } = useApp(); + const [flowEl, runChange] = useChangeFlow(); // State lưu dữ liệu form chỉnh sửa const [form, setForm] = useState({ fullName: user.fullName, email: user.email, phone: user.phone || "", status: user.status }); @@ -72,21 +74,20 @@ function InfoCard({ user, onSaved }) { if (form.phone && !isPhone(form.phone)) err.phone = "Số điện thoại chưa đúng định dạng."; if (Object.keys(err).length) return setErrors(err); + // Figma 885:10623–10647: xác nhận → đã lưu / không lưu được setBusy(true); - try { - await adminApi.updateUser(user.userId, { + const out = await runChange({ + action: "Lưu thông tin tài khoản", scope: `Tài khoản ${user.fullName}`, content: "Thông tin và trạng thái tài khoản đã chỉnh sửa", + perform: () => adminApi.updateUser(user.userId, { fullName: form.fullName.trim(), email: form.email.trim().toLowerCase(), phone: form.phone.replace(/[\s.-]/g, "") || null, status: form.status, - }); - notify("Đã cập nhật tài khoản."); - onSaved(); - } catch (ex) { - onApiError(ex); - setErrors({ form: ex.message }); - } + }), + }); setBusy(false); + if (out.error) onApiError(out.error); + if (out.ok) onSaved(); }; return ( @@ -124,6 +125,7 @@ function InfoCard({ user, onSaved }) { + {flowEl} ); } @@ -132,29 +134,29 @@ function InfoCard({ user, onSaved }) { * PasswordCard - Thẻ Đặt Lại Mật Khẩu Cho Người Dùng * * Cho phép Admin cấp lại mật khẩu mới cho người dùng. - * Sau khi đổi xong sẽ bật Modal hiển thị mật khẩu để sao chép. + * Sau khi đổi xong, hộp thoại thành công hiện mật khẩu để sao chép. */ function PasswordCard({ user }) { const { onApiError } = useApp(); const [pw, setPw] = useState(""); // Mật khẩu mới đang nhập const [error, setError] = useState(""); // Lỗi độ dài mật khẩu const [busy, setBusy] = useState(false); - const [done, setDone] = useState(null); // Lưu mật khẩu vừa đặt thành công để hiển thị modal + const [flowEl, runChange] = useChangeFlow(); const submit = async (e) => { e.preventDefault(); if (pw.length < 8) return setError("Mật khẩu mới cần ít nhất 8 ký tự."); + // Figma 885:10657–10681: mật khẩu mới chỉ hiển thị một lần trong hộp thoại thành công setBusy(true); - try { - await adminApi.resetPassword(user.userId, pw); - setDone(pw); - setPw(""); - } catch (ex) { - onApiError(ex); - setError(ex.message); - } + const out = await runChange({ + action: "Đặt lại mật khẩu", scope: `Tài khoản ${user.fullName}`, content: "Mật khẩu mới trên biểu mẫu; chỉ hiển thị một lần", + successText: `Đã đặt lại mật khẩu. Mật khẩu mới của ${user.fullName}: ${pw}. Mật khẩu mới chỉ hiển thị một lần; quản trị viên gửi lại cho người dùng.`, + perform: () => adminApi.resetPassword(user.userId, pw), + }); setBusy(false); + if (out.error) onApiError(out.error); + if (out.ok) setPw(""); }; return ( @@ -180,15 +182,7 @@ function PasswordCard({ user }) { {busy ? "Đang đặt lại…" : "Đặt lại mật khẩu"} - {/* Modal thông báo kết quả sau khi đặt lại mật khẩu */} - {done && ( - setDone(null)}> -

    - Mật khẩu mới của {user.fullName}: {done}. Gửi cho người dùng và nhắc đổi sau khi đăng nhập. -

    - -
    - )} + {flowEl} ); } @@ -202,11 +196,11 @@ function PasswordCard({ user }) { * - onSaved: callback làm mới dữ liệu */ function RolesCard({ user, allRoles, onSaved }) { - const { onApiError, notify } = useApp(); + const { onApiError } = useApp(); const [adding, setAdding] = useState(""); // roleId được chọn trong dropdown để gán thêm - const [confirm, setConfirm] = useState(null); // Role đang chờ xác nhận thu hồi const [error, setError] = useState(""); const [busy, setBusy] = useState(false); + const [flowEl, runChange] = useChangeFlow(); // Tập hợp các roleId mà user đang sở hữu const owned = new Set(user.roles.map((r) => r.roleId)); @@ -214,18 +208,15 @@ function RolesCard({ user, allRoles, onSaved }) { const available = allRoles.filter((r) => !owned.has(r.roleId)); // Hàm thực thi gọi API kèm xử lý loading/lỗi - const run = async (fn, msg) => { + // Figma 885:10691–10817: mỗi thay đổi đi qua xác nhận → đã … / không … được + const run = async (perform, action, content) => { setBusy(true); setError(""); - try { - await fn(); - notify(msg); - onSaved(); - } catch (ex) { - onApiError(ex); - setError(ex.message); - } + const out = await runChange({ action, scope: `Tài khoản ${user.fullName}`, content, perform }); setBusy(false); + if (out.error) onApiError(out.error); + if (out.ok) onSaved(); + return out; }; return ( @@ -241,7 +232,7 @@ function RolesCard({ user, allRoles, onSaved }) { @@ -271,27 +262,7 @@ function RolesCard({ user, allRoles, onSaved }) { {error && {error}} - {/* Modal xác nhận thu hồi vai trò */} - {confirm && ( - setConfirm(null)}> -

    - {user.fullName} sẽ mất vai trò {roleLabel(confirm.roleName)} và các quyền đi kèm. -

    -
    - - -
    -
    - )} + {flowEl} ); } @@ -303,7 +274,8 @@ function RolesCard({ user, allRoles, onSaved }) { * Quy tắc nghiệp vụ: Mỗi người chỉ phụ trách 1 cơ sở tại một thời điểm. */ function FacilityCard({ user, facilities, rows, onSaved }) { - const { onApiError, notify } = useApp(); + const { onApiError } = useApp(); + const [flowEl, runChange] = useChangeFlow(); const [facilityId, setFacilityId] = useState(""); // Cơ sở chọn trong dropdown để phân công const [from, setFrom] = useState(today()); // Ngày bắt đầu phân công const [error, setError] = useState(""); @@ -313,18 +285,15 @@ function FacilityCard({ user, facilities, rows, onSaved }) { const active = rows.find((r) => r.status === "ACTIVE"); // Hàm chạy API đổi trạng thái hoặc phân công - const run = async (fn, msg) => { + // Figma 885:10691–10817: mỗi thay đổi đi qua xác nhận → đã … / không … được + const run = async (perform, action, content) => { setBusy(true); setError(""); - try { - await fn(); - notify(msg); - onSaved(); - } catch (ex) { - onApiError(ex); - setError(ex.message); - } + const out = await runChange({ action, scope: `Tài khoản ${user.fullName}`, content, perform }); setBusy(false); + if (out.error) onApiError(out.error); + if (out.ok) onSaved(); + return out; }; return ( @@ -350,13 +319,14 @@ function FacilityCard({ user, facilities, rows, onSaved }) { {error && {error}} + {flowEl} {/* Bảng lịch sử các đợt phân công cơ sở */} {rows.length > 0 && ( @@ -387,7 +357,7 @@ function FacilityCard({ user, facilities, rows, onSaved }) { type="button" className="link-btn" disabled={busy} - onClick={() => run(() => adminApi.setAssignmentStatus(r.userFacilityId, "SUSPENDED"), "Đã tạm ngưng phân công.")} + onClick={() => run(() => adminApi.setAssignmentStatus(r.userFacilityId, "SUSPENDED"), "Tạm ngưng phân công", `${r.facilityName} · phân công cơ sở đang được chọn`)} > Tạm ngưng @@ -395,7 +365,7 @@ function FacilityCard({ user, facilities, rows, onSaved }) { type="button" className="link-btn link-btn--danger" disabled={busy} - onClick={() => run(() => adminApi.setAssignmentStatus(r.userFacilityId, "ENDED"), "Đã kết thúc phân công.")} + onClick={() => run(() => adminApi.setAssignmentStatus(r.userFacilityId, "ENDED"), "Kết thúc phân công", `${r.facilityName} · kết thúc phân công hiện tại; giữ lịch sử`)} > Kết thúc @@ -407,7 +377,7 @@ function FacilityCard({ user, facilities, rows, onSaved }) { type="button" className="link-btn" disabled={busy} - onClick={() => run(() => adminApi.setAssignmentStatus(r.userFacilityId, "ACTIVE"), "Đã kích hoạt lại phân công.")} + onClick={() => run(() => adminApi.setAssignmentStatus(r.userFacilityId, "ACTIVE"), "Kích hoạt lại phân công", r.facilityName)} > Kích hoạt lại diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx index 16f7c6e..0556ab2 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx @@ -6,6 +6,7 @@ import { today } from "../../../shared/utils/format.js"; import { useApp } from "../../../app/state/AppProvider.jsx"; import { createPolicy, replacePolicy } from "./policyActions.js"; import { LoadState, useConfirm } from "../components/BusinessComponents.jsx"; +import { useChangeFlow } from "../../../shared/components/ChangeFlowDialog.jsx"; import { POLICY_SECTIONS, fieldPolicy, fieldValue, policyJobs } from "./policyFields.js"; export default function PolicySettingsPage() { @@ -14,6 +15,7 @@ export default function PolicySettingsPage() { const [drafts, setDrafts] = useState({}); const [busy, setBusy] = useState(false); const [confirmEl, ask] = useConfirm(); + const [flowEl, runChange] = useChangeFlow(); const save = async policies => { let jobs; try { @@ -21,16 +23,22 @@ export default function PolicySettingsPage() { jobs = policyJobs(policies, drafts, today()); } catch (e) { return notify(e.message, 'error'); } if (!jobs.length) return notify('Chưa có thay đổi nào.'); + // Figma 885:10487–10511: xác nhận → đã lưu / không lưu được setBusy(true); try { - for (const { keys, p, body } of jobs) { - const applied = p ? await replacePolicy(p, body, ask) : (await createPolicy(body, true, ask)).active; - if (!applied) { notify('Đã giữ bản nháp; các ô chưa áp dụng vẫn được giữ lại.'); return; } - setDrafts(d => { const next = { ...d }; for (const key of keys) delete next[key]; return next; }); - } - notify('Đã lưu thay đổi chính sách.'); - } catch (e) { onApiError(e); notify(e.message, 'error'); } - finally { setBusy(false); load.reload(); } + const out = await runChange({ + action: 'Lưu chính sách cho thuê', scope: 'Toàn hệ thống', content: `${jobs.length} giá trị chính sách trên biểu mẫu`, + perform: async () => { + for (const { keys, p, body } of jobs) { + const applied = p ? await replacePolicy(p, body, ask) : (await createPolicy(body, true, ask)).active; + if (!applied) { notify('Đã giữ bản nháp; các ô chưa áp dụng vẫn được giữ lại.'); return false; } + setDrafts(d => { const next = { ...d }; for (const key of keys) delete next[key]; return next; }); + } + return true; + }, + }); + if (out.error) onApiError(out.error); + } finally { setBusy(false); load.reload(); } }; return

    Chính sách cho thuê chung

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

    @@ -44,5 +52,6 @@ export default function PolicySettingsPage() {
    } {confirmEl} + {flowEl}
    ; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/pricing/PricingPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/pricing/PricingPage.jsx index 1a6bd12..eb593be 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/pricing/PricingPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/pricing/PricingPage.jsx @@ -7,6 +7,7 @@ import { useApp } from "../../../app/state/AppProvider.jsx"; import { createPolicy, replacePolicy } from "../policies/policyActions.js"; import { POLICY_STATUS, parseMoney, policyFor, policyValueLabel, replacementOf } from "../utils/businessFormat.js"; import { LoadState, PolicyForm, useConfirm } from "../components/BusinessComponents.jsx"; +import { useChangeFlow } from "../../../shared/components/ChangeFlowDialog.jsx"; // Ba cột chính sách theo loại kho (Figma B03): khung giá, phí dịch vụ / tháng, phí quá hạn / ngày const COLUMNS = [ @@ -37,6 +38,7 @@ export default function PricingPage() { const [adding, setAdding] = useState(false); const [busy, setBusy] = useState(false); const [confirmEl, ask] = useConfirm(); + const [flowEl, runChange] = useChangeFlow(); const close = useCallback(() => setAdding(false), []); const saveTable = async ({ policies, unitTypes }) => { @@ -63,15 +65,18 @@ export default function PricingPage() { setEdit({}); return notify("Chưa có thay đổi nào."); } + // Figma 885:10521–10545: xác nhận → đã lưu / không lưu được setBusy(true); try { - for (const job of jobs) { const result = await job(); if (result === false || result?.active === false) return; } - notify(`Đã lưu ${jobs.length} thay đổi khung giá / phí. Áp dụng từ hôm nay.`); - setEdit({}); - load.reload(); - } catch (e) { - onApiError(e); - notify(e.message, "error"); + const out = await runChange({ + action: "Lưu giá và phí", scope: "Toàn hệ thống", content: `${jobs.length} thay đổi khung giá / phí, áp dụng từ hôm nay`, + perform: async () => { + for (const job of jobs) { const result = await job(); if (result === false || result?.active === false) return false; } + setEdit({}); + return true; + }, + }); + if (out.error) onApiError(out.error); load.reload(); } finally { setBusy(false); } }; @@ -179,6 +184,7 @@ export default function PricingPage() { /> )} {confirmEl} + {flowEl} ); }} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationListPage.jsx index 5eb9114..4e84b36 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationListPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationListPage.jsx @@ -3,7 +3,6 @@ import { EmptyInline } from "../../../shared/components/Inline.jsx"; import { Button, Field, LinkButton, Modal, Notice, PageHeader } from "../../../shared/components/UI.jsx"; import { dateLabel, money, shortCode } from "../../../shared/utils/format.js"; import { shortName } from "../../../shared/hooks/useBrowserEvents.js"; -import { href } from "../../../app/router.js"; import { RESERVATION_STATUS } from "../../../shared/utils/status.js"; import { facilityOf, sortedReservations } from "../../../app/state/appSelectors.js"; import { useApp } from "../../../app/state/AppProvider.jsx"; @@ -17,7 +16,15 @@ export function canCancel(data, r) { return !data.contracts.some((c) => c.reservation_id === r.reservation_id && c.handed_over); } -const statusLabel = (r) => (r.status === "CANCELLED" && r.refund_status === "PENDING" ? "Đã huỷ · Đang hoàn tiền" : RESERVATION_STATUS[r.status][0]); +// C14b/C14c — đơn đã huỷ có khoản hoàn (D27): PENDING = chờ quản lý chuyển khoản, COMPLETED = đã hoàn +const isRefundPending = (r) => r.status === "CANCELLED" && r.refund_status === "PENDING"; +const isRefunded = (r) => r.status === "CANCELLED" && r.refund_status === "COMPLETED"; +function statusCell(r) { + if (isRefundPending(r)) return Đã huỷ · Đang hoàn tiền; + if (isRefunded(r)) return Đã huỷ · Đã hoàn tiền; + return RESERVATION_STATUS[r.status][0]; +} +export const CANCEL_POLICY_HINT = "Huỷ trước ngày bắt đầu thuê: phí huỷ 10% tiền cọc, hoàn 100% tiền thuê và 90% cọc. Từ ngày bắt đầu thuê, sử dụng quy trình trả kho."; // C14a — Hộp thoại huỷ đơn & hoàn tiền function CancelDialog({ r, onDone, onClose }) { @@ -28,7 +35,6 @@ function CancelDialog({ r, onDone, onClose }) { const [error, setError] = useState(""); const paid = r.status === "CONFIRMED"; const f = facilityOf(data, r.facility_id, r.facility_name); - const pickup = data.appointments.find((a) => a.reservation_id === r.reservation_id && a.kind === "CHECK_IN"); useEffect(() => { let alive = true; @@ -50,19 +56,19 @@ function CancelDialog({ r, onDone, onClose }) { return (

    - {[shortName(f) ? `SafeSpace ${shortName(f)}` : f.name, `${r.months} tháng`, pickup ? `Lịch nhận kho ${dateLabel(pickup.date)}` : null].filter(Boolean).join(" · ")} + {[shortName(f) ? `SafeSpace ${shortName(f)}` : f.name, `${r.months} tháng`, r.start_date ? `Bắt đầu thuê ${dateLabel(r.start_date)}` : null].filter(Boolean).join(" · ")}

    {paid ? (
    Đã thanh toán (tiền thuê {r.months} tháng + cọc)
    {money(preview?.paid ?? r.initial_total)}
    -
    Phí huỷ theo chính sách huỷ
    -
    {preview ? `− ${money(preview.fee)}` : preview === false ? "Theo chính sách hiện hành" : "Đang tính…"}
    +
    Phí huỷ (10% tiền cọc)
    +
    {preview ? `− ${money(preview.fee)}` : preview === false ? "Theo chính sách hiện hành" : "Đang tính…"}
    Số tiền được hoàn
    -
    {preview ? money(preview.refund) : preview === false ? "Cơ sở xác nhận sau khi huỷ" : "Đang tính…"}
    +
    {preview ? money(preview.refund) : preview === false ? "Cơ sở xác nhận sau khi huỷ" : "Đang tính…"}
    @@ -72,7 +78,7 @@ function CancelDialog({ r, onDone, onClose }) { setReason(e.target.value)} /> - {paid &&

    Tiền hoàn về tài khoản bạn đã dùng để thanh toán qua mã QR. Huỷ xong, kho được trả lại cho khách khác đặt.

    } + {paid &&

    Bạn được hoàn 100% tiền thuê và 90% tiền cọc trong 3–5 ngày làm việc. Quản lý cơ sở chuyển khoản thủ công và cập nhật trạng thái hoàn tiền.

    } {error && {error}}
    @@ -82,14 +88,15 @@ function CancelDialog({ r, onDone, onClose }) { ); } -// C14 — Đơn đặt chỗ của tôi (C14b sau khi huỷ) +// C14 — Đơn đặt chỗ của tôi (C14b sau khi huỷ, C14c khi đã hoàn tiền) export default function ReservationListPage() { - const { data } = useApp(); + const { data, retry } = useApp(); const [cancelling, setCancelling] = useState(null); const [done, setDone] = useState(null); const list = sortedReservations(data); - const latest = list[0]; - const cancellable = list.find((r) => canCancel(data, r)); + const anyCancellable = list.some((r) => canCancel(data, r)); + const pending = done ? null : list.find(isRefundPending); + const refunded = done ? null : list.find(isRefunded); return (
    @@ -103,39 +110,45 @@ export default function ReservationListPage() { Mã đặt chỗ Cơ sở / kỳ thuê - Tổng ban đầu + Tổng thanh toán Trạng thái + Thao tác {list.map((r) => ( - - {r.reservation_id} - + {r.reservation_id} {shortName(facilityOf(data, r.facility_id, r.facility_name))} · {r.months} tháng {money(r.initial_total)} - {statusLabel(r)} + {statusCell(r)} + +
    + Xem đơn + {!done && canCancel(data, r) && ( + + )} +
    + ))}
    - Xem đơn {shortCode(latest.reservation_id)} {done ? ( - - Đã huỷ đơn {done.id}.{done.refund ? ` Số tiền ${money(done.refund)} đang được hoàn về tài khoản bạn đã thanh toán.` : ""} - +

    + Đã huỷ đơn {done.id}.{done.refund ? ` Khoản ${money(done.refund)} đang chờ quản lý cơ sở hoàn về tài khoản đã thanh toán.` : ""} +

    + ) : pending ? ( +

    Đã huỷ đơn {pending.reservation_id}. Khoản {money(pending.refund_amount)} đang chờ quản lý cơ sở hoàn về tài khoản đã thanh toán.

    + ) : refunded ? ( +

    Đã hoàn {money(refunded.refund_amount)} cho đơn {refunded.reservation_id} về tài khoản bạn đã thanh toán.

    ) : ( - cancellable && ( - <> - -

    Chỉ huỷ được đơn chưa nhận kho. Số tiền hoàn tính theo chính sách huỷ hiện hành.

    - - ) + anyCancellable &&

    {CANCEL_POLICY_HINT}

    )} Đặt thêm kho + {(done?.refund || pending) && }
    )} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx index f14acdd..5f85094 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx @@ -3,6 +3,7 @@ import { Empty, LinkButton } from "../../shared/components/UI.jsx"; import { UnitAllocationPage } from "../manager/allocations/UnitAllocationPage.jsx"; import { StaffAssignmentPage } from "../manager/assignments/StaffAssignmentPage.jsx"; import { ContractListPage } from "../manager/contracts/ContractListPage.jsx"; +import { CancellationRefundPage } from "../manager/refunds/CancellationRefundPage.jsx"; import { ManagerResultPage } from "../manager/results/ManagerResultPage.jsx"; import { ManagerDashboardPage } from "../manager/dashboard/ManagerDashboardPage.jsx"; import { RenewalApprovalPage } from "../manager/renewals/RenewalApprovalPage.jsx"; @@ -44,6 +45,7 @@ const MANAGER = { assign: [StaffAssignmentPage, "manager/assign"], renewals: [RenewalApprovalPage, "manager/renewals"], contracts: [ContractListPage, "manager/contracts"], + refunds: [CancellationRefundPage, "manager/contracts"], report: [FacilityReportPage, "manager/report"], done: [ManagerResultPage, "manager"], }; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/api/facilityOperationsApi.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/api/facilityOperationsApi.js index 224038d..d34fddd 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/api/facilityOperationsApi.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/api/facilityOperationsApi.js @@ -34,7 +34,7 @@ export async function loadBoard(role) { version: 1, log: [], payments: [], allocations: [], verifications: [], handovers: [], returns: [], tickets: [], - renewals: [], contracts: [], assignments: [], units: [], staff: [], + renewals: [], contracts: [], refunds: [], assignments: [], units: [], staff: [], revenue: { months: [], by_type: [], as_of: null }, ...data, }; @@ -63,6 +63,8 @@ export const OPS_ACTIONS = { ASSIGN: ({ id, staff }) => ["PUT", `/api/ops/assignments/${enc(id)}`, { staffId: staff }], REMIND: ({ id, note }) => ["POST", `/api/ops/contracts/${enc(id)}/reminders`, { note: note || "" }], CONFIRM_REFUND: ({ id }) => ["POST", `/api/ops/contracts/${enc(id)}/refund`], + // M08 · D27: xác nhận đã chuyển khoản hoàn cho đơn khách huỷ (backend chưa nhận phương thức / mã giao dịch → gửi kèm để lưu sau) + CONFIRM_RESERVATION_REFUND: ({ id, method, transaction_ref }) => ["POST", `/api/ops/reservations/${enc(id)}/refund`, { method: method || "BANK_TRANSFER", transactionRef: String(transaction_ref || "").trim() || null }], CREATE_UNIT: (data) => ["POST", `/api/manager/units`, toApi(data)], UPDATE_UNIT: ({ id, ...data }) => ["PUT", `/api/manager/units/${enc(id)}`, toApi(data)], LOCK_UNIT: ({ id, reason }) => ["POST", `/api/manager/units/${enc(id)}/lock`, { reason }], diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js index 47fff49..6a446e2 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js @@ -147,6 +147,13 @@ export function createOpsData(t = today()) { { id: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "K07", end: addDays(t, 6), due: "Yêu cầu gia hạn", amount: 0, state: "RENEWAL", reminders: [] }, ], + // M08 · Hoàn tiền đơn khách huỷ trước ngày bắt đầu thuê (D27: phí 10% cọc, hoàn 100% tiền thuê + 90% cọc) + refunds: [ + { id: "SS-20260918-0151", customer: "Nguyễn Hoàng Yến", cancelled_at: at(addDays(t, -1), "08:40"), rent: 3450000, deposit: 1150000, paid: 4600000, fee: 115000, amount: 4485000, status: "PENDING" }, + { id: "SS-20260916-0149", customer: "Phạm Gia Hân", cancelled_at: at(addDays(t, -3), "16:15"), rent: 1140000, deposit: 1140000, paid: 2280000, fee: 114000, amount: 2166000, status: "PENDING" }, + { id: "SS-20260905-0121", customer: "Võ Thanh Tùng", cancelled_at: at(addDays(t, -10), "10:05"), rent: 900000, deposit: 900000, paid: 1800000, fee: 0, amount: 1800000, status: "PAID", paid_at: at(addDays(t, -8), "15:20"), transaction_ref: "FT26249001233" }, + ], + // M06 · Công việc được phân công assignments: [ { id: "PC-01", title: "Bàn giao K01 · Nguyễn Thị Mai", when: at(pickup, "09:00"), staff: "NV-01", status: "ACCEPTED", ref: "BG-0142" }, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/FacilityOperationsProvider.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/FacilityOperationsProvider.jsx index eebc0c2..bd5a238 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/FacilityOperationsProvider.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/FacilityOperationsProvider.jsx @@ -1,7 +1,7 @@ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import ConfirmDialog from "../../../shared/components/ConfirmDialog.jsx"; -import { Dialog } from "../../../shared/components/UI.jsx"; -import { opsConfirmation } from "../utils/opsConfirmation.js"; +import { Button, Modal } from "../../../shared/components/UI.jsx"; +import { MANAGER_CONFIRM, opsConfirmation } from "../utils/opsConfirmation.js"; import { ApiError } from "../../../shared/api/httpClient.js"; import { callAction, loadBoard } from "../api/facilityOperationsApi.js"; import { createOpsData } from "../data/facilityOperationsSeed.js"; @@ -42,9 +42,11 @@ export function OpsProvider({ children, notify, mode = "local", onApiError, role const [loadError, setLoadError] = useState(null); const [confirmation, setConfirmation] = useState(null); const [saving, setSaving] = useState(false); - const [failure, setFailure] = useState(""); + // Kết quả sau khi lưu (Figma 03a thành công / 03b thất bại): { kind, title, text, action, detail } + const [outcome, setOutcome] = useState(null); const activeAction = useRef(false); const confirmationRef = useRef(null); + const outcomeRef = useRef(null); const ref = useRef(state); ref.current = state; @@ -129,37 +131,58 @@ export function OpsProvider({ children, notify, mode = "local", onApiError, role [source, reload, commit, notify, onApiError], ); - // Guard the mutation boundary, including future staff actions. Cancel never calls the API. + // Guard the mutation boundary. Nhân viên: mọi thao tác hỏi xác nhận rồi báo kết quả (S02–S05, S09). + // Quản lý: phân bổ, phân công, duyệt/từ chối gia hạn (Figma 885:*, M03a–d). Cancel never calls the API. + const showOutcome = useCallback((next) => new Promise((resolve) => { + outcomeRef.current = resolve; + setOutcome(next); + }), []); const run = useCallback(async (type, payload, message) => { - if (role !== "STAFF" || type === "MARK_READ") return execute(type, payload, message); + const guarded = type !== "MARK_READ" && (role === "STAFF" || MANAGER_CONFIRM.has(type)); + if (!guarded) return execute(type, payload, message); if (activeAction.current) return { ok: false, cancelled: true }; activeAction.current = true; - const accepted = await new Promise(resolve => { - confirmationRef.current = resolve; - setConfirmation(opsConfirmation(type, payload, ref.current)); - }); - confirmationRef.current = null; - if (!accepted) { - activeAction.current = false; - setConfirmation(null); - return { ok: false, cancelled: true }; - } - setSaving(true); + const spec = opsConfirmation(type, payload, ref.current); try { - const result = await execute(type, payload, message); - if (!result.ok) setFailure(result.error || "Không lưu được thay đổi. Vui lòng kiểm tra lại trạng thái trước khi thử lại."); + if (spec.confirm !== false) { + const accepted = await new Promise(resolve => { + confirmationRef.current = resolve; + setConfirmation(spec); + }); + confirmationRef.current = null; + if (!accepted) { + setConfirmation(null); + return { ok: false, cancelled: true }; + } + } + setSaving(true); + let result; + try { + result = await execute(type, payload, message); + } catch (error) { + result = { ok: false, error: error?.message }; + } + setSaving(false); + setConfirmation(null); + if (!result.ok) { + const failure = spec.failure || { title: "Chưa lưu được thay đổi", text: "Không lưu được thay đổi. Vui lòng kiểm tra lại trạng thái trước khi thử lại." }; + await showOutcome({ kind: "failure", ...failure, detail: result.error && result.error !== failure.text ? result.error : "" }); + return { ...result, shown: true }; + } + if (spec.success) await showOutcome({ kind: "success", ...spec.success }); return result; - } catch (error) { - const text = error?.message || "Chưa xác nhận được kết quả lưu. Kiểm tra trạng thái trước khi thực hiện lại."; - setFailure(text); - return { ok: false, error: text }; } finally { activeAction.current = false; setSaving(false); setConfirmation(null); } - }, [role, execute]); - useEffect(() => () => confirmationRef.current?.(false), []); + }, [role, execute, showOutcome]); + const closeOutcome = useCallback(() => { + setOutcome(null); + outcomeRef.current?.(); + outcomeRef.current = null; + }, []); + useEffect(() => () => { confirmationRef.current?.(false); outcomeRef.current?.(); }, []); useEffect(() => { if (mode !== "api") return undefined; const refresh = () => { if (!activeAction.current && !document.hidden) reload(); }; @@ -191,6 +214,15 @@ export function OpsProvider({ children, notify, mode = "local", onApiError, role return {children} {confirmation && confirmationRef.current?.(false)} onConfirm={() => confirmationRef.current?.(true)} />} - {failure && setFailure("")} />} + {outcome && ( + + + )} ; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/facilityOperationsReducer.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/facilityOperationsReducer.js index 04e7c18..f4b084e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/facilityOperationsReducer.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/facilityOperationsReducer.js @@ -92,7 +92,7 @@ const ACTIONS = { ...state, returns: patch(state.returns, id, () => ({ status: "SUBMITTED", report, submitted_at: iso(now) })), units: patchUnit(state.units, r.unit, () => ({ status: "INSPECTION" })), - contracts: state.contracts.map((c) => (c.id === r.contract ? { ...c, state: "RETURNED", due: `${money(r.unpaid)} · Chờ quản lý xác nhận hoàn cọc` } : c)), + contracts: state.contracts.map((c) => (c.id === r.contract ? { ...c, state: "RETURNED", due: `Còn phải thu ${money(r.unpaid)}` } : c)), assignments: state.assignments.map((a) => (a.ref === id ? { ...a, status: "DONE" } : a)), }; return { state: addLog(next, now, `Biên bản trả kho ${r.unit} chờ quản lý xác nhận`, "manager/contracts", "MANAGER"), result: { id } }; @@ -186,6 +186,16 @@ const ACTIONS = { return { state: addLog(next, now, `Đã xác nhận hoàn cọc ${money(refund)} · ${id}`, "manager/contracts", "MANAGER"), result: { id, refund } }; }, + // M08 · Quản lý xác nhận đã chuyển khoản hoàn tiền cho đơn khách huỷ (D27) + CONFIRM_RESERVATION_REFUND(state, { id, method, transaction_ref }, now) { + const r = find(state.refunds || [], id, "yêu cầu hoàn tiền"); + if (r.status !== "PENDING") fail("Khoản hoàn tiền này đã được xác nhận."); + const ref = String(transaction_ref || "").trim(); + if (method !== "CASH" && !ref) fail("Nhập mã giao dịch hoàn tiền."); + const next = { ...state, refunds: patch(state.refunds, id, () => ({ status: "PAID", paid_at: iso(now), method: method || "BANK_TRANSFER", transaction_ref: ref || null })) }; + return { state: addLog(next, now, `Đã xác nhận hoàn ${money(r.amount)} · ${id}`, "manager/refunds", "MANAGER"), result: { id, refund: r.amount } }; + }, + // M02a · F12 UPDATE_UNIT_STATUS(state, { code, status, reason, by }, now) { const u = state.units.find((x) => x.code === code) || fail("Không tìm thấy ô kho."); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/opsConfirmation.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/opsConfirmation.js index 6eba260..b6d4448 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/opsConfirmation.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/opsConfirmation.js @@ -1,32 +1,139 @@ -import { money } from "../../../shared/utils/format.js"; +import { dateLabel, money } from "../../../shared/utils/format.js"; + +// Nội dung hộp thoại xác nhận (02), thành công (03a) và thất bại (03b) cho thao tác tại cơ sở. +// Chữ lấy theo Figma: S02–S05, S09 (779:*), S05c–e (831:*), M03a–d (847:*), phân bổ / phân công (885:*). +// confirm: false → trang đã có hộp thoại riêng (nhập lý do…), provider chỉ hiện kết quả. +const GENERIC_FAIL = "Chưa ghi nhận thay đổi. Giữ nội dung đã nhập để kiểm tra và thử lại."; +const FEE_KEYS = [["damage_fee", "Hư hỏng"], ["cleaning_fee", "Vệ sinh"], ["overdue_fee", "Quá hạn"]]; export function opsConfirmation(type, payload, ops) { const find = key => (ops[key] || []).find(x => x.id === payload.id); + const facility = ops.facility?.name || "Cơ sở đang phụ trách"; switch (type) { case "CONFIRM_PAYMENT": { const p = find("payments"); - return { title: "Xác nhận đã thu đủ tiền?", text: "Kiểm tra khách hàng, mã đơn và số tiền thực nhận trước khi ghi nhận thanh toán.", label: "Xác nhận đã thu", rows: [["Đơn đặt chỗ", `${p?.id} · ${p?.customer}`], ["Số tiền thực nhận", money(p?.amount)], ["Hình thức thu", "Tiền mặt / chuyển khoản tại quầy"]] }; + return { + title: "Xác nhận đã thu đủ tiền?", text: "Kiểm tra khách hàng, mã đơn và số tiền thực nhận trước khi ghi nhận thanh toán.", label: "Xác nhận đã thu", + rows: [["Đơn đặt chỗ", `${p?.id} · ${p?.customer}`], ["Số tiền thực nhận", money(p?.amount)], ["Hình thức thu", "Tiền mặt / chuyển khoản tại quầy"]], + success: { title: "Đã ghi nhận thanh toán", text: `Đã thu ${money(p?.amount)} cho đơn ${p?.id}. Hệ thống cập nhật hợp đồng và quyền mở kho theo kỳ thuê.`, action: "Về danh sách thu tiền" }, + failure: { title: "Chưa xác nhận được thanh toán", text: "Chưa xác nhận được kết quả lưu. Kiểm tra trạng thái đơn trước khi thực hiện lại để tránh ghi nhận trùng." }, + }; } case "VERIFY_CUSTOMER": { const v = find("verifications"); - return { title: "Xác nhận giấy tờ khách hàng?", text: "Chỉ xác nhận khi ảnh và thông tin trên giấy tờ khớp với khách hàng.", label: "Xác nhận giấy tờ", rows: [["Khách hàng / Kho", `${v?.customer} · ${v?.unit}`], ["Giấy tờ", `${payload.doc_type} · …${String(payload.doc_no || "").slice(-4)}`]] }; + return { + title: "Xác nhận thông tin giấy tờ?", text: "Chỉ xác nhận khi đã đối chiếu đầy đủ giấy tờ và đúng người nhận chìa khóa.", label: "Xác nhận xác minh", + rows: [["Khách hàng", v?.customer], ["Đơn đặt chỗ", v?.reservation_id || v?.id], ["Nội dung xác minh", `${payload.doc_type} · …${String(payload.doc_no || "").slice(-4)} · ảnh và thông tin khớp`]], + success: { title: "Đã lưu kết quả xác minh", text: "Thông tin giấy tờ đã được xác minh. Tiếp tục ghi nhận việc nhận chìa khóa vật lý tại quầy.", action: "Tiếp tục nhận chìa khóa" }, + failure: { title: "Không lưu được kết quả xác minh", text: "Vui lòng kiểm tra lại thông tin và kết nối rồi thực hiện lại. Chưa thể chuyển sang bước nhận chìa khóa." }, + }; } case "RECORD_KEY_RECEIPT": { const h = find("handovers"); - return { title: "Xác nhận khách đã nhận chìa khóa?", text: "Ghi nhận nhận chìa khóa vật lý tại quầy. Thao tác này không kích hoạt hợp đồng hoặc quyền mở kho.", label: "Ghi nhận đã nhận chìa khóa", rows: [["Khách hàng / Kho", `${h?.customer} · ${h?.unit}`], ["Chìa khóa vật lý", "01 chìa khóa"]] }; + return { + title: "Xác nhận khách đã nhận chìa khóa?", text: "Chỉ ghi nhận sau khi khách thực sự nhận đúng chìa khóa vật lý.", label: "Xác nhận đã nhận chìa khóa", + rows: [["Khách hàng", h?.customer], ["Kho", `${h?.unit} · ${facility}`], ["Chìa khóa đã nhận", "01 chìa khóa vật lý"]], + success: { title: "Đã ghi nhận nhận chìa khóa", text: `Đã cập nhật trạng thái nhận chìa khóa cho kho ${h?.unit}. QR và PIN vẫn có hiệu lực theo ngày bắt đầu, ngày kết thúc hợp đồng.`, action: "Về danh sách nhận chìa khóa" }, + failure: { title: "Không ghi nhận được việc nhận chìa khóa", text: "Kiểm tra trạng thái nhận chìa khóa và kết nối trước khi thử lại." }, + }; } case "SUBMIT_RETURN": { const r = find("returns"); - return { title: "Gửi biên bản trả kho?", text: "Kiểm tra các mục kiểm tra và đề xuất trước khi gửi cho quản lý cơ sở.", label: "Gửi biên bản", rows: [["Khách hàng / Kho", `${r?.customer} · ${r?.unit}`], ...Object.entries({ "Đồ lưu trữ": payload.report.items, "Tường, sàn & cửa kho": payload.report.walls, "Chìa khóa vật lý": payload.report.keys, "Đề xuất": payload.report.proposal })] }; + const report = payload.report || {}; + const hasFees = FEE_KEYS.some(([k]) => report[k] != null); + const total = FEE_KEYS.reduce((sum, [k]) => sum + (Number(report[k]) || 0), 0); + return { + title: "Xác nhận gửi biên bản trả kho?", text: "Kiểm tra tình trạng kho, các khoản phí và lý do trước khi gửi cho quản lý cơ sở.", label: "Xác nhận gửi biên bản", + rows: [ + ["Kho / khách hàng", `${r?.unit} · ${r?.customer}`], + ...(hasFees ? [["Phí phát sinh", FEE_KEYS.map(([k, label]) => `${label}: ${money(Number(report[k]) || 0)}`).join(" · ")]] : []), + ["Đề xuất trạng thái", report.proposal], + ], + success: { title: "Đã gửi biên bản cho quản lý", text: `Biên bản trả kho ${r?.unit}${total ? ` và phí phát sinh ${money(total)}` : ""} đã được gửi để quản lý xem xét.`, action: "Về danh sách trả kho" }, + failure: { title: "Không gửi được biên bản", text: "Vui lòng kiểm tra kết nối và nội dung biên bản trước khi gửi lại." }, + }; } case "TICKET_RESPONSE": { const t = find("tickets"); - const states = { WAITING_CUSTOMER: "Chờ khách xác nhận", IN_PROGRESS: "Tiếp tục xử lý", DONE: "Đã xử lý xong" }; - return { title: "Lưu phản hồi hỗ trợ?", text: "Phản hồi và trạng thái xử lý sẽ được cập nhật cho yêu cầu này.", label: "Lưu phản hồi", rows: [["Yêu cầu", `${t?.id} · ${t?.customer}`], ["Phản hồi", payload.note], ["Trạng thái tiếp theo", states[payload.next]]] }; + const states = { WAITING_CUSTOMER: "Chờ khách xác nhận đã sử dụng được", IN_PROGRESS: "Tiếp tục xử lý", DONE: "Đã xử lý xong" }; + return { + title: "Xác nhận lưu và gửi phản hồi?", text: "Phản hồi và trạng thái xử lý sẽ được lưu, đồng thời thông báo tới khách hàng.", label: "Xác nhận lưu phản hồi", + rows: [["Yêu cầu hỗ trợ", `${t?.id} · Kho ${t?.unit} · ${t?.customer}`], ["Phản hồi", payload.note], ["Trạng thái tiếp theo", states[payload.next]]], + success: { title: "Đã lưu và gửi phản hồi", text: `Yêu cầu ${t?.id} đã được cập nhật. Khách hàng nhận thông báo và xem được phản hồi trong tài khoản.`, action: "Về danh sách hỗ trợ" }, + failure: { title: "Không lưu được phản hồi", text: "Phản hồi chưa gửi thành công. Kiểm tra kết nối và gửi lại sau khi rà soát nội dung." }, + }; + } + case "REISSUE_CREDENTIAL": { + const kind = payload.type in REISSUE ? payload.type : "QR"; + const [confirm, success, failure] = REISSUE[kind]; + return { + title: confirm[0], text: confirm[1], label: confirm[2], + rows: [["Khách hàng / kho", [payload.customer, payload.unit].filter(Boolean).join(" · ")], ["Loại cấp lại", { QR: "Mã QR", PIN: "PIN 6 số", KEY: "01 chìa khóa vật lý" }[kind]], ["Lý do", payload.reason]], + success: { title: success[0], text: success[1].replace("{unit}", payload.unit || ""), action: "Về yêu cầu hỗ trợ" }, + failure: { title: failure[0], text: failure[1], action: "Quay lại xác nhận" }, + }; + } + // Quản lý cơ sở + case "ALLOCATE": { + const a = find("allocations"); + return { + title: "Phân bổ ô kho?", text: "Kiểm tra thông tin trước khi xác nhận. Chọn Quay lại để giữ nguyên dữ liệu.", label: "Xác nhận", hint: "Chỉ lưu thay đổi sau khi bạn bấm Xác nhận.", + rows: [["Thao tác", "Phân bổ ô kho"], ["Phạm vi", facility], ["Nội dung", `${a?.id} · ${a?.customer} → ô ${payload.unit}`]], + success: { title: "Đã phân bổ ô kho", text: `Thay đổi đã được ghi nhận. ${facility}.`, action: "Về màn hình trước" }, + failure: { title: "Không phân bổ ô kho được", text: GENERIC_FAIL }, + }; + } + case "ASSIGN": { + const a = find("assignments"); + const staff = (ops.staff || []).find((s) => s.staff_id === payload.staff)?.full_name || payload.staff; + return { + title: "Lưu phân công nhân viên?", text: "Kiểm tra thông tin trước khi xác nhận. Chọn Quay lại để giữ nguyên dữ liệu.", label: "Xác nhận", hint: "Chỉ lưu thay đổi sau khi bạn bấm Xác nhận.", + rows: [["Thao tác", "Lưu phân công nhân viên"], ["Phạm vi", facility], ["Nội dung", `${a?.title} → ${staff}`]], + success: { title: "Đã lưu phân công nhân viên", text: `Thay đổi đã được ghi nhận. ${facility}.`, action: "Về màn hình trước" }, + failure: { title: "Không lưu phân công nhân viên được", text: GENERIC_FAIL }, + }; + } + case "DECIDE_RENEWAL": { + const r = find("renewals"); + if (!payload.approve) + return { + confirm: false, + success: { title: "Đã từ chối yêu cầu", text: "Lý do đã được gửi cho khách. Hợp đồng giữ nguyên kỳ thuê hiện tại.", action: "Về yêu cầu gia hạn" }, + failure: { title: "Chưa từ chối được yêu cầu", text: GENERIC_FAIL }, + }; + return { + title: `Duyệt gia hạn kho ${r?.unit}?`, text: "Duyệt để khách thanh toán tiền thuê kỳ mới. Chỉ cập nhật ngày kết thúc hợp đồng khi đủ điều kiện thanh toán.", label: "Xác nhận duyệt", hint: "Kiểm tra thông tin trước khi xác nhận.", + rows: [["Khách hàng", r?.customer], ["Kỳ gia hạn", r ? `${dateLabel(r.from)}–${dateLabel(r.to)}` : ""], ["Trạng thái sau khi duyệt", "Chờ khách thanh toán"]], + success: { title: "Đã duyệt · Chờ thanh toán", text: "Khách nhận khoản tiền thuê kỳ mới trong mục Thanh toán. Kỳ thuê chính thức được cập nhật khi đủ điều kiện thanh toán.", action: "Về yêu cầu gia hạn" }, + failure: { title: "Chưa duyệt được gia hạn", text: GENERIC_FAIL }, + }; } - case "REISSUE_CREDENTIAL": - return { title: "Xác nhận cấp lại?", text: payload.type === "KEY" ? "Tạo lịch nhận chìa khóa thay thế tại quầy. Quyền mở kho không thay đổi." : "Mã cũ cùng loại sẽ bị vô hiệu hóa. Thời gian hiệu lực hợp đồng không thay đổi.", label: "Xác nhận cấp lại", rows: [["Kho", payload.unit], ["Mục cần cấp lại", { QR: "Mã QR", PIN: "PIN 6 số", KEY: "Chìa khóa vật lý" }[payload.type]], ["Lý do", payload.reason]] }; default: - return { title: "Xác nhận thay đổi?", text: "Kiểm tra thông tin trước khi lưu thay đổi tại cơ sở.", label: "Xác nhận thay đổi", rows: Object.entries(payload).map(([key, value]) => [({ unit: "Kho", type: "Loại mã / chìa khóa", reason: "Lý do", status: "Trạng thái", code: "Mã kho", id: "Mã yêu cầu" })[key] || key, String(value ?? "")]) }; + return { + title: "Xác nhận thay đổi?", text: "Kiểm tra thông tin trước khi lưu thay đổi tại cơ sở.", label: "Xác nhận thay đổi", + rows: Object.entries(payload).map(([key, value]) => [({ unit: "Kho", type: "Loại mã / chìa khóa", reason: "Lý do", status: "Trạng thái", code: "Mã kho", id: "Mã yêu cầu" })[key] || key, String(value ?? "")]), + }; } } + +// S05c–e: [xác nhận, thành công, thất bại] theo loại cấp lại +const REISSUE = { + QR: [ + ["Xác nhận cấp lại QR?", "QR cũ sẽ bị vô hiệu hóa. PIN 6 số hiện tại và thời gian hiệu lực hợp đồng được giữ nguyên.", "Xác nhận cấp lại QR"], + ["Đã cấp lại QR", "QR cũ đã bị vô hiệu hóa. Khách xem QR mới trong tài khoản; PIN và kỳ hợp đồng không đổi."], + ["Chưa cấp lại được QR", "Yêu cầu chưa hoàn tất. Kiểm tra trạng thái mã và kết nối trước khi thử lại."], + ], + PIN: [ + ["Xác nhận cấp lại PIN?", "PIN cũ sẽ bị vô hiệu hóa. QR hiện tại và thời gian hiệu lực hợp đồng được giữ nguyên.", "Xác nhận cấp lại PIN"], + ["Đã cấp lại PIN 6 số", "PIN cũ đã bị vô hiệu hóa. Khách xem PIN mới trong tài khoản; QR và kỳ hợp đồng không đổi."], + ["Chưa cấp lại được PIN", "Yêu cầu chưa hoàn tất. Kiểm tra trạng thái PIN và kết nối trước khi thử lại."], + ], + KEY: [ + ["Đã giao chìa khóa thay thế?", "Chỉ ghi nhận sau khi đã đối chiếu khách hàng và giao chìa khóa tại quầy. Quyền mở kho không thay đổi.", "Xác nhận đã giao"], + ["Đã ghi nhận giao chìa khóa", "Đã ghi nhận giao 01 chìa khóa thay thế cho kho {unit}. QR, PIN và kỳ hợp đồng không đổi."], + ["Chưa lưu được giao chìa khóa", "Nếu đã giao chìa khóa, kiểm tra lại lịch sử trước khi lưu tiếp. Không giao thêm chìa khóa."], + ], +}; + +// Thao tác của quản lý dùng hộp thoại xác nhận chung (Figma 885:*, M03a). M02a, M07a, M08a có hộp thoại riêng trên trang. +export const MANAGER_CONFIRM = new Set(["ALLOCATE", "ASSIGN", "DECIDE_RENEWAL"]); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/pendingTaskCounts.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/pendingTaskCounts.js index c3eacf9..43297d2 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/pendingTaskCounts.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/pendingTaskCounts.js @@ -14,6 +14,6 @@ export function pendingTaskCounts(ops, role, me) { "manager/allocate": count(ops.allocations, a => a.status === "PENDING"), "manager/assign": count(ops.assignments, a => a.status === "OPEN"), "manager/renewals": count(ops.renewals, r => r.status === "PENDING"), - "manager/contracts": count(ops.contracts, c => ["OVERDUE", "RETURNED"].includes(c.state)), + "manager/contracts": count(ops.contracts, c => ["OVERDUE", "RETURNED"].includes(c.state)) + count(ops.refunds, r => r.status === "PENDING"), }; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/allocations/UnitAllocationPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/allocations/UnitAllocationPage.jsx index 2f93f0c..ce1e138 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/allocations/UnitAllocationPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/allocations/UnitAllocationPage.jsx @@ -1,7 +1,6 @@ import React, { useState } from "react"; import { Button, Empty, LinkButton, Notice, Tag } from "../../../shared/components/UI.jsx"; import { dateTimeLabel, rangeLabel } from "../../../shared/utils/format.js"; -import { go } from "../../../app/router.js"; import { candidateUnits } from "../../facility-operations/state/facilityOperationsReducer.js"; import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; import { QueuePicker } from "../../facility-operations/components/FacilityOperationsComponents.jsx"; @@ -23,8 +22,8 @@ export function UnitAllocationPage({ query }) { ); const submit = async () => { - const r = await run("ALLOCATE", { id: a.id, unit: chosen?.code }, `Đã phân bổ kho ${chosen?.code}`); - if (r.ok) go("manager/done?kind=allocate"); + // Figma 885:10453–10477: xác nhận → kết quả “Về màn hình trước”, ở lại trang phân bổ + await run("ALLOCATE", { id: a.id, unit: chosen?.code }, `Đã phân bổ kho ${chosen?.code}`); }; return (
    diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx index d5b16d1..ba313df 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx @@ -1,7 +1,6 @@ import React, { useState } from "react"; import { Select } from "../../../shared/components/Pickers.jsx"; import { Button, Field, Notice, Tag } from "../../../shared/components/UI.jsx"; -import { go } from "../../../app/router.js"; import { ASSIGN_STATE } from "../../facility-operations/state/facilityOperationsReducer.js"; import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; import { slotLabel } from "../../facility-operations/components/FacilityOperationsComponents.jsx"; @@ -16,8 +15,8 @@ export function StaffAssignmentPage() { const busyCount = (id) => ops.assignments.filter((a) => a.staff === id && a.status !== "DONE").length; const submit = async (e) => { e.preventDefault(); - const r = await run("ASSIGN", { id: task, staff }, `Đã phân công ${staffName(staff)}`); - if (r.ok) go("manager/done?kind=assign"); + // Figma 885:10419–10443: xác nhận → kết quả “Về màn hình trước”, ở lại trang phân công + await run("ASSIGN", { id: task, staff }, `Đã phân công ${staffName(staff)}`); }; return (
    diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/contracts/ContractListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/contracts/ContractListPage.jsx index 431cd72..9cebba1 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/contracts/ContractListPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/contracts/ContractListPage.jsx @@ -1,6 +1,6 @@ import React, { useState } from "react"; -import { Button, Field, LinkButton, Notice, Tag } from "../../../shared/components/UI.jsx"; -import { dateLabel, dateTimeLabel, daysBetween, today } from "../../../shared/utils/format.js"; +import { Button, Field, LinkButton, Modal, Notice, Tag } from "../../../shared/components/UI.jsx"; +import { dateLabel, dateTimeLabel, daysBetween, money, today } from "../../../shared/utils/format.js"; import { go, qs } from "../../../app/router.js"; import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; import { PageHeaderBlock } from "../components/PageHeaderBlock.jsx"; @@ -11,11 +11,40 @@ export const CONTRACT_STATE = (c) => : c.state === "RENEWAL" ? ["Cần duyệt", "amber"] : c.state === "RETURNED" - ? ["Chờ hoàn cọc", "blue"] + ? ["Chờ xác nhận trả kho", "amber"] : ["Đã xử lý", "green"]; +// M07a · Xác nhận trả kho (Figma 629:9147): khoản chưa thanh toán + phí theo biên bản S04 vẫn được giữ làm công nợ +function ReturnConfirmDialog({ contract, ret, onClose, onConfirm }) { + const [note, setNote] = useState(""); + const [busy, setBusy] = useState(false); + const fees = Number(ret?.report?.cleaning_fee || 0) + Number(ret?.report?.damage_fee || 0) + Number(ret?.report?.overdue_fee || 0); + const unpaid = Number(ret?.unpaid ?? contract.amount ?? 0); + return ( + +

    {[contract.customer, `Kho ${contract.unit}`, ret?.appointment ? `trả kho ${dateLabel(ret.appointment)}` : null].filter(Boolean).join(" · ")}

    +
    +
    +
    Khoản chưa thanh toán
    {money(unpaid)}
    + {fees > 0 &&
    Phí phát sinh (biên bản S04)
    {money(fees)}
    } +
    Tổng còn phải thu
    {money(unpaid + fees)}
    +
    +
    + + setNote(e.target.value)} /> + +

    Xác nhận trả kho sẽ kết thúc hợp đồng. Khoản chưa thanh toán vẫn được giữ để tiếp tục thu hồi.

    +
    + + +
    +
    + ); +} + export function ContractListPage({ query }) { const { ops, run } = useOps(); + const [returning, setReturning] = useState(false); const sel = ops.contracts.find((c) => c.id === query.get("id")) || ops.contracts.find((c) => c.state === "RETURNED") || ops.contracts[0]; const [note, setNote] = useState(""); const mismatch = ops.payments.filter((p) => p.status === "MISMATCH"); @@ -48,8 +77,8 @@ export function ContractListPage({ query }) {

    {sel.id} · Bước tiếp theo

    {sel.state === "RETURNED" ? ( <> -

    Nhân viên đã gửi biên bản trả kho {sel.unit}. Đối chiếu khoản còn nợ rồi xác nhận số tiền hoàn cọc.

    - +

    Biên bản trả kho {sel.unit} đã được gửi. Đối chiếu khoản phải thu và xác nhận trả kho; công nợ còn lại tiếp tục được theo dõi.

    + ) : sel.state === "RENEWAL" ? ( <> @@ -70,6 +99,20 @@ export function ContractListPage({ query }) { )} + {returning && sel.state === "RETURNED" && ( + x.contract === sel.id)} + onClose={() => setReturning(false)} + onConfirm={async (note) => { + const out = await run("CONFIRM_REFUND", { id: sel.id, note }, "Đã xác nhận trả kho"); + setReturning(false); + if (out.ok) go("manager/done?kind=refund"); + }} + /> + )} + {/* Figma M07: lối vào M08 hoàn tiền đơn huỷ */} + Hoàn tiền đơn huỷ{(ops.refunds || []).some((r) => r.status === "PENDING") ? ` (${ops.refunds.filter((r) => r.status === "PENDING").length})` : ""} {sel.reminders.length > 0 && (
      {sel.reminders.map((r, i) =>
    • {dateTimeLabel(r.at)}{r.text}
    • )} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/CancellationRefundPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/CancellationRefundPage.jsx new file mode 100644 index 0000000..96845c5 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/CancellationRefundPage.jsx @@ -0,0 +1,136 @@ +import React, { useState } from "react"; +import { Button, Field, LinkButton, Modal, Notice } from "../../../shared/components/UI.jsx"; +import { dateLabel, dateTimeLabel, money } from "../../../shared/utils/format.js"; +import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; +import { PageHeaderBlock } from "../components/PageHeaderBlock.jsx"; + +// Figma M08 / M08a / M08a2 / M08-kết thúc / M07e: hoàn tiền đơn khách huỷ trước ngày bắt đầu thuê (D27). +// Quản lý chuyển khoản thủ công ngoài hệ thống rồi xác nhận ở đây; thao tác không tự chuyển tiền. +// Khách trả qua PayOS nên chỉ hoàn bằng chuyển khoản (Figma M08a ẩn lựa chọn tiền mặt) +const METHODS = [["BANK_TRANSFER", "Chuyển khoản thủ công về tài khoản khách đã thanh toán"]]; +const shortId = (id) => id.replace(/^SS-\d{8}-/, "SS-"); +const amountLabel = (r) => (r.fee ? `${money(r.amount)} (100% tiền thuê + 90% cọc)` : money(r.amount)); + +function RefundDialog({ refund, onClose, onDone }) { + const { run } = useOps(); + const [method, setMethod] = useState("BANK_TRANSFER"); + const [ref, setRef] = useState(""); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + const submit = async () => { + if (method === "BANK_TRANSFER" && !ref.trim()) return setError("Nhập mã giao dịch hoàn tiền."); + setBusy(true); + setError(""); + const res = await run("CONFIRM_RESERVATION_REFUND", { id: refund.id, method, transaction_ref: ref.trim() }); + setBusy(false); + if (!res.ok) return setError(res.error || "Chưa lưu được xác nhận. Kiểm tra trạng thái giao dịch trước khi thử lưu lại. Không chuyển khoản lần nữa."); + onDone({ id: refund.id, amount: refund.amount, ref: ref.trim() }); + }; + return ( + +

      {refund.customer} · Huỷ đơn ngày {dateLabel(refund.cancelled_at)}

      +
      +
      +
      Đã thanh toán qua PayOS
      {money(refund.paid)}
      +
      Phí huỷ (10% tiền cọc)
      {refund.fee ? `− ${money(refund.fee)}` : money(0)}
      +
      Số tiền hoàn
      {money(refund.amount)}
      +
      +
      +
      + Cách hoàn tiền + {METHODS.map(([value, label]) => ( + + ))} +
      + {method === "BANK_TRANSFER" && ( + + { setRef(e.target.value); setError(""); }} /> + + )} + {error && ref.trim() && {error}} +

      Sau khi xác nhận, đơn chuyển sang “Đã hoàn tiền” và khách nhận thông báo. Không thể hoàn tác.

      +
      + + +
      +
      + ); +} + +export function CancellationRefundPage() { + const { ops } = useOps(); + const refunds = ops.refunds || []; + const pending = refunds.filter((r) => r.status === "PENDING"); + const [open, setOpen] = useState(null); + const [showBreakdown, setShowBreakdown] = useState(false); + const [confirmed, setConfirmed] = useState([]); + const next = pending[0]; + const last = confirmed[confirmed.length - 1]; + return ( +
      + +
      + + + + {refunds.length === 0 ? ( + + ) : refunds.map((r) => ( + + + + + + + ))} + +
      Đơn / kháchNgày huỷSố tiền hoànTrạng thái
      Chưa có đơn huỷ cần hoàn tiền.
      {r.id} · {r.customer}{dateTimeLabel(r.cancelled_at)}{amountLabel(r)}{r.status === "PENDING" ? Chờ hoàn : Đã hoàn{r.paid_at ? ` · ${dateLabel(r.paid_at)}` : ""}}
      +
      + {next ? ( +
      +

      {next.id} · Hoàn tiền huỷ đơn

      +

      + {last + ? `Đã xác nhận hoàn ${money(last.amount)} cho đơn ${last.id}${last.ref ? ` (mã giao dịch ${last.ref})` : ""}. Tiếp theo: chuyển ${money(next.amount)} cho đơn ${next.id}.` + : `Chuyển ${money(next.amount)} về tài khoản khách đã dùng để thanh toán qua PayOS, sau đó bấm xác nhận và nhập mã giao dịch hoàn.`} +

      + + + {showBreakdown && ( +
      +
      Đã thanh toán (tiền thuê + cọc)
      {money(next.paid)}
      +
      Tiền thuê
      {money(next.rent)}
      +
      Tiền cọc
      {money(next.deposit)}
      +
      Phí huỷ (10% tiền cọc)
      {money(next.fee)}
      +
      Hoàn cho khách
      {money(next.amount)}
      +
      + )} +
      + ) : ( +
      +

      Các khoản hoàn đã được ghi nhận

      +

      + {confirmed.length + ? `Đã ghi nhận hoàn ${confirmed.map((c) => `${money(c.amount)} cho ${shortId(c.id)}`).join(" và ")}. Không còn yêu cầu chờ hoàn trong danh sách này.` + : "Không còn yêu cầu chờ hoàn trong danh sách này."} +

      + Về hợp đồng & quá hạn +
      + )} + {open && ( + setOpen(null)} + onDone={(done) => { + setOpen(null); + setConfirmed((list) => [...list, done]); + setShowBreakdown(false); + }} + /> + )} +
      + ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/renewals/RenewalApprovalPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/renewals/RenewalApprovalPage.jsx index 20d6e67..629f420 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/renewals/RenewalApprovalPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/renewals/RenewalApprovalPage.jsx @@ -12,10 +12,16 @@ export function RenewalApprovalPage() { const [reason, setReason] = useState(""); const [err, setErr] = useState(""); const approve = (r) => run("DECIDE_RENEWAL", { id: r.id, approve: true }, `Đã duyệt gia hạn ${r.unit}`); + // M03b: nhập lý do trong hộp thoại riêng → M03d kết quả do provider hiện const doReject = async () => { - const out = await run("DECIDE_RENEWAL", { id: reject.id, approve: false, reason }, `Đã từ chối gia hạn ${reject.unit}`); - if (!out.ok) return setErr(out.error); + if (!reason.trim()) return setErr("Nhập lý do từ chối."); + const target = reject; setReject(null); + const out = await run("DECIDE_RENEWAL", { id: target.id, approve: false, reason: reason.trim() }, `Đã từ chối gia hạn ${target.unit}`); + if (!out.ok) { + if (!out.cancelled) setReject(target); + return setErr(out.shown ? "" : out.error); + } setReason(""); }; return ( @@ -54,14 +60,19 @@ export function RenewalApprovalPage() { )} Về tổng quan {reject && ( - setReject(null)}> -

      Lý do sẽ được gửi đến {reject.customer}.

      - -