Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,10 @@ theo loại kho + diện tích (D17: cỡ M 15 m², cỡ L 30 m²) và từ ch

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ợ.
- `POST /api/ops/returns/{id}/inspection` (`OpsReturnInspectionRequest`): nhận thêm `damageFee`, `cleaningFee`, `cleaningRequired`, `feeReason`; lưu vào `ReturnInspection.DamageFee` / `CleaningFee` / `CleaningRequired` (cột đã có, `ConfirmRefundAsync` đang đọc) và ghi khoản `DAMAGE_FEE` / `CLEANING_FEE` trạng thái `PENDING` để M07 trừ cọc theo D27, phần thiếu thành công nợ.
- Cập nhật 25/10: S04 **bỏ ô nhập phí quá hạn** vì `ConfirmRefundAsync` đã tự tính phí quá hạn theo số ngày trễ (chính sách `OVERDUE`); nhập tay sẽ tính trùng. Giao diện không gửi `overdueFee` nữa.
- `OpsReturnReportDto` trong `GET /api/ops/board` trả thêm `damageFee`, `cleaningFee`, `cleaningRequired`, `feeReason`. Khi chưa có, S04 hiện "Máy chủ chưa lưu phí phát sinh…" và M07 không có dòng phí.
- `POST /api/ops/contracts/{id}/refund` (M07a): giao diện gửi body `{ note }` (ghi chú khi xác nhận trả kho); endpoint hiện bỏ qua body — cần lưu vào activity log. Phản hồi `{ refund }` đang được dùng để hiện số hoàn cọc thực tế.
- 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`.
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ const at = (iso, time) => `${iso}T${time}:00`;
export function createSeedData(t = today()) {
const b015End = addDays(t, 5);
const b015Start = addMonths(b015End, -3);
const a102End = addMonths(t, 3);
// Đơn/hợp đồng A-102 bắt đầu từ ngày mai: đơn đã thanh toán chỉ huỷ được trước ngày bắt đầu thuê (C14a)
const a102Start = addDays(t, 1);
const a102End = addMonths(a102Start, 3);
return {
user: {
user_id: 101,
Expand All @@ -61,7 +63,7 @@ export function createSeedData(t = today()) {
offer_key: "normal-M",
size_label: "Cỡ M · 15 m²",
months: 3,
start_date: t,
start_date: a102Start,
end_date: a102End,
monthly_rate: 1150000,
deposit: 1150000,
Expand Down Expand Up @@ -99,7 +101,7 @@ export function createSeedData(t = today()) {
size_m2: 15,
location: "Tầng 1 · Dãy A",
months: 3,
start_date: t,
start_date: a102Start,
end_date: a102End,
monthly_rate: 1150000,
deposit: 1150000,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
timeoutLabel,
} from "../../shared/utils/format.js";
import { TICKET_TOPICS, ticketTitle } from "../../shared/utils/status.js";
import { CANCEL_DEPOSIT_FEE_RATE, CANCEL_POLICY_NAME } from "../../shared/utils/policy.js";

export class DomainError extends Error {
constructor(message, code = "INVALID") {
Expand Down Expand Up @@ -70,13 +71,11 @@ const hasPending = (state, contract_id) => ({
});

// C14a · Ước tính hoàn tiền khi huỷ đơn đã thanh toán trước ngày bắt đầu thuê (chế độ trình duyệt).
// Chính sách D27: phí huỷ cố định 10% tiền cọc; hoàn 100% tiền thuê + 90% tiền cọc.
// Chế độ API lấy từ GET /api/reservations/{id}/cancel-preview.
export const CANCEL_DEPOSIT_FEE_RATE = 0.1;
// Chính sách D27 (shared/utils/policy.js). Chế độ API lấy từ GET /api/reservations/{id}/cancel-preview.
export function cancelPreviewOf(r) {
const paid = r.initial_total || 0;
const fee = Math.round((r.deposit || 0) * CANCEL_DEPOSIT_FEE_RATE);
return { paid, fee, refund: Math.max(0, paid - fee), policy: "Huỷ trước ngày bắt đầu: phí 10% tiền cọc" };
return { paid, fee, refund: Math.max(0, paid - fee), policy: CANCEL_POLICY_NAME };
}

const handlers = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { facilityOf } from "../../../app/state/appSelectors.js";
import { useApp } from "../../../app/state/AppProvider.jsx";

// C11fc · Chọn trả phí phát sinh tại quầy → C11fcp. Không làm giảm công nợ cho tới khi nhân viên xác nhận đã thu (S09f).
function CounterDialog({ rows, contract, facilityName, onClose }) {
// Backend chưa có API lưu lựa chọn này (BACKEND-TODO S09f) → chỉ ghi trên thiết bị, thông báo nói rõ điều đó.
function CounterDialog({ rows, contract, facilityName, savedOnServer, onClose }) {
const { dispatch } = useApp();
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
Expand All @@ -25,7 +26,10 @@ function CounterDialog({ rows, contract, facilityName, onClose }) {
return (
<Modal title="Đã chọn thanh toán tại quầy" size="confirm" onClose={onClose}>
<span className="modal__state modal__state--success" aria-hidden="true" />
<p className="modal__text">{contractLabel} còn phải thu {money(total)}. Nhân viên sẽ cập nhật khi nhận đủ tiền; chọn phương thức chưa làm giảm công nợ.</p>
<p className="modal__text">
{contractLabel} còn phải thu {money(total)}. Đến quầy {facilityName || "cơ sở"} để thanh toán; nhân viên cập nhật khi nhận đủ tiền. Chọn phương thức chưa làm giảm công nợ.
{!savedOnServer && " Lựa chọn này chỉ lưu trên thiết bị của bạn; bạn vẫn có thể thanh toán qua mã QR."}
</p>
<Button block onClick={onClose}>Về khoản phải thanh toán</Button>
</Modal>
);
Expand All @@ -50,13 +54,17 @@ function CounterDialog({ rows, contract, facilityName, onClose }) {
// C11 — Thanh toán & lịch hẹn. Khoản gia hạn đã duyệt có nút "Thanh toán" mở QR PayOS (C11q), trả xong → C11b.
// C11f / C11fb / C11fq: phí phát sinh trả kho trả qua PayOS hoặc tại quầy (C11fc → C11fcp).
export default function PaymentListPage() {
const { data } = useApp();
const { data, mode } = useApp();
const [paying, setPaying] = useState(null);
const [paid, setPaid] = useState(null);
const [counter, setCounter] = useState(false);
const [counter, setCounter] = useState(null); // contract_id đang chọn trả phí tại quầy
const fees = data.ledger.filter((l) => l.fee && ["UNPAID", "AT_COUNTER"].includes(l.status));
const appointments = [...data.appointments].sort((a, b) => a.date.localeCompare(b.date));
const payable = data.ledger.filter((l) => l.payable && l.status === "UNPAID");
// Phí đã chọn "tại quầy" vẫn trả được qua QR nếu khách đổi ý (khoản chưa thu trên hệ thống)
const canPay = (l) => l.payable && (l.status === "UNPAID" || (l.fee && l.status === "AT_COUNTER"));
const payable = data.ledger.filter(canPay);
// Phí chưa thu theo từng hợp đồng: mỗi hợp đồng một nút "tại quầy", không gộp phí của nhiều hợp đồng
const unpaidFeeContracts = [...new Set(fees.filter((l) => l.status === "UNPAID").map((l) => l.contract_id))];
const contractOfRow = (l) => data.contracts.find((c) => c.contract_id === l.contract_id);
const subtitle = (l) => {
const c = contractOfRow(l);
Expand Down Expand Up @@ -109,7 +117,7 @@ export default function PaymentListPage() {
<td className={l.fee && l.status === "UNPAID" ? "tone-amber" : undefined}>{(LEDGER_STATUS[l.status] || [l.status])[0]}</td>
{payable.length > 0 && (
<td className="cell-action">
{l.payable && l.status === "UNPAID" && <Button className="btn--sm" onClick={() => setPaying(l)}>Thanh toán</Button>}
{canPay(l) && <Button className="btn--sm" onClick={() => setPaying(l)}>Thanh toán</Button>}
</td>
)}
</tr>
Expand All @@ -131,7 +139,11 @@ export default function PaymentListPage() {
) : fees.length > 0 ? (
<>
<p className="hint">{[...new Set(fees.map((l) => l.detail).filter(Boolean))].join(" ")} Thanh toán qua PayOS hoặc tại quầy; khoản còn nợ vẫn được theo dõi sau khi trả kho.</p>
{fees.some((l) => l.status === "UNPAID") && <Button variant="outline" className="btn--fit" onClick={() => setCounter(true)}>Thanh toán phí tại quầy</Button>}
{unpaidFeeContracts.map((id) => (
<Button key={id} variant="outline" className="btn--fit" onClick={() => setCounter(id)}>
Thanh toán phí tại quầy{unpaidFeeContracts.length > 1 ? ` · ${String(id).replace(/^HĐ-\d{4}-/, "HĐ-")}` : ""}
</Button>
))}
</>
) : (
payable.length > 0 && (
Expand All @@ -151,14 +163,19 @@ export default function PaymentListPage() {
onClose={() => setPaying(null)}
/>
)}
{counter && (
<CounterDialog
rows={fees.filter((l) => l.status === "UNPAID")}
contract={contractOfRow(fees[0]) ? { ...contractOfRow(fees[0]), customer: data.user?.full_name } : { contract_id: fees[0]?.contract_id, customer: data.user?.full_name }}
facilityName={(() => { const c = contractOfRow(fees[0]); return c ? facilityOf(data, c.facility_id, c.facility_name)?.name : null; })()}
onClose={() => setCounter(false)}
/>
)}
{counter && (() => {
const rows = fees.filter((l) => l.status === "UNPAID" && l.contract_id === counter);
const c = contractOfRow({ contract_id: counter });
return (
<CounterDialog
rows={rows}
contract={{ ...(c || { contract_id: counter }), customer: data.user?.full_name }}
facilityName={c ? facilityOf(data, c.facility_id, c.facility_name)?.name : null}
savedOnServer={mode !== "api"}
onClose={() => setCounter(null)}
/>
);
})()}
</main>
);
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
import React, { useEffect, useState } from "react";
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 { dateLabel, money, shortCode, today } from "../../../shared/utils/format.js";
import { CANCEL_FEE_LABEL, CANCEL_POLICY_HINT, CANCEL_REFUND_NOTE } from "../../../shared/utils/policy.js";
import { shortName } from "../../../shared/hooks/useBrowserEvents.js";
import { RESERVATION_STATUS } from "../../../shared/utils/status.js";
import { facilityOf, sortedReservations } from "../../../app/state/appSelectors.js";
import { useApp } from "../../../app/state/AppProvider.jsx";

// Đơn khách tự huỷ được: chờ thanh toán, hoặc đã thanh toán nhưng chưa nhận kho (cùng quy tắc backend:
// ReservationService.CancelReservationAsync nhận PENDING_PAYMENT / CONFIRMED)
export function canCancel(data, r) {
if (r.api_status) return ["PENDING_PAYMENT", "CONFIRMED", "PAID"].includes(r.api_status) && r.status !== "CANCELLED";
// Đơn khách tự huỷ được — cùng quy tắc backend ReservationService.CancelReservationAsync:
// PENDING_PAYMENT / PENDING_AT_FACILITY (chưa thu tiền) huỷ lúc nào cũng được;
// CONFIRMED (đã thanh toán) chỉ huỷ trước ngày bắt đầu thuê, từ ngày bắt đầu dùng quy trình trả kho.
const CANCELLABLE_API = ["PENDING_PAYMENT", "PENDING_AT_FACILITY", "CONFIRMED"];
const beforeStart = (r) => !r.start_date || today() < r.start_date;
export function canCancel(data, r, now = today()) {
if (r.status === "CANCELLED") return false;
const started = r.start_date && now >= r.start_date;
if (r.api_status) return CANCELLABLE_API.includes(r.api_status) && !(r.api_status === "CONFIRMED" && started);
if (r.status === "PENDING_PAYMENT") return true;
if (r.status !== "CONFIRMED") return false;
if (r.status !== "CONFIRMED" || started) return false;
return !data.contracts.some((c) => c.reservation_id === r.reservation_id && c.handed_over);
}

Expand All @@ -24,7 +30,6 @@ function statusCell(r) {
if (isRefunded(r)) return <span className="tone-green">Đã huỷ · Đã hoàn tiền</span>;
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 }) {
Expand All @@ -33,12 +38,24 @@ function CancelDialog({ r, onDone, onClose }) {
const [reason, setReason] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
// Backend từ chối xem trước (vd. đã đến ngày bắt đầu thuê) → hiện lý do, không cho bấm huỷ
const [blocked, setBlocked] = useState("");
const paid = r.status === "CONFIRMED";
const f = facilityOf(data, r.facility_id, r.facility_name);

useEffect(() => {
let alive = true;
if (paid) services?.cancelPreview(r).then((res) => alive && setPreview(res.ok ? res.preview : false));
if (paid && !beforeStart(r)) setBlocked("Đã đến ngày bắt đầu thuê nên không huỷ đặt chỗ được. Vui lòng đăng ký trả kho để được xử lý hoàn cọc theo chính sách.");
else if (paid)
services?.cancelPreview(r).then((res) => {
if (!alive) return;
if (res.ok) setPreview(res.preview);
else if (res.unsupported) setPreview(false);
else {
setPreview(false);
setBlocked(res.error || "Không tính được số tiền hoàn. Vui lòng thử lại sau.");
}
});
return () => {
alive = false;
};
Expand All @@ -63,7 +80,7 @@ function CancelDialog({ r, onDone, onClose }) {
<dl className="pay-rows">
<div><dt>Đã thanh toán (tiền thuê {r.months} tháng + cọc)</dt><dd>{money(preview?.paid ?? r.initial_total)}</dd></div>
<div>
<dt>Phí huỷ (10% tiền cọc)</dt>
<dt>{CANCEL_FEE_LABEL}</dt>
<dd className={preview ? "tone-red" : undefined}>{preview ? `− ${money(preview.fee)}` : preview === false ? "Theo chính sách hiện hành" : "Đang tính…"}</dd>
</div>
<div className="pay-rows__total">
Expand All @@ -78,11 +95,12 @@ function CancelDialog({ r, onDone, onClose }) {
<Field label="Lý do huỷ (không bắt buộc)">
<input maxLength={255} value={reason} placeholder="Ví dụ: Đổi kế hoạch chuyển nhà" onChange={(e) => setReason(e.target.value)} />
</Field>
{paid && <p className="hint">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.</p>}
{paid && !blocked && <p className="hint">{CANCEL_REFUND_NOTE}</p>}
{blocked && <Notice tone="error">{blocked}</Notice>}
{error && <Notice tone="error">{error}</Notice>}
<div className="modal__actions modal__actions--end">
<Button variant="outline" onClick={onClose}>Giữ đơn</Button>
<Button variant="danger" onClick={submit} disabled={busy}>{busy ? "Đang huỷ…" : "Huỷ đơn"}</Button>
<Button variant="danger" onClick={submit} disabled={busy || Boolean(blocked) || (paid && preview === null)}>{busy ? "Đang huỷ…" : "Huỷ đơn"}</Button>
</div>
</Modal>
);
Expand Down Expand Up @@ -125,7 +143,7 @@ export default function ReservationListPage() {
<td className="table__actions">
<div className="row-actions">
<LinkButton to={`reservations/${r.reservation_id}`} className="btn--sm">Xem đơn</LinkButton>
{!done && canCancel(data, r) && (
{canCancel(data, r) && (
<Button variant="outline" className="btn--sm btn--danger-outline" onClick={() => setCancelling(r)} aria-label={`Huỷ đơn ${shortCode(r.reservation_id)}`}>Huỷ đơn</Button>
)}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ export const OPS_ACTIONS = {
ALLOCATE: ({ id, unit }) => ["POST", `/api/ops/allocations/${enc(id)}`, { unitCode: unit }],
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`],
// M07a · Ghi chú gửi kèm; backend hiện chưa đọc body (BACKEND-TODO: lưu ghi chú xác nhận trả kho)
CONFIRM_REFUND: ({ id, note }) => ["POST", `/api/ops/contracts/${enc(id)}/refund`, { note: String(note || "").trim() || null }],
// 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 }],
// M02b / M02c · CreateStorageUnitRequest / UpdateStorageUnitRequest (OpsDtos.cs). Backend chưa nhận loại kho + cỡ theo tên:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ function readOps() {

const UNSUPPORTED = {
UPDATE_UNIT_STATUS: "Máy chủ chưa hỗ trợ đổi trạng thái ô kho. Cập nhật backend có PUT /api/staff/units/{mã}/status rồi thử lại.",
CONFIRM_FEE_COLLECTION: "Máy chủ chưa hỗ trợ ghi nhận thu phí tại quầy (POST /api/ops/fees/{mã}/confirm). Chưa lưu khoản thu này; không thu thêm tiền của khách.",
};

// Nhật ký / thông báo trong ca chỉ giữ ở trình duyệt (backend chưa có API thông báo)
Expand Down Expand Up @@ -103,13 +104,14 @@ export function OpsProvider({ children, notify, mode = "local", onApiError, role
async (type, payload, message) => {
if (source === "api" && type !== "MARK_READ") {
try {
await callAction(type, payload);
const res = await callAction(type, payload);
await reload();
if (message) {
commit(appendLog(ref.current, message, null));
notify?.(message);
}
return { ok: true };
// Giữ số liệu backend trả về (vd. số tiền hoàn cọc thực tế) để màn kết quả hiển thị đúng
return { ok: true, ...(res && typeof res === "object" && !Array.isArray(res) ? res : {}) };
} catch (e) {
onApiError?.(e);
// Route chưa có trên backend: ASP.NET trả 404/405 không kèm nội dung → báo rõ thay vì "Không tìm thấy dữ liệu."
Expand Down Expand Up @@ -169,7 +171,8 @@ export function OpsProvider({ children, notify, mode = "local", onApiError, role
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 });
const success = typeof spec.success === "function" ? spec.success(result) : spec.success;
if (success) await showOutcome({ kind: "success", ...success });
return result;
} finally {
activeAction.current = false;
Expand Down
Loading