From 0dc8519769ff8d86dd8a23c1d284cfd914ae70af Mon Sep 17 00:00:00 2001
From: TienPhanSE <246292360+TienPhanSE@users.noreply.github.com>
Date: Sat, 14 Nov 2026 22:22:01 +0700
Subject: [PATCH] =?UTF-8?q?fix(#61):=20s=E1=BB=ADa=20l=E1=BB=97i=20m?=
=?UTF-8?q?=E1=BB=A5c=2061?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../SafeSpace-Customer-UI/BACKEND-TODO.md | 1 +
.../customer/access/DoorCloseButton.jsx | 5 +-
.../customer/contracts/ContractPaperPage.jsx | 13 ++-
.../contracts/RentedUnitDetailPage.jsx | 42 ++++++++--
.../customer/contracts/RentedUnitListPage.jsx | 2 -
.../customer/contracts/contractPdf.js | 27 ++++++-
.../reservations/ReservationDetailPage.jsx | 2 +
.../tests/contract-paper.test.js | 9 ++-
.../tests/render.test.mjs | 3 +-
StorageProject.Api/Program.cs | 3 +
.../Workers/PayOSReconcileWorker.cs | 38 +++++++++
.../Interfaces/IPayOSService.cs | 6 ++
.../Services/PayOSGateway.cs | 18 +++++
.../Services/PayOSService.cs | 80 ++++++++++++++++++-
.../CheckoutTests.Reconcile.cs | 44 ++++++++++
StorageProject.Tests/CheckoutTests.cs | 3 +
progress.md | 8 ++
17 files changed, 286 insertions(+), 18 deletions(-)
create mode 100644 StorageProject.Api/Workers/PayOSReconcileWorker.cs
create mode 100644 StorageProject.Tests/CheckoutTests.Reconcile.cs
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
index e6cc272..549dcb1 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
@@ -155,6 +155,7 @@ tên route + tên trường JSON là giao diện chạy ngay, không phải sử
| P2 | `POST /api/reservations/{id}/pay-at-facility` → `ReservationDto` | Đạt | Giao diện gọi `confirm-transfer` (đã có) → đơn vẫn vào S09 chờ thu tiền |
| P3 | `POST /api/payments/{id}/payos` → `PayosCheckoutDto`; `GET /api/payments/{id}` (đã có) để hỏi trạng thái | Đạt | Popup C11q báo "đang tạm gián đoạn, thanh toán tại quầy" |
| P4 | Webhook PayOS — **đã có** `POST /api/payments/payos-webhook` (webhook đổi đơn sang `CONFIRMED`) | Đạt | — (giao diện hỏi trạng thái 3 giây/lần) |
+| P4b | **14/11 · mục 61:** đối soát khi webhook không về (backend chạy localhost): `GET /api/v1/reservations/{id}/status` hỏi thẳng PayOS (≤ 1 lần / 5 giây / đơn) và ghi nhận như webhook; `PayOSReconcileWorker` quét đơn đặt chỗ + khoản gia hạn PayOS đang chờ 10 giây/lần (`Worker:EnablePayOSReconcile`) | Thắng | — |
| Q1 | `GET /api/contracts/{id}/access-qr` → `AccessQrDto` | Tiến | Popup C07q báo "Mã QR đang được cơ sở kích hoạt" |
| Q2 | `POST /api/access/scan` `{ code }` → `ScanResultDto` (cho phép không đăng nhập — máy quét ở cửa) | Tiến | Màn `#/door` báo "Máy quét chưa kết nối được hệ thống" |
| R1 | `GET /api/tickets/{id}` trả thêm `responses[]` | Ngọc Mai | C12 không hiện dòng phản hồi |
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorCloseButton.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorCloseButton.jsx
index 7003fd9..542fe6f 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorCloseButton.jsx
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorCloseButton.jsx
@@ -2,6 +2,7 @@
* Lượt 6 · Figma C06-cửa (D51, 12/11): nút "Đóng cửa" trong Kho của tôi.
* Cửa không tự khoá; khách đóng bằng một lần xác nhận (không nhập lại QR/PIN).
* Kết quả: popup "Đã đóng cửa …" hoặc "Chưa đóng được cửa" (giữ khả năng thử lại).
+ * Mục 61 (14/11): chỉ hiện ở trang chi tiết kho; cửa đã đóng thì nút bị khoá (trang truyền `disabled`).
*/
import React, { useRef, useState } from "react";
import ConfirmDialog from "../../../shared/components/ConfirmDialog.jsx";
@@ -9,7 +10,7 @@ import { Button } from "../../../shared/components/UI.jsx";
import { useApp } from "../../../app/state/AppProvider.jsx";
import { dateTimeLabel } from "../../../shared/utils/format.js";
-export function DoorCloseButton({ c, disabled, variant = "outline" }) {
+export function DoorCloseButton({ c, disabled, variant = "outline", onClosed }) {
const { services } = useApp();
const [step, setStep] = useState(null); // confirm | done | failed
const [busy, setBusy] = useState(false), [result, setResult] = useState(null), guard = useRef(false);
@@ -18,7 +19,7 @@ export function DoorCloseButton({ c, disabled, variant = "outline" }) {
guard.current = true; setBusy(true);
try {
const out = await services.closeDoor(c);
- if (out.ok) { setResult(out.door); setStep("done"); }
+ if (out.ok) { setResult(out.door); setStep("done"); onClosed?.(out.door); }
else { setResult({ error: out.error }); setStep("failed"); }
} catch { setResult({ error: "Mất kết nối tới máy chủ." }); setStep("failed"); }
finally { guard.current = false; setBusy(false); }
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ContractPaperPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ContractPaperPage.jsx
index b4c0943..f1e5e92 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ContractPaperPage.jsx
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ContractPaperPage.jsx
@@ -12,7 +12,7 @@ import { api } from "../../../shared/api/customerApi.js";
import { contractOf, facilityOf } from "../../../app/state/appSelectors.js";
import { useApp } from "../../../app/state/AppProvider.jsx";
import { NotFound } from "./components/ContractNotFound.jsx";
-import { downloadContractPdf } from "./contractPdf.js";
+import { downloadContractPdf, printContract } from "./contractPdf.js";
import "../../../shared/styles/customer-detail.css";
import "./contract-paper.css";
@@ -53,8 +53,13 @@ export function ContractPaperPage({ id }) {
const fileCode = String(c.contract_id).replace(/Đ/g, "D").replace(/[^\w-]+/g, "-");
await downloadContractPdf(frame.current, { code: c.contract_id, fileName: `SafeSpace-${fileCode}.pdf` });
setPdf({ busy: false, error: "" });
- } catch {
- setPdf({ busy: false, error: "Chưa tạo được tệp PDF. Vui lòng thử lại." });
+ } catch (error) {
+ // Ghi lỗi gốc để biết nguyên nhân (mục 61), rồi mở hộp thoại In để khách vẫn lưu được PDF.
+ console.error("[Hợp đồng giấy] Tạo PDF thất bại:", error);
+ const printed = printContract(frame.current);
+ setPdf({ busy: false, error: printed
+ ? "Trình duyệt chưa tạo được tệp PDF trực tiếp nên đã mở hộp thoại In. Chọn \"Lưu dưới dạng PDF\" để tải hợp đồng."
+ : `Chưa tạo được tệp PDF (${error?.message || "lỗi không rõ"}). Vui lòng thử lại.` });
} finally {
fit();
}
@@ -84,7 +89,7 @@ export function ContractPaperPage({ id }) {
sandbox="allow-same-origin allow-modals" srcDoc={state.html} onLoad={fit} />
)}
- {issued && !offline &&
Bản này cũng đã được gửi kèm email xác nhận thanh toán. Bấm "Tải PDF" để lưu hợp đồng về máy.
}
+ {issued && !offline &&
Bấm "Tải PDF" để lưu hợp đồng về máy.
}
);
}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx
index 6281c5b..5770c0b 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx
@@ -6,10 +6,10 @@
* - Mã truy cập QR Code / PIN mở cửa kho (D22).
* - Nút chức năng: Gia hạn hợp đồng, Đăng ký trả kho, Báo cáo sự cố / Yêu cầu hỗ trợ.
*/
-import React, { useState } from "react";
+import React, { useCallback, useEffect, useState } from "react";
import { Button, DetailList, LinkButton, Notice, PageHeader, StatusTag, Tag } from "../../../shared/components/UI.jsx";
import { typeLabel } from "../../../shared/utils/catalog.js";
-import { dateLabel, daysBetween, money, rangeLabel, today } from "../../../shared/utils/format.js";
+import { dateLabel, dateTimeLabel, daysBetween, money, rangeLabel, today } from "../../../shared/utils/format.js";
import { CONTRACT_STATUS, LEDGER_STATUS } from "../../../shared/utils/status.js";
import { contractOf, contractStatus, facilityOf, pendingRenewal, pendingReturn } from "../../../app/state/appSelectors.js";
import { useApp } from "../../../app/state/AppProvider.jsx";
@@ -29,9 +29,10 @@ import "../../../shared/styles/customer-detail.css";
* @param {{ id: string|number }} props
*/
export function RentedUnitDetailPage({ id }) {
- const { data, retry } = useApp();
+ const { data, retry, services } = useApp();
const [qrOpen, setQrOpen] = useState(false);
const c = contractOf(data, id);
+ const door = useDoorState(services, c, Boolean(pendingReturn(data, id)));
if (!c) return ;
const f = facilityOf(data, c.facility_id, c.facility_name);
const renewal = pendingRenewal(data, id);
@@ -78,12 +79,13 @@ export function RentedUnitDetailPage({ id }) {
QR, PIN & chìa khóa
]] : []),
["Chìa khóa vật lý", c.handed_over ? "Đã nhận tại quầy" : "Gửi yêu cầu “Nhận chìa khóa” để cơ sở xếp lịch"],
...(pickupText ? [["Lịch nhận chìa khóa", pickupText]] : []),
]} />
{issued && !ended ? "Hợp đồng và mã ra vào đã được cấp. " : ""}QR và PIN chỉ mở được cửa trong kỳ thuê; mã tự hết hiệu lực khi hết hạn hoặc gửi trả kho thành công.
{/* D35–D36 · L13: trước ngày thuê không mở QR/PIN */}
- {issued && !ended &&
@@ -122,7 +124,37 @@ export function RentedUnitDetailPage({ id }) {
Hỗ trợ do sự cố cơ sởXác nhận khấu trừ trả khoTheo dõi gia hạnGia hạn sang ô khác / sau nâng cấpLịch khấu trừ cọcTiến độ trả kho / hoàn cọcLịch sử thanh toánChính sách cho thuê
- {qrOpen && setQrOpen(false)} />}
+ {qrOpen && { setQrOpen(false); door.reload(); }} />}
);
}
+
+/**
+ * Mục 61 (14/11): trạng thái cửa (Đang mở / Đã đóng) hiện trong khối "QR, PIN & chìa khóa".
+ * Đọc từ máy chủ khi mở trang, mỗi 15 giây và khi quay lại tab; cửa đã đóng thì nút "Đóng cửa" bị khoá.
+ */
+function useDoorState(services, c, returning) {
+ const visible = Boolean(c && (c.access_issued ?? c.status !== "DRAFT") && contractStatus(c) !== "ENDED"
+ && c.start_date <= today() && c.end_date > today() && !returning);
+ const [state, setState] = useState(null);
+ const load = useCallback(async () => {
+ if (!visible || !services?.doorState) return;
+ try { const out = await services.doorState(c); if (out?.ok && out.door) setState(out.door); } catch { /* giữ trạng thái cũ */ }
+ }, [visible, services, c?.contract_id, c?.api_id]); // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => {
+ if (!visible) return undefined;
+ load();
+ const timer = setInterval(load, 15000);
+ const onVisible = () => { if (document.visibilityState === "visible") load(); };
+ document.addEventListener("visibilitychange", onVisible);
+ return () => { clearInterval(timer); document.removeEventListener("visibilitychange", onVisible); };
+ }, [visible, load]);
+ return { visible, state, reload: load, update: (d) => setState((old) => ({ ...(old || {}), ...(d || {}), door: "LOCKED" })) };
+}
+
+function DoorStatus({ door }) {
+ if (!door.state) return Đang kiểm tra…;
+ const open = door.state.door === "OPEN";
+ return {open ? "Đang mở" : "Đã đóng"}
+ {door.state.at && · cập nhật {dateTimeLabel(door.state.at)}};
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx
index 7478e9b..84bddb1 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx
@@ -16,7 +16,6 @@ import { CONTRACT_STATUS } from "../../../shared/utils/status.js";
import { contractStatus, facilityOf, pendingRenewal, pendingReturn } from "../../../app/state/appSelectors.js";
import { useApp } from "../../../app/state/AppProvider.jsx";
import { AccessQrModal } from "../access/AccessQrModal.jsx";
-import { DoorCloseButton } from "../access/DoorCloseButton.jsx";
import { renewalView } from "./renewalStatusModel.js";
/**
@@ -60,7 +59,6 @@ export function RentedUnitListPage() {
: <>
{/* #59: xem mã được cả trước ngày thuê (chỉ mở cửa từ 00:00 ngày bắt đầu) */}
- {!prestart && }
>)}
Xem hợp đồng
>}>
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/contractPdf.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/contractPdf.js
index d581fb0..f62f4d4 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/contractPdf.js
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/contractPdf.js
@@ -14,7 +14,19 @@ const MARGIN_TOP = 18;
const MARGIN_BOTTOM = 20;
const CONTENT_W = PAGE_W - MARGIN_X * 2;
const CONTENT_H = PAGE_H - MARGIN_TOP - MARGIN_BOTTOM;
-const SCALE = 2; // độ nét ảnh chụp
+const SCALE = 2; // độ nét ảnh chụp mong muốn
+// Giới hạn canvas của trình duyệt: Chrome/Edge tối đa 32.767 px mỗi cạnh, Safari (iPhone) tối đa ~16,7 triệu điểm ảnh.
+// Hợp đồng dài vượt giới hạn thì html2canvas trả ảnh rỗng/ném lỗi, nên hạ độ nét cho vừa.
+const MAX_CANVAS_SIDE = 32000;
+const MAX_CANVAS_AREA = 16_000_000;
+
+/** Độ nét lớn nhất (≤ SCALE) để ảnh chụp tờ hợp đồng w×h px CSS không vượt giới hạn canvas. */
+export function captureScale(width, height) {
+ if (!(width > 0 && height > 0)) return SCALE;
+ const bySide = MAX_CANVAS_SIDE / Math.max(width, height);
+ const byArea = Math.sqrt(MAX_CANVAS_AREA / (width * height));
+ return Math.max(0.5, Math.min(SCALE, bySide, byArea));
+}
// Bố cục khi xuất: tờ rộng đúng vùng nội dung A4, bỏ viền / bóng của bản xem trên màn hình
const EXPORT_CSS = `html,body{background:#fff!important;padding:0!important;margin:0!important}
@@ -61,7 +73,10 @@ export async function downloadContractPdf(frame, { code, fileName }) {
const total = sheet.scrollHeight;
const pages = pageBreaks(total, CONTENT_H * pxPerMm, safe, forced);
- const shot = await html2canvas(sheet, { scale: SCALE, backgroundColor: "#ffffff", useCORS: true, logging: false });
+ const width = sheet.getBoundingClientRect().width;
+ const shot = await html2canvas(sheet, { scale: captureScale(width, total), backgroundColor: "#ffffff", useCORS: true, logging: false,
+ windowWidth: doc.documentElement.scrollWidth, windowHeight: Math.max(total, doc.documentElement.scrollHeight) });
+ if (!shot?.width || !shot?.height) throw new Error("Trình duyệt không chụp được tờ hợp đồng.");
const ratio = shot.width / sheet.getBoundingClientRect().width; // px ảnh trên mỗi px CSS
const pdf = new jsPDF({ unit: "mm", format: "a4", orientation: "portrait", compress: true });
const pagePx = { w: Math.round(PAGE_W * pxPerMm * ratio), h: Math.round(PAGE_H * pxPerMm * ratio) };
@@ -71,6 +86,7 @@ export async function downloadContractPdf(frame, { code, fileName }) {
canvas.width = pagePx.w;
canvas.height = pagePx.h;
const ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("Trình duyệt không cấp được vùng vẽ cho trang PDF.");
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
const sy = Math.round(from * ratio);
@@ -93,3 +109,10 @@ export async function downloadContractPdf(frame, { code, fileName }) {
style.remove();
}
}
+
+/** Phương án dự phòng: mở hộp thoại In của tờ hợp đồng (mẫu đã có @page A4) để khách chọn "Lưu dưới dạng PDF". */
+export function printContract(frame) {
+ const win = frame?.contentWindow;
+ if (!win || typeof win.print !== "function") return false;
+ try { win.focus(); win.print(); return true; } catch { return false; }
+}
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationDetailPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationDetailPage.jsx
index 2721bce..555d49b 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationDetailPage.jsx
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationDetailPage.jsx
@@ -101,6 +101,8 @@ export function ReservationDetailPage({ id, mode = "confirmation" }) {
paid && {contract ? "Hợp đồng và QR/PIN đã được cấp. Mã chỉ mở được trong kỳ thuê; chìa khóa vật lý nhận tại quầy." : "Đã ghi nhận thanh toán. Cơ sở đang xử lý phân bổ ô kho; hợp đồng và mã ra vào sẽ hiển thị khi hoàn tất."}
)}
{contract && Xem hợp đồng & mã mở kho}
+ {/* Mục 61: cho khách thấy email nhận thư hợp đồng; tài khoản demo có email giả thì sẽ không nhận được thư */}
+ {paid && !isDetail && data.user?.email &&
Email xác nhận thanh toán và hợp đồng được gửi tới {data.user.email}. Sai email? Cập nhật trong Tài khoản.
}
{waiting && Tiếp tục thanh toán}
{isDetail ? (
<>
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/contract-paper.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/contract-paper.test.js
index d7cd4a9..f4d2066 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/contract-paper.test.js
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/contract-paper.test.js
@@ -1,6 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { pageBreaks } from "../src/features/customer/contracts/contractPdf.js";
+import { captureScale, pageBreaks } from "../src/features/customer/contracts/contractPdf.js";
test("D58 · PDF hợp đồng: ngắt trang ở cuối đoạn, không cắt ngang dòng", () => {
// đoạn kết thúc ở 300, 590, 610, 900, 1210; trang cao 600
@@ -11,3 +11,10 @@ test("D58 · PDF hợp đồng: phụ lục luôn sang trang mới, đoạn quá
assert.deepEqual(pageBreaks(1000, 600, [100, 200, 1000], [300]), [[0, 300], [300, 900], [900, 1000]]);
assert.deepEqual(pageBreaks(500, 600, [500]), [[0, 500]]);
});
+
+test("Mục 61 · PDF hợp đồng dài: hạ độ nét để ảnh chụp không vượt giới hạn canvas", () => {
+ assert.equal(captureScale(605, 4000), 2); // hợp đồng ngắn giữ độ nét 2
+ const s = captureScale(605, 20000);
+ assert.ok(s < 2 && 605 * s * 20000 * s <= 16_000_000 + 1, "diện tích ≤ 16 triệu điểm ảnh (Safari)");
+ assert.ok(captureScale(605, 40000) * 40000 <= 32000, "cạnh dài ≤ 32.000 px (Chrome/Edge)");
+});
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs
index 58fc15b..81841cc 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs
@@ -102,7 +102,8 @@ try {
memory.set(STORAGE_KEY, JSON.stringify({ version: 5, authed: true, data: recordData }));
const returningUnits = renderToStaticMarkup(React.createElement(App));
assert.match(returningUnits, /