diff --git a/DECISIONS.md b/DECISIONS.md index 307b6ae..a43672b 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -197,6 +197,12 @@ Theo yêu cầu nhóm, dùng src/app, src/features//, src/shared, - 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. ## D28 — Kiểm thử giao diện C12/C12b/C13 bằng Playwright diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index 6a6bd55..890c0af 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -350,3 +350,33 @@ 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 +``` + +## M02b / M02c — Thêm và sửa ô kho (F40) + +`POST /api/manager/units` và `PUT /api/manager/units/{id}` đã có nhưng `CreateUnitAsync` luôn lấy loại kho đầu tiên và bỏ qua loại/cỡ. +Giao diện gửi `{ unitNumber, locationDescription, unitTypeCode: "normal" | "climate", area: 15 | 30 }`; backend cần chọn `UnitType` +theo loại kho + diện tích (D17: cỡ M 15 m², cỡ L 30 m²) và từ chối đổi loại/cỡ khi ô đang có khách thuê. + +## Phí phát sinh khi trả kho và công nợ (F40: S04, S09f, C11f) + +Giao diện đã làm theo Figma; backend cần bổ sung: + +- `POST /api/ops/returns/{id}/inspection` (`OpsReturnInspectionRequest`): nhận thêm `damageFee`, `cleaningFee`, `overdueFee`, `feeReason`; ghi các khoản `DAMAGE_FEE` / `CLEANING_FEE` / `OVERDUE_FEE` trạng thái `PENDING` để M07 trừ cọc theo D27 và phần thiếu thành công nợ. +- Khách trả phí qua PayOS: `POST /api/payments/{paymentId}/payos` cho khoản phí `PENDING` (cùng endpoint giao diện đang dùng cho gia hạn; hiện backend chưa có nên popup báo "tạm gián đoạn"). +- Khách chọn trả tại quầy (C11fc): API ghi nhận lựa chọn, ví dụ `POST /api/payments/{paymentId}/at-facility`. Giao diện tạm lưu trong trình duyệt (`overlay.feesAtCounter`). +- Nhân viên thu tại quầy (S09f): `GET /api/ops/board` trả `feeCollections[]` `{ id, contract, customer, unit, items: [[nhãn, số tiền]], amount, due, status, requestedAt }` và `POST /api/ops/fees/{id}/confirm` chuyển các khoản sang `PAID`. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md index bc1c1b2..ab6bf44 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md @@ -59,6 +59,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` | @@ -79,6 +80,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/app/data/appSeed.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js index 8d8593b..bbd581b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js @@ -169,6 +169,19 @@ export function createSeedData(t = today()) { payable: true, period: { from: b015End, to: addMonths(b015End, 3), months: 3 }, }, + // C11f · Phí phát sinh theo biên bản trả kho, khách trả qua PayOS hoặc tại quầy (S09f) + { + ref: "SS-0086-FEE", + kind: "FEE", + label: "Phí phát sinh trả kho B-015", + contract_id: "HĐ-2026-0086", + reservation_id: "SS-20260615-0086", + amount: 450000, + status: "UNPAID", + payable: true, + fee: true, + detail: "Theo biên bản trả kho B-015: phí vệ sinh 150.000 đ, phí hư hỏng ổ khóa 300.000 đ.", + }, ], appointments: [ { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx index 012507e..e51d131 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx @@ -662,6 +662,13 @@ function ApiProvider({ children }) { const out = runLocal(type, p); return out.error ? fail(out.error.message, out.error.code) : { ok: true, ...out.result }; } + // C11fc: backend chưa có API chọn trả phí tại quầy → ghi trong trình duyệt; nhân viên thu ở S09f + case "CHOOSE_FEE_AT_COUNTER": { + const rows = d.ledger.filter((l) => p.refs.includes(l.ref) && l.fee && ["UNPAID", "AT_COUNTER"].includes(l.status)); + if (!rows.length) return fail("Không còn khoản phí cần thanh toán.", "NOT_FOUND"); + updateOverlay((o) => ({ ...o, feesAtCounter: { ...(o.feesAtCounter || {}), ...Object.fromEntries(rows.map((l) => [l.api_id, Date.now()])) } })); + return { ok: true, refs: rows.map((l) => l.ref) }; + } default: return fail(`Thao tác không được hỗ trợ: ${type}`, "UNKNOWN"); } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js index 1121ad2..ba2bac8 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js @@ -186,6 +186,12 @@ const handlers = { // PayOS báo đã thanh toán (webhook ở backend; chế độ trình duyệt tự gọi để mô phỏng). // reservation_id → đơn đặt chỗ đã trả tiền thuê + cọc; ref → khoản gia hạn ở C11. + // C11fc → C11fcp: khách chọn trả phí phát sinh tại quầy; công nợ chỉ giảm khi nhân viên xác nhận đã thu (S09f) + CHOOSE_FEE_AT_COUNTER(state, { refs }) { + const rows = state.ledger.filter((l) => refs.includes(l.ref) && l.fee && ["UNPAID", "AT_COUNTER"].includes(l.status)); + if (!rows.length) fail("Không còn khoản phí cần thanh toán.", "NOT_FOUND"); + return { state: { ...state, ledger: state.ledger.map((l) => (rows.includes(l) ? { ...l, status: "AT_COUNTER" } : l)) }, result: { refs: rows.map((l) => l.ref) } }; + }, PAYOS_PAID(state, p, ctx) { if (p.ref) { const l = state.ledger.find((x) => x.ref === p.ref); @@ -197,6 +203,10 @@ const handlers = { ledger: state.ledger.map((x) => (x.ref === l.ref ? { ...x, status: "RECONCILED", payable: false } : x)), contracts: state.contracts.map((x) => (c && x.contract_id === c.contract_id && l.period?.to ? { ...x, end_date: l.period.to, status: "ACTIVE" } : x)), }; + if (l.fee) { + next = notify(next, "Đã thanh toán phí phát sinh", `${l.label} · ${l.amount.toLocaleString("vi-VN")} đ.`, "payments", ctx.now); + return { state: log(next, `Đã thanh toán ${l.label.toLowerCase()} qua QR`, "green", ctx.now), result: { ref: l.ref } }; + } next = notify(next, "Đã thanh toán gia hạn", `Kho ${l.unit_number || c?.unit_number || ""} · gia hạn đến ${l.period?.to ? dateLabel(l.period.to) : "kỳ mới"}.`, "payments", ctx.now); next = log(next, `Đã thanh toán gia hạn ${l.unit_number || ""} qua QR`, "green", ctx.now); return { state: next, result: { ref: l.ref } }; 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/facilities/FacilityManagementPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/FacilityManagementPage.jsx index ddafc2f..cc7a6f8 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/FacilityManagementPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/FacilityManagementPage.jsx @@ -6,12 +6,14 @@ import { go, href, qs } from "../../../app/router.js"; import { useApp } from "../../../app/state/AppProvider.jsx"; import { FACILITY_STATUS, areaOf, rateLabel, shortFacility } from "../utils/businessFormat.js"; import { LoadState } from "../components/BusinessComponents.jsx"; +import { useChangeFlow } from "../../../shared/components/ChangeFlowDialog.jsx"; import { coordinateLabel, facilityToForm, formToRequest, splitCoordinates } from "./facilityForm.js"; -// B05a · Sửa thông tin cơ sở (tên, địa chỉ, điện thoại, giờ ra vào, toạ độ ghim bản đồ) -function EditFacilityDialog({ facility, onClose, onSaved }) { - const { notify } = useApp(); - const [form, setForm] = useState(() => facilityToForm(facility)); +// B05a · Sửa thông tin cơ sở / B05b · Thêm cơ sở (tên, địa chỉ, điện thoại, giờ ra vào, toạ độ ghim bản đồ) +const EMPTY_FACILITY = { name: "", address: "", contactPhone: "", openingTime: "06:00", closingTime: "22:00", latitude: null, longitude: null }; +function EditFacilityDialog({ facility, onClose, onSaved, runChange }) { + const creating = !facility; + const [form, setForm] = useState(() => facilityToForm(facility || EMPTY_FACILITY)); const [errors, setErrors] = useState({}); const [busy, setBusy] = useState(false); const set = (k) => (e) => { @@ -30,30 +32,35 @@ function EditFacilityDialog({ facility, onClose, onSaved }) { e.preventDefault(); const { errors: errs, body } = formToRequest(form); if (errs) return setErrors(errs); + // Figma kết quả B05: "Đã thêm cơ sở …" / "Đã lưu thông tin cơ sở" setBusy(true); - try { - const res = await businessApi.updateFacility(facility.facilityId, body); - const warnings = res?.warnings || []; - notify(warnings.length ? `Đã lưu thông tin cơ sở. ${warnings.join(" ")}` : "Đã lưu thông tin cơ sở."); - onSaved(); - } catch (err) { - setErrors({ form: err.message }); - } finally { - setBusy(false); - } + let warnings = []; + const out = await runChange({ + action: creating ? "Thêm cơ sở" : "Lưu thông tin cơ sở", scope: body.name, confirm: false, successAction: "Đã hiểu", + successTitle: creating ? `Đã thêm cơ sở ${body.name}` : "Đã lưu thông tin cơ sở", + successText: creating ? "Cơ sở chưa có bảng giá, ô kho và nhân sự nên khách chưa đặt được." : "Bản đồ Tìm kho dùng vị trí mới ngay.", + perform: async () => { + const res = creating ? await businessApi.createFacility(body) : await businessApi.updateFacility(facility.facilityId, body); + warnings = res?.warnings || []; + return res; + }, + }); + setBusy(false); + if (out.ok) onSaved(warnings); + else if (out.error) setErrors({ form: out.error.message }); }; return ( - +
    -

    {facility.name}

    +

    {creating ? "Cơ sở mới cần có bảng giá, ô kho và nhân sự trước khi khách đặt được." : facility.name}

    - + - + - +
    @@ -73,14 +80,69 @@ function EditFacilityDialog({ facility, onClose, onSaved }) { {errors.form && {errors.form}}
    - +
    ); } -// B05: select a facility and open its business report; no unrelated CRUD controls. +// B05c · Đổi trạng thái cơ sở (Figma 634:8894): Tạm đóng / Ngừng hoạt động / Đang hoạt động, lý do bắt buộc +const STATUS_HELP = { + ACTIVE: "Mở lại nhận đặt chỗ mới tại cơ sở.", + TEMPORARILY_CLOSED: "Ngừng nhận đặt chỗ mới; khách đang thuê vẫn ra vào bình thường.", + INACTIVE: "Chỉ chọn được khi không còn hợp đồng hay đơn đặt chỗ đang xử lý.", +}; +const STATUS_RESULT = { + ACTIVE: (name) => `Khách đặt chỗ mới được ở ${name}.`, + TEMPORARILY_CLOSED: (name) => `Khách không đặt chỗ mới được ở ${name}.`, + INACTIVE: (name) => `${name} ngừng hoạt động; cơ sở không bị xoá và mở lại được bất cứ lúc nào.`, +}; +function FacilityStatusDialog({ facility, onClose, onSaved, runChange }) { + const options = Object.keys(FACILITY_STATUS).filter((k) => k !== facility.status); + const [status, setStatus] = useState(options[0]); + const [reason, setReason] = useState(""); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + const submit = async () => { + if (!reason.trim()) return setError("Nhập lý do đổi trạng thái."); + setBusy(true); + const label = FACILITY_STATUS[status][0]; + const out = await runChange({ + action: "Đổi trạng thái cơ sở", scope: facility.name, confirm: false, successAction: "Đã hiểu", + successTitle: `Đã chuyển cơ sở sang ${label}`, successText: STATUS_RESULT[status](facility.name), + perform: () => businessApi.setFacilityStatus(facility.facilityId, status, reason.trim()), + }); + setBusy(false); + if (out.ok) onSaved(); + else if (out.error) setError(out.error.message); + }; + return ( + +

    {facility.name} · Hiện tại: {FACILITY_STATUS[facility.status]?.[0] || facility.status}

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

    Cơ sở không bị xoá. Mở lại bất cứ lúc nào bằng cách chọn Đang hoạt động.

    + +