diff --git a/DECISIONS.md b/DECISIONS.md index 76b43fe..54766ea 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -589,3 +589,31 @@ Bổ sung @playwright/test trong devDependencies để kiểm thao tác biểu m - Quản lý chỉ thấy hồ sơ ở hàng chờ đối soát/xác nhận hoàn cọc khi đã có biên bản kiểm tra trả kho `COMPLETED` **và** khách hàng/cơ sở đã hoàn tất bước phản hồi khấu trừ (`DamageWorkflowResolved = true`, không còn `WAITING`/`SELF_CLEAN`/`SELF_REPLACE`/`DISPUTE`). - Khách hàng được chọn đồng ý đồng thời nhiều khoản khấu trừ (vệ sinh, hư hỏng) hoặc chọn phương án riêng cho từng khoản. - **Bỏ quản lý duyệt gia hạn (#23, thay phần duyệt gia hạn M01/M03 của D11/D32/D46b):** Khách gửi gia hạn hợp lệ (tại chỗ hoặc chuyển ô) thì hệ thống tự kiểm tra điều kiện/lịch trống, chốt giá và mở thanh toán trực tiếp (`APPROVED` / tạo `RENEWAL` `PENDING`, giữ ô mới nếu đổi ô); chỉ cập nhật `EndDate` hợp đồng sau khi thanh toán đủ. + +## D51 — 12/11/2026: Cửa kho, mã QR/PIN, công cụ demo và IP khách — Đã chốt + +> Người dùng chốt ngày 12–13/11/2026 khi làm #45, #48–#51, #54, #59. Thay ý "cửa tự khoá" và PIN có số 0 ở các quyết định trước; giữ D48 (không đổi database). Triển khai ở Lượt 6, 6b. + +- **Không tự khoá cửa:** cửa mở tới khi có người bấm "Đóng cửa" (trên máy quét, hoặc trong Kho của tôi của khách). Đóng cửa chỉ cần popup xác nhận, không nhập lại QR/PIN. Đóng khi cửa đã khoá thì không ghi thêm sự kiện. +- **PIN 6 số chỉ gồm 1–9** (bỏ số 0). Máy chủ từ chối PIN có số 0 với thông báo "Mã PIN gồm 6 số từ 1 đến 9." Bàn phím máy quét khoá phím 0. +- **Xem mã trước ngày thuê (#59):** khách xem được QR và PIN ngay khi có hợp đồng. Trước 00:00 ngày bắt đầu, quét mã bị từ chối với "Chưa đến ngày sử dụng. Có thể mở cửa từ 00:00 ngày dd/MM/yyyy." +- **Lưu trạng thái cửa trong `activity_logs`** (D48): `ACCESS_SCANNED` (kết quả OPEN/DENIED, cách xác thực QR/PIN, lý do), `DOOR_CLOSED` (CLOSE_DEVICE / CLOSE_APP), `DOOR_SUPPORT_REQUESTED`. Không lưu nguyên mã QR/PIN; Nhật ký cửa không hiển thị mã. +- **Gọi hỗ trợ tại cửa:** tạo yêu cầu hỗ trợ chủ đề mã ra vào, ưu tiên cao, gắn cơ sở và ô kho; trong 30 phút với cùng ô thì trả lại yêu cầu đang mở, không tạo trùng. +- **Công cụ demo của admin (#45, #54):** mục "Công cụ demo" trên thanh menu admin mở trang 4 thẻ (không có hàng tab): Máy quét, Chỉnh giá, Chỉnh ngày hợp đồng, Nhật ký cửa. + - Chỉnh ngày hợp đồng: ngày bắt đầu, ngày hết hạn (4 kịch bản: chưa tới ngày thuê, đang thuê, sắp hết hạn, quá hạn) và ngày giao dịch đã thanh toán (giờ Việt Nam). Máy chủ tính lại trạng thái hợp đồng, ô kho, số ngày quá hạn. + - Chỉnh giá: giá thuê tháng và số tiền giao dịch; tiền cọc chỉ xem. + - Mỗi lần chỉnh ghi `DEMO_CONTRACT_EDITED` / `DEMO_PAYMENT_EDITED` với giá trị trước/sau, lý do và admin thực hiện. + - Giao diện Máy quét và Nhật ký cửa do Thắng làm cùng lượt này (thay phân công cho Đạt trước đó). +- **IP của khách hàng:** admin không xem được IP (và thông tin thiết bị trong lịch sử đăng nhập) của tài khoản chỉ có vai trò khách. API nhật ký trả `null`, giao diện hiện "Ẩn"; database vẫn lưu. IP của nhân viên, quản lý, vận hành, admin và log hệ thống vẫn hiện. + +## D52 — 12/11/2026: Bỏ hàng tab dưới thanh menu, gộp chức năng theo vai trò — Đã chốt + +> Người dùng chốt ngày 12/11/2026 khi sửa #7. Áp dụng cho mọi vai trò; Figma đã vẽ lại (G2, menu quản lý, menu admin). Triển khai ở Lượt 4b. + +- **Không có hàng nút/tab dưới thanh menu** ở bất kỳ vai trò nào; chức năng nhỏ mở từ thẻ việc trên Tổng quan hoặc nút trên từng mục. +- **Quản lý cơ sở:** menu gồm Tổng quan, Danh sách kho, Hợp đồng & quá hạn, Hoàn tiền, Báo cáo. + - Bỏ "Phân bổ kho" và "Phân công": hệ thống tự đề xuất ô khi đặt; yêu cầu của khách hiện thẳng bên nhân viên. Tổng quan chỉ còn thẻ việc cho trường hợp cần người xử lý (ví dụ xung đột đặt kho không có ô tương đương). + - "Hoàn tiền" gộp hoàn tiền đơn huỷ, hoàn tiền mặt và hoàn cọc. + - Xử lý quá hạn mở từ nút trên từng hợp đồng. Danh sách sự cố xem trong Danh sách kho. Báo cáo cuối ngày nằm trong Báo cáo. +- **Nhân viên:** "Kiểm tra ô cũ" nằm trong "Kiểm tra trả kho". +- **Vận hành KD — Thêm cơ sở:** chưa bắt buộc kinh độ/vĩ độ; cơ sở chưa có toạ độ không hiện trên bản đồ. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs index 4e8fd5d..aa0114c 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs @@ -112,7 +112,7 @@ export function createState() { const renewEnd = addMonths(contracts[0].endDate, 3); const renewals = [{ renewalId: 1, contractId: 1, oldEndDate: contracts[0].endDate, newEndDate: renewEnd, renewalPeriodMonths: 3, oldMonthlyRate: 1500000, newMonthlyRate: 1500000, renewalAmount: 4500000, status: "APPROVED", requestedAt: days(-2) }]; payments.push({ paymentId: 3, contractId: 1, renewalId: 1, paymentType: "RENEWAL", amount: 4500000, currency: "VND", paymentMethod: "PAYOS", transactionReference: "SS-0001-REN", dueDate: contracts[0].endDate, paidAt: null, status: "PENDING", createdAt: days(-1) }); - return { policyVersions: { 1: { ...defaultRentalPolicy(), displayVersion: "10/2026" } }, rentalPolicy: { ...defaultRentalPolicy(), displayVersion: "10/2026" }, policyConsents: [], users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals, tickets, payos: new Map(), accessLogs: [], tokens: new Map(), down: false, roles, permissions, rolePermissions, userRoles, userFacilities: [], loginHistory: [], activityLogs: [] }; + return { policyVersions: { 1: { ...defaultRentalPolicy(), displayVersion: "10/2026" } }, rentalPolicy: { ...defaultRentalPolicy(), displayVersion: "10/2026" }, policyConsents: [], users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals, tickets, payos: new Map(), accessLogs: [], tokens: new Map(), doors: new Map(), down: false, roles, permissions, rolePermissions, userRoles, userFacilities: [], loginHistory: [], activityLogs: [] }; } // ---- Khu vận hành (Nhân viên / Quản lý cơ sở): chỉ bật khi { ops: true } hoặc MOCK_OPS=1. @@ -232,7 +232,8 @@ export function startMockApi( return { orderCode: o.orderCode, amount: o.amount, description: o.description, qrCode: qr, checkoutUrl: `https://pay.payos.vn/web/mock-${o.orderCode}`, expiredAt: iso(o.expiredAt), status: o.status }; }; const accessCode = (c) => { - const n = String((c.contractId * 7919 + 4821) % 1000000).padStart(6, "0"); + // D51: PIN 6 số chỉ gồm 1–9 + const n = String((c.contractId * 7919 + 4821) % 1000000).padStart(6, "0").replace(/\d/g, (d) => String(1 + (Number(d) % 9))); return { code: `SSQR-${c.contractId}-${n.slice(0, 4)}`, backup: n }; }; @@ -394,25 +395,59 @@ export function startMockApi( return send(200, { facilityId: body.facilityId, facilityName: fac(body.facilityId)?.name, unitTypeId: body.unitTypeId, unitTypeName: t?.typeName, area: t?.area, climateControlled: t?.climateControlled, monthlyRate: rate?.monthlyRate || 0, estimatedTotalRent: (rate?.monthlyRate || 0) * body.rentalPeriodMonths, requiredDeposit: rate?.monthlyRate || 0, startDate: body.startDate, expectedEndDate: addMonths(body.startDate, body.rentalPeriodMonths), availableUnitCount: count, isAvailable: count > 0 }); } + // ---- Lượt 6b · cửa mô phỏng theo ô (D51: không tự khoá) + nhật ký cửa (không lưu nguyên mã) + const vnLocal = (d) => new Date(d.getTime() + 7 * 36e5).toISOString().slice(0, 19); + const codeOf = (cc) => `HĐ-${cc.startDate.slice(0, 4)}-${String(cc.contractId).padStart(4, "0")}`; + const unitByNumber = (no, fid) => S.units.find((u) => u.unitNumber === no && (!fid || u.facilityId === Number(fid))); + const doorDto = (no, changed = false) => { const d = S.doors.get(no); const u = unitByNumber(no); return { unitNumber: no, door: d?.door === "OPEN" ? "OPEN" : "LOCKED", updatedAt: d?.at || null, changed, facilityName: u ? fac(u.facilityId)?.name : null }; }; + const doorLog = (row) => S.accessLogs.push({ logId: S.accessLogs.length + 1, at: new Date(), ...row }); + const closeDoorAt = (no, method, contractId = null) => { + const open = S.doors.get(no)?.door === "OPEN"; + if (open) { S.doors.set(no, { door: "LOCKED", at: vnLocal(new Date()) }); doorLog({ unitNumber: no, result: "CLOSED", method, contractId }); } + return doorDto(no, open); + }; + // C07r · máy quét cửa kho (thiết bị tại cơ sở, không cần đăng nhập khách) if (req.method === "POST" && path === "/api/access/scan") { const code = String(body?.code || "").trim(); const clean = code.replace(/\s/g, ""); - const c = S.contracts.find((x) => { const a = accessCode(x); return a.code === code || a.backup.replace(/\s/g, "") === clean; }); + const at = body?.unitNumber || null; + const method = /^SSQR-/i.test(code) ? "QR" : "PIN"; const now = new Date(); const out = (result, reason, cc) => { - S.accessLogs.push({ code, result, at: now }); const u = cc && unit(cc.unitId); const cust = cc && S.users.find((x) => x.userId === cc.customerId); - return send(200, { result, unitNumber: u?.unitNumber || null, customerName: cust?.fullName || null, contractCode: cc ? `HĐ-${cc.startDate.slice(0, 4)}-${String(cc.contractId).padStart(4, "0")}` : null, scannedAt: iso(now), reason }); + doorLog({ unitNumber: at || u?.unitNumber || null, result, method, reason, contractId: cc?.contractId || null }); + return send(200, { result, unitNumber: u?.unitNumber || at, customerName: cust?.fullName || null, contractCode: cc ? codeOf(cc) : null, scannedAt: iso(now), reason, scanMethod: method }); }; + if (method === "PIN" && /^\d{6}$/.test(clean) && clean.includes("0")) return out("DENIED", "Mã PIN gồm 6 số từ 1 đến 9.", null); + const c = S.contracts.find((x) => { const a = accessCode(x); return a.code === code || a.backup.replace(/\s/g, "") === clean; }); if (!c) return out("DENIED", "Mã không đúng. Kiểm tra lại mã trên ứng dụng hoặc mã dự phòng.", null); - const h = S.handovers.find((x) => x.contractId === c.contractId); + if (at && unit(c.unitId).unitNumber !== at) return out("DENIED", `Mã không thuộc ô ${at}. QR và PIN chỉ mở đúng kho của hợp đồng.`, c); if (c.status !== "ACTIVE") return out("DENIED", "Mã đã hết hiệu lực — hợp đồng đã trả kho.", c); - if (c.startDate > dateOnly(now)) return out("DENIED", "Chưa đến ngày bắt đầu hợp đồng.", c); + if (c.startDate > dateOnly(now)) return out("DENIED", `Chưa đến ngày sử dụng. Có thể mở cửa từ 00:00 ngày ${c.startDate.split("-").reverse().join("/")}.`, c); if (c.endDate <= dateOnly(now)) return out("DENIED", "Hợp đồng đã quá hạn. Vui lòng gia hạn hoặc liên hệ cơ sở.", c); + S.doors.set(unit(c.unitId).unitNumber, { door: "OPEN", at: vnLocal(now) }); return out("OPEN", null, c); } + if (path === "/api/access/door" || path === "/api/access/door/close" || path === "/api/access/support") { + const no = String((req.method === "GET" ? url.searchParams.get("unitNumber") : body?.unitNumber) || "").trim(); + const fid = req.method === "GET" ? url.searchParams.get("facilityId") : body?.facilityId; + const u = no && unitByNumber(no, fid); + if (!u) return send(404, { error: "Không tìm thấy ô kho." }); + if (req.method === "GET" && path === "/api/access/door") return send(200, doorDto(no)); + if (req.method === "POST" && path === "/api/access/door/close") return send(200, closeDoorAt(no, "CLOSE_DEVICE")); + if (req.method === "POST" && path === "/api/access/support") { + const since = Date.now() - 30 * 6e4; + const dup = S.tickets.find((t) => t.unitId === u.unitId && t.issueType === "ACCESS_CODE" && t.status === "OPEN" && new Date(t.createdAt).getTime() >= since); + const c = S.contracts.find((x) => x.unitId === u.unitId && x.status === "ACTIVE"); + const t = dup || (() => { const nt = { ticketId: S.tickets.length + 1, contractId: c?.contractId || null, customerId: c?.customerId || null, unitId: u.unitId, issueType: "ACCESS_CODE", title: `Hỗ trợ tại cửa kho ${no}`, description: body?.reason || "Khách cần hỗ trợ tại cửa.", priority: "HIGH", status: "OPEN", createdAt: new Date(), responses: [] }; S.tickets.push(nt); + // Mock: dữ liệu vận hành (nhân viên/quản lý) là bộ riêng → thêm vào bảng việc, giống BE gắn ticket theo hợp đồng/ô của cơ sở + if (O) { O.tickets = [{ id: `HT-${String(nt.ticketId).padStart(4, "0")}`, unit: no, customer: c ? S.users.find((x) => x.userId === c.customerId)?.fullName : null, title: nt.title, created_at: vnLocal(nt.createdAt).slice(0, 16), schedule: null, status: "OPEN", assignee: null, notes: [] }, ...O.tickets]; O.version = (O.version || 0) + 1; } + return nt; })(); + return send(200, { ticketCode: `HT-${String(t.ticketId).padStart(4, "0")}`, unitNumber: no, facilityName: fac(u.facilityId)?.name, status: t.status, createdAt: vnLocal(new Date(t.createdAt)), duplicate: Boolean(dup) }); + } + } const user = auth(); if (path.startsWith("/api/") && !user) return send(401); @@ -449,6 +484,49 @@ export function startMockApi( return (!f || d >= new Date(f)) && (!t || d <= new Date(t)); }; + // #49: nhật ký cửa + if (req.method === "GET" && path === "/api/admin/door-logs") { + const P = url.searchParams, f = P.get("facilityId"), no = (P.get("unitNumber") || "").trim().toLowerCase(), r = P.get("result"), from = P.get("from"), to = P.get("to"); + const rows = [...S.accessLogs].reverse().map((l) => { + const u = l.unitNumber && unitByNumber(l.unitNumber); const cc = l.contractId && S.contracts.find((x) => x.contractId === l.contractId); + return { logId: l.logId, at: vnLocal(l.at), facilityId: u?.facilityId || null, facilityName: u ? fac(u.facilityId)?.name : null, unitNumber: l.unitNumber, customerName: cc ? S.users.find((x) => x.userId === cc.customerId)?.fullName : null, contractCode: cc ? codeOf(cc) : null, result: l.result, method: l.method || null, reason: l.reason || null }; + }).filter((x) => (!f || x.facilityId === Number(f)) && (!no || String(x.unitNumber || "").toLowerCase().includes(no)) && (!r || x.result === r) && (!from || x.at.slice(0, 10) >= from) && (!to || x.at.slice(0, 10) <= to)) + .map(({ facilityId, ...x }) => x); + return send(200, page(rows)); + } + // Lượt 6 · #45 #54: công cụ demo ngày & giá + const running = (c) => { const t = dateOnly(new Date()); if (c.status !== "ACTIVE") return c.status; if (c.endDate <= t) return "OVERDUE"; return (new Date(c.endDate) - new Date(t)) / 864e5 <= 14 ? "EXPIRING" : "ACTIVE"; }; + const overdueDays = (c) => { const t = dateOnly(new Date()); return c.status === "ACTIVE" && c.endDate <= t ? Math.round((new Date(t) - new Date(c.endDate)) / 864e5) : 0; }; + const demoDto = (c) => { const u = unit(c.unitId); return { contractId: c.contractId, contractCode: `HĐ-${c.startDate.slice(0, 4)}-${String(c.contractId).padStart(4, "0")}`, customerName: S.users.find((x) => x.userId === c.customerId)?.fullName, unitNumber: u.unitNumber, facilityName: fac(u.facilityId)?.name, startDate: c.startDate, endDate: c.endDate, agreedMonthlyRate: c.agreedMonthlyRate ?? c.monthlyRate ?? 0, depositAmount: c.depositAmount ?? 0, status: running(c), overdueDays: overdueDays(c), payments: S.payments.filter((p) => p.contractId === c.contractId).map((p) => ({ paymentId: p.paymentId, paymentType: p.paymentType, status: p.status, amount: p.amount, paidAt: p.paidAt ? dbTime(p.paidAt) : null, dueDate: p.dueDate || null })) }; }; + if (req.method === "GET" && path === "/api/admin/demo/contracts") { + const q = (url.searchParams.get("search") || "").toLowerCase(); + return send(200, S.contracts.map(demoDto).filter((d) => !q || [d.contractCode, d.customerName, d.unitNumber].some((x) => String(x).toLowerCase().includes(q)))); + } + if (req.method === "PUT" && (m = path.match(/^\/api\/admin\/demo\/contracts\/(\d+)$/))) { + const c = S.contracts.find((x) => x.contractId === +m[1]); + if (!c) return msg(404, "Không tìm thấy hợp đồng."); + if (!body.startDate || !body.endDate || body.endDate <= body.startDate) return msg(400, "Ngày hết hạn phải sau ngày bắt đầu."); + const before = demoDto(c), changes = []; + if (c.startDate !== body.startDate) changes.push({ field: "Ngày bắt đầu", before: c.startDate, after: body.startDate }); + if (c.endDate !== body.endDate) changes.push({ field: "Ngày hết hạn", before: c.endDate, after: body.endDate }); + c.startDate = body.startDate; c.endDate = body.endDate; + if (body.agreedMonthlyRate != null) { changes.push({ field: "Giá thuê / tháng", before: String(before.agreedMonthlyRate), after: String(body.agreedMonthlyRate) }); c.agreedMonthlyRate = body.agreedMonthlyRate; } + const after = demoDto(c); + if (before.status !== after.status) changes.push({ field: "Trạng thái", before: before.status, after: after.status }); + log("DEMO_CONTRACT_EDITED", "CONTRACT", c.contractId, before, { ...after, reason: body.reason || null }); + return send(200, { target: after.contractCode, changes, contract: after }); + } + if (req.method === "PUT" && (m = path.match(/^\/api\/admin\/demo\/payments\/(\d+)$/))) { + const p = S.payments.find((x) => x.paymentId === +m[1]); + if (!p) return msg(404, "Không tìm thấy giao dịch."); + const changes = []; + if (body.paidAt) { if (!p.paidAt) return msg(400, "Giao dịch chưa thanh toán nên không chỉnh được ngày thanh toán."); changes.push({ field: "Ngày thanh toán", before: dbTime(p.paidAt), after: body.paidAt }); p.paidAt = new Date(`${body.paidAt}+07:00`); } + if (body.amount != null) { if (!(body.amount > 0)) return msg(400, "Số tiền phải lớn hơn 0."); changes.push({ field: "Số tiền", before: String(p.amount), after: String(body.amount) }); p.amount = body.amount; } + if (!changes.length) return msg(400, "Chưa có thay đổi."); + log("DEMO_PAYMENT_EDITED", "PAYMENT", p.paymentId, null, { changes, reason: body.reason || null }); + return send(200, { target: `TT-${String(p.paymentId).padStart(4, "0")}`, changes, contract: demoDto(S.contracts.find((c) => c.contractId === p.contractId)) }); + } + if (req.method === "GET" && path === "/api/admin/dashboard/stats") { const active = S.users.filter((u) => u.status === "ACTIVE").length; const usersByRole = Object.fromEntries(S.roles.map((r) => [r.roleName, S.userRoles.filter((x) => x.roleId === r.roleId).length]).filter(([, n]) => n)); @@ -576,13 +654,15 @@ export function startMockApi( if (req.method === "GET" && path === "/api/admin/logs/login-history") { const list = [...S.loginHistory].filter((h) => inRange(h.loginAt)).sort((a, b) => b.loginAt - a.loginAt).map((h) => { const u = S.users.find((x) => x.userId === h.userId); - return { ...h, username: u.username, fullName: u.fullName, loginAt: dbTime(h.loginAt), logoutAt: h.logoutAt ? dbTime(h.logoutAt) : null }; + const show = roleNamesOf(h.userId).some((r) => r !== "CUSTOMER"); // Lượt 6b: như BE, không trả IP/thiết bị của khách + return { ...h, username: u.username, fullName: u.fullName, loginAt: dbTime(h.loginAt), logoutAt: h.logoutAt ? dbTime(h.logoutAt) : null, ipAddress: show ? h.ipAddress : null, deviceInfo: show ? h.deviceInfo : null }; }); return send(200, page(list)); } if (req.method === "GET" && path === "/api/admin/logs/activity-logs") { const action = url.searchParams.get("action"); - const list = [...S.activityLogs].filter((l) => inRange(l.loggedAt) && (!action || l.action === action)).sort((a, b) => b.loggedAt - a.loggedAt).map(logDto); + const list = [...S.activityLogs].filter((l) => inRange(l.loggedAt) && (!action || l.action === action)).sort((a, b) => b.loggedAt - a.loggedAt).map(logDto) + .map((l) => (l.userId && !roleNamesOf(l.userId).some((r) => r !== "CUSTOMER") ? { ...l, ipAddress: null } : l)); return send(200, page(list)); } return send(404, { message: "Not found" }); @@ -602,7 +682,7 @@ export function startMockApi( const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." }); const c = S.contracts.find((x) => x.reservationId === r.reservationId); - return send(200, { ...resDto(r), checkInAppointmentAt: null, assignedUnitNumber: c ? unit(c.unitId).unitNumber : null, contractId: c?.contractId ?? null, contractStatus: c?.status ?? null }); + return send(200, { ...resDto(r), checkInAppointmentAt: null, assignedUnitNumber: c ? unit(c.unitId).unitNumber : null, proposedUnitNumber: !c && r.proposedUnitId ? unit(r.proposedUnitId).unitNumber : null, contractId: c?.contractId ?? null, contractStatus: c?.status ?? null }); } if (req.method === "POST" && path === "/api/reservations") { if (body.rentalPeriodMonths <= 0) return bad("Thời hạn thuê phải lớn hơn 0 tháng."); @@ -612,9 +692,14 @@ export function startMockApi( const rate = S.rates.find((r) => r.facilityId === body.facilityId && r.unitTypeId === body.unitTypeId); if (!rate) return bad("Chưa có bảng giá áp dụng cho cơ sở và loại kho này."); if (availability(body.facilityId, body.unitTypeId, body.startDate, body.rentalPeriodMonths) <= 0) return bad("Hiện tại đã hết kho trống cho loại kho và khoảng thời gian yêu cầu."); - const r = { reservationId: S.reservations.length + 1, customerId: me, facilityId: body.facilityId, unitTypeId: body.unitTypeId, startDate: body.startDate, expectedEndDate: addMonths(body.startDate, body.rentalPeriodMonths), rentalPeriodMonths: body.rentalPeriodMonths, quotedMonthlyRate: rate.monthlyRate, estimatedAmount: rate.monthlyRate * body.rentalPeriodMonths, requiredDeposit: rate.monthlyRate, status: "PENDING_PAYMENT", createdAt: new Date(), expiresAt: new Date(Date.now() + 24 * 3600000), cancelledAt: null, cancellationReason: null }; + // #2: giống BE UnitProposal — ô AVAILABLE đầu tiên theo mã, bỏ qua ô đã bố trí cho đơn khác còn hiệu lực trùng kỳ + const endDate = addMonths(body.startDate, body.rentalPeriodMonths); + const heldUnits = new Set(S.reservations.filter((x) => x.facilityId === body.facilityId && x.unitTypeId === body.unitTypeId && x.proposedUnitId && ["PENDING_PAYMENT", "PENDING_VERIFICATION", "CONFIRMED"].includes(x.status) && x.startDate < endDate && x.expectedEndDate > body.startDate).map((x) => x.proposedUnitId)); + const proposed = S.units.filter((u) => u.facilityId === body.facilityId && u.unitTypeId === body.unitTypeId && u.status === "AVAILABLE" && !heldUnits.has(u.unitId)).sort((a, b) => a.unitNumber.localeCompare(b.unitNumber))[0]; + if (!proposed) return bad("Hiện tại đã hết kho trống cho loại kho và khoảng thời gian yêu cầu."); + const r = { reservationId: S.reservations.length + 1, proposedUnitId: proposed.unitId, customerId: me, facilityId: body.facilityId, unitTypeId: body.unitTypeId, startDate: body.startDate, expectedEndDate: endDate, rentalPeriodMonths: body.rentalPeriodMonths, quotedMonthlyRate: rate.monthlyRate, estimatedAmount: rate.monthlyRate * body.rentalPeriodMonths, requiredDeposit: rate.monthlyRate, status: "PENDING_PAYMENT", createdAt: new Date(), expiresAt: new Date(Date.now() + 24 * 3600000), cancelledAt: null, cancellationReason: null }; S.reservations.push(r); - return send(201, { ...resDto(r), createdAt: iso(r.createdAt), expiresAt: iso(r.expiresAt) }); + return send(201, { ...resDto(r), createdAt: iso(r.createdAt), expiresAt: iso(r.expiresAt), proposedUnitNumber: proposed.unitNumber }); } if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/confirm-transfer$/))) { // Giống ReservationService.ConfirmTransferAsync: PENDING_PAYMENT → PENDING_VERIFICATION; quá hạn giữ chỗ → 400 code EXPIRED @@ -731,7 +816,15 @@ export function startMockApi( if (c.status !== "ACTIVE") return bad("QR mở cửa chỉ dùng được sau khi nhận kho và khi hợp đồng còn hiệu lực."); const u = unit(c.unitId); const a = accessCode(c); - return send(200, { contractId: c.contractId, code: a.code, backupCode: a.backup, unitNumber: u.unitNumber, unitType: ut(u.unitTypeId).climateControlled ? "Kho lạnh" : "Kho thường", location: null, validUntil: c.endDate, validFrom: c.startDate }); + return send(200, { contractId: c.contractId, code: a.code, backupCode: a.backup, unitNumber: u.unitNumber, unitType: ut(u.unitTypeId).climateControlled ? "Kho lạnh" : "Kho thường", location: null, validUntil: c.endDate, validFrom: c.startDate, usableNow: c.startDate <= dateOnly(new Date()), usableFrom: c.startDate <= dateOnly(new Date()) ? null : c.startDate }); + } + // Lượt 6 · #48–51: trạng thái cửa và đóng cửa từ ứng dụng + if ((m = path.match(/^\/api\/contracts\/(\d+)\/door(\/close)?$/))) { + const c = S.contracts.find((x) => x.contractId === +m[1] && x.customerId === me); + if (!c) return send(404, { error: "Không tìm thấy hợp đồng." }); + const no = unit(c.unitId).unitNumber; + if (req.method === "GET" && !m[2]) return send(200, doorDto(no)); + if (req.method === "POST" && m[2]) return send(200, closeDoorAt(no, "CLOSE_APP", c.contractId)); } if (req.method === "POST" && (m = path.match(/^\/api\/handovers\/(\d+)\/confirm$/))) { const h = S.handovers.find((x) => x.handoverId === +m[1]); @@ -774,6 +867,22 @@ export function startMockApi( // Giống BE thật (FacilityOpsEndpoints.cs): báo đã hỗ trợ lưu bằng chứng biên bản trả kho và hoàn tiền. return send(200, mapKeys({ ...board, me, inspection_evidence_supported: true, refund_evidence_supported: true }, camel)); } + // Lượt 5 (#58): doanh thu cơ sở theo khoảng tháng, giống GET /api/ops/revenue của BE (tiền đầy đủ theo đồng) + if (req.method === "GET" && path === "/api/ops/revenue") { + if (!isManager) return send(403, { error: "Chỉ quản lý cơ sở được xem báo cáo." }); + const from = (url.searchParams.get("from") || "").slice(0, 7), to = (url.searchParams.get("to") || "").slice(0, 7); + if (!/^\d{4}-\d{2}$/.test(from) || !/^\d{4}-\d{2}$/.test(to) || from > to) return bad("Tháng bắt đầu phải trước hoặc bằng tháng kết thúc."); + const known = new Map((O.revenue?.months || []).map((m) => [`${m.year}-${String(m.month).padStart(2, "0")}`, m.value])); + const months = []; let [y, mo] = from.split("-").map(Number); + while (`${y}-${String(mo).padStart(2, "0")}` <= to && months.length < 24) { + const key = `${y}-${String(mo).padStart(2, "0")}`, idx = y * 12 + mo; + const value = known.has(key) ? known.get(key) : key > dateOnly(new Date()).slice(0, 7) ? 0 : 9_000_000 + ((idx * 37) % 11) * 400_000; + months.push({ label: `Tháng ${mo}`, month: mo, year: y, value }); + mo++; if (mo > 12) { mo = 1; y++; } + } + const sum = months.reduce((a, m) => a + m.value, 0); + return send(200, { months, byType: [{ label: "Kho thường", value: Math.round(sum * 0.67) }, { label: "Kho lạnh", value: sum - Math.round(sum * 0.67) }], asOf: dateOnly(new Date()), forfeitedRefunds: 0 }); + } for (const [method, re, role, type, toPayload] of OPS_ROUTES) { const hit = req.method === method && path.match(re); if (!hit) continue; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs index 2612e0d..4592433 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs @@ -195,15 +195,29 @@ export function handleBusiness({ req, res, path, url, body, S, me, send }) { } // ---- Báo cáo + // Lượt 5 (#58): doanh thu mô phỏng theo cơ sở × tháng để các biểu đồ / bảng / file xuất cùng một nguồn và khớp nhau. + const ymList = (from, to) => { const out = []; let [y, m] = from.slice(0, 7).split("-").map(Number); const [ty, tm] = to.slice(0, 7).split("-").map(Number); while (y * 12 + m <= ty * 12 + tm && out.length < 36) { out.push(`${y}-${String(m).padStart(2, "0")}`); m++; if (m > 12) { m = 1; y++; } } return out; }; + const synth = (facilityId, unitTypeId, ym) => { + if (ym > today.slice(0, 7)) return 0; + const f = S.facilities.find((x) => x.facilityId === facilityId); if (!f || f.status !== "ACTIVE") return 0; + const ids = S.facilities.map((x) => x.facilityId).sort((a, b) => a - b); const rank = ids.indexOf(facilityId); + if (rank === ids.length - 1) return 0; // cơ sở cuối chưa có doanh thu → kiểm tra hiển thị 0 đ + const [y, m] = ym.split("-").map(Number), t = (y - 2025) * 12 + m; + const base = 4_200_000 - rank * 300_000, season = 1 + 0.04 * t + (m % 3 === 0 ? -0.06 : 0.03); + const share = unitTypeId ? (unitTypeId % 2 ? 0.62 : 0.38) : 1; + return Math.max(0, Math.round((base * season * share) / 10_000) * 10_000); + }; + const synthSum = (facilityId, unitTypeId, from, to) => ymList(from, to).reduce((s, ym) => s + synth(facilityId, unitTypeId, ym), 0); const snapshotAt = dbTime(new Date()); if (req.method === "GET" && path === "/api/operations/reports/facilities") { const fl = filter(); const rows = S.facilities.filter((f) => !fl.facilityId || f.facilityId === fl.facilityId).map((f) => { const s = scoped(f.facilityId, fl.unitTypeId); - return { facilityId: f.facilityId, facilityName: f.name, facilityStatus: f.status, metrics: metrics(s.units, s.contracts, s.payments) }; + return { facilityId: f.facilityId, facilityName: f.name, facilityStatus: f.status, metrics: { ...metrics(s.units, s.contracts, s.payments), rentalAndFeeRevenue: synthSum(f.facilityId, fl.unitTypeId, fl.from, fl.to) } }; }); const all = scoped(fl.facilityId, fl.unitTypeId); - return send(200, { filter: fl, snapshotAt, totals: metrics(all.units, all.contracts, all.payments), facilities: rows }), true; + const totals = { ...metrics(all.units, all.contracts, all.payments), rentalAndFeeRevenue: rows.reduce((a, r) => a + r.metrics.rentalAndFeeRevenue, 0) }; + return send(200, { filter: fl, snapshotAt, totals, facilities: rows }), true; } if (req.method === "GET" && (m = path.match(/^\/api\/operations\/reports\/facilities\/(\d+)\/contracts$/))) { const facilityId = +m[1]; @@ -229,14 +243,17 @@ export function handleBusiness({ req, res, path, url, body, S, me, send }) { return send(200, { filter: fl, snapshotAt, totals: metrics(all.units, all.contracts, all.payments), unitTypes: rows }), true; } if (req.method === "GET" && path === "/api/operations/reports/revenue-trend") { - const n = num("months") || 6; - const [y, mo] = today.split("-").map(Number); - const months = Array.from({ length: n }, (_, i) => { - const d = new Date(Date.UTC(y, mo - n + i, 1)); - const base = i === n - 1 ? 3000000 : 0; - return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, label: `${pad(d.getUTCMonth() + 1)}/${d.getUTCFullYear()}`, collected: base * 1.5, refunded: 0, rentalAndFeeRevenue: base, depositCollected: base / 2 }; + const fid = num("facilityId"), tid = num("unitTypeId"); + let from = url.searchParams.get("from"), to = url.searchParams.get("to"); + if (!from || !to) { const n = num("months") || 6; const [y, mo] = today.split("-").map(Number); const d = new Date(Date.UTC(y, mo - n, 1)); from = d.toISOString().slice(0, 10); to = today; } + if (from.slice(0, 7) > to.slice(0, 7)) return send(400, { error: "Tháng bắt đầu phải trước hoặc bằng tháng kết thúc." }), true; + const fids = S.facilities.filter((f) => !fid || f.facilityId === fid).map((f) => f.facilityId); + const months = ymList(from, to).map((ym) => { + const revenue = fids.reduce((a, id) => a + synth(id, tid, ym), 0); + const [yy, mm] = ym.split("-").map(Number); + return { year: yy, month: mm, label: `Tháng ${mm}/${yy}`, collected: Math.round(revenue * 1.25), refunded: Math.round(revenue * 0.04), rentalAndFeeRevenue: revenue, depositCollected: Math.round(revenue * 0.25) }; }); - return send(200, { facilityId: num("facilityId"), unitTypeId: null, snapshotAt, months }), true; + return send(200, { facilityId: fid, unitTypeId: tid, snapshotAt, months }), true; } if (req.method === "GET" && path === "/api/operations/reports/rental-status") { const s = scoped(num("facilityId")); @@ -252,7 +269,7 @@ export function handleBusiness({ req, res, path, url, body, S, me, send }) { rows.push(['Cơ sở', 'Doanh thu', 'Tỷ lệ lấp đầy', 'Kho quá hạn']); for (const f of S.facilities.filter(f => !fl.facilityId || f.facilityId === fl.facilityId)) { const s = scoped(f.facilityId, fl.unitTypeId), m = metrics(s.units, s.contracts, s.payments); - rows.push([f.name, m.rentalAndFeeRevenue, m.occupancyRate, m.overdueUnits]); + rows.push([f.name, synthSum(f.facilityId, fl.unitTypeId, fl.from, fl.to), m.occupancyRate, m.overdueUnits]); } } else if (view === 'unit-types') { rows.push(['Loại kho', 'Doanh thu', 'Tỷ lệ lấp đầy', 'Kho quá hạn']); @@ -262,9 +279,9 @@ export function handleBusiness({ req, res, path, url, body, S, me, send }) { } } else if (view === 'revenue-trend') { rows.push(['Tháng', 'Đã thu', 'Hoàn', 'Thuê và phí', 'Tiền cọc']); - for (let d = new Date(fl.from.slice(0, 7) + '-01T00:00:00Z'); d.toISOString().slice(0, 10) <= fl.to; d.setUTCMonth(d.getUTCMonth() + 1)) { - const current = d.toISOString().slice(0, 7) === today.slice(0, 7), revenue = current ? 3000000 : 0; - rows.push([`${d.getUTCMonth() + 1}/${d.getUTCFullYear()}`, revenue * 1.5, 0, revenue, revenue / 2]); + for (const ym of ymList(fl.from, fl.to)) { + const revenue = S.facilities.filter((f) => !fl.facilityId || f.facilityId === fl.facilityId).reduce((a, f) => a + synth(f.facilityId, fl.unitTypeId, ym), 0); + rows.push([`${ym.slice(5, 7)}/${ym.slice(0, 4)}`, Math.round(revenue * 1.25), Math.round(revenue * 0.04), revenue, Math.round(revenue * 0.25)]); } } else return bad('view không hợp lệ.'); const csv = '\ufeff' + rows.map(row => row.map(v => '"' + String(v ?? '').replaceAll('"', '""') + '"').join(',')).join('\r\n'); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json index a30be0d..79ae3fa 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json @@ -10,7 +10,7 @@ "dev": "vite --host 127.0.0.1", "build": "vite build --base=./", "preview": "vite preview --host 127.0.0.1", - "test": "node --test tests/refund-request.test.js tests/renewal-consent.test.js tests/figma-batch04.test.js tests/reservation-policy.test.js tests/damage-workflow.test.js tests/incident-workflow.test.js tests/settlement-batch08.test.js tests/admin-business-batch09.test.js tests/return-policy.test.js tests/reducer.test.js tests/api-mappers.test.js tests/admin.test.js tests/ops.test.js tests/units.test.js tests/ops-api.test.mjs tests/payment-access.test.js tests/payment-api.test.mjs tests/access.test.js tests/figma-workflow.test.js tests/auth-support-integration.test.js tests/renewal-unit-move.test.js", + "test": "node --test tests/refund-request.test.js tests/renewal-consent.test.js tests/figma-batch04.test.js tests/reservation-policy.test.js tests/damage-workflow.test.js tests/incident-workflow.test.js tests/settlement-batch08.test.js tests/admin-business-batch09.test.js tests/return-policy.test.js tests/reducer.test.js tests/api-mappers.test.js tests/admin.test.js tests/ops.test.js tests/units.test.js tests/ops-api.test.mjs tests/payment-access.test.js tests/payment-api.test.mjs tests/access.test.js tests/figma-workflow.test.js tests/auth-support-integration.test.js tests/renewal-unit-move.test.js tests/luot1-ui.test.js tests/luot2-settlement.test.js tests/luot3-renewal.test.js tests/luot4-units.test.js tests/luot4b-nav.test.js tests/luot5-reports.test.js tests/luot6-door-demo.test.mjs", "test:render": "node tests/render.test.mjs", "dev:mock": "node scripts/dev-mock.mjs", "check:structure": "node scripts/check-structure.mjs", diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-workflow-actions.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-workflow-actions.mjs index 20bab5a..8bcf68c 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-workflow-actions.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-workflow-actions.mjs @@ -15,7 +15,7 @@ async function transferNow(){const at=page.getByLabel(/Thời gian chuyển/);aw const passed=[]; await login('manager01','Manager@123');await route('manager/refunds'); const han=page.locator('.record-card').filter({hasText:'Phạm Gia Hân'});await han.getByRole('button',{name:'Xem yêu cầu hoàn tiền'}).click();assert.match(await page.getByRole('dialog').innerText(),/2.166.000/);await page.getByRole('button',{name:'Đóng chi tiết',exact:true}).click(); -await han.getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).click();await page.getByRole('dialog').getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).click();assert.match(await page.getByRole('dialog').innerText(),/Nhập mã giao dịch/);await page.getByLabel('Mã giao dịch hoàn tiền').fill('QA-REF-0139');await transferNow();await page.getByLabel('Đã chuyển đúng số tiền vào đúng tài khoản chính chủ').check();await page.getByRole('dialog').getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).click();await page.locator('.modal--success').getByRole('button',{name:'Về yêu cầu hoàn',exact:true}).click();await page.waitForTimeout(200);assert.equal(await han.getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).count(),0);passed.push('Đúng khách / bắt buộc mã giao dịch, thời gian chuyển, xác nhận chính chủ / không xác nhận hoàn hai lần'); +await han.getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).click();await page.getByRole('dialog').getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).click();assert.match(await page.getByRole('dialog').innerText(),/Nhập mã giao dịch/);await page.getByLabel('Mã giao dịch hoàn tiền').fill('QA-REF-0139');await transferNow();await page.getByLabel('Đã chuyển đúng số tiền vào đúng tài khoản nhận hoàn').check();await page.getByRole('dialog').getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).click();await page.locator('.modal--success').getByRole('button',{name:'Về yêu cầu hoàn',exact:true}).click();await page.waitForTimeout(200);assert.equal(await han.getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).count(),0);passed.push('Đúng khách / bắt buộc mã giao dịch, thời gian chuyển, xác nhận chính chủ / không xác nhận hoàn hai lần'); await route('manager/deposit-refunds');await page.getByRole('button',{name:'Xem khoản hoàn'}).click();await page.getByLabel(/Mã giao dịch/).fill('QA-DEPOSIT-0098');await transferNow();await page.getByLabel('Tôi đã chuyển đúng số tiền vào đúng tài khoản nhận').check();await page.getByRole('button',{name:'Ghi nhận đã chuyển tiền'}).click();await confirm();assert.equal(await page.getByRole('button',{name:'Ghi nhận đã chuyển tiền'}).count(),0);passed.push('Hoàn cọc độc lập và chặn xác nhận lại'); await login('customer01','Customer@123');await route('refunds');assert.match(await page.locator('main').innerText(),/Đã hoàn · 662\.500 đ/);passed.push('Khách nhìn thấy kết quả hoàn cọc sau khi quản lý xác nhận');await route('inquiries/HT-0091');await page.getByRole('button',{name:'Kiểm tra & gửi phản hồi'}).click();assert.match(await page.locator('main').innerText(),/Vui lòng nhập nội dung/);await page.getByLabel('Nội dung phản hồi').fill('Tôi cần kho cho 10 thùng đồ trong 3 tháng.');await page.getByRole('button',{name:'Kiểm tra & gửi phản hồi'}).click();await confirm();passed.push('Phản hồi khách: dữ liệu trống và gửi thành công'); await login('staff01','Staff@123');await route('staff/inquiries');await page.getByRole('button',{name:'Xem yêu cầu',exact:true}).click();assert.match(await page.locator('main').innerText(),/Tôi cần kho cho 10 thùng đồ/);passed.push('Nhân viên nhận đúng phản hồi của khách qua dữ liệu demo chung'); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/geo.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/geo.js index 541ed32..01c7aae 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/geo.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/geo.js @@ -19,6 +19,12 @@ const BY_NAME = [ // Trung tâm TP.HCM, dùng khi cơ sở chưa có toạ độ export const HCMC_CENTER = [10.7769, 106.7009]; +/** Cơ sở có vị trí thật để ghim lên bản đồ (toạ độ nhập ở Vận hành KD hoặc vị trí đã biết theo tên). */ +export function hasMapCoords(facility) { + if (facility?.lat != null && facility?.lng != null) return true; + return BY_NAME.some(([key]) => (facility?.name || "").includes(key)); +} + export function coordsOf(facility) { if (facility?.lat != null && facility?.lng != null) return [Number(facility.lat), Number(facility.lng)]; const hit = BY_NAME.find(([key]) => (facility?.name || "").includes(key)); 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 09c61bf..2d0e890 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 @@ -18,7 +18,8 @@ import { readPhotoData, verifyPhotoFile } from "../../shared/utils/refundRequest import { submitRenewalWithConsent } from "../../shared/api/renewalConsentApi.js"; import { api } from "../../shared/api/customerApi.js"; import { ApiError, setToken } from "../../shared/api/httpClient.js"; -import { isUnsupported, localAccessCode, normAccess, normCancelPreview, normPayos, normScan } from "../../features/customer/access/accessApi.js"; +import { isUnsupported, localAccessCode, normAccess, normCancelPreview, normDoor, normPayos, normScan } from "../../features/customer/access/accessApi.js"; +import { notYetMessage } from "../../shared/utils/access.js"; import { bankAccount } from "../config/payment.js"; import { vietQrPayload } from "../../shared/utils/vietqr.js"; import { composeData, emptyOverlay, mapCatalog, reservationCode, reservationsToExpire, ticketCode } from "../../shared/api/apiMappers.js"; @@ -224,7 +225,20 @@ function LocalProvider({ children }) { async accessQr(contract) { if (ref.current.data.returns.some(r => r.contract_id === contract.contract_id && !["CANCELLED", "REJECTED"].includes(r.status))) return { ok: false, error: "QR đã hết hiệu lực do đã gửi trả kho." }; if (contract.access_issued === false || ["DRAFT", "ENDED"].includes(contract.status)) return { ok: false, error: "QR mở cửa chỉ được cấp khi hợp đồng đã được xác nhận." }; - return { ok: true, access: localAccessCode(contract) }; + const access = localAccessCode(contract); + return { ok: true, access: { ...access, usable_now: localDate(new Date()) >= String(contract.start_date).slice(0, 10) } }; + }, + // Lượt 6 · D51: cửa mô phỏng trên trình duyệt (không có máy chủ) — mở khi quét hợp lệ, giữ mở tới khi bấm Đóng cửa + async doorState(contract) { + let doors; try { doors = JSON.parse(localStorage.getItem("safespace.doors") || "{}"); } catch { doors = {}; } + const d = doors[contract.contract_id]; return { ok: true, door: { unit: contract.unit_number, door: d?.door === "OPEN" ? "OPEN" : "LOCKED", at: d?.at || null, changed: false } }; + }, + async closeDoor(contract) { + let doors; try { doors = JSON.parse(localStorage.getItem("safespace.doors") || "{}"); } catch { doors = {}; } + const open = doors[contract.contract_id]?.door === "OPEN", at = new Date().toISOString(); + doors[contract.contract_id] = { door: "LOCKED", at: open ? at : doors[contract.contract_id]?.at || null }; + try { localStorage.setItem("safespace.doors", JSON.stringify(doors)); } catch { /* bộ nhớ trình duyệt bị chặn */ } + return { ok: true, door: { unit: contract.unit_number, door: "LOCKED", at: doors[contract.contract_id].at, changed: open } }; }, async scan(code, unit) { const d = ref.current.data; @@ -237,8 +251,10 @@ function LocalProvider({ children }) { if (!c) return { ok: true, scan: { result: "DENIED", unit: null, customer: null, contract: null, at: now, reason: "Mã không đúng. Kiểm tra lại mã trên ứng dụng hoặc mã dự phòng." } }; if (d.returns.some(r => r.contract_id === c.contract_id && !["CANCELLED", "REJECTED"].includes(r.status))) return { ok: true, scan: { result: "DENIED", at: now, reason: "QR đã hết hiệu lực do đã gửi trả kho." } }; if (c.status === "ENDED") return { ok: true, scan: { result: "DENIED", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: "Mã đã hết hiệu lực — hợp đồng đã trả kho." } }; - if (c.access_issued === false || c.start_date > localDate(new Date())) return { ok: true, scan: { result: "DENIED", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: "Chưa đến ngày bắt đầu hợp đồng hoặc mã chưa được cấp." } }; + if (c.access_issued === false) return { ok: true, scan: { result: "DENIED", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: "Mã ra vào chưa được cấp." } }; + if (c.start_date > localDate(new Date())) return { ok: true, scan: { result: "DENIED", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: notYetMessage(c.start_date) } }; if (c.end_date <= localDate(new Date())) return { ok: true, scan: { result: "DENIED", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: "Hợp đồng đã quá hạn. Vui lòng gia hạn hoặc liên hệ cơ sở." } }; + try { const doors = JSON.parse(localStorage.getItem("safespace.doors") || "{}"); doors[c.contract_id] = { door: "OPEN", at: now }; localStorage.setItem("safespace.doors", JSON.stringify(doors)); } catch { /* bộ nhớ trình duyệt bị chặn */ } return { ok: true, scan: { result: "OPEN", unit: c.unit_number, customer: d.user.full_name, contract: c.contract_id, at: now, reason: null } }; }, async cancelPreview(r) { @@ -857,6 +873,8 @@ function ApiProvider({ children }) { return access ? { ok: true, access } : fail("Máy chủ chưa trả mã mở cửa."); }), scan: (code, unit) => guard(async () => ({ ok: true, scan: normScan(await api.scanAccess({ code: String(code || "").trim(), unitNumber: unit || null })) })), + doorState: (contract) => guard(async () => ({ ok: true, door: normDoor(await api.doorState(contract.api_id)) })), + closeDoor: (contract) => guard(async () => ({ ok: true, door: normDoor(await api.closeDoor(contract.api_id)) })), cancelPreview: (r) => guard(async () => { const preview = normCancelPreview(await api.cancelPreview(r.api_id)); 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 d7d4e32..8e88244 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 @@ -11,6 +11,7 @@ import { requireRentalPolicy } from "../../shared/utils/rentalPolicy.js"; import { storedRefundChoice, validateRefundChoice } from "../../shared/utils/refundRequest.js"; import { isReturnFee, NO_RETURN_COLLECTION } from "../../shared/utils/returnPolicy.js"; import { RENTAL_PLANS, SIZE_BANDS, offerByKey, quote } from "../../shared/utils/catalog.js"; +import { unitsFor } from "../../shared/utils/units.js"; import { addDays, addMonths, @@ -88,6 +89,16 @@ 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 (shared/utils/policy.js). Chế độ API lấy từ GET /api/reservations/{id}/cancel-preview. +/** #2 · Mô phỏng: chọn ô đầu tiên khả dụng cả kỳ (theo thứ tự mã ô), bỏ qua ô đã bố trí cho đơn khác còn hiệu lực trùng kỳ. */ +export function proposeUnit(state, facility, offer, start, end) { + const held = new Set((state.reservations || []) + .filter(r => r.facility_id === facility.facility_id && r.unit_code && ["PENDING_PAYMENT", "PENDING_VERIFICATION", "CONFIRMED"].includes(r.status) && r.start_date < end && r.end_date > start) + .map(r => r.unit_code)); + const busy = new Set((state.contracts || []).filter(c => c.facility_id === facility.facility_id && c.status !== "ENDED" && c.start_date < end && c.end_date > start).map(c => c.unit_number)); + const unit = unitsFor(facility).find(u => u.offer_key === offer.key && u.bookable_for_period && !held.has(u.code) && !busy.has(u.code)); + return unit?.code || null; +} + export function cancelPreviewOf(r) { const paid = r.initial_total || 0; const fee = Math.round((r.deposit || 0) * CANCEL_DEPOSIT_FEE_RATE); @@ -129,6 +140,9 @@ const handlers = { if (dup) return { state, result: { reservation_id: dup.reservation_id } }; const q = quote({ offer, months, start_date: p.start_date }); + // #2: hệ thống tự bố trí ô khả dụng cả kỳ, không trùng ô đã bố trí cho đơn khác còn hiệu lực cùng kỳ. + const unit_code = proposeUnit(state, facility, offer, p.start_date, q.end_date); + if (!unit_code) fail("Không có ô phù hợp nào trống trong toàn bộ kỳ thuê tại cơ sở này. Đổi ngày bắt đầu, diện tích hoặc cơ sở để hệ thống tìm lại.", "NO_UNIT"); const reservation_id = newReservationId(state, ctx.now); const timeout = ctx.timeoutSeconds; const reservation = { @@ -138,7 +152,8 @@ const handlers = { band: offer.band, offer_key: offer.key, size_label: offer.size_label, - unit_code: p.unit_code || null, // ô khách chọn trên sơ đồ (quản lý phân bổ chính thức ở M05) + unit_code, // #2: ô hệ thống bố trí; khách không phải chọn trên sơ đồ + unit_assigned: false, months, start_date: p.start_date, end_date: q.end_date, @@ -216,7 +231,9 @@ const handlers = { CHOOSE_RENEWAL_AT_COUNTER(state, { renewal_id }) { const r = state.renewals.find(x => x.renewal_id === renewal_id); if (!r || r.status !== "APPROVED") fail("Yêu cầu chưa được duyệt hoặc đã được thanh toán."); - return { state: { ...state, renewals: state.renewals.map(x => x === r ? { ...x, at_counter: true } : x) }, result: { renewal_id } }; + // #28: dòng sổ thu tương ứng chuyển "Chờ thu tại quầy", không còn trả bằng QR. + const ledger = state.ledger.map(l => l.kind === "RENEWAL" && l.contract_id === r.contract_id && l.period?.to === r.new_end && l.status === "UNPAID" ? { ...l, status: "AT_COUNTER", payable: false, method: "CASH" } : l); + return { state: { ...state, ledger, renewals: state.renewals.map(x => x === r ? { ...x, at_counter: true } : x) }, result: { renewal_id } }; }, CHOOSE_FEE_AT_COUNTER() { fail(NO_RETURN_COLLECTION); }, PAYOS_PAID(state, p, ctx) { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx index 5a32554..8c45ddd 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx @@ -8,6 +8,7 @@ * 2. Thêm tài khoản mới (admin/new) * 3. Cấu hình phân quyền (admin/permissions) * 4. Nhật ký hoạt động & đăng nhập (admin/logs) + * 5. Công cụ demo (admin/demo): máy quét, chỉnh giá, chỉnh ngày hợp đồng, nhật ký cửa * - Menu quản trị (UserMenu): Xem thông tin tài khoản đăng nhập hiện tại và nút đăng xuất. */ @@ -23,6 +24,7 @@ const TABS = [ ["new", "Thêm tài khoản"], ["permissions", "Quyền truy cập"], ["logs", "Nhật ký hoạt động"], + ["demo", "Công cụ demo"], // Lượt 6 · trang thẻ chọn: Máy quét, Chỉnh giá, Chỉnh ngày hợp đồng, Nhật ký cửa (Figma A-DEMO) ]; function UserMenu() { @@ -49,11 +51,12 @@ function UserMenu() { {/* Menu thả xuống */} {open && (
-

- {user?.username} -
- {user?.email} -

+ {/* #7: mỗi thông tin một dòng, không gộp tên đăng nhập và email vào cùng một dòng; Vận hành KD không gắn cơ sở nào */} +
+ {user?.full_name || user?.username} + Quản trị + {user?.email && {user.email}} +
{/* Nút Đăng xuất: gọi logout từ context và điều hướng về trang đăng nhập */}
+ ; +} + +export default function ContractToolPage({ mode = "dates" }) { + const { user, onApiError } = useApp(); + const dates = mode === "dates"; + const now = today(); + const [search, setSearch] = useState(""), [list, setList] = useState({ loading: true, error: "", rows: [] }); + const [selectedId, setSelectedId] = useState(null); + const [form, setForm] = useState({ start: "", end: "", rate: "", reason: "" }); + const [confirm, setConfirm] = useState(false), [busy, setBusy] = useState(false), [error, setError] = useState(""); + const [result, setResult] = useState(null), [payment, setPayment] = useState(null), [history, setHistory] = useState([]); + const seq = useRef(0), guard = useRef(false); + + const load = async (q = search) => { + const n = ++seq.current; + setList((s) => ({ ...s, loading: true, error: "" })); + try { + const rows = await adminApi.demoContracts(q.trim() || undefined); + if (n !== seq.current) return; + const safe = Array.isArray(rows) ? rows : []; + setList({ loading: false, error: "", rows: safe }); + setSelectedId((id) => (safe.some((r) => r.contractId === id) ? id : safe[0]?.contractId ?? null)); + } catch (e) { if (n === seq.current) { setList({ loading: false, error: e.message || "Không tải được danh sách hợp đồng.", rows: [] }); onApiError?.(e); } } + }; + useEffect(() => { const t = setTimeout(() => load(search), 250); return () => clearTimeout(t); }, [search]); // eslint-disable-line react-hooks/exhaustive-deps + const c = useMemo(() => list.rows.find((r) => r.contractId === selectedId) || null, [list.rows, selectedId]); + const reset = () => c && setForm({ start: c.startDate, end: c.endDate, rate: String(c.agreedMonthlyRate), reason: "" }); + useEffect(() => { reset(); setError(""); }, [c?.contractId]); // eslint-disable-line react-hooks/exhaustive-deps + + const changed = c && (dates ? form.start !== c.startDate || form.end !== c.endDate : Number(form.rate) !== Number(c.agreedMonthlyRate)); + const ask = () => { + const e = contractFormError(dates ? { ...form, rate: "" } : { start: c.startDate, end: c.endDate, rate: form.rate }); + if (e) return setError(`${e} Dữ liệu đã nhập vẫn được giữ.`); + setError(""); setConfirm(true); + }; + const stamp = () => `${dateTimeLabel(new Date().toISOString())} · ${user?.full_name || "Quản trị"}`; + const applied = (res) => { + setResult(res); + setHistory((h) => [...res.changes.map((x) => ({ text: `${x.field} ${changeText(x.field, x.before)} → ${changeText(x.field, x.after)}`, at: stamp() })), ...h].slice(0, 6)); + setList((s) => ({ ...s, rows: s.rows.map((r) => (r.contractId === res.contract.contractId ? res.contract : r)) })); + }; + const save = async () => { + if (guard.current) return; guard.current = true; setBusy(true); + try { + const body = dates ? { startDate: form.start, endDate: form.end, agreedMonthlyRate: null, reason: form.reason.trim() || null } + : { startDate: c.startDate, endDate: c.endDate, agreedMonthlyRate: Number(form.rate), reason: form.reason.trim() || null }; + const res = await adminApi.demoEditContract(c.contractId, body); + setConfirm(false); applied(res); + } catch (e) { setConfirm(false); setError(`${e.message || "Chưa lưu được."} Dữ liệu đã nhập vẫn được giữ.`); onApiError?.(e); } + finally { guard.current = false; setBusy(false); } + }; + const savePayment = async (body, setDialogError) => { + if (guard.current) return; guard.current = true; setBusy(true); + try { const res = await adminApi.demoEditPayment(payment.paymentId, body); setPayment(null); applied(res); } + catch (e) { setDialogError(`${e.message || "Chưa lưu được."} Dữ liệu đã nhập vẫn được giữ.`); onApiError?.(e); } + finally { guard.current = false; setBusy(false); } + }; + + const days = dates ? overdueDays(form.end, now) : 0; + const confirmRows = !c ? [] : dates + ? [["Ngày bắt đầu", `${dateLabel(c.startDate)} → ${dateLabel(form.start)}`], ["Ngày hết hạn", `${dateLabel(c.endDate)} → ${dateLabel(form.end)}`], ["Sau khi lưu", expectedState(form.start, form.end, now)]] + : [["Giá thuê / tháng", `${money(c.agreedMonthlyRate)} → ${money(Number(form.rate))}`], ["Tiền cọc", `Giữ nguyên ${money(c.depositAmount)}`]]; + + return ( +
+ + {c && {c.contractCode} · {c.customerName}} + +
+
+
+

1 · Chọn hợp đồng

+
+ setSearch(e.target.value)} /> + + + +
+ {list.error && {list.error} } +
+ {!c ? (!list.loading && !list.error &&
) : <> + {dates ? <> +
+

2 · Mô phỏng nhanh

+

Chọn một tình huống, hệ thống điền sẵn ngày bắt đầu và hết hạn.

+
+ {SCENARIOS.map(([key, label, make]) => )} +
+
+
+

3 · Ngày hợp đồng

+
+ { setForm({ ...form, start: e.target.value }); setError(""); }} /> + { setForm({ ...form, end: e.target.value }); setError(""); }} /> +
+
+ : ( +
+

2 · Giá thuê

+
+ { setForm({ ...form, rate: e.target.value.replace(/[^\d]/g, "") }); setError(""); }} /> + +
+
+ )} +
+

{dates ? "4 · Giao dịch đã phát sinh" : "3 · Số tiền giao dịch"}

+ {!c.payments.length ?

Hợp đồng chưa có giao dịch.

: c.payments.map((p) => ( +
+ {payCode(p.paymentId)} · {TYPE[p.paymentType] || p.paymentType} + {money(p.amount)} · {p.paidAt ? `ngày giao dịch ${dateTimeLabel(p.paidAt)}` : p.dueDate ? `chưa thanh toán · hạn ${dateLabel(p.dueDate)}` : "chưa thanh toán"} + +
+ ))} +
+ } +
+ {c && } +
+ {confirm && c && setConfirm(false)} onConfirm={save} />} + {payment && setPayment(null)} />} + {result && [x.field, `${changeText(x.field, x.before)} → ${changeText(x.field, x.after)}`])} + onCancel={() => setResult(null)} onConfirm={() => setResult(null)} />} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DemoShared.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DemoShared.jsx new file mode 100644 index 0000000..bf155d1 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DemoShared.jsx @@ -0,0 +1,12 @@ +/** Lượt 6b · đầu trang chung của các công cụ demo: link quay lại trang thẻ chọn, breadcrumb, tiêu đề, nhãn. */ +import React from "react"; +import { PageHeader } from "../../../shared/components/UI.jsx"; +import { href } from "../../../app/router.js"; + +export function DemoHead({ title, description, children, hub = false }) { + return <> + {!hub && ← Công cụ demo} +

SafeSpace / Quản trị hệ thống / Công cụ demo{hub ? "" : ` / ${title}`}

+ {children} + ; +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DemoToolsPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DemoToolsPage.jsx new file mode 100644 index 0000000..2544fe3 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DemoToolsPage.jsx @@ -0,0 +1,31 @@ +/** + * DEMO TOOLS PAGE - TRANG THẺ CHỌN CÔNG CỤ DEMO (Lượt 6b · Figma A-DEMO) + * Ấn "Công cụ demo" trên thanh menu admin → 4 thẻ: Máy quét, Chỉnh giá, Chỉnh ngày hợp đồng, Nhật ký cửa. + * Không có hàng tab dưới menu; mỗi công cụ là một trang riêng có link "← Công cụ demo". + */ +import React from "react"; +import { Tag } from "../../../shared/components/UI.jsx"; +import { href } from "../../../app/router.js"; +import { DemoHead } from "./DemoShared.jsx"; +import { TOOLS } from "./demoModel.js"; +import "./demo-tools.css"; + +export default function DemoToolsPage() { + return ( +
+ + {TOOLS.length} công cụ + +
+ {TOOLS.map(([key, icon, title, desc, meta, link], i) => ( + + {title} + {desc} + {meta}{link} + + ))} +
+

Mọi thay đổi ở Chỉnh giá và Chỉnh ngày hợp đồng được ghi vào Nhật ký hoạt động kèm giá trị trước/sau và người chỉnh.

+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DoorLogPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DoorLogPage.jsx new file mode 100644 index 0000000..2be05e0 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DoorLogPage.jsx @@ -0,0 +1,67 @@ +/** + * DOOR LOG PAGE - NHẬT KÝ CỬA (Lượt 6b · #49 · Figma A-NK-CỬA) + * Mỗi lần mở, từ chối, đóng cửa là một dòng; lọc theo cơ sở, ô kho, kết quả, khoảng ngày. + * Không hiển thị nguyên mã QR hay PIN (máy chủ không trả về). + */ +import React, { useEffect, useRef, useState } from "react"; +import { adminApi } from "../api/adminApi.js"; +import { Button, Empty, Field, Notice, Tag } from "../../../shared/components/UI.jsx"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { dateLabel, today } from "../../../shared/utils/format.js"; +import { DemoHead } from "./DemoShared.jsx"; +import { DOOR_RESULT, doorLogLine } from "./demoModel.js"; +import "./demo-tools.css"; + +const PAGE_SIZE = 20; + +export default function DoorLogPage() { + const { onApiError } = useApp(); + const [facilities, setFacilities] = useState([]); + const [filter, setFilter] = useState({ facilityId: "", unitNumber: "", result: "", from: today(), to: today() }); + const [page, setPage] = useState(1), [data, setData] = useState({ loading: true, error: "", items: [], total: 0, pages: 1 }); + const seq = useRef(0); + useEffect(() => { adminApi.facilities().then((l) => setFacilities(l || [])).catch(() => setFacilities([])); }, []); + const load = async () => { + const n = ++seq.current; + if (filter.from && filter.to && filter.to < filter.from) return setData((d) => ({ ...d, loading: false, error: "Đến ngày phải sau hoặc bằng Từ ngày." })); + setData((d) => ({ ...d, loading: true, error: "" })); + try { + const res = await adminApi.doorLogs({ ...filter, unitNumber: filter.unitNumber.trim(), page, pageSize: PAGE_SIZE }); + if (n !== seq.current) return; + setData({ loading: false, error: "", items: res?.items || [], total: res?.totalItems ?? 0, pages: Math.max(1, res?.totalPages || 1) }); + } catch (e) { if (n === seq.current) { setData((d) => ({ ...d, loading: false, error: e.message || "Không tải được nhật ký cửa." })); onApiError?.(e); } } + }; + useEffect(() => { const t = setTimeout(load, 250); return () => clearTimeout(t); }, [filter, page]); // eslint-disable-line react-hooks/exhaustive-deps + const set = (k) => (e) => { setPage(1); setFilter({ ...filter, [k]: e.target.value }); }; + const isToday = filter.from === today() && filter.to === today(); + return ( +
+ + {isToday ? "Hôm nay" : `${dateLabel(filter.from)} – ${dateLabel(filter.to)}`} · {data.total} sự kiện + +
+ + + + + +
+ {data.error ? {data.error} + : data.loading && !data.items.length ?

Đang tải nhật ký cửa…

+ : !data.items.length ?
+ : } + {data.pages > 1 &&
+ + Trang {page}/{data.pages} + +
} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DoorScannerTool.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DoorScannerTool.jsx new file mode 100644 index 0000000..f664a33 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/DoorScannerTool.jsx @@ -0,0 +1,221 @@ +/** + * DOOR SCANNER TOOL - MÁY QUÉT TẠI CỬA KHO (Lượt 6b · #48 #50 #51 #59 · Figma A-DEMO-CỬA) + * + * Mô phỏng thiết bị kiểm soát ra vào có bàn phím (D21: không dùng thiết bị thật): + * - Chọn cơ sở và ô kho → nhập PIN 6 số (chỉ 1–9, D51) hoặc "Mở cửa bằng QR" (camera; không có camera thì dán mã). + * - Cửa không tự khoá (D51): mở tới khi bấm "Đóng cửa" (popup xác nhận, không nhập lại mã). + * - "Gọi hỗ trợ" gửi yêu cầu tới nhân viên cơ sở; trong 30 phút không tạo yêu cầu trùng. + * - Mọi lần mở, từ chối, đóng đều vào Nhật ký cửa (không lưu nguyên mã QR/PIN). + */ +import React, { useEffect, useRef, useState } from "react"; +import { adminApi } from "../api/adminApi.js"; +import ConfirmDialog from "../../../shared/components/ConfirmDialog.jsx"; +import { Button, Field, Icon, Modal, Notice, Tag } from "../../../shared/components/UI.jsx"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { dateTimeLabel } from "../../../shared/utils/format.js"; +import { DemoHead } from "./DemoShared.jsx"; +import { PIN_LENGTH, pinError, scanScreen } from "./demoModel.js"; +import "./demo-tools.css"; + +const SCREEN = { + IDLE: ["", "Nhập mã PIN 6 số"], + OPEN: ["is-open", "ĐÃ MỞ CỬA"], + DENIED: ["is-denied", "TỪ CHỐI"], + NOT_YET: ["is-wait", "CHƯA ĐẾN NGÀY"], + LOCKED: ["is-locked", "CỬA ĐÃ KHOÁ"], +}; +const clock = () => new Date().toTimeString().slice(0, 5); + +/** Đọc QR bằng camera (BarcodeDetector). Không có camera / trình duyệt chặn → báo lỗi để chọn nhập PIN hoặc dán mã. */ +function QrDialog({ onCode, onClose, onPin }) { + const video = useRef(null); + const [state, setState] = useState("starting"); // starting | live | blocked | missing + const [paste, setPaste] = useState(""); + useEffect(() => { + let stream, timer, stop = false; + (async () => { + if (!navigator.mediaDevices?.getUserMedia || typeof window.BarcodeDetector !== "function") return setState("missing"); + try { + stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } }); + if (stop) return; + video.current.srcObject = stream; await video.current.play(); setState("live"); + const detector = new window.BarcodeDetector({ formats: ["qr_code"] }); + const tick = async () => { + if (stop) return; + try { const [hit] = await detector.detect(video.current); if (hit?.rawValue) return onCode(hit.rawValue); } catch { /* khung hình chưa sẵn sàng */ } + timer = setTimeout(tick, 300); + }; + tick(); + } catch (e) { setState(e?.name === "NotAllowedError" ? "blocked" : "missing"); } + })(); + return () => { stop = true; clearTimeout(timer); stream?.getTracks().forEach((t) => t.stop()); }; + }, []); // eslint-disable-line react-hooks/exhaustive-deps + if (state === "blocked") return ; + return + {state === "missing" + ?

Thiết bị này không có camera hoặc trình duyệt chưa hỗ trợ đọc QR. Dán nội dung mã QR của khách bên dưới, hoặc dùng PIN 6 số.

+ :
} + setPaste(e.target.value)} /> +
+ + +
+
; +} + +export default function DoorScannerTool() { + const { onApiError } = useApp(); + const [facilities, setFacilities] = useState([]), [units, setUnits] = useState([]); + const [facilityId, setFacilityId] = useState(""), [unit, setUnit] = useState(""); + const [door, setDoor] = useState(null), [pin, setPin] = useState(""), [pinMsg, setPinMsg] = useState(""); + const [scan, setScan] = useState(null), [busy, setBusy] = useState(false), [popup, setPopup] = useState(null), [reason, setReason] = useState(""); + const [loadError, setLoadError] = useState(""); + const guard = useRef(false), pad = useRef(null); + + useEffect(() => { (async () => { + try { const list = await adminApi.facilities(); setFacilities(list || []); if (list?.[0]) setFacilityId(String(list[0].facilityId)); } + catch (e) { setLoadError(e.message || "Không tải được danh sách cơ sở."); onApiError?.(e); } + })(); }, []); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { if (!facilityId) return; (async () => { + try { const list = await adminApi.facilityUnits(facilityId); setUnits(list || []); setUnit(list?.[0]?.unitNumber || ""); } + catch (e) { setUnits([]); setUnit(""); setLoadError(e.message || "Không tải được danh sách ô kho."); } + })(); }, [facilityId]); + const refreshDoor = async (u = unit) => { + if (!u) return setDoor(null); + try { setDoor(await adminApi.doorState(u, facilityId || undefined)); } catch { setDoor(null); } + }; + useEffect(() => { setScan(null); setPin(""); setPinMsg(""); refreshDoor(unit); }, [unit]); // eslint-disable-line react-hooks/exhaustive-deps + + const facilityName = facilities.find((f) => String(f.facilityId) === String(facilityId))?.name || ""; + const run = async (fn) => { + if (guard.current) return; guard.current = true; setBusy(true); + try { await fn(); } finally { guard.current = false; setBusy(false); } + }; + const doScan = (code, method) => run(async () => { + try { + const res = await adminApi.scan(code, unit); + const s = { ...res, method, at: res.scannedAt || new Date().toISOString() }; + setScan(s); setPin(""); + setPopup({ kind: scanScreen(s), scan: s }); + refreshDoor(); + } catch (e) { setPopup({ kind: "ERROR", text: e.message || "Máy quét chưa kết nối được hệ thống mở cửa.", retry: () => doScan(code, method) }); } + }); + const pressDigit = (d) => { if (busy) return; setPinMsg(""); setPin((p) => (p.length < PIN_LENGTH ? p + d : p)); }; + const submitPin = () => { const e = pinError(pin); if (e) return setPinMsg(e); doScan(pin, "PIN"); }; + const closeDoor = () => run(async () => { + try { const d = await adminApi.closeDoor(unit, facilityId || undefined); setDoor(d); setScan(null); setPopup({ kind: "CLOSED", door: d }); } + catch (e) { setPopup({ kind: "ERROR", text: e.message || "Không gửi được lệnh đóng cửa.", retry: closeDoor }); } + }); + const support = () => run(async () => { + try { const r = await adminApi.doorSupport({ unitNumber: unit, facilityId: facilityId ? Number(facilityId) : null, reason: reason.trim() || null }); setReason(""); setPopup({ kind: "SUPPORT_OK", res: r }); } + catch (e) { setPopup({ kind: "ERROR", text: `${e.message || "Chưa gửi được yêu cầu hỗ trợ."} Nội dung đã nhập vẫn được giữ.`, retry: support }); } + }); + const onKey = (e) => { + if (/^[0-9]$/.test(e.key)) pressDigit(e.key); + else if (e.key === "Backspace") setPin((p) => p.slice(0, -1)); + else if (e.key === "Enter") submitPin(); + else if (e.key === "Escape") setPin(""); + }; + + const open = door?.door === "OPEN"; + const screen = scan ? scanScreen(scan) : door?.door === "LOCKED" && door?.updatedAt && !pin ? "LOCKED" : "IDLE"; + const [screenCls, screenTitle] = SCREEN[screen]; + return ( +
+ + Mô phỏng · chưa kết nối thiết bị + + {loadError && {loadError}} +
+
+
+

1 · Chọn cửa kho

+
+ + +
+
+
+

2 · Máy quét tại cửa {unit}

+
+
+

SafeSpace Access

+
+
+
+
+ +
+ + {popup?.kind === "QR" && setPopup(null)} onPin={() => { setPopup(null); pad.current?.focus(); }} onCode={(code) => { setPopup(null); doScan(code, "QR"); }} />} + {popup?.kind === "OPEN" && r[1])} onCancel={() => setPopup(null)} onConfirm={() => setPopup(null)} />} + {popup?.kind === "NOT_YET" && r[1])} onCancel={() => setPopup(null)} onConfirm={() => setPopup(null)} />} + {popup?.kind === "DENIED" && setPopup(null)} onConfirm={() => setPopup(null)} />} + {popup?.kind === "CLOSE" && setPopup(null)} onConfirm={closeDoor} />} + {popup?.kind === "CLOSED" && setPopup(null)} onConfirm={() => setPopup(null)} />} + {popup?.kind === "SUPPORT" && setPopup(null)} onConfirm={support}> +