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
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
* 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";
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);
Expand All @@ -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); }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
}
Expand Down Expand Up @@ -84,7 +89,7 @@ export function ContractPaperPage({ id }) {
sandbox="allow-same-origin allow-modals" srcDoc={state.html} onLoad={fit} />
)}
</section>
{issued && !offline && <p className="hint contract-paper__hint">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.</p>}
{issued && !offline && <p className="hint contract-paper__hint">Bấm "Tải PDF" để lưu hợp đồng về máy.</p>}
</main>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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 <NotFound />;
const f = facilityOf(data, c.facility_id, c.facility_name);
const renewal = pendingRenewal(data, id);
Expand Down Expand Up @@ -78,12 +79,13 @@ export function RentedUnitDetailPage({ id }) {
<h2>QR, PIN & chìa khóa</h2>
<DetailList items={[
["QR & PIN 6 số", ended || ret || c.end_date <= today() ? "Đã hết hiệu lực" : issued ? (prestart ? `Đã cấp · ${usableFromText(c.start_date).replace("Có thể mở cửa", "mở cửa")}` : `Đã cấp · hiệu lực từ ${dateLabel(c.start_date)}`) : "Chưa được cấp"],
...(door.visible ? [["Trạng thái cửa", <DoorStatus door={door} />]] : []),
["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]] : []),
]} />
<p className="hint">{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.</p>
{/* D35–D36 · L13: trước ngày thuê không mở QR/PIN */}
{issued && !ended && <div className="customer-detail__actions"><Button disabled={Boolean(ret) || c.end_date <= today()} onClick={() => setQrOpen(true)}>{ret || c.end_date <= today() ? "QR đã hết hiệu lực" : "Mã QR mở cửa"}</Button>{!prestart && !ret && c.end_date > today() && <DoorCloseButton c={c} />}{prestart && <p className="hint">{usableFromText(c.start_date)}.</p>}</div>}
{issued && !ended && <div className="customer-detail__actions"><Button disabled={Boolean(ret) || c.end_date <= today()} onClick={() => setQrOpen(true)}>{ret || c.end_date <= today() ? "QR đã hết hiệu lực" : "Mã QR mở cửa"}</Button>{door.visible && <DoorCloseButton c={c} disabled={door.state?.door === "LOCKED"} onClosed={door.update} />}{prestart && <p className="hint">{usableFromText(c.start_date)}.</p>}</div>}
</section>
<section className="panel customer-detail__card">
<h2>Chính sách áp dụng</h2>
Expand Down Expand Up @@ -122,7 +124,37 @@ export function RentedUnitDetailPage({ id }) {
</aside>
</div>
<div className="workflow-links"><LinkButton to={`units/${encodeURIComponent(id)}/incident`} variant="outline">Hỗ trợ do sự cố cơ sở</LinkButton><LinkButton to={`units/${encodeURIComponent(id)}/deduction`} variant="outline">Xác nhận khấu trừ trả kho</LinkButton><LinkButton to={`units/${encodeURIComponent(id)}/renewal-status`} variant="outline">Theo dõi gia hạn</LinkButton><LinkButton to={`units/${encodeURIComponent(id)}/renew-other`} variant="outline">Gia hạn sang ô khác / sau nâng cấp</LinkButton><LinkButton to={`units/${encodeURIComponent(id)}/deposit`} variant="outline">Lịch khấu trừ cọc</LinkButton><LinkButton to={`units/${encodeURIComponent(id)}/progress`} variant="outline">Tiến độ trả kho / hoàn cọc</LinkButton><LinkButton to="payments/history" variant="outline">Lịch sử thanh toán</LinkButton><LinkButton to="policies" variant="outline">Chính sách cho thuê</LinkButton></div>
{qrOpen && <AccessQrModal c={c} facility={f} onClose={() => setQrOpen(false)} />}
{qrOpen && <AccessQrModal c={c} facility={f} onClose={() => { setQrOpen(false); door.reload(); }} />}
</main>
);
}

/**
* 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 <span className="hint">Đang kiểm tra…</span>;
const open = door.state.door === "OPEN";
return <span className="customer-detail__door"><Tag tone={open ? "amber" : "green"}>{open ? "Đang mở" : "Đã đóng"}</Tag>
{door.state.at && <span className="hint"> · cập nhật {dateTimeLabel(door.state.at)}</span>}</span>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand Down Expand Up @@ -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) */}
<Button variant="outline" disabled={Boolean(pendingReturn(data, c.contract_id)) || c.end_date <= now} onClick={() => setQrContract(c)}>Mã QR mở cửa</Button>
{!prestart && <DoorCloseButton c={c} disabled={Boolean(pendingReturn(data, c.contract_id)) || c.end_date <= now} />}
</>)}
<LinkButton to={`units/${c.contract_id}`}>Xem hợp đồng</LinkButton>
</>}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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) };
Expand All @@ -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);
Expand All @@ -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; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ export function ReservationDetailPage({ id, mode = "confirmation" }) {
paid && <Notice tone={contract ? "success" : "info"}>{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."}</Notice>
)}
{contract && <LinkButton to={`units/${contract.contract_id}`} block>Xem hợp đồng & mã mở kho</LinkButton>}
{/* 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 && <p className="hint">Email xác nhận thanh toán và hợp đồng được gửi tới <b>{data.user.email}</b>. Sai email? Cập nhật trong <a href="#/profile">Tài khoản</a>.</p>}
{waiting && <LinkButton to={`checkout/${r.reservation_id}`} block>Tiếp tục thanh toán</LinkButton>}
{isDetail ? (
<>
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)");
});
Original file line number Diff line number Diff line change
Expand Up @@ -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, /<button[^>]*disabled[^>]*>Mã QR mở cửa<\/button>/);
assert.match(returningUnits, /<button[^>]*disabled[^>]*>Đóng cửa<\/button>/, "đã gửi trả kho thì không điều khiển cửa");
// Mục 61 (14/11): nút Đóng cửa chỉ còn ở trang chi tiết kho, không có trên thẻ danh sách
assert.ok(!returningUnits.includes(">Đóng cửa<"), "danh sách Kho của tôi không có nút Đóng cửa");
const renewalData = createSeedData();
const renewal = renewalData.renewals[0];
const renewalPayment = renewalData.ledger.find(row => row.kind === "RENEWAL" && row.contract_id === renewal.contract_id);
Expand Down
3 changes: 3 additions & 0 deletions StorageProject.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,9 @@
builder.Services.AddHostedService<OverdueWorker>();
}
builder.Services.AddHostedService<ExpiredRenewalWorker>();
// Mục 61: đối soát PayOS khi webhook không về được (backend chạy localhost)
if (builder.Configuration.GetValue<bool>("Worker:EnablePayOSReconcile", !builder.Environment.IsEnvironment("Testing")))
builder.Services.AddHostedService<PayOSReconcileWorker>();
if (builder.Configuration.GetValue<bool>("Worker:EnableFacilityWorkflow", true))
{
builder.Services.AddHostedService<FacilityWorkflowWorker>(); // D40 tự chốt sau 48 giờ, D42 báo cáo 22:00
Expand Down
Loading
Loading