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
36 changes: 36 additions & 0 deletions C07-QR-HUONG-DAN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# C07 — Xem và quét QR mở cửa (frontend)

## Phạm vi
Chỉ thêm frontend C07q, C07r1, C07r2 theo Figma; không triển khai backend QR. File code cũ `src/pages/Units.jsx` chỉ thêm 1 import và 1 lần render component. Không đổi đăng nhập, đặt kho, thanh toán, bàn giao, trả kho, giao diện KD, backend hay database.

## Xem giao diện
Vào `SafeSpace-Customer-UI/SafeSpace-Customer-UI`, tạo/cập nhật `.env.local`:
```
VITE_USE_API=false
```
Chạy `npm install`, `npm run dev`. Đăng nhập `mai.nguyen@example.com` / `SafeSpace@123`, chọn Kho của tôi → B-015 → Mở cửa kho → bấm trực tiếp hình QR để mô phỏng máy quét, giống prototype Figma. Nút Quay lại đưa về QR; Đóng, Escape hoặc bấm nền ngoài đóng hộp thoại.
A-102 chưa được bàn giao (`handed_over: false`) nên QR bị khóa. Không đổi dữ liệu A-102 chỉ để mở khóa.
Nếu đang đăng nhập tài khoản cục bộ khác không có hợp đồng, nó sẽ không có QR. Tính năng không kiểm tra email cố định; lấy hợp đồng và người dùng từ state.

## Hành vi
- Chỉ hiện mã khi hợp đồng đã bàn giao, trạng thái ACTIVE/EXPIRING và trong kỳ thuê.
- QR thật được tạo bằng thư viện qrcode đã có; chứa mã tham chiếu ngẫu nhiên, không chứa thông tin cá nhân.
- Mã dự phòng, ô kho và hạn hợp đồng lấy theo phiên mô phỏng và hợp đồng hiện tại.
- Bấm QR kiểm tra lại quyền phiên mô phỏng, mã, ô kho, ngày cấp, ngày hiệu lực và trạng thái; hợp lệ hiện Mở cửa, không hợp lệ hiện Từ chối.
- Nhật ký mô phỏng nằm riêng trong localStorage, tối đa 100 lần; không phải activity_logs database.
- Mã cấp lại khi mở popup; mã mô phỏng hết hiệu lực sau ngày cấp.
- Không có thao tác đóng cửa kho. Đóng chỉ đóng popup; cửa vật lý khách tự đóng.
- Màn nhập mã dự phòng/camera không có trong khung Figma này nên không thêm.

## Chế độ API
Khi `VITE_USE_API=true`, các chức năng cũ vẫn dùng backend như trước. QR sẽ báo máy chủ chưa hỗ trợ; không giả lập thành công trên tài khoản thật. Đổi `src/state/useAccessQr.js` khi triển khai API cấp mã, kiểm mã và thu hồi mã; backend phải tự kiểm tra quyền sở hữu, đúng ô và thời hạn. Không dùng kiểm tra frontend làm kiểm soát cửa thật.

## Các file thêm
- src/components/AccessQr.jsx: giao diện và popup.
- src/styles/access-qr.css: CSS riêng C07.
- src/state/useAccessQr.js: ranh giới mô phỏng/tích hợp sau.
- src/lib/access.js: kiểm tra mô phỏng.
- src/assets/access/check.svg, close.svg: icon xuất từ Figma 601:9827/601:9837, kích thước 96×96.
- tests/access.test.js: chạy `node --test tests/access.test.js`.

Thiết kế tham chiếu: Figma SafeSpace - Modern UI, C07q 601:9806, C07r1 601:9826, C07r2 601:9836. Vùng giữ chỗ QR trong thiết kế được thay bằng QR có thể giải mã, thông tin minh họa được thay bằng dữ liệu hợp đồng.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import React, { useCallback, useEffect, useState } from "react";
import QRCode from "qrcode";
import { Button, Modal, Notice } from "./UI";
import { useAccessQr } from "../state/useAccessQr";
import { accessError } from "../lib/access";
import { dateLabel, today } from "../lib/format";
import { typeLabel } from "../lib/catalog";
import check from "../assets/access/check.svg";
import close from "../assets/access/close.svg";
import "../styles/access-qr.css";

export default function AccessQr({ contract, facility, user }) {
const [opened, setOpened] = useState(false);
const [credential, setCredential] = useState(null);
const [svg, setSvg] = useState("");
const [result, setResult] = useState(null);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const { getCredential, scan } = useAccessQr(contract.contract_id);
const dismiss = useCallback(() => { setOpened(false); setResult(null); setCredential(null); setSvg(""); setError(""); }, []);
useEffect(() => { dismiss(); }, [contract.contract_id, user.user_id, dismiss]);
const open = async () => {
setBusy(true); setError("");
try {
const value = await getCredential();
const image = await QRCode.toString(value.code, { type: "svg", margin: 2, width: 176, errorCorrectionLevel: "M" });
setCredential(value); setSvg(image); setOpened(true);
} catch (e) { setError(e.message); }
finally { setBusy(false); }
};
const scanCode = async () => {
if (busy) return;
setBusy(true); setError("");
try { setResult(await scan(credential, credential.code, contract.unit_number)); }
catch (e) { setResult({ allowed: false, message: e.message }); }
finally { setBusy(false); }
};
const unavailable = accessError(contract, today());
return <div className="c07-access">
<Button onClick={open} disabled={busy || Boolean(unavailable)} title={unavailable || undefined}>{busy ? "Đang xử lý…" : (contract.handed_over ? "Mở cửa kho" : "Mở cửa kho (QR)")}</Button>
{error && <Notice tone="error">{error}</Notice>}
{opened && credential && <Modal title={result ? (result.allowed ? "Mở cửa" : "Từ chối") : `QR mở cửa · Kho ${contract.unit_number}`} onClose={dismiss} size={result ? (result.allowed ? "c07-access-allowed" : "c07-access-denied") : "c07-access-qr"}>
{result ? <div className="access-result-content" role="status">
<img className="access-result-icon" src={result.allowed ? check : close} alt="" />
<p className="access-scanner-label">CỬA KHO {contract.unit_number} · MÁY QUÉT</p>
<p className="access-result-title">{result.allowed ? "Mở cửa" : "Từ chối"}</p>
<p className="access-result-description">{result.allowed ? <>{user.full_name} · {contract.contract_id}<br />{new Date(result.at).toLocaleString("vi-VN")} · Đã ghi nhật ký ra vào</> : <>{result.message}<br />Liên hệ nhân viên cơ sở nếu cần hỗ trợ.</>}</p>
<Button variant="outline" onClick={() => setResult(null)}>Quay lại</Button>
</div> : <>
<p className="access-subtitle">{facility.name}{contract.location ? ` · ${contract.location}` : ""}</p>
<button type="button" className="access-code" onClick={scanCode} disabled={busy} aria-label="Quét QR mở cửa">
<span className="access-code-image" dangerouslySetInnerHTML={{ __html: svg }} />
<strong>QR mở cửa</strong>
<span>Mã riêng cho hợp đồng {contract.contract_id}</span>
</button>
<dl className="access-details">
<div><dt>Mã dự phòng</dt><dd>{credential.backupCode.replace(/(.{4})(.{4})/, "$1 $2")}</dd></div>
<div><dt>Ô kho</dt><dd>{contract.unit_number} · {typeLabel(contract.type)}</dd></div>
<div><dt>Hiệu lực đến</dt><dd>{dateLabel(contract.end_date)}</dd></div>
</dl>
<p className="access-help">Đưa mã vào máy quét ở cửa kho. Nếu không quét được, nhập mã dự phòng. Mã hết hiệu lực khi trả kho hoặc hợp đồng hết hạn.</p>
<Button variant="outline" block onClick={dismiss}>Đóng</Button>
</>}
</Modal>}
</div>;
}
15 changes: 15 additions & 0 deletions SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/access.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// UI-only simulator. Never use this validator as a physical door authorization boundary.
export function accessError(contract, date) {
if (!contract) return "Không tìm thấy hợp đồng thuộc tài khoản của bạn.";
if (["ENDED", "TERMINATED", "CANCELLED", "RETURNED"].includes(contract.status)) return "Mã đã hết hiệu lực — hợp đồng đã trả kho.";
if (!contract.handed_over) return "Kho chưa được bàn giao.";
if (!contract.start_date || !contract.end_date || date < contract.start_date.slice(0, 10) || date > contract.end_date.slice(0, 10)) return "Mã đã hết hiệu lực hoặc hợp đồng chưa đến ngày bắt đầu.";
if (!["ACTIVE", "EXPIRING"].includes(contract.status)) return "Hợp đồng không còn hiệu lực.";
return "";
}
export function validateAccess({ contract, credential, code, unit, owner, date }) {
const error = accessError(contract, date);
if (error) return { allowed: false, message: error };
if (!credential || credential.owner !== owner || credential.contractId !== contract.contract_id || credential.date !== date || credential.unit !== unit || contract.unit_number !== unit || !code || (code !== credential.code && code.replace(/\s/g, "") !== credential.backupCode)) return { allowed: false, message: "Mã không hợp lệ hoặc không đúng ô kho." };
return { allowed: true };
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState } from "react";
import AccessQr from "../components/AccessQr";
import { EmptyInline } from "../components/Inline";
import { DatePicker, Select } from "../components/Pickers";
import { Button, Empty, Field, LinkButton, Notice, PageHeader, StatusTag, Tag } from "../components/UI";
Expand Down Expand Up @@ -112,6 +113,7 @@ export function UnitDetail({ id }) {
</section>
<aside className="panel booking">
<h2>Bạn cần làm gì?</h2>
<AccessQr contract={c} facility={f} user={data.user} />
{renewal && <Notice>Yêu cầu gia hạn thêm {renewal.months} tháng đang chờ cơ sở duyệt.</Notice>}
{ret && <Notice>Yêu cầu trả kho ngày {dateLabel(ret.date)} đang chờ cơ sở xác nhận.</Notice>}
<div className="stack stack--col">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useCallback } from "react";
import { useApp } from "./store";
import { USE_API } from "../config/api";
import { today } from "../lib/format";
import { accessError, validateAccess } from "../lib/access";

// Local simulator is explicitly restricted to VITE_USE_API=false.
// Replace this boundary with authenticated backend operations when Ops is ready.
export function useAccessQr(id) {
const { data } = useApp();
const getCredential = useCallback(async () => {
if (USE_API) throw new Error("Chức năng QR chưa được máy chủ hỗ trợ. Vui lòng liên hệ nhân viên cơ sở.");
const contract = data.contracts.find(c => c.contract_id === id);
const error = accessError(contract, today());
if (error) throw new Error(error);
const credential = { owner: data.user.user_id, contractId: id, unit: contract.unit_number, date: today(), code: crypto.randomUUID(), backupCode: String(crypto.getRandomValues(new Uint32Array(1))[0] % 100000000).padStart(8, "0") };
return credential;
}, [data, id]);
const scan = useCallback(async (credential, code, unit) => {
if (USE_API) throw new Error("Chức năng quét QR chưa được máy chủ hỗ trợ.");
const result = validateAccess({ contract: data.contracts.find(c => c.contract_id === id), credential, code, unit, owner: data.user.user_id, date: today() });
const at = new Date().toISOString();
// Separate simulator journal; no changes to contract, payment or Ops state.
const key = `safespace.access.scans.${data.user.user_id}`;
let journal;
try { journal = JSON.parse(localStorage.getItem(key) || "[]"); } catch { journal = []; }
if (!Array.isArray(journal)) journal = [];
localStorage.setItem(key, JSON.stringify([...journal.slice(-99), { contractId: id, unit, allowed: result.allowed, message: result.message, at }]));
return { ...result, at };
}, [data, id]);
return { getCredential, scan };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
.modal--c07-access-qr,:is(.modal--c07-access-allowed,.modal--c07-access-denied) { width:480px; max-width:calc(100vw - 32px); color:var(--text); }
.modal--c07-access-qr { padding:32px; border-radius:12px; display:flex; flex-direction:column; align-items:center; gap:16px; }
.modal.modal--c07-access-qr > h2 { font-size:22px; font-weight:600; line-height:27px; text-align:center; margin:0; }
.access-subtitle { color:var(--muted); font-size:15px; line-height:18px; text-align:center; }
.access-code { width:240px; height:240px; flex-shrink:0; background:var(--soft); border:1px solid var(--line); border-radius:12px; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:8px; cursor:pointer; padding:6px; }
.access-code-image,.access-code-image svg { width:160px; height:160px; display:block; }
.access-code strong { font-size:16px; line-height:19px; font-weight:600; }
.access-code > span:last-child { color:var(--muted); font-size:13px; line-height:16px; }
.access-details { width:100%; display:flex; flex-direction:column; gap:8px; font-size:15px; line-height:18px; }
.access-details > div { display:flex; justify-content:space-between; gap:12px; }
.access-details dt { color:var(--muted); }
.access-details dd { font-weight:600; text-align:right; }
.access-help { font-size:14px; line-height:17px; color:var(--muted); width:100%; }
.modal--c07-access-qr > .btn { min-height:48px; margin:0; border-radius:6px; }
:is(.modal--c07-access-allowed,.modal--c07-access-denied) { --access-success-bg:#e0f7eb; --access-success:#05855e; --access-error-bg:#fce8e8; --access-error:#cc2626; padding:48px 40px 40px; border-radius:16px; }
:is(.modal--c07-access-allowed,.modal--c07-access-denied) > h2 { position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%); }
.modal--c07-access-allowed { background:var(--access-success-bg); }
.modal--c07-access-denied { background:var(--access-error-bg); }
.access-result-content { display:flex; flex-direction:column; align-items:center; gap:16px; text-align:center; }
.access-result-icon { width:96px; height:96px; }
.access-scanner-label { font-size:13px; line-height:16px; font-weight:600; color:var(--muted); }
.access-result-title { font-size:32px; line-height:39px; font-weight:700; color:var(--access-success); }
.modal--c07-access-denied .access-result-title { color:var(--access-error); }
.access-result-description { font-size:16px; line-height:19px; width:100%; }
.access-result-content > .btn { min-height:48px; border-radius:6px; padding:12px; background:var(--white); }
@media(max-width:520px) { .modal--c07-access-qr,:is(.modal--c07-access-allowed,.modal--c07-access-denied) { padding:24px; } }

.c07-access { display:grid; gap:12px; justify-items:start; }
.c07-access > .btn { min-height:48px; border-radius:6px; padding:12px; }

.modal--c07-access-qr,:is(.modal--c07-access-allowed,.modal--c07-access-denied) { max-height:calc(100dvh - 32px); overflow-y:auto; }

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion feature_list.json
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@
"behavior": "Frontend B01–B05 và tích hợp API theo operations-api(3).md; không sửa backend/database",
"verification": "_fe; npm run test:business; kiểm tra trình duyệt và đối chiếu source backend",
"state": "passing", "depends_on": [], "evidence": "2026-10-15: phạm vi chỉ frontend. npm test 38/38, test:business 8/8, render 76 route, build/init FE PASS. Browser 13 nhóm PASS; 14 màn role khác giống từng pixel. 77 file source/config backend giữ nguyên byte. Không xác nhận backend/DB thật."
}
},
{"id": "F32", "flow": 2, "uc": [], "actor": "Khách hàng", "behavior": "Frontend C07 xem QR và mô phỏng quét theo Figma; không bao gồm API/DB QR", "state": "passing", "verification": "node --test tests/access.test.js; npm test; npm run test:render; npm run build; kiểm tra browser C07", "evidence": "2026-10-16: 42 test gốc + 10 test QR + 9 test business PASS; 76 route SSR PASS; build PASS; browser popup 480x598, success/denial, mobile, guards PASS. Backend QR chưa triển khai, ngoài phạm vi."}
]
}
7 changes: 7 additions & 0 deletions progress.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,10 @@
(`services/`, `customer.css`); nhắc tag "BẢN DEMO UI" không còn trong code.
- Phiên sau nên: chạy `./init.sh` đầy đủ trên máy có .NET; sau đó làm F28 (test backend) hoặc F21
(khu Nhân viên / Quản lý) tuỳ nhóm ưu tiên.

## C07 QR frontend — 2026-10-16 — Tiến / Codex
- Thêm component QR riêng + 2 dòng vào Units.jsx; không sửa nghiệp vụ cũ, API hoặc DB.
- C07q xem QR, C07r1/C07r2 kết quả quét; mô phỏng chỉ VITE_USE_API=false, API thật báo chưa hỗ trợ.
- Kiểm chứng: 42 test gốc, 10 test QR, 9 test business pass; 76 route SSR pass; Vite build pass.
- Browser Chromium: popup 480x598, QR, kết quả mở cửa, từ chối hết hạn, icon 96px, Escape, Đóng, khóa chưa bàn giao, mobile 390px, không pageerror.
- Chưa có backend QR; hướng dẫn C07-QR-HUONG-DAN.md.