From 467921f620bd0777baf897d47d23c7fd5c9e117e Mon Sep 17 00:00:00 2001 From: Vector Date: Wed, 18 Nov 2026 11:44:37 +0700 Subject: [PATCH 1/2] =?UTF-8?q?D64-D66:=20ho=C3=A0n=20ti=E1=BB=81n=20kh?= =?UTF-8?q?=C3=B4ng=20c=E1=BA=A7n=20m=C3=A3=20giao=20d=E1=BB=8Bch,=20s?= =?UTF-8?q?=E1=BA=AFp=20h=E1=BA=BFt=20h=E1=BA=A1n=2010=20ng=C3=A0y,=20b?= =?UTF-8?q?=E1=BB=8F=20giao=20vi=E1=BB=87c=20nh=C3=A2n=20vi=C3=AAn;=20chu?= =?UTF-8?q?=C3=B4ng=20=C4=91=C3=A3=20=C4=91=E1=BB=8Dc=20th=C3=AC=20xo?= =?UTF-8?q?=C3=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DECISIONS.md | 25 +++ .../SafeSpace-Customer-UI/BACKEND-TODO.md | 2 +- .../SafeSpace-Customer-UI/mock/mock-api.mjs | 2 +- .../scripts/check-workflow-actions.mjs | 5 +- .../src/app/state/AppProvider.jsx | 13 +- .../src/app/state/appReducer.js | 7 +- .../src/app/state/appSelectors.js | 5 +- .../src/features/admin/demo/demoModel.js | 2 +- .../business/policies/policyFields.js | 4 +- .../customer/contracts/ReturnProgressPage.jsx | 2 +- .../customer/contracts/ReturnRequestPage.jsx | 2 +- .../dashboard/CustomerDashboardPage.jsx | 2 +- .../customer/payments/RefundTrackingPage.jsx | 2 +- .../FacilityOperationsRoutes.jsx | 2 - .../components/StaffTasks.jsx | 9 +- .../data/facilityOperationsSeed.js | 2 +- .../settlements/settlementModel.js | 12 +- .../state/facilityOperationsReducer.js | 1 - .../utils/pendingTaskCounts.js | 7 +- .../workflows/cashRefundModel.js | 6 +- .../workflows/useWorkflowData.js | 4 +- .../assignments/StaffAssignmentPage.jsx | 73 -------- .../manager/cash/CashRefundApprovalPage.jsx | 51 +++--- .../manager/overdue/OverdueCasePage.jsx | 19 +- .../refunds/CancellationRefundPage.jsx | 28 ++- .../manager/refunds/DepositRefundPage.jsx | 164 ++++-------------- .../staff/overdue/OverdueRemovalPage.jsx | 4 +- .../staff/payments/CashRefundCounterPage.jsx | 43 +---- .../src/shared/api/apiMappers.js | 3 +- .../src/shared/components/Header.jsx | 4 +- .../src/shared/utils/notices.js | 3 + .../SafeSpace-Customer-UI/tests/ops.test.js | 5 +- .../tests/reducer.test.js | 17 +- .../tests/render.test.mjs | 4 +- .../tests/return-policy.test.js | 10 +- .../tests/settlement-batch08.test.js | 10 +- .../Data/DbSeeder.DemoFacilities.cs | 4 +- .../Services/DemoToolsService.cs | 2 +- .../Services/FacilityOpsService.Actions.cs | 15 +- .../Services/FacilityOpsService.Board.cs | 2 +- .../Services/FacilityOpsService.Refunds.cs | 6 +- .../Services/FacilityOpsService.Workflows.cs | 19 +- .../Services/OpsRules.cs | 2 +- .../Services/OverdueProcessor.cs | 8 +- .../D32RefundEvidenceTests.Phien3.cs | 26 ++- .../D32RefundEvidenceTests.cs | 5 +- StorageProject.Tests/DoorStateTests.cs | 1 + StorageProject.Tests/OverdueProcessorTests.cs | 2 +- ...tandardizedOperationalParametersP2Tests.cs | 6 +- progress.md | 31 ++++ 50 files changed, 287 insertions(+), 396 deletions(-) delete mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/utils/notices.js diff --git a/DECISIONS.md b/DECISIONS.md index f5de6f4..25abd57 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -731,3 +731,28 @@ Bổ sung @playwright/test trong devDependencies để kiểm thao tác biểu m - **Gia hạn (D50 #23):** chữ hiển thị không còn "chờ quản lý duyệt" / "cơ sở duyệt và chốt giá"; dùng "chờ xác nhận" / "đã được xác nhận". - **Màn khách hàng:** dưới họ tên trên thanh đầu trang hiện vai trò "Khách hàng" (giống thẻ vai trò của nhân viên, quản lý, admin). - **Hotline ở chân trang** hiện chữ thường cùng màu các dòng khác, không còn là liên kết `tel:`. Số hotline giữ theo D50. + +## D64 — 18/11/2026: Xác nhận hoàn tiền không cần mã giao dịch; trả kho chỉ chọn ngày — Đã chốt + +> Người dùng (Thắng) chốt ngày 18/11/2026, Figma đã sửa trước (M-ĐS-CHỐT chuyển khoản + bản tiền mặt, M08a/M08a2, D30-15). Thay ý "nhập mã giao dịch ngân hàng" ở mục 21 (D50), dòng "Chuyển khoản: quản lý … nhập mã giao dịch" và các dòng D27/D32 yêu cầu mã giao dịch, thời điểm chuyển cho bước xác nhận hoàn. + +- Khách điền thông tin nhận hoàn (chuyển khoản: ngân hàng, số tài khoản, chủ tài khoản; hoặc tiền mặt tại quầy). Quản lý thấy đủ thông tin đó và **chỉ bấm xác nhận**: "Xác nhận đã chuyển khoản" hoặc "Xác nhận đã trả tiền mặt". **Không nhập mã giao dịch, không nhập thời gian chuyển**; máy chủ ghi thời điểm xác nhận làm ngày hoàn. +- Áp dụng cho hoàn cọc sau trả kho và hoàn tiền đơn huỷ (M08). Vẫn giữ: xác nhận một lần (409 khi bấm lặp), khoá phương thức theo lựa chọn khách, kiểm tra tài khoản nhận đủ thông tin. +- API giữ nguyên trường `transactionRef`/`transferredAt` nhưng **không bắt buộc**; có gửi mã (dữ liệu cũ) thì vẫn kiểm tra ≤ 100 ký tự và không trùng. Khách không còn thấy dòng "Mã giao dịch" ở theo dõi khoản hoàn. +- Trả kho: khách chỉ chọn **ngày** mong muốn trả kho, không chọn giờ hay buổi sáng/chiều (giữ đúng mục 9 / D59). + +## D65 — 18/11/2026: Mốc "Sắp hết hạn" còn 10 ngày — Đã chốt + +> Người dùng (Thắng) chốt ngày 18/11/2026. Thay mốc 30 ngày của D11 (và mốc 14 ngày của Công cụ demo / bảng kho quản lý). + +- Hợp đồng chỉ chuyển "Sắp hết hạn" (EXPIRING) khi còn **≤ 10 ngày** tới ngày kết thúc; còn hơn 10 ngày là "Đang thuê". Áp dụng thống nhất cho khách (Kho của tôi, tổng quan), quản lý, Công cụ demo và tiến trình quét hằng ngày. +- Tiến trình quét hằng ngày đưa hợp đồng EXPIRING còn hơn 10 ngày (đánh theo mốc cũ hoặc vừa gia hạn) về lại ACTIVE. Email nhắc gia hạn giữ nguyên mốc 3 ngày. + +## D66 — 18/11/2026: Mỗi cơ sở một nhân viên — bỏ giao việc; quản lý tự xác nhận đã trả tiền mặt — Đã chốt + +> Người dùng (Thắng) chốt ngày 18/11/2026, chọn phương án (a). Thay phần "quản lý duyệt chi tiền mặt và giao nhân viên, nhân viên tick 4 mục và chi" của D42/D44, phần "quản lý phân công nhân viên xử lý đồ quá hạn" và trang M06 Phân công công việc. + +- Mỗi cơ sở mặc định 1 nhân viên; **không có thao tác giao việc** nào cho nhân viên. +- **Hoàn tiền mặt tại quầy:** bỏ bước "Duyệt & giao" và ô chọn nhân viên. Khoản tiền mặt chờ khách đến nhận ngay khi được tạo; khi khách nhận đủ tiền, **quản lý bấm "Xác nhận đã trả tiền mặt"** (Figma M-ĐS-CHỐT · tiền mặt), không nhập mã giao dịch. Hạn nhận 30 ngày tính từ lúc tạo khoản (khoản cũ đã duyệt vẫn tính từ lần duyệt). Nhân viên chỉ còn gọi nhắc khách ở ngày 10, 20, 25. +- **Xử lý đồ quá hạn từ ngày 20:** bỏ bước quản lý phân công; hồ sơ hiện thẳng ở "Công việc xử lý đồ quá hạn" của nhân viên cơ sở. +- Bỏ trang M06 "Phân công công việc" (đã ẩn khỏi menu từ #7). Yêu cầu hỗ trợ giữ cách hiện tại: nhân viên của cơ sở thấy và nhận xử lý, không cần giao. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index 549dcb1..d1f7e18 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -101,7 +101,7 @@ Mã việc khớp kế hoạch "SafeSpace — Kế hoạch hoàn thiện cập n | T04 | Khách chọn trả gia hạn tại quầy; nhân viên xác nhận thu | `POST /api/renewals/{id}/counter-payment`; board `counterRenewals[]` + `POST /api/ops/counter-renewals/actions` `{action:"COLLECT_RENEWAL"}` (xem `APPROVED-FE-API-GAPS.md`) | Đạt | P1 | | T05 | Biên bản trả kho lưu phí và ảnh | `POST /api/ops/returns/{id}/inspection` nhận thêm `damageFee`, `cleaningRequired`, `feeReason`, `photos[]` (ảnh kho trống bắt buộc); lưu `ReturnInspection.DamageFee/CleaningFee/CleaningRequired`. Vệ sinh = 10% cọc cố định, không nhập tay | Ngọc Mai | P0 | | T06 | Quyết toán trả kho: tổng khấu trừ ≤ `DepositAmount`; bỏ `Debt`; không để khoản `DAMAGE_FEE`/`OVERDUE_FEE` nào ở trạng thái chờ thu sau quyết toán | `RefundPolicy.Calculate`, `ConfirmRefundAsync`, `RefundPolicyTests` | Ngọc Mai | P0 | -| T07 | Hoàn cọc hai bước: M07 chốt → `REFUND` `PENDING`; màn hoàn cọc ghi `transactionRef` → `PAID`. Ô cần vệ sinh giữ `MAINTENANCE` | `POST /api/ops/contracts/{id}/refund` (chỉ chốt số), `GET /api/ops/deposit-refunds`, `POST /api/ops/deposit-refunds/actions` `{action:"CONFIRM_DEPOSIT_REFUND", id, transactionRef}` | Ngọc Mai | P0 | +| T07 | Hoàn cọc hai bước: M07 chốt → `REFUND` `PENDING`; màn hoàn cọc bấm xác nhận → `PAID` (D64 18/11: `transactionRef`, `transferredAt` không bắt buộc). Ô cần vệ sinh giữ `MAINTENANCE` | `POST /api/ops/contracts/{id}/refund` (chỉ chốt số), `GET /api/ops/deposit-refunds`, `POST /api/ops/deposit-refunds/actions` `{action:"CONFIRM_DEPOSIT_REFUND", id, transactionRef}` | Ngọc Mai | P0 | | T08 | Tài khoản nhận hoàn chính chủ khi huỷ đơn và khi gửi trả kho: `bankName`, `accountNumber` (6–19 chữ số), `accountHolder` (trùng tên hợp đồng) | `POST /api/reservations/{id}/cancel`, `POST /api/contracts/{id}/move-out` | Ngọc Mai | P1 | | T09 | Phí quá hạn = `DepositAmount × rate × số ngày trễ`, tối đa `DepositAmount`; dừng khi gửi trả kho. Thêm `CalculationType` `DEPOSIT_PERCENT_PER_DAY` cho chính sách `OVERDUE` (mặc định 5) | `RefundPolicy.OverdueFeeFor`, seed/B02, test | Tiến | P0 | | T11 | Job quá hạn mỗi ngày: EXPIRING/OVERDUE, tạo `OverdueCase`, cộng phí theo ngày không trùng, mốc nhắc ngày 10–14, việc xử lý đồ ngày 20 | Worker mới (giống `ExpiredCashHoldWorker`) | Tiến | P1 | 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 b259097..fd16a31 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs @@ -497,7 +497,7 @@ export function startMockApi( 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 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 <= 10 ? "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 })) }; }; // D57 · Chỉnh giá theo cơ sở (demo): giá 4 loại kho của một cơ sở 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 8bcf68c..f5711c1 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 @@ -11,12 +11,11 @@ async function route(path){await page.goto('http://127.0.0.1:5173/#/'+path);awai // Nút xác nhận / nút đóng thông báo thành công theo chữ Figma từng màn (useWorkflowChange opts), nên bấm theo vị trí. async function confirm(){await page.locator('.modal--confirm:not(.modal--success):not(.modal--failure)').getByRole('button').last().click();await page.locator('.modal--success').getByRole('button').first().click();} // Thời gian chuyển phải sau lúc duyệt đối soát và không ở tương lai: lấy đúng mốc hiện tại (max của ô). -async function transferNow(){const at=page.getByLabel(/Thời gian chuyển/);await at.fill(await at.getAttribute('max'));} 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 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 han.getByRole('button',{name:'Xác nhận đã hoàn',exact:true}).click();assert.match(await page.getByRole('dialog').innerText(),/Không cần nhập mã giao dịch/);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('D64: M08 chỉ bấm xác nhận, không nhập mã giao dị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();assert.match(await page.locator('main').innerText(),/Số tài khoản/);await page.getByRole('button',{name:'Xác nhận đã chuyển khoản'}).click();await confirm();assert.equal(await page.getByRole('button',{name:'Xác nhận đã chuyển khoản'}).count(),0);passed.push('D64: hoàn cọc chỉ bấm xác nhận đã chuyển khoản, 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'); await route('staff/renewal-payments');await page.getByRole('button',{name:'Xác nhận đã thu',exact:true}).click();await confirm();assert.equal(await page.getByRole('button',{name:'Xác nhận đã thu',exact:true}).count(),0);passed.push('Thu gia hạn tại quầy một lần'); 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 64123aa..409abd9 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 @@ -13,6 +13,7 @@ import { defaultRentalPolicy } from "../../features/facility-operations/workflow import { isReturnFee, NO_RETURN_COLLECTION, visitDateError } from "../../shared/utils/returnPolicy.js"; import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import { customerNotifications } from "../../features/customer/notifications/customerNotifications.js"; +import { noticeKey } from "../../shared/utils/notices.js"; import { submitCancellation, submitReturnRequest } from "../../shared/api/refundRequestApi.js"; import { readPhotoData, verifyPhotoFile } from "../../shared/utils/refundRequest.js"; import { submitRenewalWithConsent } from "../../shared/api/renewalConsentApi.js"; @@ -394,13 +395,18 @@ function ApiProvider({ children }) { updateOverlay(o => { const byId = new Map(events.map(event => [event.id, event])); const ids = new Set(o.notifications.map(notice => notice.id)); - const incoming = events.filter(event => !ids.has(event.id)); + // Thông báo quá hạn: thời điểm của sự kiện là 00:00 nên bị xếp dưới các thông báo khác trong ngày và khách không thấy. + // Lần đầu phát hiện và mỗi lần số ngày quá hạn đổi → đưa lên đầu chuông, chưa đọc (cùng nhịp với email quá hạn). + const stamp = new Date().toISOString(); + const isOverdue = id => typeof id === "string" && id.startsWith("SERVER-OVERDUE-"); + const dismissed = new Set(o.dismissedNotices || []); + const incoming = events.filter(event => !ids.has(event.id) && !dismissed.has(noticeKey(event))).map(event => isOverdue(event.id) ? { ...event, created_at: stamp } : event); let updated = false; const existing = o.notifications.map(notice => { - const event = typeof notice.id === "string" && notice.id.startsWith("SERVER-OVERDUE-") ? byId.get(notice.id) : null; + const event = isOverdue(notice.id) ? byId.get(notice.id) : null; if (!event || event.detail === notice.detail) return notice; updated = true; - return { ...notice, detail: event.detail }; + return { ...notice, detail: event.detail, created_at: stamp, read: false }; }); return incoming.length || updated ? { ...o, notifications: [...incoming, ...existing] } : o; }); @@ -585,6 +591,7 @@ function ApiProvider({ children }) { ...o, returns: next.returns, notifications: next.notifications, + dismissedNotices: next.dismissedNotices || o.dismissedNotices || [], activities: next.activities, appointments: [...next.appointments.filter((a) => !prev.appointments.some((x) => x.appointment_id === a.appointment_id)), ...o.appointments], name: next.user?.full_name !== prev.user?.full_name ? next.user.full_name : o.name, 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 e68e190..cef38b8 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 @@ -7,6 +7,7 @@ * - Thanh toán: PAY_ORDER, ADD_PAYMENT, REFUND_SETTLEMENT * - Hỗ trợ: CREATE_TICKET, REPLY_TICKET */ +import { noticeKey } from "../../shared/utils/notices.js"; import { requireRentalPolicy } from "../../shared/utils/rentalPolicy.js"; import { storedRefundChoice, validateRefundChoice } from "../../shared/utils/refundRequest.js"; import { isReturnFee, NO_RETURN_COLLECTION, visitDateError } from "../../shared/utils/returnPolicy.js"; @@ -483,12 +484,16 @@ const handlers = { return { state: { ...state, user: { ...state.user, password: p.next } }, result: {} }; }, + // Đã đọc thì xoá khỏi chuông (18/11); nhớ khoá để thông báo sinh từ máy chủ không quay lại. MARK_READ(state, p) { const all = !p.ids; + const read = state.notifications.filter((n) => all || p.ids.includes(n.id)); + const keys = read.map(noticeKey).filter(Boolean); return { state: { ...state, - notifications: state.notifications.map((n) => (all || p.ids.includes(n.id) ? { ...n, read: true } : n)), + notifications: state.notifications.filter((n) => !(all || p.ids.includes(n.id))), + dismissedNotices: [...keys, ...(state.dismissedNotices || []).filter((k) => !keys.includes(k))].slice(0, 500), }, result: {}, }; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js index 55f836e..31c2a3d 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js @@ -22,12 +22,13 @@ export const facilityOf = (data, id, name) => }; export const contractOf = (data, id) => data.contracts.find((c) => c.contract_id === id); -// Trạng thái hợp đồng suy ra theo ngày (ACTIVE → EXPIRING trong 30 ngày → OVERDUE) +// Trạng thái hợp đồng suy ra theo ngày (ACTIVE → EXPIRING khi còn ≤ 10 ngày, D65 → OVERDUE) +export const EXPIRING_DAYS = 10; export function contractStatus(c, now = new Date()) { if (c.status === "ENDED") return "ENDED"; const left = daysBetween(localDate(now), c.end_date); if (left < 0) return "OVERDUE"; - if (left <= 30) return "EXPIRING"; + if (left <= EXPIRING_DAYS) return "EXPIRING"; return "ACTIVE"; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/demoModel.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/demoModel.js index ec24daf..6e5330c 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/demoModel.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/demo/demoModel.js @@ -16,7 +16,7 @@ export function expectedState(start, end, today) { if (!start || !end) return null; if (start > today) return "Chưa tới ngày thuê"; if (end <= today) return `Quá hạn ${Math.round((Date.parse(today) - Date.parse(end)) / 86400000)} ngày`; - return Math.round((Date.parse(end) - Date.parse(today)) / 86400000) <= 14 ? "Sắp hết hạn" : "Đang thuê"; + return Math.round((Date.parse(end) - Date.parse(today)) / 86400000) <= 10 ? "Sắp hết hạn" : "Đang thuê"; } export function contractFormError({ start, end, rate }) { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyFields.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyFields.js index 1ead171..acf7234 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyFields.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyFields.js @@ -24,8 +24,8 @@ export const SYSTEM_ENFORCED_POLICIES = [ { key: 'expiring', label: 'Thông báo sắp hết hạn hợp đồng', - value: '30 ngày trước khi hết hạn', - reference: 'D11 · OverdueProcessor', + value: '10 ngày trước khi hết hạn', + reference: 'D65 · OverdueProcessor', description: 'Hệ thống tự động rà soát hàng ngày và gửi thông báo nhắc gia hạn đến khách hàng.', }, { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnProgressPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnProgressPage.jsx index 9b46e58..ffd7394 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnProgressPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnProgressPage.jsx @@ -14,6 +14,6 @@ export function ReturnProgressPage({ id }) { const ret = pendingReturn(data, id), refund = load.data?.find(r => r.contractId === id && String(r.ownerId) === String(user?.user_id)); return

{ret ? "Đã gửi lịch trả kho" : "Chưa có yêu cầu trả kho"}

{ret && <>Nhân viên sẽ kiểm tra kho và chụp ảnh hiện trạng trước khi đối soát hoàn cọc. Cần hỗ trợ ra vào, vui lòng liên hệ nhân viên.}
-

Biên bản & hoàn cọc

{refund ? <>{refund.transactionRef &&

Mã giao dịch: {refund.transactionRef}

} :

Chưa có kết quả kiểm tra / đối soát cọc từ cơ sở.

}
+

Biên bản & hoàn cọc

{refund ? <> :

Chưa có kết quả kiểm tra / đối soát cọc từ cơ sở.

}
Về hợp đồngLiên hệ cơ sở
; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnRequestPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnRequestPage.jsx index 34e6b36..fcf56e8 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnRequestPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnRequestPage.jsx @@ -2,7 +2,7 @@ * RETURN REQUEST PAGE - ĐĂNG KÝ LỊCH TRẢ KHO (C08 / UC06) * * Thủ tục trả kho (Move-out): - * - Chọn ngày hẹn trả kho thực tế và giờ kiểm kê dự kiến. + * - Chỉ chọn ngày hẹn trả kho (D64: không chọn giờ / buổi sáng chiều). * - Lựa chọn hình thức nhận hoàn tiền cọc (Chuyển khoản ngân hàng hoặc Tiền mặt tại quầy - D42). * - Lưu ý hướng dẫn dọn hết đồ đạc và bàn giao lại chìa khóa/thẻ từ. */ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/dashboard/CustomerDashboardPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/dashboard/CustomerDashboardPage.jsx index d8170c0..47e2d83 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/dashboard/CustomerDashboardPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/dashboard/CustomerDashboardPage.jsx @@ -68,7 +68,7 @@ export default function CustomerDashboardPage() {
{active.length}Kho đang thuê
-
{expiring.length}Sắp hết hạn (30 ngày)
+
{expiring.length}Sắp hết hạn (10 ngày)
{unpaid}Hoá đơn chưa thanh toán
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/RefundTrackingPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/RefundTrackingPage.jsx index 534a0e1..0c5e484 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/RefundTrackingPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/RefundTrackingPage.jsx @@ -25,7 +25,7 @@ export function RefundTrackingPage() {
    {[["Gửi trả kho", r.requestedAt || ret?.requested_at], ["Nhân viên kiểm tra", r.inspectedAt], ["Duyệt đối soát", r.approvedAt], ["Chuyển khoản", r.status === "PAID" ? r.paidAt : null]].map(([label,time],i) =>
  1. {time ? "✓" : i+1}
    {label}

    {i === 3 && r.status === "PAID" ? time ? stamp(time) : "Đã chuyển · chưa có thời điểm" : i === 3 && r.amount != null && r.amount <= 0 ? "Không có khoản chuyển" : stamp(time)}

  2. )}

Khoản hoàn cọc · {r.contractId}

Liên hệ cơ sở
- +
: }} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx index 2d9f098..11f7b93 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx @@ -24,7 +24,6 @@ import { RefundCenterPage } from "../manager/refunds/RefundCenterPage.jsx"; import { Empty, LinkButton } from "../../shared/components/UI.jsx"; import { UnitAllocationPage } from "../manager/allocations/UnitAllocationPage.jsx"; -import { StaffAssignmentPage } from "../manager/assignments/StaffAssignmentPage.jsx"; import { ContractListPage } from "../manager/contracts/ContractListPage.jsx"; import { CancellationRefundPage } from "../manager/refunds/CancellationRefundPage.jsx"; import { ManagerResultPage } from "../manager/results/ManagerResultPage.jsx"; @@ -82,7 +81,6 @@ const MANAGER = { "": [ManagerDashboardPage, "manager"], units: [UnitManagementPage, "manager/units"], allocate: [UnitAllocationPage, "manager"], // chỉ còn cho đơn đã thanh toán mà hệ thống không bố trí được ô - assign: [StaffAssignmentPage, "manager"], // bỏ khỏi navbar: yêu cầu của khách hiện thẳng bên nhân viên renewals: [RenewalApprovalPage, "manager/renewals"], contracts: [ContractListPage, "manager/contracts"], refunds: [CancellationRefundPage, "manager/refund"], diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/StaffTasks.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/StaffTasks.jsx index 6172ef4..e4c66cd 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/StaffTasks.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/StaffTasks.jsx @@ -85,14 +85,13 @@ export function staffTasks(ops, me, kind = "all") { }), ); (ops.cash_refunds || []) - .filter((r) => ["READY", "REMIND", "APPOINTMENT"].includes(r.status) && - (!r.staff_id && !r.staffId || !me?.staff_id || (r.staff_id || r.staffId) === me.staff_id)) + .filter((r) => r.status === "REMIND") // D66: quản lý xác nhận đã trả tiền mặt; nhân viên chỉ gọi nhắc khách .forEach((r) => list.push({ - key: r.id, kind: "reconcile", status: ["Chờ chi tiền", "amber"], title: `Hoàn tiền ${r.id}`, + key: r.id, kind: "reconcile", status: ["Cần gọi nhắc", "amber"], title: `Hoàn tiền ${r.id}`, meta: `${r.customer} · ${r.reference || "Tiền mặt"}`, - when: `${money(r.amount)} · Chi tiền mặt tại quầy`, - cta: "Chi tiền", to: "staff/cash-refunds", sort: r.deadlineDate || r.deadline_date || "", + when: `${money(r.amount)} · Gọi nhắc khách đến nhận tiền mặt`, + cta: "Gọi nhắc", to: "staff/cash-refunds", sort: r.deadlineDate || r.deadline_date || "", }), ); } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js index dec5c50..aa08bd3 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js @@ -43,7 +43,7 @@ const LAYOUT = [ function createUnits(t) { const usage = { K01: ["Nguyễn Thị Mai", "WAITING_HANDOVER", addMonths(addDays(t, 6), 3)], - K02: ["Lê Văn Tùng", "EXPIRING", addDays(t, 14)], + K02: ["Lê Văn Tùng", "EXPIRING", addDays(t, 9)], K03: ["Trần Quốc Bảo", "OVERDUE", addDays(t, -3)], K04: ["Lê Văn An", "OVERDUE", addDays(t, -4)], K05: ["Võ Thị Hạnh", "WAITING_HANDOVER", addMonths(t, 3)], diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/settlements/settlementModel.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/settlements/settlementModel.js index ce728ce..107e1ef 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/settlements/settlementModel.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/settlements/settlementModel.js @@ -26,11 +26,12 @@ export function transferProof(item,payload,now=new Date()) { if (!isCash) { const error=validateRefundBank({bankName:item.bankName,accountNumber:item.accountNumber,accountHolder:item.accountHolder},item.customer);if(error)throw new Error(error); } - const ref=String(payload.transactionRef||payload.transaction_ref||"").trim();if(!ref||ref.length>100)throw new Error(isCash ? "Nhập mã phiếu chi không quá 100 ký tự." : "Nhập mã giao dịch không quá 100 ký tự."); + // D64 (18/11): không nhập mã giao dịch / thời gian; quản lý chỉ bấm xác nhận. Mã (nếu có, dữ liệu cũ) tối đa 100 ký tự. + const ref=String(payload.transactionRef||payload.transaction_ref||"").trim();if(ref.length>100)throw new Error("Mã giao dịch không quá 100 ký tự."); if(payload.confirmed!==true)throw new Error(isCash ? "Cần xác nhận đã chi tiền mặt cho khách hàng." : "Cần xác nhận đã chuyển đúng số tiền vào đúng tài khoản."); - const paidAt=actualVnTime(payload.transferredAt,now); + const paidAt=payload.transferredAt?actualVnTime(payload.transferredAt,now):now.toISOString(); if(item.inspectedAt&&Number.isFinite(Date.parse(item.inspectedAt))&&Date.parse(paidAt)h.id===payload.id);if(!h||h.status!=="WAITING")throw new Error("Lịch nhận chìa khóa không còn chờ xử lý."); @@ -76,12 +77,13 @@ export function opsReceiptCheck(type,payload,res,board) { if(type==="SUBMIT_RETURN") {const r=board.returns?.find(r=>r.id===payload.id);if(r?.status!=="SUBMITTED"||!r.submitted_at||["damage_fee","cleaning_fee","cleaning_required","damage_item","fee_reason"].some(k=>r.report?.[k]!==payload.report[k])||(payload.files?.length&&!r.report?.photos?.length))throw new Error("Chưa xác nhận ảnh và các khoản khấu trừ đã được lưu đầy đủ.");} if(type==="CONFIRM_REFUND"&&(!knownMoney(res?.refund)||res?.refundStatus!=="PENDING"||!board.contracts?.some(c=>c.id===payload.id&&c.state==="CLOSED")))throw new Error("Chưa xác nhận khoản hoàn chờ chuyển tiền."); if(type==="CONFIRM_DEPOSIT_REFUND")transferProof(ops.deposit_refunds?.find(r=>r.id===payload.id),payload); - if(type==="CONFIRM_RESERVATION_REFUND") {const r=board.refunds?.find(r=>r.id===payload.id);if(r?.status!=="PAID"||r.transaction_ref!==payload.transaction_ref?.trim()||!r.paid_at)throw new Error("Máy chủ chưa xác nhận bằng chứng chuyển tiền.");} + if(type==="CONFIRM_RESERVATION_REFUND") {const r=board.refunds?.find(r=>r.id===payload.id);if(r?.status!=="PAID"||(r.transaction_ref||null)!==(String(payload.transaction_ref||"").trim()||null)||!r.paid_at)throw new Error("Máy chủ chưa xác nhận bằng chứng chuyển tiền.");} } export function validateRemoval(item,payload,policy,actor,now=new Date()) { if(!item||item.status==="DONE")throw new Error("Biên bản đã được lưu; không gửi lại."); if(!actor.roles?.some(r=>["STAFF","MANAGER"].includes(r))||actor.facilityId!==item.facilityId)throw new Error("Hồ sơ không thuộc cơ sở phụ trách."); - if(actor.roles.includes("STAFF")&&item.assignee!==actor.name)throw new Error("Bạn chưa được phân công hồ sơ này."); + // D66: mỗi cơ sở 1 nhân viên, không phân công; chỉ chặn khi hồ sơ cũ đã giao cho người khác. + if(actor.roles.includes("STAFF")&&item.assignee&&item.assignee!==actor.name)throw new Error("Hồ sơ đã giao cho nhân viên khác."); const performedAt=actualVnTime(payload.performedAt,now),day=new Intl.DateTimeFormat("sv-SE",{timeZone:"Asia/Ho_Chi_Minh"}).format(new Date(performedAt)),days=Math.floor((Date.parse(`${day}T00:00:00Z`)-Date.parse(`${item.endDate}T00:00:00Z`))/86400000),removalDay=Number.isSafeInteger(policy?.removalDay)&&policy.removalDay>=20?policy.removalDay:20; if(!Number.isFinite(days)||days ({ status: "PAID", paid_at: iso(now), method: method || "BANK_TRANSFER", transaction_ref: ref || null })) }; return { state: addLog(next, now, `Đã xác nhận hoàn ${money(r.amount)} · ${id}`, "manager/refunds", "MANAGER"), result: { id, refund: r.amount } }; }, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/pendingTaskCounts.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/pendingTaskCounts.js index 786196f..f172a8a 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/pendingTaskCounts.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/pendingTaskCounts.js @@ -8,10 +8,7 @@ export function pendingTaskCounts(ops, role, me) { if (role === "STAFF") { const counterPayments = count(ops.payments, p => p.status === "PENDING"); const renewalPayments = count(ops.counter_renewals, r => r.status === "PENDING"); - const cashRefunds = count(ops.cash_refunds, r => - ["READY", "REMIND", "APPOINTMENT"].includes(r.status) && - (!r.staff_id && !r.staffId || !me?.staff_id || (r.staff_id || r.staffId) === me.staff_id) - ); + const cashRefunds = count(ops.cash_refunds, r => r.status === "REMIND"); // D66: nhân viên chỉ gọi nhắc const reconcile = counterPayments + renewalPayments + cashRefunds; const verifications = count(ops.verifications, v => v.status === "TODO"); @@ -55,7 +52,7 @@ export function pendingTaskCounts(ops, role, me) { // MANAGER const overdueCases = count(ops.overdue_cases, c => c.status !== "DONE"); - const managerCashRefunds = count(ops.cash_refunds, r => r.status === "WAITING_APPROVAL"); + const managerCashRefunds = count(ops.cash_refunds, r => ["WAITING_APPROVAL", "READY", "REMIND", "APPOINTMENT"].includes(r.status)); // D66: chờ quản lý xác nhận đã trả // Xung đột đặt kho: hệ thống tự đề xuất đổi ô cho khách; quản lý chỉ cần xử lý khi không còn ô tương đương (NONE). const unitConflicts = count(ops.unit_conflicts, c => c.status === "OPEN" && c.option === "NONE"); const depositRefunds = count(ops.deposit_refunds, r => r.status === "PENDING" && !isCashRefund(r)); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/workflows/cashRefundModel.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/workflows/cashRefundModel.js index fa17ab7..517e643 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/workflows/cashRefundModel.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/workflows/cashRefundModel.js @@ -10,14 +10,14 @@ */ // D42/D44 · Khoản hoàn tiền mặt tại quầy (GET /api/ops/cash-refunds). export const CASH_STATUS = { - WAITING_APPROVAL: ["Chờ quản lý duyệt", "amber"], - READY: ["Đã duyệt · chờ khách đến", "blue"], + WAITING_APPROVAL: ["Chờ khách đến nhận", "blue"], + READY: ["Chờ khách đến nhận", "blue"], REMIND: ["Cần gọi nhắc khách", "amber"], APPOINTMENT: ["Khách đã hẹn ngày đến", "blue"], EXPIRED: ["Quá 30 ngày · khách mất khoản hoàn", "red"], FORFEITED: ["Quá 30 ngày · khách mất khoản hoàn", "red"], SWITCHED: ["Khách đổi sang chuyển khoản", "green"], - PAID: ["Đã chi tại quầy", "green"], + PAID: ["Đã trả tiền mặt", "green"], }; export const CASH_SOURCE = { RESERVATION: "Huỷ đơn", DEPOSIT: "Hoàn cọc", INCIDENT: "Sự cố cơ sở" }; export const cashPath = (id, action) => `/api/ops/cash-refunds/${encodeURIComponent(id)}/${action}`; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/workflows/useWorkflowData.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/workflows/useWorkflowData.js index 9a47649..ba90243 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/workflows/useWorkflowData.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/workflows/useWorkflowData.js @@ -74,7 +74,7 @@ export function useWorkflowData(resource) { try { localStorage.setItem(KEY, JSON.stringify(next)); } catch { /* retained only in memory */ } setData(next[storageResource]); window.dispatchEvent(new Event("safespace-workflows")); } else { - let requestPayload=action==="CONFIRM_DEPOSIT_REFUND"?{...payload,transactionRef:payload.transactionRef.trim(),transferredAt:actualVnTime(payload.transferredAt)}:payload; + let requestPayload=action==="CONFIRM_DEPOSIT_REFUND"?{...payload,transactionRef:String(payload.transactionRef||"").trim()||null,transferredAt:payload.transferredAt?actualVnTime(payload.transferredAt):null}:payload; if(action==="RECORD_REMOVAL") {requestPayload={...payload,location:payload.location?.trim()||OVERDUE_HOLDING_AREA,photos:[],beforePhotos:undefined,afterPhotos:undefined};for(const file of removalPhotos(payload)){await verifyPhotoFile(file);requestPayload.photos.push(await readPhotoData(file));}} if(activeActor.current!==actorKey)throw new Error("Tài khoản đã thay đổi. Tải lại trước khi gửi."); if(action==="RECORD_REMOVAL")requestPayload.performedAt=actualVnTime(payload.performedAt); @@ -96,7 +96,7 @@ export function useWorkflowData(resource) { } inquiryRequest.current = null; } - if(action==="CONFIRM_DEPOSIT_REFUND") {const item=result?.item;if(item?.id!==payload.id||item.status!=="PAID"||item.transactionRef!==payload.transactionRef.trim()||!Number.isFinite(Date.parse(item.paidAt))||item.amount!==data.find(r=>r.id===payload.id)?.amount||item.facilityId!==facilityId||!Number.isSafeInteger(item.version)||item.version<=data.find(r=>r.id===payload.id)?.version||["contractId","ownerId","customer","bankName","accountNumber","accountHolder"].some(k=>item[k]!==data.find(r=>r.id===payload.id)?.[k])){const error=new Error("Máy chủ chưa xác nhận bằng chứng chuyển tiền; tải lại trước khi gửi tiếp.");error.uncertain=true;throw error;}setData(previous=>previous.map(r=>r.id===item.id?item:r));} + if(action==="CONFIRM_DEPOSIT_REFUND") {const item=result?.item;if(item?.id!==payload.id||item.status!=="PAID"||(item.transactionRef||null)!==(String(payload.transactionRef||"").trim()||null)||!Number.isFinite(Date.parse(item.paidAt))||item.amount!==data.find(r=>r.id===payload.id)?.amount||item.facilityId!==facilityId||!Number.isSafeInteger(item.version)||item.version<=data.find(r=>r.id===payload.id)?.version||["contractId","ownerId","customer","bankName","accountNumber","accountHolder"].some(k=>item[k]!==data.find(r=>r.id===payload.id)?.[k])){const error=new Error("Máy chủ chưa xác nhận bằng chứng chuyển tiền; tải lại trước khi gửi tiếp.");error.uncertain=true;throw error;}setData(previous=>previous.map(r=>r.id===item.id?item:r));} else if(action==="RECORD_REMOVAL") {if(result?.item?.id!==payload.id||result.item.status!=="DONE"||!result.item.record?.savedAt||result.item.facilityId!==facilityId||!(result.item.record?.photos?.length||result.item.record?.afterPhotos?.length)){const error=new Error("Máy chủ chưa xác nhận biên bản và bằng chứng xử lý.");error.uncertain=true;throw error;}setData(previous=>previous.map(r=>r.id===result.item.id?result.item:r));} else if (resource === "inquiries") setData(previous => { const item = result.item; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx deleted file mode 100644 index 07e3234..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx +++ /dev/null @@ -1,73 +0,0 @@ -/** - * STAFF ASSIGNMENT PAGE - PHÂN CÔNG CÔNG VIỆC CHO NHÂN VIÊN CƠ SỞ (M06) - * - * Nghiệp vụ: - * - Quản lý cơ sở phân công các đầu việc (bàn giao kho, kiểm kê trả kho, xử lý sự cố) - * cho nhân viên thuộc cơ sở phụ trách (A06). - * - Hiển thị tình trạng công việc: Chưa giao (OPEN), Đã giao (ASSIGNED), Hoàn tất (COMPLETED). - */ -import React, { useState } from "react"; -import { Select } from "../../../shared/components/Pickers.jsx"; -import { Button, Field, Notice, Tag } from "../../../shared/components/UI.jsx"; -import { ASSIGN_STATE } from "../../facility-operations/state/facilityOperationsReducer.js"; -import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; -import { slotLabel } from "../../facility-operations/components/FacilityOperationsComponents.jsx"; -import { PageHeaderBlock } from "../components/PageHeaderBlock.jsx"; - -/** - * Màn hình quản lý phân bổ công việc hàng ngày cho đội ngũ nhân viên cơ sở. - */ -export function StaffAssignmentPage() { - const { ops, run } = useOps(); - const open = ops.assignments.filter((a) => a.status !== "DONE"); - const [task, setTask] = useState(() => (open.find((a) => a.status === "OPEN") || open[0])?.id || ""); - const [staff, setStaff] = useState(ops.staff[0]?.staff_id || ""); - const staffName = (id) => ops.staff.find((s) => s.staff_id === id)?.full_name || "Chưa phân công"; - const busyCount = (id) => ops.assignments.filter((a) => a.staff === id && a.status !== "DONE").length; - const submit = async (e) => { - e.preventDefault(); - // Figma 885:10419–10443: xác nhận → kết quả “Về màn hình trước”, ở lại trang phân công - await run("ASSIGN", { id: task, staff }, `Đã phân công ${staffName(staff)}`); - }; - return ( -
- -
- - - - {ops.assignments.map((a) => ( - - - - - - - ))} - -
Công việcLịch hẹnNhân viênTrạng thái
{a.title}{slotLabel(a.when)}{staffName(a.staff)}{ASSIGN_STATE[a.status][0]}
-
- {open.length > 0 ? ( -
- - - - - - - -
- ) : ( - Tất cả công việc đã hoàn tất. - )} -
- ); -} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/cash/CashRefundApprovalPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/cash/CashRefundApprovalPage.jsx index 9961c3f..c8e5294 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/cash/CashRefundApprovalPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/cash/CashRefundApprovalPage.jsx @@ -1,60 +1,57 @@ /** - * CASH REFUND APPROVAL PAGE - PHÊ DUYỆT HOÀN TIỀN MẶT TẠI QUẦY (M08 / D42 / D44) + * CASH REFUND PAGE - HOÀN TIỀN MẶT TẠI QUẦY (M08 / D42 / D44 / D66) * - * Nghiệp vụ D42 / D44: - * - Khách hàng chọn nhận tiền hoàn bằng tiền mặt (CASH) khi hủy đơn hoặc trả kho. - * - Quản lý cơ sở xem xét hồ sơ, duyệt và giao việc cho nhân viên chi tiền tại quầy. - * - Hạn nhận tiền mặt là 30 ngày; quá hạn hệ thống tự động tịch thu (FORFEITED). + * - Khách chọn nhận tiền hoàn bằng tiền mặt khi huỷ đơn, trả kho hoặc kết thúc do sự cố. + * - D66 (18/11): mỗi cơ sở 1 nhân viên nên không còn bước duyệt & giao nhân viên. Khi khách đến nhận đủ tiền, + * quản lý bấm "Xác nhận đã trả tiền mặt" (Figma M-ĐS-CHỐT · tiền mặt). Không nhập mã giao dịch. + * - Hạn nhận tiền mặt 30 ngày; quá hạn khách mất khoản hoàn (FORFEITED). Nhân viên gọi nhắc ở ngày 10, 20, 25. */ import React, { useState } from "react"; -import { Button, Field, Modal, Notice, PageHeader, Tag } from "../../../shared/components/UI.jsx"; -import { Select } from "../../../shared/components/Pickers.jsx"; +import { Button, DetailList, Modal, Notice, PageHeader, Tag } from "../../../shared/components/UI.jsx"; import { money } from "../../../shared/utils/format.js"; import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; import { RecordCard, WorkflowEmpty, WorkflowState } from "../../facility-operations/workflows/WorkflowComponents.jsx"; import { useOpsEndpoint } from "../../facility-operations/workflows/useOpsEndpoint.js"; import { CASH_SOURCE, CASH_STATUS, cashPath } from "../../facility-operations/workflows/cashRefundModel.js"; -// D42/D44 · Quản lý duyệt chi tiền mặt và giao nhân viên. Không đổi được cách nhận hoàn khách đã chọn. +const OPEN = ["WAITING_APPROVAL", "READY", "REMIND", "APPOINTMENT"]; +// Máy chủ vẫn nhận bốn mục đối chiếu; quản lý xác nhận một lần thay cho các mục này. +const CONFIRM_ALL = { identityChecked: true, codeChecked: true, amountCounted: true, signed: true }; + /** - * Màn hình quản lý cơ sở phê duyệt yêu cầu chi tiền mặt hoàn cọc hoặc hoàn tiền hủy đơn. + * Màn hình quản lý cơ sở xác nhận đã trả tiền mặt cho khách tại quầy. */ export function CashRefundApprovalPage({ embedded = false } = {}) { - const { ops, reload: reloadOps } = useOps() || {}; + const { reload: reloadOps } = useOps() || {}; const load = useOpsEndpoint("/api/ops/cash-refunds"); - const [approve, setApprove] = useState(null), [error, setError] = useState(""); + const [paying, setPaying] = useState(null), [error, setError] = useState(""); const items = Array.isArray(load.data) ? load.data : []; + const close = () => { setPaying(null); setError(""); }; const save = async () => { - if (!approve.staffId) return setError("Chọn nhân viên chi tiền."); - const res = await load.post(cashPath(approve.item.id, "approve"), { staffId: approve.staffId }); - if (!res.ok) return setError(res.error); - setApprove(null); setError(""); + const res = await load.post(cashPath(paying.id, "pay"), CONFIRM_ALL); + if (!res.ok) return setError(res.error || "Chưa ghi nhận được. Tải lại trước khi thử tiếp; không trả tiền lần nữa."); + close(); await reloadOps?.(); }; const Wrap = embedded ? "section" : "main"; return - {embedded ?

Hoàn tiền mặt tại quầy

: } + {embedded ?

Hoàn tiền mặt tại quầy

: } {items.map(r => { const [label, tone] = CASH_STATUS[r.status] || [r.status, "amber"]; - const staffCode = r.staffId || r.staff_id; - const staffName = r.staffName || r.staff_name; return {label}{["WAITING_APPROVAL", "READY", "REMIND"].includes(r.status) && }}> + actions={<>{label}{OPEN.includes(r.status) && }}> {money(r.amount)} -

{r.deadlineDate ? `Hạn nhận ${r.deadlineDate}` : "Chưa duyệt"}{staffName ? ` · nhân viên: ${staffName}` : staffCode ? ` · nhân viên: ${staffCode}` : ""}{r.paidAt ? ` · đã chi ${r.paidAt}${r.paidBy ? ` bởi ${r.paidBy}` : ""}` : ""}{r.appointmentDate ? ` · khách hẹn ${r.appointmentDate}` : ""}

+

{r.deadlineDate ? `Hạn nhận ${r.deadlineDate}` : "Chờ khách đến nhận"}{r.paidAt ? ` · đã trả ${r.paidAt}${r.paidBy ? ` bởi ${r.paidBy}` : ""}` : ""}{r.appointmentDate ? ` · khách hẹn ${r.appointmentDate}` : ""}

; })} {!items.length && }
- {approve && { setApprove(null); setError(""); }}> -

Chi {money(approve.item.amount)} cho {approve.item.customer}. Nhân viên được giao tick đủ 4 mục khi chi.

- + {paying && +

Chỉ xác nhận khi khách đã nhận đủ tiền tại quầy. Không cần nhập mã giao dịch.

+ {error && {error}} -
+
}
; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/overdue/OverdueCasePage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/overdue/OverdueCasePage.jsx index b7dd550..e002cd8 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/overdue/OverdueCasePage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/overdue/OverdueCasePage.jsx @@ -7,7 +7,7 @@ * - Sau thời hạn quy định, chuyển sang quy trình niêm phong và xử lý tài sản bỏ lại (S06). */ import React, { useState } from "react"; -import { Button, Field, LinkButton, Notice, PageHeader } from "../../../shared/components/UI.jsx"; +import { Button, LinkButton, Notice, PageHeader } from "../../../shared/components/UI.jsx"; import { dateLabel, money } from "../../../shared/utils/format.js"; import { depositSchedule, policyRate } from "../../facility-operations/workflows/workflowModel.js"; import { useWorkflowData } from "../../facility-operations/workflows/useWorkflowData.js"; @@ -17,10 +17,10 @@ import { InfoTiles, RecordCard, useWorkflowChange, WorkflowEmpty, WorkflowState * Màn hình xử lý các ca vi phạm hợp đồng và nợ phí quá hạn. */ export function OverdueCasePage({ query = new URLSearchParams() } = {}) { - const load = useWorkflowData("overdue"), policy = useWorkflowData("policy"), defaultRate = policyRate(policy.data), [selected, setSelected] = useState(""), [assignee, setAssignee] = useState(""), [error, setError] = useState(""); + const load = useWorkflowData("overdue"), policy = useWorkflowData("policy"), defaultRate = policyRate(policy.data), [selected, setSelected] = useState(""); const [dialog, ask] = useWorkflowChange(load); return
- + {/* #7: mở từ nút "Xử lý quá hạn" trên hợp đồng → chỉ hiện hồ sơ của hợp đồng đó */} {query.get("contract") &&

Đang xem hồ sơ của {query.get("contract")} · Xem tất cả hồ sơ quá hạn

} @@ -39,7 +39,7 @@ export function OverdueCasePage({ query = new URLSearchParams() } = {}) { title={`${item.customer} · Kho ${item.unit}`} subtitle={`${item.contractId} · Hết hạn ${dateLabel(item.endDate)}`} status={item.status === "DONE" ? "Đã lập biên bản" : `Quá hạn ${overdueDays} ngày`} - actions={} + actions={} > ) : canAssign ? ( -
{ - e.preventDefault(); - if (!assignee.trim()) return setError("Nhập nhân viên phụ trách."); - ask("ASSIGN_REMOVAL", { id: item.id, assignee }, "Phân công xử lý đồ quá hạn?", "Nhân viên cần lập biên bản và ghi vị trí thực tế sau khi thực hiện."); - }}> - - { setAssignee(e.target.value); setError(""); }} /> - - -
+

Đã đến mốc xử lý đồ. Nhân viên của cơ sở thấy việc này ở "Công việc xử lý đồ quá hạn" và lập biên bản; không cần phân công (D66).

) : (

Chưa đến mốc xử lý đồ (ngày thứ {disposalDay} quá hạn). Cọc cạn vào ngày thứ {depletionDay}.

)} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/CancellationRefundPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/CancellationRefundPage.jsx index 0b05246..4d4d2e6 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/CancellationRefundPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/CancellationRefundPage.jsx @@ -6,10 +6,9 @@ * - Hoàn lại 100% tiền thuê đã trả và 95% tiền cọc ban đầu. * - Hỗ trợ hoàn qua chuyển khoản ngân hàng hoặc tiền mặt tại quầy (D42). */ -import { transferProof,actualVnTime,knownMoney } from "../../facility-operations/settlements/settlementModel.js"; +import { transferProof,knownMoney } from "../../facility-operations/settlements/settlementModel.js"; import { amountLabel } from "../../facility-operations/damage/DamageComponents.jsx"; import ConfirmDialog from "../../../shared/components/ConfirmDialog.jsx"; -import { vnDateTimeInput } from "../../facility-operations/damage/damageModel.js"; import { InfoTiles, RecordCard } from "../../facility-operations/workflows/WorkflowComponents.jsx"; import React, { useState } from "react"; import { Button, Field, LinkButton, Modal, Notice } from "../../../shared/components/UI.jsx"; @@ -23,25 +22,25 @@ import { CANCEL_FEE_LABEL, CANCEL_REFUND_SHORT } from "../../../shared/utils/pol // Khách trả qua PayOS nên chỉ hoàn bằng chuyển khoản (Figma M08a ẩn lựa chọn tiền mặt) const METHOD_LOCKED = "Chuyển khoản về tài khoản khách đã khai báo"; +// D64 (18/11, Figma M08a/M08a2): không nhập mã giao dịch / thời gian; bấm "Xác nhận đã hoàn" là xác nhận đã chuyển. function RefundDialog({ refund, onClose, onDone }) { const { run } = useOps(); const method = "BANK_TRANSFER"; - const [at,setAt]=useState(""),[confirmed,setChecked]=useState(false); - const [ref, setRef] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const submit = async () => { if(busy)return; - try{transferProof(refund,{transactionRef:ref,transferredAt:at,confirmed});}catch(error){return setError(error.message);} + try{transferProof(refund,{confirmed:true});}catch(error){return setError(error.message);} setBusy(true); setError(""); - const res = await run("CONFIRM_RESERVATION_REFUND", { id: refund.id, method, transaction_ref: ref.trim(),transferredAt:actualVnTime(at),confirmed }); + const res = await run("CONFIRM_RESERVATION_REFUND", { id: refund.id, method, confirmed: true }); setBusy(false); - if (!res.ok) return setError(res.error || "Chưa lưu được xác nhận. Kiểm tra trạng thái giao dịch trước khi thử lưu lại. Không chuyển khoản lần nữa."); - onDone({ id: refund.id, amount: refund.amount, ref: ref.trim() }); + if (!res.ok) return setError(res.error || "Chưa lưu được xác nhận. Kiểm tra trạng thái trước khi thử lại. Không chuyển khoản lần nữa."); + onDone({ id: refund.id, amount: refund.amount }); }; + const account = refund.bankName && refund.accountNumber ? `${refund.bankName} · ${refund.accountNumber} · ${refund.accountHolder || ""}` : "Chưa có dữ liệu tài khoản nhận hoàn"; return ( - +

{refund.customer} · Huỷ đơn ngày {dateLabel(refund.cancelled_at)}

@@ -50,13 +49,8 @@ function RefundDialog({ refund, onClose, onDone }) {
Số tiền hoàn
{amountLabel(refund.amount)}
-

Hình thức hoàn cố định theo lựa chọn của khách: {METHOD_LOCKED}.

- - { setRef(e.target.value); setError(""); }} /> - - {error && ref.trim() && {error}} -

Sau khi xác nhận, đơn chuyển sang “Đã hoàn tiền” và khách nhận thông báo. Không thể hoàn tác.

- setAt(e.target.value)}/> + + {error && {error}}
); } @@ -79,7 +73,7 @@ export function CancellationRefundPage({ embedded = false } = {}) { }>Số tiền hoàn: {amountLabel(r.amount)}{r.fee > 0 &&

{CANCEL_REFUND_SHORT}

})} {!refunds.length && Chưa có đơn huỷ cần hoàn tiền.} {!embedded && Về Hoàn tiền} - {detail && setDetail(null)}>

{detail.status === "PENDING" ? "Khoản hoàn đang chờ thực hiện; kiểm tra giao dịch trước khi xác nhận." : detail.status==="PAID"?`Đã ghi nhận hoàn tiền${detail.transaction_ref ? ` · ${detail.transaction_ref}` : ""}.`:"Chưa rõ trạng thái chuyển tiền."}

} + {detail && setDetail(null)}>

{detail.status === "PENDING" ? "Khoản hoàn đang chờ thực hiện; kiểm tra giao dịch trước khi xác nhận." : detail.status==="PAID"?"Đã ghi nhận hoàn tiền.":"Chưa rõ trạng thái chuyển tiền."}

} {open && setOpen(null)} onDone={result => { setOpen(null); setConfirmed(result); }} />} ; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/DepositRefundPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/DepositRefundPage.jsx index 9e50245..33a93b0 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/DepositRefundPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/refunds/DepositRefundPage.jsx @@ -7,7 +7,7 @@ * - Tuyệt đối không tạo nợ âm vượt quá tiền cọc đang giữ; tạo lệnh thanh toán REFUND cho số tiền còn lại. */ import React,{useState} from "react"; -import { Button, DetailList, Empty, Field, LinkButton, Notice, PageHeader, Tag } from "../../../shared/components/UI.jsx"; +import { Button, DetailList, Empty, LinkButton, Notice, PageHeader, Tag } from "../../../shared/components/UI.jsx"; import { useWorkflowData } from "../../facility-operations/workflows/useWorkflowData.js"; import { useWorkflowChange, WorkflowState } from "../../facility-operations/workflows/WorkflowComponents.jsx"; import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; @@ -15,144 +15,48 @@ import { isCashRefund, transferProof, knownMoney } from "../../facility-operatio import { SettlementTable } from "../../facility-operations/settlements/SettlementComponents.jsx"; import { settlementFromRefund } from "../../facility-operations/settlements/settlementModel.js"; import { amountLabel,timeLabel } from "../../facility-operations/damage/DamageComponents.jsx"; -import { vnDateTimeInput } from "../../facility-operations/damage/damageModel.js"; import "../../../shared/styles/customer-detail.css"; import { go, qs } from "../../../app/router.js"; +// D64 (18/11, Figma M-ĐS-CHỐT): quản lý thấy thông tin nhận hoàn khách đã điền và chỉ bấm xác nhận; +// không nhập mã giao dịch hay thời gian chuyển (máy chủ ghi thời điểm xác nhận). function TransferForm({item,load,ask}) { - const hasBank = Boolean(item.bankName && item.bankName !== "CASH" && item.accountNumber); const method = (item.method === "CASH" || item.bankName === "CASH") ? "CASH" : "BANK_TRANSFER"; - const [ref, setRef] = useState(() => item.transactionRef || ""); - const [at, setAt] = useState(() => vnDateTimeInput()); - const [confirmed, setConfirmed] = useState(false); - const [error, setError] = useState(""); - const isCash = method === "CASH"; - const payload = { - id: item.id, - transactionRef: ref, - transferredAt: at, - confirmed, - expectedVersion: item.version, - method - }; + const [error, setError] = useState(""); + const payload = { id: item.id, confirmed: true, expectedVersion: item.version, method }; const disabled = load.busy || load.needsRefresh; let valid = false; - try { - transferProof(item, payload); - valid = true; - } catch {} - + try { transferProof(item, payload); valid = true; } catch {} + const rows = isCash + ? [["Khách chọn nhận", "Tiền mặt tại quầy"], ["Người nhận", item.customer || item.accountHolder || "Chưa có dữ liệu"], ["Số tiền cần trả", amountLabel(item.amount)]] + : [["Khách chọn nhận", "Chuyển khoản"], ["Ngân hàng", item.bankName || "Chưa có dữ liệu"], ["Số tài khoản", item.accountNumber || "Chưa có dữ liệu"], + ["Chủ tài khoản", item.accountHolder || "Chưa có dữ liệu"], ["Số tiền cần chuyển", amountLabel(item.amount)]]; + const submit = (e) => { + e.preventDefault(); + if (disabled) return; + try { transferProof(item, payload); } catch (err) { return setError(err.message); } + setError(""); + ask("CONFIRM_DEPOSIT_REFUND", payload, + isCash ? `Xác nhận đã trả ${amountLabel(item.amount)} tiền mặt?` : `Xác nhận đã chuyển ${amountLabel(item.amount)}?`, + isCash ? "Chỉ xác nhận khi khách đã nhận đủ tiền tại quầy. Không cần nhập mã giao dịch." + : `Kiểm tra đã chuyển đúng số tiền vào ${item.bankName || "tài khoản"} · ${item.accountNumber || ""} · ${item.accountHolder || ""}. Không cần nhập mã giao dịch.`, + { confirmLabel: isCash ? "Đã trả tiền mặt" : "Đã chuyển khoản", + successTitle: `Đã hoàn tiền ${amountLabel(item.amount)}`, + failTitle: isCash ? "Chưa ghi nhận được trả tiền mặt" : "Chưa ghi nhận được chuyển khoản", + doneLabel: "Về hợp đồng & quá hạn", onDone: () => go("manager/contracts") }); + }; return ( -
{ - e.preventDefault(); - if (disabled) return; - try { - transferProof(item, payload); - setError(""); - ask( - "CONFIRM_DEPOSIT_REFUND", - payload, - isCash - ? `Xác nhận đã chi ${amountLabel(item.amount)} tiền mặt?` - : `Ghi nhận đã chuyển ${amountLabel(item.amount)}?`, - isCash - ? `Chỉ xác nhận sau khi đã chi đủ ${amountLabel(item.amount)} tiền mặt cho khách hàng tại quầy và có chữ ký nhận.` - : `Chỉ ghi nhận sau khi đã chuyển ${amountLabel(item.amount)} vào đúng tài khoản. Thao tác không thực hiện chuyển tiền.`, - { - confirmLabel: isCash ? "Xác nhận đã chi tiền" : "Xác nhận đã chuyển", - successTitle: isCash ? `Đã chi hoàn cọc ${amountLabel(item.amount)}` : `Đã hoàn cọc ${amountLabel(item.amount)}`, - failTitle: isCash ? "Chưa ghi nhận được chi tiền mặt" : "Chưa ghi nhận được chuyển khoản", - doneLabel: "Về hợp đồng & quá hạn", - onDone: () => go("manager/contracts"), - } - ); - } catch (err) { - setError(err.message); - } - }} - noValidate - > -

{isCash ? "Ghi nhận chi tiền mặt tại quầy" : "Ghi nhận chuyển khoản"}

- - - {isCash - ? "Khách hàng đã chọn nhận tiền mặt tại quầy cơ sở. Kiểm tra CCCD trùng tên hợp đồng trước khi chi tiền và lưu phiếu chi." - : "Khách đã chọn nhận chuyển khoản ngân hàng. Chuyển đúng số tiền vào tài khoản nhận hoàn rồi nhập mã giao dịch."} - - - - -
- - setRef(e.target.value)} - placeholder={isCash ? "Ví dụ: PC-001" : "Mã trên biên lai chuyển khoản, ví dụ FT26316123456789"} - /> - - - setAt(e.target.value)} - /> - -
- - {!isCash &&

Nhập mã giao dịch ngân hàng sau khi chuyển tiền.

} - - + +

Bước tiếp theo

+

{isCash + ? "Khách đã chọn nhận tiền mặt tại quầy. Khi khách đến nhận đủ tiền, bấm xác nhận. Không cần nhập mã giao dịch." + : "Khách đã chọn nhận hoàn bằng chuyển khoản. Chuyển đúng số tiền vào tài khoản dưới đây rồi bấm xác nhận. Không cần nhập mã giao dịch."}

+ {error && {error}} -

- {isCash - ? "Kiểm tra kỹ thông tin người nhận và ký nhận trước khi ghi nhận." - : "Thiếu tài khoản nhận hoàn, thời gian, mã giao dịch ngân hàng hoặc xác nhận thì không được ghi nhận."} -

-
- - Xem biên bản & ảnh - - + Xem biên bản & ảnh +
); @@ -164,8 +68,8 @@ export function DepositRefundPage({query=new URLSearchParams(),embedded=false}) const base=useWorkflowData("depositRefunds"),{ops,source,run,saving,needsRefresh}=useOps(),[selected,setSelected]=useState(query.get("id")||""); const load=source==="local"?{...base,data:ops.deposit_refunds||[],loading:false,error:"",busy:saving,needsRefresh,demo:true,run:(action,payload)=>run(action,payload)}:base; const [dialog,ask]=useWorkflowChange(load),item=load.data?.find(r=>r.id===selected); - // D42/D47: hoàn cọc tiền mặt nằm ở mục "Hoàn tiền mặt tại quầy" (quản lý duyệt & giao, nhân viên chi) — không lặp ở đây. + // D42/D47/D66: hoàn cọc tiền mặt nằm ở mục "Hoàn tiền mặt tại quầy" (quản lý xác nhận đã trả) — không lặp ở đây. const transfers=(load.data||[]).filter(r=>!isCashRefund(r)); const Wrap=embedded?"section":"main"; - return {embedded?

{item?`Hoàn cọc ${item.contractId} · ${item.customer}`:"Hoàn cọc sau trả kho"}

:<>

SafeSpace / Quản lý cơ sở / Hoàn tiền

}{!selected?
{transfers.map(r=>

{r.customer} · Kho {r.unit}

{r.contractId} · {amountLabel(r.amount)}

{r.status==="PAID"?"Đã hoàn":r.status==="PENDING"?"Chờ hoàn":r.status==="NO_REFUND"?"Không còn khoản hoàn":"Chưa rõ trạng thái"}
)}{!transfers.length&&}
:!item?:<>
{item.status==="PENDING"&&knownMoney(item.amount)&&item.amount>0&&isCashRefund(item)?Khách chọn nhận tiền mặt tại quầy. Duyệt và giao nhân viên chi ở mục Hoàn tiền mặt tại quầy; nhân viên xác nhận khi đã chi cho khách. Mở Hoàn tiền mặt tại quầy:item.status==="PENDING"&&knownMoney(item.amount)&&item.amount>0?:{item.status==="PAID"?`Đã ghi nhận ${item.method==="CASH"?"chi tiền mặt":"chuyển tiền"} lúc ${timeLabel(item.paidAt)}.`:knownMoney(item.amount)&&item.amount===0?"Không còn khoản hoàn; không tạo giao dịch chuyển tiền.":"Chưa có đủ dữ liệu khoản hoàn để thao tác."}}
}
{dialog}
; + return {embedded?

{item?`Hoàn cọc ${item.contractId} · ${item.customer}`:"Hoàn cọc sau trả kho"}

:<>

SafeSpace / Quản lý cơ sở / Hoàn tiền

}{!selected?
{transfers.map(r=>

{r.customer} · Kho {r.unit}

{r.contractId} · {amountLabel(r.amount)}

{r.status==="PAID"?"Đã hoàn":r.status==="PENDING"?"Chờ hoàn":r.status==="NO_REFUND"?"Không còn khoản hoàn":"Chưa rõ trạng thái"}
)}{!transfers.length&&}
:!item?:<>
{item.status==="PENDING"&&knownMoney(item.amount)&&item.amount>0&&isCashRefund(item)?Khách chọn nhận tiền mặt tại quầy. Khi khách đến nhận đủ tiền, xác nhận ở mục Hoàn tiền mặt tại quầy. Mở Hoàn tiền mặt tại quầy:item.status==="PENDING"&&knownMoney(item.amount)&&item.amount>0?:{item.status==="PAID"?`Đã ghi nhận ${item.method==="CASH"?"chi tiền mặt":"chuyển tiền"} lúc ${timeLabel(item.paidAt)}.`:knownMoney(item.amount)&&item.amount===0?"Không còn khoản hoàn; không tạo giao dịch chuyển tiền.":"Chưa có đủ dữ liệu khoản hoàn để thao tác."}}
}
{dialog}
; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/overdue/OverdueRemovalPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/overdue/OverdueRemovalPage.jsx index a8c1c76..adf6f2d 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/overdue/OverdueRemovalPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/overdue/OverdueRemovalPage.jsx @@ -38,7 +38,7 @@ export function OverdueRemovalPage() { { confirmLabel: "Lưu biên bản", successTitle: "Đã lưu biên bản xử lý đồ", failTitle: "Chưa lưu được biên bản", doneLabel: "Về công việc trong ngày", onDone: () => go("staff") }); }; return
- {(load.data || []).map(item => open(item)}>{selected === item.id ? "Thu gọn" : item.record ? "Xem biên bản" : "Lập biên bản"}}> + {(load.data || []).map(item => open(item)}>{selected === item.id ? "Thu gọn" : item.record ? "Xem biên bản" : "Lập biên bản"}}> {selected === item.id && (item.record ? :
submit(e, item)} noValidate> @@ -61,6 +61,6 @@ export function OverdueRemovalPage() { {error &&

{error}

}
)} -
)}{!load.data?.length && !load.error && Về công việc trong ngày} +
)}{!load.data?.length && !load.error && Về công việc trong ngày}
{dialog}
; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/payments/CashRefundCounterPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/payments/CashRefundCounterPage.jsx index a92c646..802e00b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/payments/CashRefundCounterPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/payments/CashRefundCounterPage.jsx @@ -16,7 +16,6 @@ import { RecordCard, WorkflowEmpty, WorkflowState } from "../../facility-operati import { useOpsEndpoint } from "../../facility-operations/workflows/useOpsEndpoint.js"; import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; import { CASH_STATUS, CASH_SOURCE, cashPath } from "../../facility-operations/workflows/cashRefundModel.js"; -import { useMe } from "../hooks/useStaffIdentity.js"; const CALL_RESULTS = { APPOINTMENT: "Khách hẹn đến quầy · ghi ngày hẹn", @@ -24,27 +23,17 @@ const CALL_RESULTS = { SWITCH_TO_BANK: "Khách muốn đổi sang chuyển khoản", WRONG_NUMBER: "Sai số điện thoại · báo quản lý", }; -const PAY_CHECKS = [ - ["identityChecked", "CCCD trùng tên trên hợp đồng"], - ["codeChecked", "Khách đọc đúng mã đơn và số điện thoại"], - ["amountCounted", "Đã đếm đủ tiền trước mặt khách"], - ["signed", "Khách đã nhận tiền và ký sổ chi tại quầy"], -]; -// Figma S10 / S10b · D42/D44: nhân viên gọi nhắc (ngày 10, 20, 25) và chi tiền hoàn tại quầy sau khi quản lý duyệt. +// Figma S10b · D42/D44/D66: nhân viên chỉ gọi nhắc khách (ngày 10, 20, 25); quản lý xác nhận đã trả tiền mặt. /** * Màn hình nhân viên thực hiện chi trả tiền mặt cho khách hàng tại cơ sở. */ export function CashRefundCounterPage() { const { reload: reloadOps } = useOps() || {}; const load = useOpsEndpoint("/api/ops/cash-refunds"); - const me = useMe(); - const [call, setCall] = useState(null), [pay, setPay] = useState(null), [error, setError] = useState(""); - const items = (Array.isArray(load.data) ? load.data : []).filter(r => - ["READY", "REMIND", "APPOINTMENT"].includes(r.status) && - (!r.staffId && !r.staff_id || !me?.staff_id || (r.staffId || r.staff_id) === me.staff_id) - ); - const close = () => { setCall(null); setPay(null); setError(""); }; + const [call, setCall] = useState(null), [error, setError] = useState(""); + const items = (Array.isArray(load.data) ? load.data : []).filter(r => ["WAITING_APPROVAL", "READY", "REMIND", "APPOINTMENT"].includes(r.status)); + const close = () => { setCall(null); setError(""); }; const saveCall = async () => { if (call.result === "APPOINTMENT" && !call.appointmentDate) return setError("Chọn ngày khách hẹn đến quầy."); const deadline = String(call.item?.deadlineDate || "").slice(0, 10); @@ -52,28 +41,18 @@ export function CashRefundCounterPage() { const res = await load.post(cashPath(call.item.id, "calls"), { result: call.result, appointmentDate: call.result === "APPOINTMENT" ? call.appointmentDate : null, note: call.note.trim() || null }); if (res.ok) { close(); await reloadOps?.(); } else setError(res.error); }; - const savePay = async () => { - if (PAY_CHECKS.some(([k]) => !pay[k])) return setError("Tick đủ 4 mục trước khi xác nhận đã chi."); - const { item, ...checks } = pay; - const res = await load.post(cashPath(item.id, "pay"), checks); - if (res.ok) { close(); await reloadOps?.(); } else setError(res.error); - }; return
- + {items.map(r => { - const staffCode = r.staffId || r.staff_id; - const staffName = r.staffName || r.staff_name; - const isOther = staffCode && me?.staff_id && staffCode !== me.staff_id; return Đã giao cho {staffName || staffCode} : <> - }> + actions={}> {money(r.amount)} -

Hạn nhận {r.deadlineDate ? vnDate(r.deadlineDate) : "Chưa có thông tin"}{staffName ? ` · nhân viên: ${staffName}` : staffCode ? ` · nhân viên: ${staffCode}` : ""}{r.daysSinceApproved != null ? ` · ngày ${r.daysSinceApproved} sau khi duyệt` : ""}{r.appointmentDate ? ` · khách hẹn ${r.appointmentDate}` : ""}{r.lastCall ? ` · lần gọi trước: ${r.lastCall}` : ""}

+

Hạn nhận {r.deadlineDate ? vnDate(r.deadlineDate) : "Chưa có thông tin"}{r.daysSinceApproved != null ? ` · ngày ${r.daysSinceApproved} kể từ khi chốt hoàn` : ""}{r.appointmentDate ? ` · khách hẹn ${r.appointmentDate}` : ""}{r.lastCall ? ` · lần gọi trước: ${r.lastCall}` : ""}

; })} - {!items.length && } + {!items.length && }
{call &&
{Object.entries(CALL_RESULTS).map(([k, label]) => )}
@@ -83,11 +62,5 @@ export function CashRefundCounterPage() { {error && {error}}
} - {pay && -

Chi {money(pay.item.amount)} cho {pay.item.customer}. Không chi nếu chưa đối chiếu đủ.

-
{PAY_CHECKS.map(([k, label]) => )}
- {error && {error}} -
-
}
; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/api/apiMappers.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/api/apiMappers.js index 43ba4a6..7060393 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/api/apiMappers.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/api/apiMappers.js @@ -162,6 +162,7 @@ const EMPTY_OVERLAY = { returns: [], appointments: [], notifications: [], + dismissedNotices: [], // khoá thông báo đã đọc (đã xoá khỏi chuông) để không sinh lại từ dữ liệu máy chủ activities: [], name: null, phone: null, @@ -194,6 +195,7 @@ export function composeData({ catalog, remote, overlay: ov, session, timeoutSeco returns: remote ? [] : [...overlay.returns], tickets: [], notifications: [...overlay.notifications], + dismissedNotices: [...(overlay.dismissedNotices || [])], activities: [...overlay.activities], }; if (!remote) return base; @@ -523,4 +525,3 @@ export function usernameFromEmail(email) { if (e.length <= 50) return e; return `${e.split("@")[0].slice(0, 40)}${Date.now().toString(36).slice(-6)}`; } - diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/components/Header.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/components/Header.jsx index 33f9ac5..a34f757 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/components/Header.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/components/Header.jsx @@ -85,7 +85,7 @@ function NotificationPopup({ onClose, anchorRef }) { {(data.notifications_error || error) &&
Chưa tải được thông báo

{error || "Kiểm tra kết nối rồi thử lại."}

} -

{unread ? `${unread} thông báo mới` : "Đã đọc tất cả"}

+

{unread ? `${unread} thông báo mới` : "Không có thông báo mới"}

    {items.map((n) => (
  • @@ -101,7 +101,7 @@ function NotificationPopup({ onClose, anchorRef }) { {items.length > 0 && !unread &&

    Bạn đã xem hết thông báo hiện tại.

    } {unread > 0 && ( )} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/utils/notices.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/utils/notices.js new file mode 100644 index 0000000..dc8bc2f --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/shared/utils/notices.js @@ -0,0 +1,3 @@ +// Chuông thông báo (18/11): đã đọc thì xoá khỏi chuông và nhớ khoá để thông báo sinh từ máy chủ không quay lại. +// Thông báo quá hạn gắn thêm nội dung để khi số ngày quá hạn đổi thì hiện lại. +export const noticeKey = (n) => (typeof n?.id === "string" && n.id.startsWith("SERVER-OVERDUE-") ? `${n.id}|${n.detail}` : n?.id); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js index c28658e..4cc3178 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js @@ -73,7 +73,7 @@ test("phân công việc hỗ trợ cho nhân viên → yêu cầu chuyển sang assert.equal(s.assignments.find((a) => a.id === "PC-03").status, "DONE"); }); -test("M08 · xác nhận hoàn tiền đơn huỷ theo D27: cần mã giao dịch, chỉ một lần", () => { +test("M08 · xác nhận hoàn tiền đơn huỷ: D64 không cần mã giao dịch, chỉ một lần", () => { let s = createOpsData(T); const pending = s.refunds.filter((r) => r.status === "PENDING"); assert.equal(pending.length, 2); @@ -82,7 +82,8 @@ test("M08 · xác nhận hoàn tiền đơn huỷ theo D27: cần mã giao dịc assert.equal(r.amount, r.rent + r.deposit - r.fee, `${r.id}: hoàn 100% thuê + 90% cọc`); } const id = pending[0].id; - assert.match(run(s, "CONFIRM_RESERVATION_REFUND", { id, method: "BANK_TRANSFER", transaction_ref: " " }).error.message, /mã giao dịch/); + assert.match(run(s, "CONFIRM_RESERVATION_REFUND", { id, method: "BANK_TRANSFER" }).error.message, /xác nhận/); + assert.ok(!run(s, "CONFIRM_RESERVATION_REFUND", { id, method: "BANK_TRANSFER", confirmed: true }).error, "D64: không nhập mã vẫn xác nhận được"); const out = run(s, "CONFIRM_RESERVATION_REFUND", { id, method: "BANK_TRANSFER", transaction_ref: "FT26258904512",confirmed:true,transferredAt:"2026-09-14T01:00:00Z" }); assert.ok(!out.error); s = out.state; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js index 9fce520..f6372c8 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js @@ -132,7 +132,7 @@ test("trả kho: tạo lịch hẹn chờ xác nhận, không đổi trạng th assert.match(run(s, "REQUEST_RETURN", { contract_id: "HĐ-2026-0142", date: "2026-09-20", slot: "09:00–09:30" }).error.message, /quá khứ/); }); -test("hợp đồng: trạng thái suy ra theo ngày (30 ngày → sắp hết hạn)", () => { +test("hợp đồng: trạng thái suy ra theo ngày (≤ 10 ngày → sắp hết hạn, D65)", () => { const s = createSeedData(T); assert.equal(contractStatus(s.contracts[0], NOW), "ACTIVE"); assert.equal(contractStatus(s.contracts[1], NOW), "EXPIRING"); @@ -269,3 +269,18 @@ test("huỷ đơn (C14a, D49): đơn đã thanh toán chưa nhận kho được assert.equal(out.state.contracts.find((c) => c.reservation_id === r.reservation_id).status, "ENDED"); assert.match(run(s, "CANCEL_RESERVATION", { reservation_id: "SS-20260615-0086" }).error.message, /nhận kho/); }); + +test("chuông 18/11: đã đọc thì xoá khỏi chuông và nhớ khoá; quá hạn đổi số ngày thì khoá khác", async () => { + const { noticeKey } = await import("../src/shared/utils/notices.js"); + const s = { ...createSeedData(T), notifications: [ + { id: "SERVER-PAID-1", title: "a", detail: "x", created_at: "2026-11-17T01:00:00Z", read: false }, + { id: "SERVER-OVERDUE-9-2026-11-05", title: "b", detail: "Quá hạn 12 ngày", created_at: "2026-11-18T01:00:00Z", read: false }, + ] }; + const one = run(s, "MARK_READ", { ids: ["SERVER-PAID-1"] }).state; + assert.deepEqual(one.notifications.map(n => n.id), ["SERVER-OVERDUE-9-2026-11-05"]); + assert.ok(one.dismissedNotices.includes("SERVER-PAID-1")); + const all = run(one, "MARK_READ", {}).state; + assert.equal(all.notifications.length, 0); + assert.ok(all.dismissedNotices.includes("SERVER-OVERDUE-9-2026-11-05|Quá hạn 12 ngày")); + assert.notEqual(noticeKey({ id: "SERVER-OVERDUE-9-2026-11-05", detail: "Quá hạn 13 ngày" }), "SERVER-OVERDUE-9-2026-11-05|Quá hạn 12 ngày"); +}); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs index 85d8fe3..04deb71 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs @@ -243,7 +243,7 @@ try { "staff/reconcile?id=SS-20260914-0142", "staff/verify?id=XM-0142", "staff/handover?id=BG-0115", "staff/return?id=TK-0098", "staff/support?id=HT-0082", "staff/done?kind=payment", "staff/nope", ], - MANAGER: ["manager/incidents", "manager/incidents?id=SC-local-0086", "manager/incidents?id=missing","manager/overdue", "manager/cash-refunds", "manager/unit-conflicts", "manager/daily-report", "manager/deposit-refunds","manager", "manager/units", "manager/units?tab=OVERDUE", "manager/units?tab=MAINTENANCE", "manager/allocate", "manager/assign", "manager/renewals", "manager/contracts", "manager/refunds", "manager/report", "manager/done", "staff"], + MANAGER: ["manager/incidents", "manager/incidents?id=SC-local-0086", "manager/incidents?id=missing","manager/overdue", "manager/cash-refunds", "manager/unit-conflicts", "manager/daily-report", "manager/deposit-refunds","manager", "manager/units", "manager/units?tab=OVERDUE", "manager/units?tab=MAINTENANCE", "manager/allocate", "manager/renewals", "manager/contracts", "manager/refunds", "manager/report", "manager/done", "staff"], }; for (const acc of OPS_ACCOUNTS) { seed(true, acc); @@ -415,7 +415,7 @@ try { assert.equal(fewItems.clean, 3); assert.equal(fewItems.dirty, false); window.location.hash="#/staff/return?id=TK-0098";b8html=renderToStaticMarkup(React.createElement(App));assert.ok(b8html.includes("Tải ảnh hiện trạng / hư hỏng · Bắt buộc")&&b8html.includes("Lưu nháp"));assert.ok(!b8html.includes("Ảnh kho trống do khách gửi"),"Task #8 bỏ khung ảnh khách gửi");assert.ok(!b8html.includes("Đã chuyển hết đồ khỏi kho"),"Không điền sẵn kết luận kiểm kê"); seed(true,manager);window.location.hash="#/manager/contracts?id=missing";b8html=renderToStaticMarkup(React.createElement(App));assert.ok(b8html.includes("Không tìm thấy hợp đồng"));assert.ok(!b8html.includes("Bước tiếp theo"));assert.ok(!b8html.includes('table--hover')); - window.location.hash="#/manager/deposit-refunds?id=HC-0098";b8html=renderToStaticMarkup(React.createElement(App));for(const text of ["Mã giao dịch","Thời gian chuyển","đúng tài khoản nhận"])assert.ok(b8html.includes(text),text);assert.match(b8html,/]*disabled[^>]*>Ghi nhận đã chuyển tiền<\/button>/);assert.ok(!b8html.includes("Tạo lại mã")&&!b8html.includes('value="FT'),"Task #21 bỏ nút Tạo lại mã và tự sinh mã");assert.ok(!b8html.includes("Tiền mặt tại quầy"),"Task #20 khóa hình thức hoàn theo khách"); + window.location.hash="#/manager/deposit-refunds?id=HC-0098";b8html=renderToStaticMarkup(React.createElement(App));for(const text of ["Khách chọn nhận","Số tài khoản","Chủ tài khoản","Không cần nhập mã giao dịch"])assert.ok(b8html.includes(text),text);assert.ok(!b8html.includes("Mã giao dịch ngân hàng")&&!b8html.includes("Thời gian chuyển"),"D64 bỏ ô mã giao dịch và thời gian");assert.match(b8html,/]*>Xác nhận đã chuyển khoản<\/button>/);assert.ok(!b8html.includes("Tạo lại mã")&&!b8html.includes('value="FT'),"Task #21 bỏ nút Tạo lại mã và tự sinh mã");assert.ok(!b8html.includes("Tiền mặt tại quầy"),"Task #20 khóa hình thức hoàn theo khách"); delete b8ops.deposit_refunds[0].amount;memory.set(OPS_KEY,JSON.stringify(b8ops));b8html=renderToStaticMarkup(React.createElement(App));assert.ok(b8html.includes("Chưa có dữ liệu"));assert.ok(!b8html.includes("Không còn khoản hoàn;")); b8ops.deposit_refunds[0].amount=0;b8ops.deposit_refunds[0].status="NO_REFUND";memory.set(OPS_KEY,JSON.stringify(b8ops));b8html=renderToStaticMarkup(React.createElement(App));assert.ok(b8html.includes("không tạo giao dịch chuyển tiền"));assert.ok(!b8html.includes('type="datetime-local"')); b8ops.refunds=[{...b8ops.refunds[0],status:"UNKNOWN",amount:undefined}];memory.set(OPS_KEY,JSON.stringify(b8ops));window.location.hash="#/manager/refunds";b8html=renderToStaticMarkup(React.createElement(App));assert.ok(b8html.includes("Chưa rõ trạng thái")&&b8html.includes("Chưa có dữ liệu"));assert.ok(!b8html.includes("Đã hoàn")); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/return-policy.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/return-policy.test.js index e2681f6..1f894f7 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/return-policy.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/return-policy.test.js @@ -99,15 +99,15 @@ test("badge nhân viên và quản lý hiển thị đúng cho tất cả các t const staffBadges = pendingTaskCounts(opsStaff, "STAFF", meStaff); assert.equal(staffBadges["staff/renewal-payments"], 1); - assert.equal(staffBadges["staff/cash-refunds"], 2); // CH-01 và CH-03 + assert.equal(staffBadges["staff/cash-refunds"], 1); // D66: nhân viên chỉ gọi nhắc (CH-02 · REMIND), không phân công assert.equal(staffBadges["staff/recheck"], 1); // TK-02 assert.equal(staffBadges["staff/overdue"], 1); assert.equal(staffBadges["staff/inquiries"], 1); - assert.equal(staffBadges["staff/reconcile"], 4); // 1 payment + 1 renewal + 2 cash refunds + assert.equal(staffBadges["staff/reconcile"], 3); // 1 payment + 1 renewal + 1 gọi nhắc assert.equal(staffBadges["staff/verify"], 2); // 1 verify + 1 handover assert.equal(staffBadges["staff/return"], 3); // 1 scheduled + 1 recheck + 1 đồ quá hạn (#7: cùng trang Kiểm tra trả kho) assert.equal(staffBadges["staff/support"], 3); // 2 tickets (NV-01 + null) + 1 inquiry - assert.equal(staffBadges["staff"], 12); // 4 + 2 + 2 + 3 + 1 overdue + assert.equal(staffBadges["staff"], 11); // 3 + 2 + 2 + 3 + 1 overdue const opsManager = { allocations: [{ status: "PENDING" }], @@ -126,13 +126,13 @@ test("badge nhân viên và quản lý hiển thị đúng cho tất cả các t assert.equal(mgrBadges["manager/allocate"], undefined); assert.equal(mgrBadges["manager/assign"], undefined); assert.equal(mgrBadges["manager/renewals"], undefined); - assert.equal(mgrBadges["manager/cash-refunds"], 1); + assert.equal(mgrBadges["manager/cash-refunds"], 2); // D66: mọi khoản chờ khách nhận đều chờ quản lý xác nhận đã trả assert.equal(mgrBadges["manager/deposit-refunds"], 1); assert.equal(mgrBadges["manager/unit-conflicts"], 1); // chỉ ca không còn ô tương đương; SWAP do khách tự chọn assert.equal(mgrBadges["manager/overdue"], 1); assert.equal(mgrBadges["manager/refunds"], 1); assert.equal(mgrBadges["manager/contracts"], 2); // 1 hợp đồng quá hạn + 1 hồ sơ quá hạn - assert.equal(mgrBadges["manager/refund"], 3); // 1 đơn huỷ + 1 hoàn cọc + 1 tiền mặt chờ duyệt + assert.equal(mgrBadges["manager/refund"], 4); // 1 đơn huỷ + 1 hoàn cọc + 2 tiền mặt chờ xác nhận đã trả (D66) assert.equal(mgrBadges["manager"], 2); // Tổng quan: 1 đơn chưa có ô + 1 ca không còn ô tương đương }); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/settlement-batch08.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/settlement-batch08.test.js index ac44102..f696855 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/settlement-batch08.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/settlement-batch08.test.js @@ -11,7 +11,7 @@ test('hoàn tiền cần đủ tài khoản hợp lệ, số tiền, mã giao d assert.throws(()=>transferProof(item,{...proof,method:'CASH'},now)); assert.throws(()=>transferProof({...item,method:'CASH',bankName:'CASH'},{...proof,method:'BANK_TRANSFER'},now)); for(const patch of [{amount:undefined},{amount:0},{amount:-1},{status:'PAID'},{accountHolder:''},{accountNumber:'123'},{bankName:''}])assert.throws(()=>transferProof({...item,...patch},proof,now)); - for(const patch of [{transactionRef:''},{confirmed:false},{transferredAt:'2026-10-29T10:00'},{transferredAt:'2026-02-30T10:00'}])assert.throws(()=>transferProof(item,{...proof,...patch},now)); + for(const patch of [{confirmed:false},{transferredAt:'2026-10-29T10:00'},{transferredAt:'2026-02-30T10:00'}])assert.throws(()=>transferProof(item,{...proof,...patch},now)); }); test('thiếu hồ sơ xác minh hoặc checklist không được nhận chìa khóa; không đổi ô/ngày',()=>{ const ops=createOpsData('2026-10-28'),h=ops.handovers.find(h=>h.status==='WAITING'),p={id:h.id,identity_checked:true,condition_checked:true,key_delivered:true}; @@ -56,3 +56,11 @@ test('ngày xử lý thực tế phải đủ mốc, đúng cơ sở/phân công assert.throws(()=>validateRemoval(r,{...p,photos:Array(11).fill(photo)},{},a,now),/tối đa 10/); assert.throws(()=>validateRemoval(r,{...p,photos:[]},{},a,now),/ít nhất (1|một) ảnh/);assert.throws(()=>validateRemoval(r,{...p,confirmed:false},{},a,now)); }); + +test('D64: xác nhận hoàn tiền không cần mã giao dịch và thời gian chuyển', () => { + const item={id:'HC-1',status:'PENDING',amount:500000,customer:'Nguyen Van A',bankName:'Vietcombank',accountNumber:'0071001234567',accountHolder:'NGUYEN VAN A'}; + const now=new Date('2026-11-18T03:00:00Z'); + const out=transferProof(item,{confirmed:true},now); + assert.equal(out.transactionRef,null); assert.equal(out.transferredAt,now.toISOString()); assert.equal(out.method,'BANK_TRANSFER'); + assert.throws(()=>transferProof(item,{confirmed:false},now)); +}); diff --git a/StorageProject.Infrastructure/Data/DbSeeder.DemoFacilities.cs b/StorageProject.Infrastructure/Data/DbSeeder.DemoFacilities.cs index ce64c9a..c615f5b 100644 --- a/StorageProject.Infrastructure/Data/DbSeeder.DemoFacilities.cs +++ b/StorageProject.Infrastructure/Data/DbSeeder.DemoFacilities.cs @@ -63,13 +63,13 @@ public static partial class DbSeeder /// /// Thứ tự hợp đồng demo: (loại kho, bắt đầu cách hôm nay bao nhiêu ngày, số tháng). Cơ sở có N hợp đồng lấy N dòng đầu. - /// Mọi kỳ thuê đều còn hiệu lực; dòng 3 hết hạn trong khoảng 12 ngày để thử mốc "Sắp hết hạn" (14 ngày). + /// Mọi kỳ thuê đều còn hiệu lực; dòng 3 hết hạn trong khoảng 5–7 ngày để thử mốc "Sắp hết hạn" (10 ngày, D65). /// private static readonly (string Type, int DaysAgo, int Months)[] DemoOrderSlots = [ ("NormalL", 8, 6), // tháng này ("ColdM", 120, 6), // 4 tháng trước - ("ColdL", 80, 3), // ~2,5 tháng trước, sắp hết hạn + ("ColdL", 85, 3), // ~2,8 tháng trước, sắp hết hạn ("NormalM", 155, 9), // 5 tháng trước ("NormalM", 60, 12), // 2 tháng trước ("NormalL", 35, 6), // tháng trước diff --git a/StorageProject.Infrastructure/Services/DemoToolsService.cs b/StorageProject.Infrastructure/Services/DemoToolsService.cs index 249b59a..4bb7f60 100644 --- a/StorageProject.Infrastructure/Services/DemoToolsService.cs +++ b/StorageProject.Infrastructure/Services/DemoToolsService.cs @@ -21,7 +21,7 @@ public class DemoToolsService(AppDbContext dbContext) : IDemoToolsService public const string PaymentEdited = "DEMO_PAYMENT_EDITED"; private static readonly TimeSpan VnOffset = TimeSpan.FromHours(7); private static readonly string[] Running = ["ACTIVE", "EXPIRING", "OVERDUE"]; - private const int ExpiringDays = 14; + private const int ExpiringDays = OpsRules.DefaultExpiringThresholdDays; // D65: 10 ngày private const decimal MaxAmount = 10_000_000_000m; private static DateOnly Today => DateOnly.FromDateTime(DateTime.UtcNow + VnOffset); diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs index 9a6a29a..4b87eb3 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs @@ -601,7 +601,7 @@ private void SettleFromDeposit(RentalContract contract, string type, decimal bud /// /// M08 · Quản lý ghi bằng chứng đã chuyển khoản hoàn cho đơn đã huỷ (khoản REFUND ghi lúc khách huỷ). - /// D32: chỉ hoàn vào tài khoản chính chủ khách khai khi huỷ; cần mã giao dịch, thời điểm chuyển thực tế và xác nhận. + /// D32/D64: hoàn vào tài khoản khách khai khi huỷ; chỉ cần xác nhận (mã giao dịch và thời điểm chuyển không bắt buộc). /// public async Task ConfirmReservationRefundAsync(OpsActor actor, string id, OpsReservationRefundRequest request, CancellationToken ct = default) { @@ -610,7 +610,7 @@ public async Task ConfirmReservationRefundAsync(OpsActor actor, string var method = (request.Method ?? "BANK_TRANSFER").Trim().ToUpperInvariant(); if (method != "BANK_TRANSFER") throw new ArgumentException("Hoàn tiền chỉ chuyển khoản vào tài khoản chính chủ của khách."); if (!request.Confirmed) throw new ArgumentException("Cần xác nhận đã chuyển đúng số tiền vào đúng tài khoản."); - var reference = TransactionRefOf(request.TransactionRef); + var reference = OptionalTransactionRefOf(request.TransactionRef); await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation-refund:{facility.FacilityId}:{id}", ct); var r = await ReservationAsync(facility.FacilityId, id, ct); @@ -627,8 +627,8 @@ public async Task ConfirmReservationRefundAsync(OpsActor actor, string { throw new InvalidOperationException("Đơn huỷ chưa có tài khoản nhận hoàn hợp lệ. Liên hệ khách bổ sung trước khi chuyển tiền."); } - var paidAt = TransferTimeOf(request.TransferredAt, r.CancelledAt ?? pending.CreatedAt, "huỷ đơn"); - await EnsureUniqueTransactionRefAsync(reference, pending.PaymentId, ct); + var paidAt = request.TransferredAt is null ? NowUtc : TransferTimeOf(request.TransferredAt, r.CancelledAt ?? pending.CreatedAt, "huỷ đơn"); + if (reference != null) await EnsureUniqueTransactionRefAsync(reference, pending.PaymentId, ct); pending.Status = "PAID"; pending.PaidAt = paidAt; pending.UpdatedAt = NowUtc; pending.TransactionReference = reference; @@ -643,6 +643,13 @@ public async Task ConfirmReservationRefundAsync(OpsActor actor, string // Bằng chứng chuyển tiền dùng chung cho M08 (đơn huỷ) và hoàn cọc sau trả kho // ------------------------------------------------------------------ + /// + /// D64 (18/11): quản lý chỉ bấm xác nhận đã chuyển / đã trả tiền mặt, không bắt nhập mã giao dịch. + /// Có gửi mã (dữ liệu cũ) thì vẫn kiểm tra độ dài; để trống thì không lưu mã. + /// + internal static string? OptionalTransactionRefOf(string? value) => + string.IsNullOrWhiteSpace(value) ? null : TransactionRefOf(value); + /// Chuẩn hoá và kiểm tra định dạng mã giao dịch ngân hàng. internal static string TransactionRefOf(string? value) { diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs index f80963d..3ce3c2c 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs @@ -117,7 +117,7 @@ string UnitState(StorageUnit u) } if (c == null) return "ACTIVE"; if (c.Status == "OVERDUE" || c.EndDate < today) return "OVERDUE"; - if (c.Status == "EXPIRING" || c.EndDate <= today.AddDays(14)) return "EXPIRING"; + if (c.EndDate <= today.AddDays(OpsRules.DefaultExpiringThresholdDays)) return "EXPIRING"; // D65: ≤ 10 ngày return "ACTIVE"; } diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Refunds.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Refunds.cs index 856cef0..cbebe69 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Refunds.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Refunds.cs @@ -77,7 +77,7 @@ public async Task ConfirmDepositRefundAsync(OpsActor actor, De var facility = await FacilityOfAsync(actor, ct); var paymentId = ParseCode(request.Id, "HC-", "khoản hoàn cọc"); if (!request.Confirmed) throw new ArgumentException("Cần xác nhận đã chuyển đúng số tiền hoặc đã chi tiền mặt cho khách."); - var reference = TransactionRefOf(request.TransactionRef); + var reference = OptionalTransactionRefOf(request.TransactionRef); await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"deposit-refund:{paymentId}", ct); var p = await DepositRefundQuery().AsSplitQuery() @@ -108,8 +108,8 @@ public async Task ConfirmDepositRefundAsync(OpsActor actor, De } } - var paidAt = TransferTimeOf(request.TransferredAt, p.CreatedAt, "chốt đối soát"); - await EnsureUniqueTransactionRefAsync(reference, p.PaymentId, ct); + var paidAt = request.TransferredAt is null ? NowUtc : TransferTimeOf(request.TransferredAt, p.CreatedAt, "chốt đối soát"); + if (reference != null) await EnsureUniqueTransactionRefAsync(reference, p.PaymentId, ct); p.Status = "PAID"; p.PaidAt = paidAt; diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Workflows.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Workflows.cs index 5d549d4..4467bee 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Workflows.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Workflows.cs @@ -377,18 +377,19 @@ private static CashState CashStateOf(Payment p, IEnumerable logs, D long? staffId = assigned != null && long.TryParse(Read(assigned, "staffId"), out var s) ? s : null; if (p.Status == "PAID") return new CashState("PAID", approved?.LoggedAt, staffId, null, 0, null, null, lastCall, paid); var forfeited = list.LastOrDefault(l => l.Action == FlowAction.CashForfeited); - if (approved == null) return new CashState("WAITING_APPROVAL", null, null, null, 0, null, null, lastCall, null); + // D66 (18/11): không còn bước duyệt & giao nhân viên; hạn 30 ngày tính từ lúc tạo khoản hoàn (hoặc lần duyệt cũ nếu có). + var startAt = approved?.LoggedAt ?? DateTime.SpecifyKind(p.CreatedAt, DateTimeKind.Utc); - var approvedDay = DateOnly.FromDateTime(approved.LoggedAt + VnOffset); + var approvedDay = DateOnly.FromDateTime(startAt + VnOffset); var deadline = approvedDay.AddDays(CashRefundDays); var days = today.DayNumber - approvedDay.DayNumber; DateOnly? appointment = lastCall != null && DateOnly.TryParseExact(Read(lastCall, "appointmentDate"), "yyyy-MM-dd", Invariant, System.Globalization.DateTimeStyles.None, out var a) ? a : null; // D44: quá 30 ngày (tính từ lần duyệt đầu) chưa nhận → khách mất khoản hoàn; hết hạn hiện ngay, worker ghi sổ sau. if (forfeited != null || p.Status == "CANCELLED" || days > CashRefundDays) - return new CashState("FORFEITED", approved.LoggedAt, staffId, deadline, days, null, appointment, lastCall, forfeited); + return new CashState("FORFEITED", startAt, staffId, deadline, days, null, appointment, lastCall, forfeited); if (appointment.HasValue && appointment.Value >= today) { - return new CashState("APPOINTMENT", approved.LoggedAt, staffId, deadline, days, null, appointment, lastCall, null); + return new CashState("APPOINTMENT", startAt, staffId, deadline, days, null, appointment, lastCall, null); } // Mốc gọi nhắc gần nhất đã tới mà chưa gọi sau mốc đó. int? milestone = CashReminderDays.Where(d => days >= d).Select(d => (int?)d).LastOrDefault(); @@ -397,10 +398,10 @@ private static CashState CashStateOf(Payment p, IEnumerable logs, D var milestoneUtc = UtcFromLocal(approvedDay.AddDays(milestone.Value), 0); if (lastCall == null || lastCall.LoggedAt < milestoneUtc) { - return new CashState("REMIND", approved.LoggedAt, staffId, deadline, days, milestone, appointment, lastCall, null); + return new CashState("REMIND", startAt, staffId, deadline, days, milestone, appointment, lastCall, null); } } - return new CashState("READY", approved.LoggedAt, staffId, deadline, days, null, appointment, lastCall, null); + return new CashState("READY", startAt, staffId, deadline, days, null, appointment, lastCall, null); } /// Xác định nguồn gốc và chủ thể của khoản tiền hoàn mặt. @@ -546,9 +547,13 @@ public async Task RecordCashRefundCallAsync(OpsActor actor, strin return (await ToCashDtosAsync([p], ct))[0]; } - /// D42 · S10: Nhân viên xác nhận đã chi tiền mặt cho khách sau khi tick đủ 4 mục kiểm tra. + /// + /// D42/D66: Quản lý cơ sở xác nhận đã trả tiền mặt cho khách tại quầy (không còn bước duyệt & giao nhân viên, + /// không nhập mã giao dịch). Giao diện gửi đủ 4 mục đối chiếu khi quản lý bấm xác nhận. + /// public async Task PayCashRefundAsync(OpsActor actor, string id, CashRefundPayRequest request, CancellationToken ct = default) { + RequireManager(actor); if (!(request.IdentityChecked && request.CodeChecked && request.AmountCounted && request.Signed)) { throw new ArgumentException("Tick đủ 4 mục kiểm tra trước khi xác nhận đã chi."); diff --git a/StorageProject.Infrastructure/Services/OpsRules.cs b/StorageProject.Infrastructure/Services/OpsRules.cs index f57957b..d1c66d2 100644 --- a/StorageProject.Infrastructure/Services/OpsRules.cs +++ b/StorageProject.Infrastructure/Services/OpsRules.cs @@ -95,7 +95,7 @@ public static bool Overlaps(DateOnly aFrom, DateOnly? aTo, DateOnly bFrom, DateO // Mốc thời gian và tham số vận hành chuẩn hóa theo P2 (SSFRMS-Business-Policies-Audit-and-Refactor-Plan.md) public const int DefaultOnlineReservationHoldMinutes = 15; // Giữ chỗ trực tuyến 15 phút (D02) - public const int DefaultExpiringThresholdDays = 30; // Mốc sắp hết hạn EXPIRING 30 ngày (D11) + public const int DefaultExpiringThresholdDays = 10; // Mốc sắp hết hạn EXPIRING 10 ngày (D65, thay 30 ngày của D11) public const int DefaultRenewalPaymentDeadlineHours = 24; // Hạn thanh toán sau khi duyệt gia hạn 24 giờ (D11/D32) public const int DefaultReletBufferDays = 3; // Ngày đệm cho thuê lại 3 ngày (D41) public const decimal DefaultDepositMonths = 1.0m; // Mức cọc mặc định 1 tháng tiền thuê (D09/D16/D32) diff --git a/StorageProject.Infrastructure/Services/OverdueProcessor.cs b/StorageProject.Infrastructure/Services/OverdueProcessor.cs index 454a49b..b807698 100644 --- a/StorageProject.Infrastructure/Services/OverdueProcessor.cs +++ b/StorageProject.Infrastructure/Services/OverdueProcessor.cs @@ -7,7 +7,7 @@ namespace StorageProject.Infrastructure.Services; /// /// T11 · Xử lý tự động hợp đồng quá hạn hàng ngày (D32): -/// 1. Cập nhật hợp đồng sắp hết hạn (EXPIRING: trong vòng 30 ngày trước EndDate). +/// 1. Cập nhật hợp đồng sắp hết hạn (EXPIRING: còn ≤ 10 ngày trước EndDate, D65). /// 2. Chuyển hợp đồng đã quá hạn sang OVERDUE khi qua ngày EndDate. /// 3. Tính phí quá hạn theo chính sách OVERDUE (mặc định 5% cọc ban đầu mỗi ngày trễ), tối đa 100% cọc. /// 4. Dừng tăng phí khi khách đã gửi yêu cầu trả kho (RETURN_PENDING). @@ -29,11 +29,15 @@ public static async Task ProcessDailyOverdueAsync(AppDbContext dbContext, ILogge var nowUtc = DateTime.UtcNow; var today = DateOnly.FromDateTime(nowUtc + VnOffset); - // 1. ACTIVE sắp hết hạn trong 30 ngày -> EXPIRING (P2: OpsRules.DefaultExpiringThresholdDays). Cập nhật có điều kiện trong một câu lệnh để không ghi đè + // 1. ACTIVE còn ≤ 10 ngày (D65) -> EXPIRING (P2: OpsRules.DefaultExpiringThresholdDays). Cập nhật có điều kiện trong một câu lệnh để không ghi đè // trạng thái khách vừa đổi (ví dụ vừa gửi trả kho) giữa lúc đọc và lúc lưu (S05). await dbContext.RentalContracts .Where(c => c.Status == "ACTIVE" && c.EndDate >= today && c.EndDate <= today.AddDays(OpsRules.DefaultExpiringThresholdDays)) .ExecuteUpdateAsync(u => u.SetProperty(c => c.Status, "EXPIRING"), ct); + // D65: hợp đồng đã đánh EXPIRING theo mốc cũ 30 ngày (hoặc vừa gia hạn) mà còn hơn 10 ngày thì trở lại ACTIVE. + await dbContext.RentalContracts + .Where(c => c.Status == "EXPIRING" && c.EndDate > today.AddDays(OpsRules.DefaultExpiringThresholdDays)) + .ExecuteUpdateAsync(u => u.SetProperty(c => c.Status, "ACTIVE"), ct); dbContext.ChangeTracker.Clear(); // ExecuteUpdate không qua tracker; đọc lại từ DB sau bước này await CustomerEmailDelivery.QueueRenewalRemindersAsync(dbContext, today, nowUtc, ct); diff --git a/StorageProject.Tests/D32RefundEvidenceTests.Phien3.cs b/StorageProject.Tests/D32RefundEvidenceTests.Phien3.cs index 302992e..fabd3a0 100644 --- a/StorageProject.Tests/D32RefundEvidenceTests.Phien3.cs +++ b/StorageProject.Tests/D32RefundEvidenceTests.Phien3.cs @@ -242,27 +242,23 @@ public async Task CashRefund_CustomerChoice_ManagerApproves_StaffPaysWithFourChe await Assert.ThrowsAsync(() => f.Ops.ConfirmDepositRefundAsync(f.ManagerActor, new DepositRefundActionRequest("CONFIRM_DEPOSIT_REFUND", listed.Id, 1, "FT1", DateTime.UtcNow, true))); - Assert.Equal("WAITING_APPROVAL", Assert.Single(await f.Ops.GetCashRefundsAsync(f.StaffActor)).Status); - await Assert.ThrowsAsync(() => - f.Ops.PayCashRefundAsync(f.StaffActor, cashId, new CashRefundPayRequest(true, true, true, true))); + // D66 (18/11): không còn bước duyệt & giao nhân viên — khoản tiền mặt chờ khách đến nhận ngay, quản lý xác nhận đã trả + var waiting = Assert.Single(await f.Ops.GetCashRefundsAsync(f.ManagerActor)); + Assert.Equal("READY", waiting.Status); + Assert.NotNull(waiting.DeadlineDate); await Assert.ThrowsAsync(() => - f.Ops.ApproveCashRefundAsync(f.StaffActor, cashId, new OpsAssignRequest($"NV-{f.Staff.UserId:00}"))); - - var approved = await f.Ops.ApproveCashRefundAsync(f.ManagerActor, cashId, new OpsAssignRequest($"NV-{f.Staff.UserId:00}")); - Assert.Equal("READY", approved.Status); - Assert.NotNull(approved.DeadlineDate); - + f.Ops.PayCashRefundAsync(f.StaffActor, cashId, new CashRefundPayRequest(true, true, true, true))); await Assert.ThrowsAsync(() => - f.Ops.PayCashRefundAsync(f.StaffActor, cashId, new CashRefundPayRequest(true, true, false, true))); - var paid = await f.Ops.PayCashRefundAsync(f.StaffActor, cashId, new CashRefundPayRequest(true, true, true, true)); + f.Ops.PayCashRefundAsync(f.ManagerActor, cashId, new CashRefundPayRequest(true, true, false, true))); + var paid = await f.Ops.PayCashRefundAsync(f.ManagerActor, cashId, new CashRefundPayRequest(true, true, true, true)); Assert.Equal("PAID", paid.Status); - Assert.Equal("Trần Nhân Viên", paid.PaidBy); + Assert.Equal(f.Manager.FullName, paid.PaidBy); await Assert.ThrowsAsync(() => - f.Ops.PayCashRefundAsync(f.StaffActor, cashId, new CashRefundPayRequest(true, true, true, true))); + f.Ops.PayCashRefundAsync(f.ManagerActor, cashId, new CashRefundPayRequest(true, true, true, true))); f.Db.ChangeTracker.Clear(); var done = await f.Db.Payments.SingleAsync(p => p.PaymentId == payment.PaymentId); Assert.Equal("PAID", done.Status); - Assert.StartsWith($"CASH:{f.Staff.UserId}:", done.TransactionReference); + Assert.StartsWith($"CASH:{f.Manager.UserId}:", done.TransactionReference); } [Fact] @@ -305,7 +301,7 @@ await Assert.ThrowsAsync(() => // D44: quá 30 ngày chưa nhận → khách mất khoản hoàn; không chi, không đổi sang chuyển khoản Assert.Equal("FORFEITED", Assert.Single(await f.Ops.GetCashRefundsAsync(f.StaffActor)).Status); await Assert.ThrowsAsync(() => - f.Ops.PayCashRefundAsync(f.StaffActor, cashId, new CashRefundPayRequest(true, true, true, true))); + f.Ops.PayCashRefundAsync(f.ManagerActor, cashId, new CashRefundPayRequest(true, true, true, true))); await Assert.ThrowsAsync(() => f.Ops.SwitchCashRefundToBankAsync(f.Customer.UserId, cashId, new RefundBankInput("Vietcombank", "0123456789", "NGUYEN VAN AN"))); Assert.Equal(1, await f.Ops.ForfeitExpiredCashRefundsAsync()); diff --git a/StorageProject.Tests/D32RefundEvidenceTests.cs b/StorageProject.Tests/D32RefundEvidenceTests.cs index 930cce8..fa5f49d 100644 --- a/StorageProject.Tests/D32RefundEvidenceTests.cs +++ b/StorageProject.Tests/D32RefundEvidenceTests.cs @@ -244,10 +244,11 @@ await f.Ops.SubmitReturnInspectionAsync(f.StaffActor, returnId, // Task #20: khóa hình thức hoàn theo lựa chọn khách (BANK_TRANSFER không được đổi sang CASH) await Assert.ThrowsAsync(() => f.Ops.ConfirmDepositRefundAsync(f.ManagerActor, request with { Method = "CASH" })); - var paid = await f.Ops.ConfirmDepositRefundAsync(f.ManagerActor, request); + // D64 (18/11): quản lý chỉ bấm xác nhận, không nhập mã giao dịch / thời gian chuyển + var paid = await f.Ops.ConfirmDepositRefundAsync(f.ManagerActor, request with { TransactionRef = null, TransferredAt = null }); Assert.Equal("PAID", paid.Status); Assert.Equal(2, paid.Version); - Assert.Equal("FT26302000001", paid.TransactionRef); + Assert.Null(paid.TransactionRef); Assert.NotNull(paid.PaidAt); // Gửi lại cùng yêu cầu (mạng lỗi, bấm lặp) không chuyển lần hai await Assert.ThrowsAsync(() => f.Ops.ConfirmDepositRefundAsync(f.ManagerActor, request)); diff --git a/StorageProject.Tests/DoorStateTests.cs b/StorageProject.Tests/DoorStateTests.cs index 75c1ad1..7441423 100644 --- a/StorageProject.Tests/DoorStateTests.cs +++ b/StorageProject.Tests/DoorStateTests.cs @@ -25,6 +25,7 @@ public sealed class DemoToolsRuleTests [InlineData(2026, 11, 9, "OVERDUE", 3)] [InlineData(2026, 11, 12, "OVERDUE", 0)] [InlineData(2026, 11, 20, "EXPIRING", 0)] + [InlineData(2026, 11, 23, "ACTIVE", 0)] // D65: còn 11 ngày chưa phải sắp hết hạn [InlineData(2027, 2, 12, "ACTIVE", 0)] public void Running_status_and_overdue_days_follow_end_date(int y, int m, int d, string status, int overdue) { diff --git a/StorageProject.Tests/OverdueProcessorTests.cs b/StorageProject.Tests/OverdueProcessorTests.cs index bd83feb..e05e1ba 100644 --- a/StorageProject.Tests/OverdueProcessorTests.cs +++ b/StorageProject.Tests/OverdueProcessorTests.cs @@ -274,7 +274,7 @@ public async Task ProcessDailyOverdue_TransitionsActiveToExpiring_WhenWithin30Da CustomerId = customer.UserId, UnitId = unit.UnitId, StartDate = today.AddDays(-60), - EndDate = today.AddDays(15), // Hết hạn trong 15 ngày tới + EndDate = today.AddDays(8), // Hết hạn trong 8 ngày tới (mốc 10 ngày, D65) DepositAmount = 1_000_000m, AgreedMonthlyRate = 1_000_000m, Status = "ACTIVE", diff --git a/StorageProject.Tests/StandardizedOperationalParametersP2Tests.cs b/StorageProject.Tests/StandardizedOperationalParametersP2Tests.cs index 55c98dc..8272771 100644 --- a/StorageProject.Tests/StandardizedOperationalParametersP2Tests.cs +++ b/StorageProject.Tests/StandardizedOperationalParametersP2Tests.cs @@ -9,7 +9,7 @@ namespace StorageProject.Tests; /// - Giữ chỗ online 15 phút /// - Giữ chỗ tại quầy cuối ngày hẹn (giờ VN) /// - Hạn thanh toán gia hạn (min(24h, ngày hết hạn)) -/// - Mốc EXPIRING 30 ngày +/// - Mốc EXPIRING 10 ngày (D65) /// - Ngày đệm cho thuê lại RELET_BUFFER mặc định 3 ngày /// public class StandardizedOperationalParametersP2Tests @@ -76,9 +76,9 @@ public void ReletBuffer_DefaultsTo3Days_AndAllowsValidRange0To60() } [Fact] - public void ExpiringThreshold_DefaultsTo30Days() + public void ExpiringThreshold_DefaultsTo10Days() { - Assert.Equal(30, OpsRules.DefaultExpiringThresholdDays); + Assert.Equal(10, OpsRules.DefaultExpiringThresholdDays); } } diff --git a/progress.md b/progress.md index 990f6c9..c1c444e 100644 --- a/progress.md +++ b/progress.md @@ -1,3 +1,34 @@ +## 2026-11-18 — Chuông: mới nhất lên đầu, đã đọc thì xoá + +- `appReducer.MARK_READ`: thông báo đã đọc (bấm vào hoặc "Đã đọc tất cả") bị xoá khỏi chuông, khoá được nhớ trong `dismissedNotices` (tối đa 500, `shared/utils/notices.js`) để thông báo sinh từ dữ liệu máy chủ không quay lại sau khi tải lại. Thông báo quá hạn dùng khoá kèm nội dung nên số ngày quá hạn đổi thì hiện lại, lên đầu. +- `AppProvider.loadCustomer` bỏ qua khoá đã đọc; chuông vẫn xếp mới nhất lên đầu. `Header`: "Không có thông báo mới", nút "Đã đọc tất cả · xoá khỏi chuông". +- Kiểm chứng: `npm test` 233/233 (thêm test MARK_READ), `test:render` PASS, build OK; Chrome chế độ demo: bấm 1 thông báo → còn 4 sau tải lại, "Đã đọc tất cả" → 0 và vẫn 0 sau tải lại. + +## 2026-11-18 — Chuông không hiện thông báo quá hạn dù đã có email + +- Nguyên nhân: thông báo quá hạn lấy thời điểm 00:00 của ngày tính nên bị xếp dưới các thông báo khác trong ngày (hợp đồng, giữ chỗ, thanh toán), khách không thấy dù email quá hạn đã gửi. +- `AppProvider.jsx`: thông báo `SERVER-OVERDUE-*` lần đầu xuất hiện và mỗi lần số ngày quá hạn đổi thì đưa lên đầu chuông, đánh dấu chưa đọc (cùng nhịp email). Không đổi mã thông báo nên không tạo trùng. +- Kiểm chứng: `npm test` 232/232, `test:render` PASS, build OK. Chưa thử với backend thật. + +## 2026-11-18 — D66: bỏ giao việc nhân viên; quản lý xác nhận đã trả tiền mặt + +- FE: `CashRefundApprovalPage.jsx` bỏ "Duyệt & giao"/chọn nhân viên, thay bằng nút "Xác nhận đã trả tiền mặt" + popup (người nhận, số tiền); `CashRefundCounterPage.jsx` (nhân viên) chỉ còn ghi cuộc gọi nhắc; `StaffTasks`/`pendingTaskCounts`: nhân viên chỉ có việc gọi nhắc (REMIND), quản lý đếm mọi khoản chờ khách nhận. `OverdueCasePage` bỏ form phân công xử lý đồ; `OverdueRemovalPage` và `validateRemoval` không đòi phân công. Xoá trang M06 `manager/assignments`. +- BE: `FacilityOpsService.Workflows.cs` — khoản tiền mặt không còn trạng thái chờ duyệt (hạn 30 ngày tính từ lúc tạo khoản), `PayCashRefundAsync` chỉ quản lý được xác nhận. Sửa test xUnit `D32RefundEvidenceTests.Phien3` theo luồng mới. +- **Kiểm chứng:** `npm test` 232/232, `test:render` PASS (177 route, bỏ `manager/assign`), `vite build` OK, `test:workflow-actions` PASS. Chưa chạy `dotnet test` ở môi trường soạn patch. + +## 2026-11-18 — D65: "Sắp hết hạn" khi còn ≤ 10 ngày + +- FE: `appSelectors.contractStatus` dùng `EXPIRING_DAYS = 10` (trước 30); tổng quan khách ghi "Sắp hết hạn (10 ngày)"; Công cụ demo, máy chủ giả, dữ liệu mẫu và nội dung chính sách hệ thống đổi theo. +- BE: `OpsRules.DefaultExpiringThresholdDays = 10`; `OverdueProcessor` thêm bước đưa EXPIRING còn > 10 ngày về ACTIVE; bảng kho quản lý (`FacilityOpsService.Board`) và `DemoToolsService` dùng chung mốc; seed demo dòng kho lạnh hết hạn sau ~5–7 ngày. Sửa test xUnit theo mốc mới. +- **Kiểm chứng:** xem mục D64 cùng ngày (chạy chung một lượt). Chưa chạy `dotnet test` ở môi trường soạn patch. + +## 2026-11-18 — D64: xác nhận hoàn tiền không cần mã giao dịch; trả kho chỉ chọn ngày + +- Figma (sửa trước, viền đỏ): M-ĐS-CHỐT chuyển khoản + bản tiền mặt và popup, M08a/M08a2 bỏ ô mã giao dịch, D30-15 phía khách bỏ dòng mã giao dịch; popup "chưa nhập mã giao dịch" chuyển vào Lưu trữ. +- FE: `DepositRefundPage.jsx` khối "Bước tiếp theo" hiện cách nhận, ngân hàng, số tài khoản, chủ tài khoản, số tiền + nút "Xác nhận đã chuyển khoản" (hoặc tiền mặt); `CancellationRefundPage.jsx` bỏ ô mã giao dịch, thời gian và ô tick. `settlementModel.transferProof` không bắt mã/thời gian; `useWorkflowData`, `opsReceiptCheck`, reducer M08 chấp nhận mã rỗng. Khách: `RefundTrackingPage` thay "Mã giao dịch" bằng "Ngày hoàn", `ReturnProgressPage` bỏ dòng mã. Trả kho đã chỉ có ô chọn ngày (không đổi giao diện, sửa chú thích). +- BE: `FacilityOpsService.Actions.cs` / `.Refunds.cs` — `transactionRef`, `transferredAt` không bắt buộc (`OptionalTransactionRefOf`, trống thì ghi thời điểm xác nhận); có mã thì vẫn kiểm tra độ dài và trùng. Sửa test xUnit `D32RefundEvidenceTests` xác nhận không cần mã. +- **Kiểm chứng:** `npm test` 232/232, `test:render` PASS 178 route, `check:structure` PASS, `vite build` OK, `test:workflow-actions` PASS trên Chrome (M08 và hoàn cọc chỉ bấm xác nhận, chặn xác nhận lại, khách thấy "Đã hoàn"). **Chưa build/chạy `dotnet test`** (môi trường soạn patch không có .NET SDK), chưa thử SQL Server thật. + ## 2026-11-14 — Máy quét mô phỏng 16:9: cảnh kho thường / kho lạnh theo ô đang chọn - Theo Figma "Bổ sung · 12/11 · Công cụ demo" vẽ lại 14/11 (4 ảnh nền của nhóm, khung 1440×810): `DoorSimulatorPage.jsx` chọn cảnh theo loại ô (`sceneKind` trong `demoModel.js`: `climateControlled` → kho lạnh, còn lại kho thường) và trạng thái cửa (đóng/mở). Ảnh mới `src/assets/demo/door-scene-{normal,cold}-{closed,open}.webp`; bỏ 2 ảnh cảnh cũ. From 6d2ec7209d4e29cc7f66172a8dfbf7b369bd0f73 Mon Sep 17 00:00:00 2001 From: Vector Date: Wed, 18 Nov 2026 12:04:47 +0700 Subject: [PATCH 2/2] =?UTF-8?q?S=E1=BB=ADa=20test=20theo=20lu=E1=BA=ADt=20?= =?UTF-8?q?ho=C3=A0n=20ti=E1=BB=81n=20v=C3=A0=20s=E1=BA=AFp=20h=E1=BA=BFt?= =?UTF-8?q?=20h=E1=BA=A1n=20m=E1=BB=9Bi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tests/business-frontend.test.mjs | 2 +- StorageProject.Tests/D32RefundEvidenceTests.cs | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs index 3625137..92770eb 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs @@ -178,7 +178,7 @@ test('P0 · chính sách: phân nhóm rõ ràng, bỏ ánh xạ RENEWAL=24 sang assert.ok(ENGINE_SECTIONS[0].fields.some(f => f.key === 'deposit')); assert.ok(ENGINE_SECTIONS[0].fields.some(f => f.key === 'overdue')); assert.ok(ENGINE_SECTIONS[0].fields.some(f => f.key === 'relet')); - assert.ok(SYSTEM_ENFORCED_POLICIES.some(f => f.key === 'expiring' && f.value.includes('30 ngày'))); + assert.ok(SYSTEM_ENFORCED_POLICIES.some(f => f.key === 'expiring' && f.value.includes('10 ngày'))); assert.ok(GUIDELINE_SECTIONS[0].fields.some(f => f.key === 'refund')); }); diff --git a/StorageProject.Tests/D32RefundEvidenceTests.cs b/StorageProject.Tests/D32RefundEvidenceTests.cs index fa5f49d..4ded5ba 100644 --- a/StorageProject.Tests/D32RefundEvidenceTests.cs +++ b/StorageProject.Tests/D32RefundEvidenceTests.cs @@ -365,14 +365,16 @@ await reservations.CancelReservationAsync(f.Customer.UserId, r.ReservationId, " Assert.Equal("PENDING", refund.Status); var code = $"SS-{cancelled.CreatedAt.AddHours(7):yyyyMMdd}-{cancelled.ReservationId:0000}"; + // Quản lý chỉ bấm xác nhận: chưa xác nhận thì từ chối; không cần mã giao dịch / thời gian chuyển await Assert.ThrowsAsync(() => f.Ops.ConfirmReservationRefundAsync(f.ManagerActor, code, - new OpsReservationRefundRequest("BANK_TRANSFER", "", DateTime.UtcNow, true))); + new OpsReservationRefundRequest("BANK_TRANSFER", null, null, false))); await f.Ops.ConfirmReservationRefundAsync(f.ManagerActor, code, - new OpsReservationRefundRequest("BANK_TRANSFER", "FT26302000099", DateTime.UtcNow, true)); + new OpsReservationRefundRequest("BANK_TRANSFER", null, null, true)); f.Db.ChangeTracker.Clear(); var done = await f.Db.Payments.SingleAsync(p => p.PaymentId == refund.PaymentId); Assert.Equal("PAID", done.Status); - Assert.Equal("FT26302000099", done.TransactionReference); + Assert.NotNull(done.PaidAt); + Assert.Null(done.TransactionReference); await Assert.ThrowsAsync(() => f.Ops.ConfirmReservationRefundAsync(f.ManagerActor, code, new OpsReservationRefundRequest("BANK_TRANSFER", "FT26302000100", DateTime.UtcNow, true))); }