diff --git a/AGENTS.md b/AGENTS.md index 88d598f..94ecb5d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,6 +17,8 @@ 9. **Không xoá/sửa test để cho pass.** Test sai → ghi lý do trong `progress.md` rồi mới sửa. 10. Làm trên nhánh `feature/` → Pull Request vào `main`. Không push thẳng `main`. 11. Tiếng Việt cho giao diện và tài liệu; tên biến, hàm, API bằng tiếng Anh. +12. **AI không được tự `git push`, tạo Pull Request hay merge lên repo này.** Chỉ sửa code và commit trên máy; + giao lại cho thành viên nhóm (patch / file zip / hướng dẫn lệnh) để người đó tự kiểm tra rồi tự push. ## 2. Dự án là gì @@ -40,6 +42,7 @@ Hệ thống quản lý và cho thuê kho tự phục vụ **SafeSpace** cho 5 n | `…/src/api/` | Gọi API + `mappers.js` chuyển dữ liệu backend → giao diện | | `…/BE-CONTRACT.md` | Endpoint giao diện cần backend bổ sung | | `…/BACKEND-TODO.md` | Việc backend còn thiếu, xếp ưu tiên A/B/C, mẫu JSON `GET /api/ops/board` | +| `docs/facility-ops-api.md`, `docs/operations-api.md` | API khu Nhân viên / Quản lý cơ sở và khu Vận hành KD | | `…/CUSTOMER-FLOW-COVERAGE.md`, `ADMIN-FLOW-COVERAGE.md`, `OPS-FLOW-COVERAGE.md` | Đối chiếu màn Figma ↔ route ↔ component ↔ API | ## 4. Đọc thêm khi cần (tiết lộ dần) @@ -64,7 +67,8 @@ cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm run dev # UI: http:// ``` Cần: .NET SDK 10 (project đặt `net10.0`), Node ≥ 22.12, SQL Server (mặc định `.\SQLEXPRESS`). -Tài khoản seed: `customer01`/`Customer@123`, `staff01`/`Staff@123`, `ops01`/`Ops@123` (Vận hành KD), `admin`/`Admin@123`. +Tài khoản seed: `customer01`…`customer06`/`Customer@123`, `staff01`, `staff02`/`Staff@123`, `manager01`/`Manager@123` +(cả ba phụ trách SafeSpace Nguyễn Lương Bằng), `ops01`/`Ops@123` (Vận hành KD), `admin`/`Admin@123`. Không có backend: tạo `.env.local` với `VITE_USE_API=false`, hoặc `MOCK_OPS=1 npm run dev:mock` (máy chủ giả có cả `/api/ops/*`, thêm `manager01`/`Manager@123`). diff --git a/DECISIONS.md b/DECISIONS.md index 6ba929d..dd4dddf 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -86,3 +86,33 @@ "Cọc còn giữ"; "Doanh thu thuê và phí" không trừ REFUND. Khi thêm hoàn tiền thuê/phí thì phải thêm liên kết khoản gốc. - Cơ sở `TEMPORARILY_CLOSED` chặn đặt chỗ mới; `INACTIVE` chỉ khi không còn hợp đồng / đơn đang xử lý. Không xoá cơ sở. +## D17 — Mô hình kho theo Figma 14/10: 2 cỡ, mọi cơ sở có kho lạnh, gợi ý theo khu vực — Đã chốt (14/10/2026) +- Chỉ còn 2 cỡ kho: **Cỡ M · 15 m²** và **Cỡ L · 30 m²** (bỏ cỡ S). Loại kho từ backend: diện tích ≤ 20 m² là M, lớn hơn là L. +- Cả 12 cơ sở đều có kho thường và kho lạnh. Mỗi cơ sở 12 ô: 8 kho thường (4 M + 4 L) và 4 kho lạnh (2 M + 2 L). + Sơ đồ ô kho: dãy A cỡ M (K01–K04 thường, K05–K06 lạnh), dãy B cỡ L (K07–K10 thường, K11–K12 lạnh). +- Gợi ý cơ sở theo **khu vực khách chọn**, không theo vị trí người dùng: bỏ "Gần bạn nhất" và "Cách bạn … km". +- Tên loại kho hiển thị là "Kho lạnh" (thay "Kiểm soát nhiệt độ") cho khớp Figma. +- Nhân viên / quản lý cơ sở thấy tên cơ sở phụ trách dưới vai trò trên header (SRS A06: mỗi người 1 cơ sở). +- Trang chủ theo Figma mới: hero ảnh + tìm theo khu vực, số liệu, 4 loại kho, 3 bước, cơ sở theo khu vực, kêu gọi, footer. +- Backend đổi seed cho khớp (4 loại kho, 12 cơ sở, 12 ô mỗi cơ sở) — đã làm ở D18. + +## D18 — Backend khu Nhân viên / Quản lý cơ sở (`/api/ops/*`) và seed theo D17 — Đã chốt (14/10/2026) +- Làm đúng hợp đồng giao diện đã có (`src/ops/api.js`, mẫu JSON trong `BACKEND-TODO.md`); tài liệu `docs/facility-ops-api.md`. +- Id trong API là **mã hiển thị** (`SS-…`, `XM-`/`BG-`, `TK-`, `HT-`, `GH-`, `HĐ-…`, `PC-`, `NV-`), backend đọc số cuối. +- Phạm vi: chỉ cơ sở đang phân công trong `user_facilities` (A06); khác cơ sở trả 404, chưa phân công trả 403. +- Không thêm bảng mới. Phần bảng chưa có cột (loại giấy tờ + 4 số cuối, biên bản trả kho 4 mục, phản hồi hỗ trợ, + lý do từ chối gia hạn, lần nhắc khách, thời điểm khách báo chuyển khoản, báo sai lệch) lưu và đọc lại từ `activity_logs`. +- `handover_records.StaffId` và `return_inspections.StaffId` bắt buộc: việc **chưa giao** tạm ghi người tạo (quản lý); + bảng M06 coi người không có role STAFF là "chưa giao" (`OPEN`). +- Trạng thái hỗ trợ: giao diện `WAITING_CUSTOMER` = DB `RESOLVED`, `DONE` = DB `CLOSED`. +- Mở khoá: `CARD` → `ACCESS_CARD`; `PIN`, `FINGER` → `ACCESS_CODE` (mã tham chiếu ghi phương thức, **không lưu bí mật**). +- Báo sai lệch thanh toán không đổi trạng thái đơn (vẫn `PENDING_VERIFICATION`); sau khi quản lý làm rõ, nhân viên xác nhận lại. +- Phân bổ ô: ô phải trống và **đúng loại kho** của đơn; lúc này mới tạo hợp đồng `DRAFT` và ghi khoản cọc + tiền thuê `PAID` + (bảng `payments` bắt buộc có hợp đồng nên không ghi được lúc nhân viên đối soát). +- Hoàn cọc: khoản còn nợ được trừ vào cọc (đánh dấu `PAID`, ghi chú "Trừ vào tiền cọc"), phần còn lại tạo khoản `REFUND`. +- Thêm trạng thái đơn `PENDING_VERIFICATION` (migration viết tay `20261014150000_ReservationPendingVerification`). +- Sửa lỗi cũ: `HandoverService` ghi `COMPLETED` và `RenewalService` ghi `PENDING_PAYMENT` — cả hai vi phạm CHECK trong DB; + nay ghi `HANDED_OVER` và `PENDING` (gia hạn chờ quản lý duyệt ở M03). +- Seed D17: 4 loại kho, 12 cơ sở, 12 ô K01–K12 mỗi cơ sở, giá cùng công thức `src/lib/catalog.js`. Loại kho S/M/L/XL và + cơ sở "Quận 7" đời cũ chỉ chuyển ngừng dùng (không xoá). Muốn dữ liệu sạch: xoá database rồi chạy lại API. + diff --git a/README.md b/README.md index a88e8e9..511cd19 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,10 @@ Hệ thống quản lý và cho thuê kho tự quản thông minh (SafeSpace Sel --- +> **Quy định cho công cụ AI (Claude, Cursor, Copilot, Codex…):** AI chỉ được sửa code và commit trên máy, +> **không được tự `git push`, tạo Pull Request hay merge** lên repo này. Thành viên nhóm tự kiểm tra rồi tự push. +> Quy tắc đầy đủ cho AI nằm trong [`AGENTS.md`](AGENTS.md). + ## 📋 Yêu Cầu Môi Trường (Prerequisites) Trước khi chạy dự án, hãy đảm bảo máy tính đã cài đặt các công cụ sau: @@ -89,7 +93,10 @@ Hệ thống đã tạo sẵn các tài khoản để kiểm thử quy trình: |-----------|--------------------------|---------------------|-------| | **CUSTOMER** | `customer01` | `Customer@123` | Khách hàng mẫu (Nguyễn Văn An) | | **CUSTOMER** | `customer02` | `Customer@123` | Khách hàng mẫu (Trần Thị Mai) | -| **STAFF** | `staff01` | `Staff@123` | Nhân viên vận hành | +| **CUSTOMER** | `customer03` … `customer06` | `Customer@123` | Khách đang thuê / chờ bàn giao / quá hạn tại cơ sở mẫu | +| **STAFF** | `staff01`, `staff02` | `Staff@123` | Nhân viên cơ sở SafeSpace Nguyễn Lương Bằng (`#/staff`) | +| **MANAGER** | `manager01` | `Manager@123` | Quản lý cơ sở SafeSpace Nguyễn Lương Bằng (`#/manager`) | +| **OPERATIONS** | `ops01` | `Ops@123` | Quản lý vận hành kinh doanh | | **ADMIN** | `admin` | `Admin@123` | Quản trị viên hệ thống | *(Bạn cũng có thể bấm nút **"Đăng ký"** trực tiếp trên giao diện để tạo tài khoản mới)*. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index b3375fa..b344726 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -17,13 +17,16 @@ loại kho từ `/api/availability/check`. ## A. Ưu tiên 1 — chặn luồng chính +> **Đã làm (14/10/2026, nhánh `feature/ops-backend`, D18):** toàn bộ A1–A4 theo đúng bảng dưới. Tài liệu API: +> `docs/facility-ops-api.md`. Còn lại: chạy thử với SQL Server rồi đổi F03, F11–F21 sang `passing`. + ### A1. Dữ liệu seed & phân quyền -- [ ] `DbSeeder`: thêm tài khoản **quản lý cơ sở** `manager01 / Manager@123` (role `MANAGER`); hiện chỉ có `staff01`. -- [ ] Gán `UserFacility` cho `staff01` và `manager01` (ví dụ cơ sở SafeSpace Nguyễn Lương Bằng). Mọi endpoint mục A2–A3 +- [x] `DbSeeder`: thêm tài khoản **quản lý cơ sở** `manager01 / Manager@123` (role `MANAGER`); hiện chỉ có `staff01`. +- [x] Gán `UserFacility` cho `staff01` và `manager01` (ví dụ cơ sở SafeSpace Nguyễn Lương Bằng). Mọi endpoint mục A2–A3 chỉ trả / cho sửa dữ liệu của cơ sở được gán. -- [ ] Gán quyền cho role `STAFF` (`HANDOVER_MANAGE`, `RETURN_MANAGE`, `TICKET_MANAGE`, `PAYMENT_CONFIRM`) và `MANAGER` +- [x] Gán quyền cho role `STAFF` (`HANDOVER_MANAGE`, `RETURN_MANAGE`, `TICKET_MANAGE`, `PAYMENT_CONFIRM`) và `MANAGER` (thêm `UNIT_MANAGE`, `ASSIGNMENT_MANAGE`, `RENEWAL_MANAGE`, `REPORT_VIEW`). Hiện chỉ `ADMIN` có quyền. -- [ ] Endpoint mục A2 cho role `STAFF` **và** `MANAGER`; mục A3 chỉ `MANAGER` (sai vai trò → **403**). +- [x] Endpoint mục A2 cho role `STAFF` **và** `MANAGER`; mục A3 chỉ `MANAGER` (sai vai trò → **403**). ### A2. Khu Nhân viên cơ sở (Figma S01–S09) — chưa có endpoint nào Bảng trong DB đã có sẵn (`HandoverRecord`, `ReturnInspection`, `UnitAssignment`, `MaintenanceRequest`, `Payment`, @@ -49,14 +52,14 @@ Bảng trong DB đã có sẵn (`HandoverRecord`, `ReturnInspection`, `UnitAssig | M03 | `POST /api/ops/renewals/{id}/reject` | `{ reason }` | `reason` rỗng → 400; gửi lý do cho khách | | M07 | `POST /api/ops/contracts/{id}/reminders` | `{ note }` | Ghi lịch sử nhắc khách (`OverdueCase`) | | M07 | `POST /api/ops/contracts/{id}/refund` | — | Chỉ sau biên bản trả kho. Hoàn cọc = cọc − khoản còn nợ; kho → `AVAILABLE`; hợp đồng đóng | -| M01/M02/M04 | (trong `GET /api/ops/board`) | — | `units` (86 kho của cơ sở), `revenue` 6 tháng + cơ cấu theo loại kho, tỷ lệ lấp đầy tính từ `units` | +| M01/M02/M04 | (trong `GET /api/ops/board`) | — | `units` (12 ô của cơ sở, D17), `revenue` 6 tháng + cơ cấu theo loại kho, tỷ lệ lấp đầy tính từ `units` | Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái) xem `src/ops/reducer.js` — có test `tests/ops.test.js`. ### A4. Khách báo đã chuyển khoản (Figma C04) -- [ ] `POST /api/reservations/{id}/confirm-transfer` → đơn `PENDING_PAYMENT` chuyển `PENDING_VERIFICATION` (để hiện ở +- [x] `POST /api/reservations/{id}/confirm-transfer` → đơn `PENDING_PAYMENT` chuyển `PENDING_VERIFICATION` (để hiện ở S09 của nhân viên). Hiện giao diện chỉ lưu trong trình duyệt nên **nhân viên không thấy khách đã chuyển**. -- [ ] Thêm trạng thái `PENDING_VERIFICATION` cho `Reservation` (entity hiện liệt kê `PENDING_PAYMENT, CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW`). +- [x] Thêm trạng thái `PENDING_VERIFICATION` cho `Reservation` (entity hiện liệt kê `PENDING_PAYMENT, CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW`). --- diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md index 98c15f0..d42c39b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -79,7 +79,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: | C03b | `POST /api/quotes` `{facilityId, type, band, months, startDate}` | → `monthlyRate, rentTotal, deposit, initialTotal, endDate, available` | | C03c | `GET /api/facilities/{id}/photos` | 4+ ảnh kèm chú thích (mặt tiền, sơ đồ, ...) | | C04 | `POST /api/reservations` | Tạo đơn `PENDING_PAYMENT`, trả `reservationId, expiresAt, timeoutSeconds, transferAmount, transferContent` (UI tự tạo VietQR từ tài khoản nhận) | -| C04 | `POST /api/reservations/{id}/confirm-transfer` | → `PENDING_VERIFICATION`; sau `expiresAt` trả lỗi mã `EXPIRED` | +| C04 | `POST /api/reservations/{id}/confirm-transfer` | → `PENDING_VERIFICATION`; sau `expiresAt` trả lỗi mã `EXPIRED` — **đã có** (D18) | | C04b | (job nền) | Tự chuyển `PENDING_PAYMENT` quá hạn sang `CANCELLED`, `cancelReason` kiểu "Quá 1 phút chưa xác nhận" | | C14, C05 | `GET /api/reservations`, `GET /api/reservations/{id}` | | | C06, C07 | `GET /api/contracts`, `GET /api/contracts/{id}` | Thêm `unitNumber, sizeM2, location, handedOver, depositAmount` | 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 0e19256..0792109 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs @@ -104,8 +104,8 @@ export function createState() { return { users, facilities, unitTypes, rates, units, reservations, contracts, handovers, payments, renewals: [], tickets, tokens: new Map(), down: false, roles, permissions, rolePermissions, userRoles, userFacilities: [], loginHistory: [], activityLogs: [] }; } -// ---- Khu vận hành (Nhân viên / Quản lý cơ sở): backend thật CHƯA có, chỉ bật khi { ops: true } hoặc MOCK_OPS=1. -// Đây là bản chạy được của hợp đồng đề xuất trong BE-CONTRACT.md mục 5, dùng lại nghiệp vụ src/ops/reducer.js. +// ---- Khu vận hành (Nhân viên / Quản lý cơ sở): chỉ bật khi { ops: true } hoặc MOCK_OPS=1. +// Cùng hợp đồng với backend thật (docs/facility-ops-api.md), dùng lại nghiệp vụ src/ops/reducer.js. const camel = (k) => k.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase()); const snake = (k) => k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`); const mapKeys = (v, fn) => @@ -131,7 +131,7 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M const S = createState(); let O = null; if (ops) { - // Tài khoản quản lý cơ sở (DbSeeder thật chưa có) + gán nhân viên staff01 vào cơ sở + // Tài khoản quản lý cơ sở manager01 (giống DbSeeder) + gán nhân viên staff01 vào cơ sở S.users.push({ userId: S.users.length + 1, username: "manager01", email: "manager01@storage.vn", password: "Manager@123", fullName: "Phạm Thu Hà", status: "ACTIVE", phone: null, createdAt: days(-20), updatedAt: days(-20) }); S.userRoles.push({ userId: S.users.length, roleId: 2 }); O = createOpsData(); @@ -159,7 +159,7 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M const availability = (facilityId, unitTypeId, startDate, months) => { const end = addMonths(startDate, months); const free = S.units.filter((u) => u.facilityId === facilityId && u.unitTypeId === unitTypeId && u.status === "AVAILABLE").length; - const held = S.reservations.filter((r) => r.facilityId === facilityId && r.unitTypeId === unitTypeId && ["PENDING_PAYMENT", "CONFIRMED"].includes(r.status) && r.startDate < end && r.expectedEndDate > startDate).length; + const held = S.reservations.filter((r) => r.facilityId === facilityId && r.unitTypeId === unitTypeId && ["PENDING_PAYMENT", "PENDING_VERIFICATION", "CONFIRMED"].includes(r.status) && r.startDate < end && r.expectedEndDate > startDate).length; return Math.max(0, free - held); }; @@ -426,6 +426,19 @@ export function startMockApi(port = 5199, { verbose = false, ops = process.env.M S.reservations.push(r); return send(201, { ...resDto(r), createdAt: iso(r.createdAt), expiresAt: iso(r.expiresAt) }); } + if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/confirm-transfer$/))) { + // Giống ReservationService.ConfirmTransferAsync: PENDING_PAYMENT → PENDING_VERIFICATION; quá hạn giữ chỗ → 400 code EXPIRED + const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); + if (!r) return send(404, { error: "Không tìm thấy đơn đặt chỗ." }); + if (r.status === "PENDING_VERIFICATION") return send(200, resDto(r)); + if (r.status !== "PENDING_PAYMENT") return bad("Đơn đặt chỗ này không còn chờ chuyển khoản."); + if (r.expiresAt && r.expiresAt <= new Date()) { + Object.assign(r, { status: "EXPIRED", cancelledAt: new Date(), cancellationReason: "Quá thời gian giữ chỗ chưa xác nhận chuyển khoản" }); + return send(400, { error: "Đơn đặt chỗ đã hết thời gian giữ chỗ.", code: "EXPIRED" }); + } + r.status = "PENDING_VERIFICATION"; + return send(200, resDto(r)); + } if (req.method === "POST" && (m = path.match(/^\/api\/reservations\/(\d+)\/cancel$/))) { const r = S.reservations.find((x) => x.reservationId === +m[1] && x.customerId === me); if (!r) return bad("Không tìm thấy đơn đặt chỗ hợp lệ."); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs index 5e26292..42232fc 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/dev-mock.mjs @@ -26,7 +26,7 @@ console.log(` customer01 / Customer@123 → Khách hàng staff01 / Staff@123 → Nhân viên cơ sở (#/staff) manager01 / Manager@123 → Quản lý cơ sở (#/manager) — chỉ khi chạy với MOCK_OPS=1 - MOCK_OPS=1 bật các endpoint /api/ops/* (backend thật CHƯA có, xem BE-CONTRACT.md mục 5). - Không bật: khu vận hành báo "backend chưa có API" và dùng dữ liệu mẫu trong trình duyệt. + MOCK_OPS=1 bật các endpoint /api/ops/* (giống backend thật, xem docs/facility-ops-api.md). + Không bật: khu vận hành dùng dữ liệu cục bộ trong trình duyệt. Mỗi lời gọi API sẽ hiện bên dưới (xanh = thành công, đỏ = lỗi từ máy chủ). `); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js index 4b6ef08..7972762 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/endpoints.js @@ -18,6 +18,8 @@ export const api = { reservation: (id) => request(`/api/reservations/${id}`), createReservation: (body) => request("/api/reservations", { method: "POST", body }), cancelReservation: (id, reason) => request(`/api/reservations/${id}/cancel`, { method: "POST", body: { reason } }), + // C04: khách báo đã chuyển khoản → PENDING_VERIFICATION (nhân viên đối soát ở S09) + confirmTransfer: (id) => request(`/api/reservations/${id}/confirm-transfer`, { method: "POST" }), // Hợp đồng, thanh toán, gia hạn, bàn giao contracts: () => request("/api/contracts"), diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js index 9093887..2ab5fc0 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js @@ -82,7 +82,6 @@ export function mapCatalog({ facilities = [], unitTypes = [], rates = [] }) { city, phone: f.contactPhone || "", hours: open && close ? `${open}–${close}` : "06:00–22:00", - distance_km: null, camera: true, has_climate: offers.some((o) => o.type === "climate"), offers, @@ -95,6 +94,7 @@ export function mapCatalog({ facilities = [], unitTypes = [], rates = [] }) { // ---------- Trạng thái ---------- const RESERVATION = { PENDING_PAYMENT: "PENDING_PAYMENT", + PENDING_VERIFICATION: "PENDING_VERIFICATION", UNIT_ASSIGNED: "CONFIRMED", CONFIRMED: "CONFIRMED", CHECKED_IN: "CHECKED_IN", @@ -110,7 +110,7 @@ const TICKET_NOTE = { RESOLVED: "Yêu cầu đã được xử lý.", CANCELLED: "Bạn đã huỷ yêu cầu này.", }; -const RENEWAL = { PENDING_PAYMENT: "PENDING", PENDING_APPROVAL: "PENDING", APPROVED: "APPROVED", COMPLETED: "APPROVED", REJECTED: "REJECTED", CANCELLED: "REJECTED" }; +const RENEWAL = { PENDING: "PENDING", PENDING_PAYMENT: "PENDING", PENDING_APPROVAL: "PENDING", PAID: "APPROVED", APPROVED: "APPROVED", COMPLETED: "APPROVED", REJECTED: "REJECTED", CANCELLED: "REJECTED" }; function offerOfType(unitTypes, id, name) { const t = unitTypes.find((x) => x.unitTypeId === id) || unitTypes.find((x) => x.typeName === name); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/UnitMap.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/UnitMap.jsx index 240281c..95308fe 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/UnitMap.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/components/UnitMap.jsx @@ -2,7 +2,7 @@ import React from "react"; import { typeLabel } from "../lib/catalog"; import { LEGEND, UNIT_STATUS, countBy, freeCount } from "../lib/units"; -// Sơ đồ 10 ô kho (Figma C03b-sđ): chú giải, dãy A – hành lang – dãy B, ô đang chọn có viền sáng. +// Sơ đồ 12 ô kho (Figma C03b-sđ, 14/10): chú giải, dãy A cỡ M – hành lang – dãy B cỡ L, ô đang chọn có viền sáng. export default function UnitMap({ units, selected, onSelect }) { const counts = countBy(units); const rowA = units.filter((u) => u.row === "A"); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js index 9fadd1c..c04c3b3 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js @@ -4,32 +4,32 @@ import { addDays, addMonths, today } from "../lib/format.js"; export const SEED_EMAIL = "mai.nguyen@example.com"; export const SEED_PASSWORD = "SafeSpace@123"; -// Danh sách 12 cơ sở SafeSpace (tên, giá, khoảng cách theo Figma C02). +// Danh sách 12 cơ sở SafeSpace (Figma 14/10). Cơ sở nào cũng có kho thường và kho lạnh, cỡ M và L. +// Gợi ý theo khu vực khách chọn, không theo vị trí người dùng → không có khoảng cách. const FACILITIES = [ - [1, "SafeSpace Nguyễn Lương Bằng", "Quận 7", 1.2, 1150000, true, "Số 12 Nguyễn Lương Bằng, Tân Phú"], - [2, "SafeSpace Him Lam", "Quận 7", 2.8, 1050000, true, "Khu dân cư Him Lam, Tân Hưng"], - [3, "SafeSpace Phú Xuân", "Quận 7", 5.4, 890000, true, "Đường Nguyễn Hữu Thọ, Phú Xuân"], - [4, "SafeSpace Tân Thuận", "Quận 4", 6.1, 1100000, true, "Đường Huỳnh Tấn Phát, Tân Thuận"], - [5, "SafeSpace Phú Mỹ Hưng", "Huyện Nhà Bè", 6.8, 1250000, true, "Đường Nguyễn Lương Bằng, Phú Mỹ"], - [6, "SafeSpace Bình Thạnh", "Quận Bình Thạnh", 8.7, 980000, true, "Đường Nguyễn Xí, Phường 26"], - [7, "SafeSpace Nhà Bè", "Huyện Nhà Bè", 9.3, 850000, true, "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè"], - [8, "SafeSpace Bình Chánh", "Huyện Bình Chánh", 12.4, 790000, false, "Quốc lộ 50, Bình Chánh"], - [9, "SafeSpace Thủ Đức", "TP. Thủ Đức", 15.2, 920000, false, "Đường Võ Văn Ngân, Linh Chiểu"], - [10, "SafeSpace Gò Vấp", "Quận Gò Vấp", 16.8, 930000, true, "Đường Quang Trung, Phường 10"], - [11, "SafeSpace Tân Bình", "Quận Tân Bình", 18.1, 1020000, true, "Đường Cộng Hòa, Phường 13"], - [12, "SafeSpace Bình Tân", "Quận Bình Tân", 19.5, 820000, false, "Đường Kinh Dương Vương, An Lạc"], + [1, "SafeSpace Nguyễn Lương Bằng", "Quận 7", 1150000, "Số 12 Nguyễn Lương Bằng, Tân Phú"], + [2, "SafeSpace Him Lam", "Quận 7", 1050000, "Khu dân cư Him Lam, Tân Hưng"], + [3, "SafeSpace Phú Xuân", "Quận 7", 890000, "Đường Nguyễn Hữu Thọ, Phú Xuân"], + [4, "SafeSpace Tân Thuận", "Quận 7", 1100000, "Đường Huỳnh Tấn Phát, Tân Thuận"], + [5, "SafeSpace Phú Mỹ Hưng", "Quận 7", 1250000, "Đường Nguyễn Lương Bằng, Tân Phong"], + [6, "SafeSpace Bình Thạnh", "Quận Bình Thạnh", 980000, "Đường Nguyễn Xí, Phường 26"], + [7, "SafeSpace Nhà Bè", "Huyện Nhà Bè", 850000, "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè"], + [8, "SafeSpace Bình Chánh", "Huyện Bình Chánh", 790000, "Quốc lộ 50, Bình Hưng"], + [9, "SafeSpace Thủ Đức", "TP. Thủ Đức", 920000, "Đường Võ Văn Ngân, Linh Chiểu"], + [10, "SafeSpace Gò Vấp", "Quận Gò Vấp", 930000, "Đường Quang Trung, Phường 10"], + [11, "SafeSpace Tân Bình", "Quận Tân Bình", 1020000, "Đường Cộng Hòa, Phường 13"], + [12, "SafeSpace Bình Tân", "Quận Bình Tân", 820000, "Đường Kinh Dương Vương, An Lạc"], ]; export function createFacilities() { - return FACILITIES.map(([facility_id, name, district, distance_km, base_price, has_climate, street]) => withOffers({ + return FACILITIES.map(([facility_id, name, district, base_price, street]) => withOffers({ facility_id, name, district, city: "TP. Hồ Chí Minh", address: `${street}, ${district}, TP. Hồ Chí Minh`, - distance_km, base_price, - has_climate, + has_climate: true, camera: true, hours: "06:00–22:00", })); @@ -59,7 +59,7 @@ export function createSeedData(t = today()) { type: "normal", band: "M", offer_key: "normal-M", - size_label: "10 – 20 m²", + size_label: "Cỡ M · 15 m²", months: 3, start_date: t, end_date: a102End, @@ -74,16 +74,16 @@ export function createSeedData(t = today()) { reservation_id: "SS-20260615-0086", facility_id: 1, type: "climate", - band: "S", - offer_key: "climate-S", - size_label: "2 – 5 m²", + band: "M", + offer_key: "climate-M", + size_label: "Cỡ M · 15 m²", months: 3, start_date: b015Start, end_date: b015End, - monthly_rate: 500000, - deposit: 500000, - rent_total: 1500000, - initial_total: 2000000, + monthly_rate: 1380000, + deposit: 1380000, + rent_total: 4140000, + initial_total: 5520000, status: "CHECKED_IN", created_at: at(addDays(b015Start, -2), "14:30"), }, @@ -96,7 +96,7 @@ export function createSeedData(t = today()) { unit_number: "A-102", type: "normal", band: "M", - size_m2: 12, + size_m2: 15, location: "Tầng 1 · Dãy A", months: 3, start_date: t, @@ -112,14 +112,14 @@ export function createSeedData(t = today()) { facility_id: 1, unit_number: "B-015", type: "climate", - band: "S", - size_m2: 5, + band: "M", + size_m2: 15, location: "Tầng 1 · Dãy B", months: 3, start_date: b015Start, end_date: b015End, - monthly_rate: 500000, - deposit: 500000, + monthly_rate: 1380000, + deposit: 1380000, status: "EXPIRING", handed_over: true, }, @@ -146,7 +146,7 @@ export function createSeedData(t = today()) { label: "Thuê kho B-015 · 3 tháng", contract_id: "HĐ-2026-0086", reservation_id: "SS-20260615-0086", - amount: 1500000, + amount: 4140000, status: "RECONCILED", }, { @@ -154,7 +154,7 @@ export function createSeedData(t = today()) { label: "Cọc hợp đồng B-015", contract_id: "HĐ-2026-0086", reservation_id: "SS-20260615-0086", - amount: 500000, + amount: 1380000, status: "DEPOSIT_HELD", }, ], diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/catalog.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/catalog.js index a757636..0805791 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/catalog.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/catalog.js @@ -2,18 +2,18 @@ import { addMonths } from "./format.js"; export const UNIT_TYPES = [ { id: "normal", label: "Kho thường" }, - { id: "climate", label: "Kiểm soát nhiệt độ" }, + { id: "climate", label: "Kho lạnh" }, ]; export const typeLabel = (id) => UNIT_TYPES.find((t) => t.id === id)?.label || "Kho thường"; -// Nhóm diện tích theo Figma (C03 "10 – 20 m²", P01 "2–5 m²" / "Trên 20 m²") +// Hai cỡ kho theo Figma 14/10: mỗi cơ sở có 8 kho thường (4 M + 4 L) và 4 kho lạnh (2 M + 2 L) export const SIZE_BANDS = [ - { id: "S", label: "2 – 5 m²", name: "Small", note: "Vali, tài liệu và đồ cá nhân" }, - { id: "M", label: "10 – 20 m²", name: "Medium", note: "Đồ nội thất và hàng kinh doanh" }, - { id: "L", label: "Trên 20 m²", name: "Large", note: "Nhiều hàng hóa và nhu cầu dài hạn" }, + { id: "M", label: "Cỡ M · 15 m²", short: "15 m²", area: 15, name: "Cỡ M", note: "Đồ đạc một phòng, hàng shop online, hồ sơ giấy tờ" }, + { id: "L", label: "Cỡ L · 30 m²", short: "30 m²", area: 30, name: "Cỡ L", note: "Đồ chuyển nhà 2–3 phòng ngủ, hàng tồn kho số lượng lớn" }, ]; -export const bandLabel = (id) => SIZE_BANDS.find((b) => b.id === id)?.label || "10 – 20 m²"; -export const bandOfArea = (area) => (area <= 5 ? "S" : area <= 20 ? "M" : "L"); +export const bandLabel = (id) => SIZE_BANDS.find((b) => b.id === id)?.label || SIZE_BANDS[0].label; +// Loại kho từ backend: đến 20 m² là cỡ M, lớn hơn là cỡ L +export const bandOfArea = (area) => (area <= 20 ? "M" : "L"); // Gói thuê trong Figma: 1 / 3 / 6 tháng export const RENTAL_PLANS = [1, 3, 6]; @@ -25,7 +25,7 @@ export const BUDGET_LIMIT = 1100000; // chip "Dưới 1.100.000 đ / tháng" // - Dữ liệu cục bộ: sinh từ giá gốc của cơ sở × loại kho × nhóm diện tích // - Backend: mỗi loại kho (UnitType) có bảng giá tại cơ sở là một offer -const BAND_FACTOR = { S: 0.63, M: 1, L: 1.75 }; +const BAND_FACTOR = { M: 1, L: 1.75 }; const TYPE_FACTOR = { normal: 1, climate: 1.2 }; const round10k = (n) => Math.round(n / 10000) * 10000; @@ -51,7 +51,7 @@ export const offerLabel = (o) => `${typeLabel(o.type)} · ${o.size_label}`; const matches = (o, f) => (!f.type || o.type === f.type) && (!f.band || o.band === f.band); -// Gói hiển thị trên thẻ cơ sở: khớp bộ lọc; nếu chưa lọc thì ưu tiên "Kho thường · 10 – 20 m²" như Figma +// Gói hiển thị trên thẻ cơ sở: khớp bộ lọc; nếu chưa lọc thì ưu tiên "Kho thường · Cỡ M" như Figma export function displayOffer(facility, filters = {}) { const list = (facility?.offers || []).filter((o) => matches(o, filters)); if (!list.length) return null; @@ -94,12 +94,6 @@ export const DEFAULT_FILTERS = { type: "", band: "", area: "", camera: false, bu export const hasActiveFilters = (f) => Boolean(f.type || f.band || f.area || f.camera || f.budget); -// Theo khoảng cách; không có khoảng cách (dữ liệu backend) thì giữ thứ tự danh mục (sort ổn định) -const byDistance = (a, b) => { - if (a.distance_km == null || b.distance_km == null) return (a.distance_km == null) - (b.distance_km == null); - return a.distance_km - b.distance_km; -}; - // Lọc + sắp xếp danh sách cơ sở (C02 / C03) export function searchFacilities(facilities, filters) { const f = { ...DEFAULT_FILTERS, ...filters }; @@ -111,6 +105,8 @@ export function searchFacilities(facilities, filters) { if (f.budget && offer.monthly_rate >= BUDGET_LIMIT) return false; return true; }); + // Gợi ý theo khu vực khách chọn (không theo vị trí): "Phù hợp nhất" giữ thứ tự danh mục, hoặc sắp theo giá + if (f.sort !== "price") return list; const price = (x) => displayOffer(x, f).monthly_rate; - return [...list].sort((a, b) => (f.sort === "price" ? price(a) - price(b) || byDistance(a, b) : byDistance(a, b))); + return [...list].sort((a, b) => price(a) - price(b)); } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/format.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/format.js index ba1a697..85a5d59 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/format.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/format.js @@ -58,9 +58,6 @@ export function daysBetween(fromIso, toIso) { return Math.round((parse(toIso) - parse(fromIso)) / 86400000); } -export const distanceLabel = (km) => - `${new Intl.NumberFormat("vi-VN", { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(km)} km`; - // Số điện thoại hiển thị dạng che bớt: 09•• ••• 142 export function maskPhone(phone) { const digits = String(phone || "").replace(/\D/g, ""); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/units.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/units.js index 9aa704e..f771adb 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/units.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/units.js @@ -1,7 +1,7 @@ // Sơ đồ & tình trạng từng ô kho của một cơ sở (Figma C03b-sđ). // Backend chưa có API danh sách ô kho → sinh cố định theo mã cơ sở. Khi có API, // thay unitsFor() bằng dữ liệu StorageUnit (UnitNumber, Floor, Zone, Status, UnitType). -import { offerByKey } from "./catalog.js"; +import { SIZE_BANDS } from "./catalog.js"; // Trạng thái ô kho hiển thị cho khách (map từ StorageUnit.Status của backend) export const UNIT_STATUS = { @@ -16,42 +16,38 @@ export const LEGEND = ["FREE", "RENTED", "HELD", "SERVICE"]; export const fromBackendStatus = (s) => s === "AVAILABLE" ? "FREE" : s === "RESERVED" || s === "ASSIGNED" ? "HELD" : ["MAINTENANCE", "INSPECTION", "OUT_OF_SERVICE"].includes(s) ? "SERVICE" : "RENTED"; -// Bố cục theo Figma: dãy A (K01–K05, 5 m²) và dãy B (K06–K10, 10 m²), hành lang ở giữa +// Bố cục theo Figma 14/10: 12 ô, hành lang ở giữa. +// Dãy A cỡ M: K01–K04 kho thường, K05–K06 kho lạnh. Dãy B cỡ L: K07–K10 kho thường, K11–K12 kho lạnh. const LAYOUT = [ - ["K01", "A", 5], ["K02", "A", 5], ["K03", "A", 5], ["K04", "A", 5], ["K05", "A", 5], - ["K06", "B", 10], ["K07", "B", 10], ["K08", "B", 10], ["K09", "B", 10], ["K10", "B", 10], + ["K01", "A", "normal", "M"], ["K02", "A", "normal", "M"], ["K03", "A", "normal", "M"], ["K04", "A", "normal", "M"], + ["K05", "A", "climate", "M"], ["K06", "A", "climate", "M"], + ["K07", "B", "normal", "L"], ["K08", "B", "normal", "L"], ["K09", "B", "normal", "L"], ["K10", "B", "normal", "L"], + ["K11", "B", "climate", "L"], ["K12", "B", "climate", "L"], ]; // Tình trạng mẫu của Figma, xoay vòng theo mã cơ sở để mỗi cơ sở khác nhau nhưng luôn ổn định -const PATTERN = ["FREE", "RENTED", "FREE", "HELD", "FREE", "RENTED", "FREE", "SERVICE", "FREE", "RENTED"]; -const COLD = ["K04", "K05", "K09", "K10"]; +const PATTERN = ["FREE", "RENTED", "FREE", "HELD", "FREE", "RENTED", "FREE", "SERVICE", "FREE", "RENTED", "FREE", "RENTED"]; const NON_FREE = ["RENTED", "HELD", "SERVICE"]; const areaText = (n) => `${String(n).replace(".", ",")} m²`; +const BAND_AREA = Object.fromEntries(SIZE_BANDS.map((b) => [b.id, b.area])); -// Gán gói kho cho 10 ô: dữ liệu cục bộ theo bố cục Figma (5 m² / 10 m²); -// dữ liệu backend (gói theo UnitType) → dãy A nhận các loại nhỏ, dãy B các loại lớn. +// Gán gói kho cho 12 ô theo loại (thường / lạnh) và cỡ (M / L). +// Dữ liệu backend chưa đủ 4 loại thì ô lấy gói gần nhất: cùng loại + cùng cỡ → cùng cỡ → cùng loại → gói bất kỳ. function offersForLayout(facility) { const offers = facility.offers || []; - if (!offers.some((o) => o.unit_type_id)) { - return LAYOUT.map(([code, , area]) => { - const wantCold = facility.has_climate !== false && COLD.includes(code); - const band = area <= 5 ? "S" : "M"; - return { offer: offerByKey(facility, `${wantCold ? "climate" : "normal"}-${band}`) || offerByKey(facility, `normal-${band}`), area }; - }); - } - const sorted = [...offers].sort((x, y) => (x.area || 0) - (y.area || 0)); - const half = Math.max(1, Math.ceil(sorted.length / 2)); - const small = sorted.slice(0, half); - const large = sorted.length > 1 ? sorted.slice(half) : sorted; - return LAYOUT.map(([, row], i) => { - const pool = row === "A" ? small : large; - const offer = pool[(row === "A" ? i : i - 5) % pool.length]; - return { offer, area: offer?.area ?? (row === "A" ? 5 : 10) }; + return LAYOUT.map(([, , type, band]) => { + const offer = + offers.find((o) => o.type === type && o.band === band) || + offers.find((o) => o.band === band) || + offers.find((o) => o.type === type) || + offers[0] || + null; + return { offer, area: offer?.area ?? BAND_AREA[band] }; }); } /** - * 10 ô kho của một cơ sở. + * 12 ô kho của một cơ sở. * `stock` (không bắt buộc): { [offer.key]: số ô trống } lấy từ POST /api/availability/check — * khi có, số ô "Còn trống" của mỗi loại khớp đúng số backend trả về. */ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx index 699828b..80b926b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx @@ -79,7 +79,7 @@ function Bell({ role }) { ); } -function UserMenu({ roleLabel, tone }) { +function UserMenu({ roleLabel, tone, facilityName }) { const { user, logout } = useApp(); const [open, setOpen] = useState(false); const ref = useRef(null); @@ -89,6 +89,7 @@ function UserMenu({ roleLabel, tone }) { {open && (
@@ -116,7 +117,7 @@ function UserMenu({ roleLabel, tone }) { // Khung chung khu vận hành (Figma S01 / M01): logo, tên + vai trò, chuông, thanh điều hướng theo vai trò export default function OpsShell({ role, active, children }) { const { mode } = useApp(); - const { source } = useOps(); + const { source, ops } = useOps(); const staff = role === "STAFF"; const tabs = staff ? STAFF_TABS : MANAGER_TABS; const home = staff ? "staff" : "manager"; @@ -130,7 +131,8 @@ export default function OpsShell({ role, active, children }) {
@@ -146,7 +148,7 @@ export default function OpsShell({ role, active, children }) { {mode === "api" && source === "local" && (

- Backend chưa có API cho khu vận hành (GET /api/ops/board trả 404) — đang hiển thị dữ liệu mẫu lưu trong trình duyệt. + Chưa kết nối được dữ liệu vận hành của cơ sở. Thao tác trên màn hình này đang được lưu tạm trên trình duyệt.

)} {children} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js index 237f29a..9131363 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js @@ -1,6 +1,6 @@ -// API khu vận hành (Nhân viên cơ sở / Quản lý cơ sở). Backend StorageProject.Api CHƯA có các endpoint này; -// hợp đồng đề xuất nằm ở BE-CONTRACT.md mục 5 và được mock/mock-api.mjs làm mẫu chạy được. -// Khi backend trả 404 cho GET /api/ops/board, giao diện tự dùng dữ liệu mẫu trong trình duyệt. +// API khu vận hành (Nhân viên cơ sở / Quản lý cơ sở): StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs, +// tài liệu ở docs/facility-ops-api.md; mock/mock-api.mjs (MOCK_OPS=1) chạy cùng hợp đồng để thử không cần .NET. +// Backend cũ trả 404 cho GET /api/ops/board → giao diện dùng dữ liệu cục bộ trong trình duyệt (ops/store.jsx). import { request } from "../api/http.js"; const enc = encodeURIComponent; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js index f8ec3a9..5df7be7 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js @@ -1,6 +1,6 @@ -// Dữ liệu vận hành tại cơ sở cho khu Nhân viên (S01–S09) và Quản lý cơ sở (M01–M08). -// Backend chưa có API cho hai vai trò này → dữ liệu khởi tạo ở đây, lưu trong trình duyệt -// (ops/store.jsx). Khi có API, thay từng nhánh trong ops/store.jsx, giữ nguyên hình dạng dữ liệu. +// Dữ liệu vận hành tại cơ sở cho khu Nhân viên (S01–S09) và Quản lý cơ sở (M01–M08) khi chạy không backend +// (VITE_USE_API=false) hoặc máy chủ giả lập. Có backend thì dữ liệu lấy từ GET /api/ops/board (ops/api.js); +// hình dạng dữ liệu hai bên giống nhau. import { addDays, addMonths, today } from "../lib/format.js"; export const OPS_PASSWORD = "SafeSpace@123"; @@ -30,57 +30,35 @@ export const UNIT_STATE = { }; const at = (iso, time) => `${iso}T${time}:00`; -const ZONES = ["A", "B", "C", "D", "E", "F"]; -const SIZES = [6, 8, 10, 12, 15]; -const NAMES = [ - "Lê Minh Châu", "Phạm Gia Huy", "Trịnh Thu Trang", "Võ Quốc Việt", "Đặng Mỹ Linh", "Bùi Anh Tuấn", "Hồ Ngọc Hân", - "Ngô Thành Đạt", "Đỗ Khánh Vy", "Mai Xuân Lộc", "Tạ Minh Khôi", "Lâm Bảo Ngọc", "Châu Gia Kiệt", "Kiều Phương Anh", + +// 12 ô kho của cơ sở theo D17 (Figma 14/10) — cùng sơ đồ với giao diện khách (src/lib/units.js) và DbSeeder: +// dãy A cỡ M 15 m² (K01–K04 thường, K05–K06 lạnh), dãy B cỡ L 30 m² (K07–K10 thường, K11–K12 lạnh). +const LAYOUT = [ + ["K01", "normal", 15], ["K02", "normal", 15], ["K03", "normal", 15], ["K04", "normal", 15], + ["K05", "climate", 15], ["K06", "climate", 15], + ["K07", "normal", 30], ["K08", "normal", 30], ["K09", "normal", 30], ["K10", "normal", 30], + ["K11", "climate", 30], ["K12", "climate", 30], ]; -// 86 ô kho của cơ sở (Figma M01: 86 kho, tỷ lệ lấp đầy 78%) function createUnits(t) { - const named = [ - { code: "A-102", tenant: "Nguyễn Thị Mai", area: 12, floor: 1, type: "normal", status: "WAITING_HANDOVER", end: addMonths(addDays(t, 6), 3) }, - { code: "C-208", tenant: "Lê Văn Tùng", area: 8, floor: 2, type: "normal", status: "EXPIRING", end: addDays(t, 14) }, - { code: "A-045", tenant: "Trần Quốc Bảo", area: 15, floor: 1, type: "normal", status: "OVERDUE", end: addDays(t, -3) }, - { code: "D-019", tenant: "Hoàng Thị Lan", area: 10, floor: 1, type: "climate", status: "OVERDUE", end: addDays(t, -3) }, - { code: "E-301", tenant: null, area: 6, floor: 3, type: "normal", status: "EMPTY", end: null }, - { code: "C-012", tenant: "Lê Văn An", area: 10, floor: 1, type: "normal", status: "OVERDUE", end: addDays(t, -4) }, - { code: "B-015", tenant: "Nguyễn Thị Mai", area: 5, floor: 1, type: "climate", status: "EXPIRING", end: addDays(t, 5) }, - { code: "F-077", tenant: "Đỗ Minh Khang", area: 12, floor: 2, type: "normal", status: "EXPIRING", end: addDays(t, 6) }, - { code: "A-108", tenant: null, area: 15, floor: 1, type: "normal", status: "EMPTY", end: null }, - { code: "A-110", tenant: "Phan Quốc Huy", area: 10, floor: 1, type: "normal", status: "WAITING_HANDOVER", end: addMonths(addDays(t, 1), 6) }, - { code: "B-021", tenant: "Đặng Thu Trang", area: 6, floor: 1, type: "climate", status: "WAITING_HANDOVER", end: addMonths(addDays(t, 2), 3) }, - { code: "A-104", tenant: null, area: 12, floor: 1, type: "normal", status: "EMPTY", end: null }, - { code: "A-115", tenant: "Võ Thị Hạnh", area: 12, floor: 1, type: "normal", status: "WAITING_HANDOVER", end: addMonths(t, 3) }, - { code: "B-004", tenant: null, area: 5, floor: 1, type: "climate", status: "EMPTY", end: null }, - { code: "D-006", tenant: null, area: 4, floor: 1, type: "climate", status: "EMPTY", end: null }, - ]; - const taken = new Set(named.map((u) => u.code)); - const out = [...named]; - let i = 0; - while (out.length < 86) { - const zone = ZONES[i % ZONES.length]; - const num = 100 + Math.floor(i / ZONES.length) * 7 + (i % 5); - const code = `${zone}-${String(num).padStart(3, "0")}`; - i++; - if (taken.has(code)) continue; - taken.add(code); - // ~78% đang có khách; còn lại trống / bảo trì - const r = (i * 37) % 100; - const status = r < 70 ? "ACTIVE" : r < 76 ? "EXPIRING" : r < 96 ? "EMPTY" : "MAINTENANCE"; - const rented = status === "ACTIVE" || status === "EXPIRING"; - out.push({ - code, - tenant: rented ? NAMES[i % NAMES.length] : null, - area: SIZES[i % SIZES.length], - floor: Number(num.toString()[0]), - type: zone === "D" || zone === "B" ? "climate" : "normal", - status, - end: rented ? addDays(t, status === "EXPIRING" ? 5 + (i % 20) : 40 + ((i * 11) % 200)) : null, - }); - } - return out; + const usage = { + K01: ["Nguyễn Thị Mai", "WAITING_HANDOVER", addMonths(addDays(t, 6), 3)], + K02: ["Lê Văn Tùng", "EXPIRING", addDays(t, 14)], + 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)], + K06: [null, "EMPTY", null], + K07: ["Đỗ Minh Khang", "EXPIRING", addDays(t, 6)], + K08: ["Phan Quốc Huy", "WAITING_HANDOVER", addMonths(addDays(t, 1), 6)], + K09: [null, "EMPTY", null], + K10: ["Hoàng Thị Lan", "OVERDUE", addDays(t, -3)], + K11: ["Đặng Thu Trang", "WAITING_HANDOVER", addMonths(addDays(t, 2), 3)], + K12: ["Nguyễn Thị Mai", "EXPIRING", addDays(t, 5)], + }; + return LAYOUT.map(([code, type, area]) => { + const [tenant, status, end] = usage[code]; + return { code, tenant, area, floor: "trệt", type, status, end }; + }); } export function createOpsData(t = today()) { @@ -95,17 +73,17 @@ export function createOpsData(t = today()) { payments: [ { id: "SS-20260914-0142", customer: "Nguyễn Thị Mai", amount: 4600000, method: "Chuyển khoản ngân hàng", - reported_at: at(t, "09:12"), memo: "SS 20260914 0142 MAI", offer: "Kho thường · 10–20 m²", + reported_at: at(t, "09:12"), memo: "SS 20260914 0142 MAI", offer: "Kho thường · Cỡ M · 15 m²", start: pickup, end: addMonths(pickup, 3), pickup: at(pickup, "09:00"), status: "PENDING", }, { id: "SS-20260913-0147", customer: "Trương Gia Bảo", amount: 2520000, method: "Chuyển khoản ngân hàng", - reported_at: at(addDays(t, -1), "20:41"), memo: "SS 20260913 0147 BAO", offer: "Kiểm soát nhiệt độ · 2–5 m²", + reported_at: at(addDays(t, -1), "20:41"), memo: "SS 20260913 0147 BAO", offer: "Kho lạnh · Cỡ M · 15 m²", start: addDays(t, 3), end: addMonths(addDays(t, 3), 3), pickup: at(addDays(t, 3), "15:00"), status: "PENDING", }, { id: "SS-20260930-0151", customer: "Lý Minh Đức", amount: 2160000, method: "Chuyển khoản ngân hàng", - reported_at: at(t, "07:55"), memo: "SS 20260930 0151 DUC", offer: "Kho thường · 2–5 m²", + reported_at: at(t, "07:55"), memo: "SS 20260930 0151 DUC", offer: "Kho thường · Cỡ L · 30 m²", start: addDays(t, 4), end: addMonths(addDays(t, 4), 3), pickup: at(addDays(t, 4), "10:00"), status: "PENDING", }, ], @@ -113,31 +91,31 @@ export function createOpsData(t = today()) { // M05 · Đơn đã đối soát, chờ quản lý phân bổ ô kho allocations: [ { - id: "SS-20260912-0138", customer: "Hồ Ngọc Hân", type: "normal", offer: "Kho thường · 10–20 m²", min_area: 10, max_area: 20, + id: "SS-20260912-0138", customer: "Hồ Ngọc Hân", type: "normal", offer: "Kho thường · Cỡ L · 30 m²", min_area: 30, max_area: 30, start: addDays(t, 6), end: addMonths(addDays(t, 6), 3), pickup: at(addDays(t, 6), "10:30"), status: "PENDING", unit: null, }, ], // S02 · Xác minh khách khi đến nhận kho verifications: [ - { id: "XM-0115", reservation_id: "SS-20260908-0115", customer: "Võ Thị Hạnh", unit: "A-115", appointment: at(t, "15:30"), status: "DONE", doc_type: "Căn cước công dân", doc_last4: "4821", verified_at: at(t, "08:40") }, - { id: "XM-0142", reservation_id: "SS-20260914-0142", customer: "Nguyễn Thị Mai", unit: "A-102", appointment: at(pickup, "09:00"), status: "TODO" }, - { id: "XM-0131", reservation_id: "SS-20260910-0131", customer: "Phan Quốc Huy", unit: "A-110", appointment: at(addDays(t, 1), "08:30"), status: "TODO" }, - { id: "XM-0135", reservation_id: "SS-20260911-0135", customer: "Đặng Thu Trang", unit: "B-021", appointment: at(addDays(t, 2), "14:00"), status: "TODO" }, + { id: "XM-0115", reservation_id: "SS-20260908-0115", customer: "Võ Thị Hạnh", unit: "K05", appointment: at(t, "15:30"), status: "DONE", doc_type: "Căn cước công dân", doc_last4: "4821", verified_at: at(t, "08:40") }, + { id: "XM-0142", reservation_id: "SS-20260914-0142", customer: "Nguyễn Thị Mai", unit: "K01", appointment: at(pickup, "09:00"), status: "TODO" }, + { id: "XM-0131", reservation_id: "SS-20260910-0131", customer: "Phan Quốc Huy", unit: "K08", appointment: at(addDays(t, 1), "08:30"), status: "TODO" }, + { id: "XM-0135", reservation_id: "SS-20260911-0135", customer: "Đặng Thu Trang", unit: "K11", appointment: at(addDays(t, 2), "14:00"), status: "TODO" }, ], // S03 · Bàn giao kho (sau khi xác minh) handovers: [ - { id: "BG-0115", verification_id: "XM-0115", unit: "A-115", customer: "Võ Thị Hạnh", status: "WAITING", method: null }, - { id: "BG-0142", verification_id: "XM-0142", unit: "A-102", customer: "Nguyễn Thị Mai", status: "WAITING", method: null }, - { id: "BG-0131", verification_id: "XM-0131", unit: "A-110", customer: "Phan Quốc Huy", status: "WAITING", method: null }, - { id: "BG-0135", verification_id: "XM-0135", unit: "B-021", customer: "Đặng Thu Trang", status: "WAITING", method: null }, + { id: "BG-0115", verification_id: "XM-0115", unit: "K05", customer: "Võ Thị Hạnh", status: "WAITING", method: null }, + { id: "BG-0142", verification_id: "XM-0142", unit: "K01", customer: "Nguyễn Thị Mai", status: "WAITING", method: null }, + { id: "BG-0131", verification_id: "XM-0131", unit: "K08", customer: "Phan Quốc Huy", status: "WAITING", method: null }, + { id: "BG-0135", verification_id: "XM-0135", unit: "K11", customer: "Đặng Thu Trang", status: "WAITING", method: null }, ], // S04 · Kiểm tra trả kho returns: [ { - id: "TK-0098", contract: "HĐ-0098", unit: "C-012", customer: "Lê Văn An", appointment: at(pickup, "10:00"), + id: "TK-0098", contract: "HĐ-0098", unit: "K04", customer: "Lê Văn An", appointment: at(pickup, "10:00"), deposit: 1150000, unpaid: 460000, status: "SCHEDULED", report: null, }, ], @@ -145,47 +123,46 @@ export function createOpsData(t = today()) { // S05 · Yêu cầu hỗ trợ tại cơ sở tickets: [ { - id: "HT-0082", unit: "B-015", customer: "Nguyễn Thị Mai", title: "Thẻ ra vào không mở được cổng", created_at: at(t, "09:45"), + id: "HT-0082", unit: "K12", customer: "Nguyễn Thị Mai", title: "Thẻ ra vào không mở được cổng", created_at: at(t, "09:45"), schedule: at(t, "14:00"), status: "OPEN", assignee: null, notes: [], }, { - id: "HT-0079", unit: "A-045", customer: "Trần Quốc Bảo", title: "Cửa cuốn kho kẹt khi mở", created_at: at(addDays(t, -1), "16:20"), + id: "HT-0079", unit: "K03", customer: "Trần Quốc Bảo", title: "Cửa cuốn kho kẹt khi mở", created_at: at(addDays(t, -1), "16:20"), schedule: at(addDays(t, 1), "09:00"), status: "IN_PROGRESS", assignee: "NV-01", notes: [], }, ], // M03 · Yêu cầu gia hạn chờ duyệt renewals: [ - { id: "GH-0208", contract: "HĐ-0088", customer: "Lê Văn Tùng", unit: "C-208", from: addDays(t, 14), to: addMonths(addDays(t, 14), 3), months: 3, requested: at(addDays(t, -1), "10:05"), status: "PENDING" }, - { id: "GH-0077", contract: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "F-077", from: addDays(t, 6), to: addMonths(addDays(t, 6), 3), months: 3, requested: at(addDays(t, -2), "15:40"), status: "PENDING" }, - { id: "GH-0015", contract: "HĐ-2026-0086", customer: "Nguyễn Thị Mai", unit: "B-015", from: addDays(t, 5), to: addMonths(addDays(t, 5), 1), months: 1, requested: at(addDays(t, -2), "08:12"), status: "PENDING" }, - { id: "GH-0120", contract: "HĐ-0120", customer: "Lê Minh Châu", unit: "E-120", from: addDays(t, 9), to: addMonths(addDays(t, 9), 6), months: 6, requested: at(addDays(t, -3), "19:02"), status: "PENDING" }, + { id: "GH-0208", contract: "HĐ-0088", customer: "Lê Văn Tùng", unit: "K02", from: addDays(t, 14), to: addMonths(addDays(t, 14), 3), months: 3, requested: at(addDays(t, -1), "10:05"), status: "PENDING" }, + { id: "GH-0077", contract: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "K07", from: addDays(t, 6), to: addMonths(addDays(t, 6), 3), months: 3, requested: at(addDays(t, -2), "15:40"), status: "PENDING" }, + { id: "GH-0015", contract: "HĐ-2026-0086", customer: "Nguyễn Thị Mai", unit: "K12", from: addDays(t, 5), to: addMonths(addDays(t, 5), 1), months: 1, requested: at(addDays(t, -2), "08:12"), status: "PENDING" }, ], // M07 · Hợp đồng quá hạn / cần xử lý contracts: [ - { id: "HĐ-0061", customer: "Trần Quốc Bảo", unit: "A-045", end: addDays(t, -3), due: "Tiền thuê kỳ mới · Chưa thanh toán", amount: 1250000, state: "OVERDUE", reminders: [] }, - { id: "HĐ-0098", customer: "Lê Văn An", unit: "C-012", end: addDays(t, -4), due: "460.000 đ · Chờ đối soát", amount: 460000, state: "OVERDUE", reminders: [] }, - { id: "HĐ-0073", customer: "Hoàng Thị Lan", unit: "D-019", end: addDays(t, -3), due: "Tiền thuê kỳ mới · Chưa thanh toán", amount: 1380000, state: "OVERDUE", reminders: [] }, - { id: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "F-077", end: addDays(t, 6), due: "Yêu cầu gia hạn", amount: 0, state: "RENEWAL", reminders: [] }, + { id: "HĐ-0061", customer: "Trần Quốc Bảo", unit: "K03", end: addDays(t, -3), due: "Tiền thuê kỳ mới · Chưa thanh toán", amount: 1250000, state: "OVERDUE", reminders: [] }, + { id: "HĐ-0098", customer: "Lê Văn An", unit: "K04", end: addDays(t, -4), due: "460.000 đ · Chờ đối soát", amount: 460000, state: "OVERDUE", reminders: [] }, + { id: "HĐ-0073", customer: "Hoàng Thị Lan", unit: "K10", end: addDays(t, -3), due: "Tiền thuê kỳ mới · Chưa thanh toán", amount: 1380000, state: "OVERDUE", reminders: [] }, + { id: "HĐ-0077", customer: "Đỗ Minh Khang", unit: "K07", end: addDays(t, 6), due: "Yêu cầu gia hạn", amount: 0, state: "RENEWAL", reminders: [] }, ], // M06 · Công việc được phân công assignments: [ - { id: "PC-01", title: "Bàn giao A-102 · Nguyễn Thị Mai", when: at(pickup, "09:00"), staff: "NV-01", status: "ACCEPTED", ref: "BG-0142" }, - { id: "PC-02", title: "Kiểm tra trả kho C-012", when: at(pickup, "10:00"), staff: "NV-01", status: "WAITING", ref: "TK-0098" }, + { id: "PC-01", title: "Bàn giao K01 · Nguyễn Thị Mai", when: at(pickup, "09:00"), staff: "NV-01", status: "ACCEPTED", ref: "BG-0142" }, + { id: "PC-02", title: "Kiểm tra trả kho K04 · Lê Văn An", when: at(pickup, "10:00"), staff: "NV-01", status: "WAITING", ref: "TK-0098" }, { id: "PC-03", title: "HT-0082 · Lỗi thẻ ra vào", when: at(t, "14:00"), staff: null, status: "OPEN", ref: "HT-0082" }, ], - // M04 · Doanh thu 6 tháng gần nhất (triệu đồng) và cơ cấu theo loại kho + // M04 · Doanh thu thuê và phí 6 tháng gần nhất (triệu đồng) và cơ cấu theo loại kho của tháng này revenue: { - months: [66.0, 72.7, 69.6, 81.3, 87.0, 92.4].map((value, i) => { + months: [11.2, 12.4, 11.9, 13.1, 14.6, 15.8].map((value, i) => { const m = new Date(`${addMonths(t.slice(0, 8) + "01", i - 5)}T00:00:00`); return { label: `Tháng ${m.getMonth() + 1}`, month: m.getMonth() + 1, year: m.getFullYear(), value }; }), by_type: [ - { label: "Kho thường", value: 58.4 }, - { label: "Kiểm soát nhiệt độ", value: 34.0 }, + { label: "Kho thường", value: 10.6 }, + { label: "Kho lạnh", value: 5.2 }, ], as_of: t, }, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js index 4b02ec3..e35bed9 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js @@ -15,10 +15,12 @@ const addLog = (state, now, text, to, role = "ALL") => ({ log: [{ id: `L-${now.getTime()}-${state.log.length}`, text, to, role, at: iso(now), read: false }, ...state.log].slice(0, 60), }); -// Diện tích từ nhãn gói ("Kho thường · 10–20 m²") → khoảng m² +// Diện tích từ nhãn gói → khoảng m² ("Kho lạnh · Cỡ M · 15 m²" → [15, 15]; nhãn cũ "10–20 m²" → [10, 20]) export function areaRange(offer = "") { const m = offer.match(/(\d+)\s*[–-]\s*(\d+)\s*m²/); if (m) return [Number(m[1]), Number(m[2])]; + const one = offer.match(/(\d+)\s*m²/); + if (one) return [Number(one[1]), Number(one[1])]; if (/Trên\s*20/.test(offer)) return [20, 999]; return [0, 999]; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx index dab6eb4..529a620 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx @@ -6,7 +6,7 @@ import { reduceOps } from "./reducer"; // Kho dữ liệu vận hành cho khu Nhân viên & Quản lý cơ sở. // - mode "api": đọc GET /api/ops/board, mỗi thao tác gọi endpoint tương ứng (ops/api.js) rồi nạp lại. -// - backend chưa có API (404) hoặc chạy không backend: dữ liệu mẫu lưu trong trình duyệt, dùng chung +// - backend không có /api/ops (404, bản backend cũ) hoặc chạy không backend: dữ liệu cục bộ lưu trong trình duyệt, dùng chung // giữa nhân viên và quản lý (thao tác bên này hiện ngay bên kia, kể cả khác tab). export const OPS_KEY = "safespace.ops.v1"; const OpsContext = createContext(null); @@ -49,7 +49,7 @@ export function OpsProvider({ children, notify, mode = "local", onApiError }) { setSource("api"); } catch (e) { if (e instanceof ApiError && (e.status === 404 || e.status === 405)) { - // Backend chưa có endpoint vận hành → dữ liệu mẫu + // Backend không có endpoint vận hành (bản cũ) → dữ liệu cục bộ commit(readOps()); setSource("local"); } else { @@ -63,7 +63,7 @@ export function OpsProvider({ children, notify, mode = "local", onApiError }) { if (mode === "api") reload(); }, [mode, reload]); - // Lưu + đồng bộ giữa các tab khi dùng dữ liệu mẫu + // Lưu + đồng bộ giữa các tab khi dùng dữ liệu cục bộ useEffect(() => { if (source !== "local" || !state) return; try { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/tasks.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/tasks.jsx index 72623e4..eb7ffc0 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/tasks.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/tasks.jsx @@ -73,7 +73,7 @@ export function staffTasks(ops, me, kind = "all") { list.push({ key: h.id, kind: "handover", status: ready ? ["Sẵn sàng bàn giao", "green"] : ["Chờ xác minh", "gray"], title: `Kho #${h.unit} · ${h.customer}`, - meta: `${ready ? "Đã xác minh khách · " : ""}${unit?.type === "climate" ? "Kiểm soát nhiệt độ" : "Kho thường"}${unit ? ` · ${unit.area} m²` : ""}`, + meta: `${ready ? "Đã xác minh khách · " : ""}${unit?.type === "climate" ? "Kho lạnh" : "Kho thường"}${unit ? ` · ${unit.area} m²` : ""}`, when: v ? `Hẹn ${slot(v.appointment)}` : "Chưa có lịch hẹn", cta: ready ? "Bàn giao" : "Xác minh trước", outline: !ready, to: ready ? `staff/handover?id=${h.id}` : `staff/verify?id=${v?.id}`, sort: v?.appointment || "", diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Checkout.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Checkout.jsx index 8c614c3..561ab0e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Checkout.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Checkout.jsx @@ -3,7 +3,6 @@ import { Photo } from "../components/Photo"; import { Button, DetailList, Empty, Icon, LinkButton, Notice } from "../components/UI"; import PaymentQr from "../components/PaymentQr"; import { bandLabel, typeLabel } from "../lib/catalog"; -import { distanceLabel } from "../lib/format"; import { dateLabel, formatCountdown, money, rangeLabel } from "../lib/format"; import { useNow, shortName } from "../lib/hooks"; import { go } from "../lib/router"; @@ -64,7 +63,6 @@ export function Checkout({ id }) {

{facility.name}

{[facility.district, facility.city].filter(Boolean).join(", ") || facility.address} - {facility.distance_km != null && ` · Cách bạn ${distanceLabel(facility.distance_km)}`}

diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FacilityDetail.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FacilityDetail.jsx index f427a38..8efb78c 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FacilityDetail.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FacilityDetail.jsx @@ -6,7 +6,7 @@ import { Button, Empty, Field, LinkButton, Notice } from "../components/UI"; import UnitMap from "../components/UnitMap"; import { RENTAL_PLANS, UNIT_TYPES, offerTypes, pickOffer, quote } from "../lib/catalog"; import { UNIT_STATUS, unitsFor } from "../lib/units"; -import { dateLabel, distanceLabel, money, today } from "../lib/format"; +import { dateLabel, money, today } from "../lib/format"; import { go, href, qs } from "../lib/router"; import { useApp } from "../state/store"; @@ -162,8 +162,7 @@ export default function FacilityDetail({ id, query }) {

{facility.name}

- {place} - {facility.distance_km != null && ` · Cách bạn ${distanceLabel(facility.distance_km)}`} · {stockText} + {place} · {stockText}

- @@ -101,7 +97,7 @@ export default function FindList({ query }) {

{f.name}

- {f.distance_km != null ? `${f.city} · Cách bạn ${distanceLabel(f.distance_km)}` : [f.district, f.city].filter(Boolean).join(", ")} + {[f.district, f.city].filter(Boolean).join(", ")}

{compactLabel(offer.size_label)} · {typeLabel(offer.type)} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx index c1956da..c515a7e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx @@ -10,7 +10,7 @@ import { go, href, qs } from "../lib/router"; import { useApp } from "../state/store"; import { filtersFromQuery } from "./FindList"; -// Nhãn loại kho & diện tích trên thẻ / popup: "Kho thường · Kiểm soát nhiệt độ | 2 – 5 m² · 10 – 20 m²" +// Nhãn loại kho & diện tích trên thẻ / popup: "Kho thường · Kho lạnh | Cỡ M · 15 m² · Cỡ L · 30 m²" function specLabel(f) { const types = offerTypes(f).map(typeLabel).join(" · "); const sizes = [...new Set(f.offers.map((o) => o.size_label.replaceAll(" – ", "–")))].slice(0, 2).join(" · "); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx index 9c78160..5fba6a6 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx @@ -1,96 +1,274 @@ import React, { useState } from "react"; import { Photo } from "../components/Photo"; -import { Pagination } from "../components/Pickers"; +import { Select } from "../components/Pickers"; import { Icon, LinkButton } from "../components/UI"; -import { minRate, offerTypes, typeLabel } from "../lib/catalog"; +import { SIZE_BANDS, UNIT_TYPES, areaLabel, listAreas, minRate } from "../lib/catalog"; import { money } from "../lib/format"; +import { go, href, qs } from "../lib/router"; import { useApp } from "../state/store"; -const PER_PAGE = 9; +// Trang chủ theo Figma "START · SafeSpace / Trang chủ" (14/10): +// hero ảnh + tìm kho theo khu vực → số liệu → 4 loại kho → 3 bước → cơ sở theo khu vực → kêu gọi → footer. +// Gợi ý theo khu vực khách chọn, không theo vị trí người dùng. -const FEATURES = [ - ["bolt", "Tiện lợi", "Đặt kho, quản lý và gia hạn chỉ trong vài thao tác, mọi lúc mọi nơi."], - ["shield", "An toàn", "Giám sát 24/7, kiểm soát ra vào chặt chẽ và bảo vệ tài sản của bạn."], - ["auto", "Tự động hoá", "Theo dõi tình trạng kho, lịch hẹn và hợp đồng rõ ràng trong một tài khoản."], +const UNITS_PER_FACILITY = 12; // 8 kho thường (4 M + 4 L) + 4 kho lạnh (2 M + 2 L) +const CARDS_SHOWN = 6; + +const KINDS = [ + { type: "normal", band: "M", note: "Đồ đạc một phòng, hàng shop online, hồ sơ giấy tờ." }, + { type: "normal", band: "L", note: "Đồ chuyển nhà 2–3 phòng ngủ, hàng tồn kho số lượng lớn." }, + { type: "climate", band: "M", note: "Thiết bị điện tử, tài liệu, đồ gỗ cần tránh ẩm." }, + { type: "climate", band: "L", note: "Hàng hoá cần giữ nhiệt độ ổn định, kho hàng cho cửa hàng." }, +]; + +const STEPS = [ + ["Chọn khu vực", "Chọn quận bạn muốn gửi đồ, SafeSpace gợi ý các cơ sở trong khu vực đó."], + ["Chọn loại và cỡ kho", "Kho thường hoặc kho lạnh, cỡ M hay L. Giá hiện rõ theo tháng."], + ["Xem ô trống và đặt chỗ", "Xem sơ đồ từng ô, tiền thuê, tiền cọc và thanh toán bằng QR."], ]; +const districtOf = (area) => area.split(",")[0].trim(); +const lowest = (facilities, filter) => { + const rates = facilities.map((f) => minRate(f, filter)).filter((x) => x != null); + return rates.length ? Math.min(...rates) : null; +}; + +function HeroSearch({ facilities }) { + const [draft, setDraft] = useState({ area: "", type: "", band: "" }); + const set = (key) => (e) => setDraft({ ...draft, [key]: e.target.value }); + return ( +

{ + e.preventDefault(); + go(`find${qs(draft)}`); + }} + > + + + + +
+ ); +} + +function FacilityCard({ f }) { + const from = minRate(f); + const types = [...new Set(f.offers.map((o) => o.type))]; + return ( + + +
+ {f.district || districtOf(areaLabel(f))} +

{f.name}

+
    + {types.includes("normal") &&
  • Kho thường
  • } + {types.includes("climate") &&
  • Kho lạnh
  • } +
  • Cỡ M · L
  • +
+
+

+ Từ + {from != null ? `${money(from)} / tháng` : "Liên hệ"} +

+ Xem ô trống → +
+
+
+ ); +} + export default function Home() { const { data, authed } = useApp(); - const [page, setPage] = useState(1); - const total = data.facilities.length; - const pages = Math.ceil(total / PER_PAGE); - const from = (page - 1) * PER_PAGE; - const shown = data.facilities.slice(from, from + PER_PAGE); + const facilities = data.facilities; + const [area, setArea] = useState(""); + const areas = listAreas(facilities); + const inArea = area ? facilities.filter((f) => areaLabel(f) === area) : facilities; + const shown = inArea.slice(0, CARDS_SHOWN); + const hours = facilities[0]?.hours || "06:00–22:00"; return ( <> -
-
-
- HỆ THỐNG KHO BÃI TỰ ĐỘNG -

- Thêm không gian. -
- Thêm an tâm. -

-

Tìm kho vừa nhu cầu, đặt chỗ rõ ràng và quản lý không gian lưu trữ của bạn ở một nơi.

-
- Bắt đầu ngay - Tìm hiểu thêm -
+
+ {facilities[0] && } +
+ {facilities.length} cơ sở · TP. Hồ Chí Minh +

+ Kho riêng an toàn, +
+ gần nơi bạn cần. +

+

+ Chọn khu vực, chọn kho thường hoặc kho lạnh cỡ M hay L,{" "} +
+ xem ô còn trống và chi phí trước khi đặt. +

+ +
+
+ +
+
+

{facilities.length}cơ sở tại TP.HCM

+

{facilities.length * UNITS_PER_FACILITY}ô kho cỡ M và L

+

24/7camera giám sát

+

{hours}ra vào mỗi ngày

+
+
+ +
+
+
+ Loại kho +

Hai cỡ kho, thường hoặc lạnh

+

Mỗi cơ sở có 8 kho thường và 4 kho lạnh, chia đều cỡ M và L.

+
+
+ {KINDS.map(({ type, band, note }) => { + const size = SIZE_BANDS.find((b) => b.id === band); + const from = lowest(facilities, { type, band }); + return ( + + {type === "climate" ? "Kho lạnh" : "Kho thường"} +

{size.label}

+

{note}

+

+ Giá từ + {from != null ? `${money(from)} / tháng` : "Xem giá theo cơ sở"} +

+ Xem cơ sở còn trống → +
+ ); + })}
-
-
-
- {FEATURES.map(([icon, title, text], i) => ( -
- - - -

{title}

-

{text}

-
- ))} +
+
+
+ Cách đặt kho +

Đặt kho trong 3 bước

+
+
    + {STEPS.map(([title, text], i) => ( +
  1. + {i + 1} +

    {title}

    +

    {text}

    +
  2. + ))} +
-
-

Một không gian phù hợp, gần bạn

-

Xem hình ảnh cơ sở, diện tích và giá thuê trước khi đặt chỗ.

-
- {shown.map((f) => ( -
- -

{f.name}

-

{minRate(f) != null ? `Từ ${money(minRate(f))} / tháng` : "Liên hệ để nhận giá"}

-

{offerTypes(f).map(typeLabel).join(" · ") || "Kho thường"}

- Khám phá cơ sở -
- ))} +
+
+
+ Cơ sở +

Chọn khu vực, xem cơ sở gần đó

+
+
+ + {areas.map((a) => ( + + ))} +
+
+ {shown.map((f) => ( + + ))} +
+ + {area ? `Xem tất cả ${inArea.length} cơ sở tại ${districtOf(area)} →` : `Xem tất cả ${facilities.length} cơ sở →`} +
-
-
-

Sẵn sàng bắt đầu?

-

{authed ? "Chào mừng bạn quay lại SafeSpace." : "Khách hàng mới tạo tài khoản nhanh chóng chưa đầy 1 phút."}

-
- {authed ? ( - <> - Tìm kho mới - Xem tổng quan - - ) : ( - <> - Tạo tài khoản khách hàng - Đăng nhập - - )} +
+
+
+
+

{authed ? "Chào mừng bạn quay lại SafeSpace" : "Quản lý mọi kho thuê trong một tài khoản"}

+

Theo dõi đặt chỗ, hợp đồng, thanh toán, gia hạn và yêu cầu hỗ trợ.

+
+
+ {authed ? ( + <> + Xem tổng quan + Tìm kho mới + + ) : ( + <> + Tạo tài khoản + Đăng nhập + + )} +
+
+ + ); } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx index eb434c7..ceb4f20 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx @@ -8,16 +8,21 @@ export function Pricing() { const { data } = useApp(); return (
- -
+ +
{SIZE_BANDS.map((b) => { - const rates = data.facilities.map((f) => minRate(f, { band: b.id })).filter((x) => x != null); - const min = rates.length ? Math.min(...rates) : null; + const from = (type) => { + const rates = data.facilities.map((f) => minRate(f, { band: b.id, type })).filter((x) => x != null); + return rates.length ? Math.min(...rates) : null; + }; + const normal = from("normal"); + const cold = from("climate"); return (

{b.name}

- {b.label.replaceAll(" – ", "–")} -

{min == null || b.id === "L" ? "Xem giá theo cơ sở" : `Từ ${money(min)} / tháng`}

+ {b.short} +

{normal == null ? "Xem giá theo cơ sở" : `Từ ${money(normal)} / tháng`}

+ {cold != null &&

Kho lạnh từ {money(cold)} / tháng

}

{b.note}

Tìm kho phù hợp
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx index 9f07dae..fae43e6 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx @@ -441,7 +441,18 @@ function ApiProvider({ children }) { if (!r) return fail("Không tìm thấy đơn đặt chỗ.", "NOT_FOUND"); if (r.status === "CANCELLED") return fail("Đơn đặt chỗ đã hết thời gian giữ chỗ.", "EXPIRED"); if (r.status !== "PENDING_PAYMENT") return { ok: true, reservation_id: r.reservation_id }; - updateOverlay((o) => ({ ...o, transfers: { ...o.transfers, [r.api_id]: Date.now() } })); + try { + await api.confirmTransfer(r.api_id); + } catch (e) { + if (e instanceof ApiError && e.data?.code === "EXPIRED") { + await loadCustomer().catch(() => {}); + return fail(e.message, "EXPIRED"); + } + // Backend cũ chưa có confirm-transfer: ghi nhận tạm trên trình duyệt như trước + if (!(e instanceof ApiError && (e.status === 404 || e.status === 405))) throw e; + updateOverlay((o) => ({ ...o, transfers: { ...o.transfers, [r.api_id]: Date.now() } })); + } + await loadCustomer().catch(() => {}); remember("Đã nhận thông tin đặt chỗ", `${shortCode(r.reservation_id)} · Chờ nhân viên đối soát chuyển khoản.`, "reservations", `Đơn ${shortCode(r.reservation_id)} đã gửi — chờ đối soát thanh toán`); return { ok: true, reservation_id: r.reservation_id }; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/styles/ss.css b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/styles/ss.css index 1b0843e..6a449a3 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/styles/ss.css +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/styles/ss.css @@ -169,21 +169,6 @@ h4 { font-size: 16px; font-weight: 700; color: var(--ink); } .pagination p { font-size: 13px; color: var(--muted); } /* ---------- Home ---------- */ -.hero { background: var(--ink); color: #fff; } -.hero__inner { max-width: 1440px; margin: 0 auto; padding: 72px var(--pad-x); display: grid; grid-template-columns: 1fr 1.15fr; gap: 56px; align-items: center; } -.hero h1 { font-size: 46px; line-height: 1.12; font-weight: 800; margin: 18px 0 16px; color: #fff; } -.hero p { color: #cbd5e1; font-size: 17px; max-width: 460px; } -.hero__actions { display: flex; gap: 12px; margin-top: 28px; } -.hero__photo { border-radius: 16px; overflow: hidden; aspect-ratio: 16 / 10; } -.features { background: #eef1f8; padding: 44px 0; margin-bottom: 0; } -.features__grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; } -.feature { padding: 22px 24px; display: grid; gap: 8px; } -.feature__icon { width: 36px; height: 36px; border-radius: 10px; background: var(--soft); color: var(--blue); display: grid; place-items: center; } -.feature__icon--dark { background: var(--ink); color: #fff; } -.feature p { color: var(--muted); font-size: 14.5px; } -.home-list { padding-top: 56px; padding-bottom: 72px; } -.home-list h2 { font-size: 26px; font-weight: 800; } -.home-list .lead { margin: 8px 0 24px; font-size: 15px; } .facility-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; } .facility-card { padding: 12px 12px 20px; display: grid; gap: 6px; align-content: start; } .facility-card h3 { font-size: 19px; margin-top: 12px; } @@ -194,10 +179,6 @@ h4 { font-size: 16px; font-weight: 700; color: var(--ink); } .facility-card--compact .price { font-size: 14px; } .facility-card--compact .muted { font-size: 13px; } .facility-card .price { margin-top: 8px; } -.cta { background: var(--ink); color: #fff; text-align: center; padding: 56px 24px 64px; } -.cta h2 { color: #fff; font-size: 26px; font-weight: 800; } -.cta p { color: #cbd5e1; margin: 10px 0 22px; } -.cta__actions { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; } /* Photos */ .photo { position: relative; overflow: hidden; border-radius: 10px; background: #dbeafe; aspect-ratio: 16 / 10; } @@ -424,6 +405,7 @@ a.cell-strong:hover { color: var(--blue); } .usermenu__btn:hover { background: var(--soft); } .usermenu__btn strong { font-size: 15px; font-weight: 500; color: var(--text); } .usermenu__btn small { font-size: 12.5px; color: var(--red); font-weight: 600; } +.usermenu__facility { font-size: 12px; color: var(--muted); font-weight: 400; } .usermenu__pop { position: absolute; right: 0; top: calc(100% + 8px); background: #fff; border: 1px solid var(--line); border-radius: 12px; box-shadow: 0 14px 34px rgba(16, 21, 42, 0.15); padding: 12px; min-width: 220px; z-index: 55; display: grid; gap: 10px; } .usermenu__pop p { font-size: 14px; font-weight: 600; color: var(--ink); } .usermenu__pop p span { font-weight: 400; color: var(--muted); font-size: 13px; } @@ -468,6 +450,7 @@ a.cell-strong:hover { color: var(--blue); } .inline-form { flex-direction: column; align-items: stretch; } .admin-form { padding: 22px 18px; } .usermenu__btn strong { max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; } + .usermenu__facility { max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; } } /* ---------- Responsive ---------- */ @@ -524,10 +507,11 @@ a.cell-strong:hover { color: var(--blue); } .unit-dot--service, .unit-tile--service { background: #f9e9e5; } .unit-dot--free { border-color: var(--blue); } .unit-plan { background: #f7f9fc; border: 1px solid var(--line); border-radius: 10px; padding: 16px; display: grid; gap: 12px; } -.unit-row { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 16px; } -.unit-tile { border: 0; border-radius: 10px; min-height: 130px; padding: 12px 6px; display: grid; align-content: center; justify-items: center; gap: 6px; cursor: pointer; color: var(--text); font-size: 14px; box-shadow: inset 0 0 0 0 transparent; transition: transform 0.12s, box-shadow 0.12s; } +.unit-row { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 12px; } +.unit-tile { border: 0; border-radius: 10px; min-height: 130px; padding: 12px 4px; text-align: center; display: grid; align-content: center; justify-items: center; gap: 6px; cursor: pointer; color: var(--text); font-size: 14px; box-shadow: inset 0 0 0 0 transparent; transition: transform 0.12s, box-shadow 0.12s; } .unit-row--tall .unit-tile { min-height: 170px; } .unit-tile strong { font-size: 22px; font-weight: 700; } +.unit-tile span { font-size: 13px; white-space: nowrap; } .unit-tile--free { color: #fff; } .unit-tile:hover { transform: translateY(-2px); } .unit-tile.is-selected { box-shadow: inset 0 0 0 4px var(--soft), 0 0 0 2px var(--blue); } @@ -677,3 +661,93 @@ label.search-input input { border: 0; outline: 0; flex: 1; font-size: 14px; back .map-empty strong { font-size: 18px; color: var(--ink); } .map-empty span { color: var(--muted); } .ops-banner { max-width: 1440px; margin: 16px auto 0; padding: 10px var(--pad-x); background: var(--amber-bg); color: var(--amber); font-size: 14px; } + +/* ---------- Trang chủ (Figma START · Trang chủ, 14/10) ---------- */ +.home-hero { position: relative; overflow: hidden; background: var(--ink); color: #fff; } +.home-hero__bg { position: absolute; inset: 0; aspect-ratio: auto; border-radius: 0; z-index: 0; } +.home-hero::after { content: ""; position: absolute; inset: 0; z-index: 1; background: linear-gradient(90deg, rgba(16, 21, 42, 0.94) 0%, rgba(16, 21, 42, 0.72) 55%, rgba(16, 21, 42, 0.25) 100%); } +.home-hero__inner { position: relative; z-index: 2; max-width: 1440px; margin: 0 auto; padding: 104px var(--pad-x) 72px; display: grid; gap: 20px; justify-items: start; } +.home-hero__badge { border: 1px solid rgba(255, 255, 255, 0.3); background: rgba(255, 255, 255, 0.14); border-radius: 999px; padding: 6px 14px; font-size: 14px; font-weight: 600; letter-spacing: 0.04em; } +.home-hero h1 { font-size: 64px; line-height: 1.08; font-weight: 800; letter-spacing: -0.02em; color: #fff; } +.home-hero p { font-size: 19px; line-height: 1.5; color: rgba(255, 255, 255, 0.86); } +.home-search { margin-top: 36px; width: 100%; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)) auto; align-items: center; background: #fff; color: var(--text); border-radius: 20px; padding: 12px; box-shadow: 0 18px 48px rgba(10, 20, 51, 0.28); } +.home-search__field { display: grid; gap: 4px; padding: 8px 20px; border-right: 1px solid var(--line); } +.home-search__field:nth-child(3) { border-right: 0; } +.home-search__field > span { font-size: 12px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); } +.home-search__field select { border: 0; background-color: transparent; padding-left: 0; font-size: 17px; font-weight: 600; color: var(--text); } +.home-search__submit { padding: 18px 28px; border-radius: 14px; font-size: 16px; } +.home-stats { background: var(--white); border-bottom: 1px solid var(--line); } +.home-stats__grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); padding-top: 32px; padding-bottom: 32px; } +.home-stats__grid p { display: grid; gap: 2px; padding-left: 28px; border-left: 1px solid var(--line); } +.home-stats__grid p:first-child { padding-left: 0; border-left: 0; } +.home-stats__grid strong { font-size: 30px; font-weight: 800; color: var(--ink); line-height: 1.2; } +.home-stats__grid span { color: var(--muted); font-size: 15px; } +.home-section { background: var(--white); padding: 88px 0; } +.home-section--tint { background: var(--bg); } +.home-head { display: grid; gap: 8px; margin-bottom: 36px; } +.home-head h2 { font-size: 36px; font-weight: 800; letter-spacing: -0.01em; color: var(--text); } +.home-head p { color: var(--muted); font-size: 17px; } +.home-eyebrow { font-size: 13px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--blue); } +.home-link { color: var(--blue); font-weight: 600; font-size: 15px; } +.home-kinds { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 24px; } +.home-kind { background: var(--white); border: 1px solid var(--line); border-radius: 20px; padding: 24px; display: grid; gap: 12px; align-content: start; color: var(--text); transition: transform 0.15s, box-shadow 0.15s; } +.home-kind:hover, .home-facility:hover { transform: translateY(-3px); box-shadow: 0 14px 30px rgba(16, 21, 42, 0.1); } +.home-kind__tag { justify-self: start; background: var(--soft); color: var(--blue); border-radius: 999px; padding: 4px 10px; font-size: 13px; font-weight: 600; } +.home-kind__tag--cold { background: #e0f2fe; color: #0369a1; } +.home-kind h3 { font-size: 24px; font-weight: 800; } +.home-kind__note { color: var(--muted); font-size: 15px; min-height: 45px; } +.home-kind__price { display: grid; border-top: 1px solid var(--line); padding-top: 14px; } +.home-kind__price small, .home-facility__foot small { color: var(--muted); font-size: 13px; } +.home-kind__price strong { font-size: 20px; font-weight: 700; color: var(--ink); } +.home-steps { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 24px; } +.home-steps li { border: 1px solid var(--line); border-radius: 20px; padding: 28px; display: grid; gap: 12px; align-content: start; } +.home-steps__num { width: 44px; height: 44px; border-radius: 999px; background: var(--blue); color: #fff; display: grid; place-items: center; font-weight: 800; font-size: 18px; } +.home-steps h3 { font-size: 21px; font-weight: 800; } +.home-steps p { color: var(--muted); font-size: 15px; } +.home-chips { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 28px; } +.home-chip { border: 1px solid var(--line); background: var(--white); border-radius: 999px; padding: 9px 16px; font-size: 15px; font-weight: 500; cursor: pointer; color: var(--text); } +.home-chip span { color: var(--muted); margin-left: 4px; } +.home-chip.is-on { background: var(--ink); border-color: var(--ink); color: #fff; font-weight: 600; } +.home-chip.is-on span { color: rgba(255, 255, 255, 0.7); } +.home-facilities { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 24px; } +.home-facility { background: var(--white); border: 1px solid var(--line); border-radius: 20px; overflow: hidden; display: grid; color: var(--text); transition: transform 0.15s, box-shadow 0.15s; } +.home-facility .photo { border-radius: 0; aspect-ratio: 16 / 9.2; } +.home-facility__body { padding: 20px 24px 24px; display: grid; gap: 10px; } +.home-facility h3 { font-size: 21px; font-weight: 800; } +.home-tags { display: flex; flex-wrap: wrap; gap: 8px; } +.home-tags li { background: var(--bg); color: var(--muted); border-radius: 999px; padding: 3px 10px; font-size: 13px; font-weight: 500; } +.home-facility__foot { display: flex; justify-content: space-between; align-items: flex-end; padding-top: 6px; } +.home-facility__foot p { display: grid; } +.home-facility__foot strong { font-size: 18px; font-weight: 700; color: var(--ink); } +.home-more { margin-top: 28px; } +.home-cta { background: var(--ink); color: #fff; border-radius: 28px; padding: 56px; display: flex; justify-content: space-between; align-items: center; gap: 32px; } +.home-cta h2 { color: #fff; font-size: 32px; font-weight: 800; } +.home-cta p { color: rgba(255, 255, 255, 0.78); margin-top: 10px; font-size: 17px; } +.home-cta__actions { display: flex; gap: 12px; flex-shrink: 0; } +.home-footer { background: var(--white); border-top: 1px solid var(--line); padding: 56px 0 40px; } +.home-footer__cols { display: grid; grid-template-columns: 2fr 1fr 1fr 1.2fr; gap: 48px; } +.home-footer__cols > * { display: grid; gap: 10px; align-content: start; } +.home-footer__cols strong { font-size: 15px; color: var(--text); } +.home-footer__brand { font-size: 24px !important; font-weight: 800; color: var(--blue) !important; } +.home-footer__cols p, .home-footer__cols a { color: var(--muted); font-size: 15px; } +.home-footer__cols a:hover { color: var(--blue); } +.home-footer__copy { color: var(--muted); font-size: 13px; margin-top: 40px; } +@media (max-width: 1100px) { + .home-hero__inner { padding-top: 80px; padding-bottom: 56px; } + .home-kinds { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .home-facilities { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .home-search { grid-template-columns: 1fr; gap: 4px; } + .home-search__field { border-right: 0; border-bottom: 1px solid var(--line); padding: 10px 12px; } + .home-search__submit { margin-top: 8px; } +} +@media (max-width: 720px) { + .home-hero h1 { font-size: 36px; } + .home-hero p br { display: none; } + .home-stats__grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; } + .home-stats__grid p:nth-child(3) { padding-left: 0; border-left: 0; } + .home-section { padding: 56px 0; } + .home-head h2 { font-size: 28px; } + .home-kinds, .home-steps, .home-facilities, .home-footer__cols { grid-template-columns: 1fr; } + .home-cta { flex-direction: column; align-items: flex-start; padding: 36px 24px; } + .home-cta h2 { font-size: 26px; } +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js index 18fac75..218f384 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js @@ -58,8 +58,8 @@ test("danh mục: cơ sở, quận / thành phố, giờ mở cửa và gói kho assert.equal(tb.city, "TP. Hồ Chí Minh"); assert.equal(tb.hours, "07:00–22:00"); assert.deepEqual(tb.offers.map((o) => [o.unit_type_id, o.type, o.band, o.monthly_rate]), [ - [1, "normal", "S", 500000], - [2, "climate", "S", 1500000], + [1, "normal", "M", 500000], + [2, "climate", "M", 1500000], [3, "climate", "M", 3000000], ]); assert.equal(tb.offers[1].size_label, "4 m²"); @@ -121,3 +121,12 @@ test("tên đăng nhập backend sinh từ email (≤ 50 ký tự)", () => { assert.equal(usernameFromEmail(" Mai.Tran@Example.com "), "mai.tran@example.com"); assert.ok(usernameFromEmail(`${"a".repeat(60)}@example.com`).length <= 50); }); + +test("backend trả PENDING_VERIFICATION (confirm-transfer) → chờ đối soát, không bị huỷ theo giờ giữ chỗ trong trình duyệt", () => { + const verifying = { ...remote, reservations: remote.reservations.map((r) => (r.reservationId === 2 ? { ...r, status: "PENDING_VERIFICATION" } : r)) }; + const hold = { holds: { 2: NOW.getTime() - 10000 } }; + const later = new Date(NOW.getTime() + 55000); + const d = composeData({ catalog, remote: verifying, overlay: hold, session, timeoutSeconds: 60, now: later }); + assert.equal(d.reservations[1].status, "PENDING_VERIFICATION"); + assert.equal(reservationsToExpire({ remote: verifying, overlay: { holds: hold.holds, transfers: {} }, timeoutSeconds: 60, now: later }).length, 0); +}); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops-api.test.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops-api.test.mjs index e4cd0df..e23a4e2 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops-api.test.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops-api.test.mjs @@ -59,7 +59,7 @@ test("khu vận hành qua API: nhân viên xử lý, quản lý phân bổ / duy board = fromApi((await call("GET", "/api/ops/board", undefined, manager)).data); assert.equal(board.units.find((u) => u.code === unit.code).status, "WAITING_HANDOVER"); - assert.equal(board.units.find((u) => u.code === "A-102").status, "ACTIVE"); + assert.equal(board.units.find((u) => u.code === "K01").status, "ACTIVE"); assert.equal(board.contracts.find((c) => c.id === "HĐ-0098").state, "CLOSED"); assert.ok(board.revenue.by_type.length === 2, "báo cáo có cơ cấu theo loại kho"); } finally { @@ -78,3 +78,25 @@ test("backend chưa bật ops → GET /api/ops/board trả 404 (giao diện chuy server.close(); } }); + +test("khách báo đã chuyển khoản qua API → PENDING_VERIFICATION, gọi lại vẫn an toàn; đơn không còn chờ thì báo lỗi", async () => { + const { server } = await startMockApi(PORT + 2); + try { + const url = `http://localhost:${PORT + 2}`; + const post = async (path, token) => { + const res = await fetch(url + path, { method: "POST", headers: { Authorization: `Bearer ${token}` } }); + return { status: res.status, data: await res.json() }; + }; + const { token } = await (await fetch(`${url}/api/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: "customer01", password: "Customer@123" }) })).json(); + let out = await post("/api/reservations/2/confirm-transfer", token); + assert.equal(out.status, 200); + assert.equal(out.data.status, "PENDING_VERIFICATION"); + out = await post("/api/reservations/2/confirm-transfer", token); + assert.equal(out.status, 200, "bấm hai lần không lỗi"); + out = await post("/api/reservations/1/confirm-transfer", token); + assert.equal(out.status, 400, "đơn đã nhận kho không còn chờ chuyển khoản"); + assert.equal((await post("/api/reservations/999/confirm-transfer", token)).status, 404); + } finally { + server.close(); + } +}); 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 ae0418d..9d51f96 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/ops.test.js @@ -7,10 +7,14 @@ import { candidateUnits, reduceOps } from "../src/ops/reducer.js"; const T = "2026-09-14"; const run = (s, type, payload) => reduceOps(s, { type, payload }, new Date(`${T}T10:00:00`)); -test("dữ liệu khởi tạo: 86 kho, 3 khoản chờ đối soát, 3 khách cần xác minh", () => { +test("dữ liệu khởi tạo: 12 ô theo D17, 3 khoản chờ đối soát, 3 khách cần xác minh", () => { const s = createOpsData(T); - assert.equal(s.units.length, 86); - assert.equal(new Set(s.units.map((u) => u.code)).size, 86); + assert.equal(s.units.length, 12); + assert.deepEqual(s.units.map((u) => u.code), ["K01", "K02", "K03", "K04", "K05", "K06", "K07", "K08", "K09", "K10", "K11", "K12"]); + assert.deepEqual(s.units.map((u) => `${u.type}:${u.area}`).join(" "), "normal:15 normal:15 normal:15 normal:15 climate:15 climate:15 normal:30 normal:30 normal:30 normal:30 climate:30 climate:30"); + // Mọi ô được nhắc tới trong việc vận hành đều có thật trong sơ đồ + const codes = new Set(s.units.map((u) => u.code)); + for (const x of [...s.verifications, ...s.handovers, ...s.returns, ...s.tickets, ...s.renewals, ...s.contracts]) assert.ok(codes.has(x.unit), x.id); assert.equal(s.payments.filter((p) => p.status === "PENDING").length, 3); assert.equal(s.verifications.filter((v) => v.status === "TODO").length, 3); assert.equal(s.revenue.months.at(-1).label, "Tháng 9"); @@ -23,7 +27,7 @@ test("đối soát đơn chưa có kho → chuyển quản lý phân bổ, rồi s = out.state; const a = s.allocations.find((x) => x.id === "SS-20260913-0147"); assert.equal(a.type, "climate"); - assert.deepEqual([a.min_area, a.max_area], [2, 5]); + assert.deepEqual([a.min_area, a.max_area], [15, 15]); const unit = candidateUnits(s, a)[0]; assert.ok(unit); out = run(s, "ALLOCATE", { id: a.id, unit: unit.code }); @@ -40,7 +44,7 @@ test("không bàn giao khi chưa xác minh; xác minh rồi bàn giao thì kho h s = run(s, "VERIFY_CUSTOMER", { id: "XM-0142", doc_type: "CCCD", doc_no: "079123456789", photo_ok: true, info_ok: true }).state; assert.equal(s.verifications.find((v) => v.id === "XM-0142").doc_last4, "6789"); s = run(s, "HANDOVER", { id: "BG-0142", method: "PIN" }).state; - assert.equal(s.units.find((u) => u.code === "A-102").status, "ACTIVE"); + assert.equal(s.units.find((u) => u.code === "K01").status, "ACTIVE"); }); test("trả kho → quản lý xác nhận hoàn cọc = cọc − khoản nợ, kho trống lại", () => { @@ -49,7 +53,7 @@ test("trả kho → quản lý xác nhận hoàn cọc = cọc − khoản nợ, assert.equal(s.contracts.find((c) => c.id === "HĐ-0098").state, "RETURNED"); const out = run(s, "CONFIRM_REFUND", { id: "HĐ-0098" }); assert.equal(out.result.refund, 1150000 - 460000); - assert.equal(out.state.units.find((u) => u.code === "C-012").status, "EMPTY"); + assert.equal(out.state.units.find((u) => u.code === "K04").status, "EMPTY"); }); test("duyệt / từ chối gia hạn; từ chối bắt buộc có lý do", () => { @@ -59,7 +63,7 @@ test("duyệt / từ chối gia hạn; từ chối bắt buộc có lý do", () assert.equal(s.contracts.find((c) => c.id === "HĐ-0077").state, "RESOLVED"); s = run(s, "DECIDE_RENEWAL", { id: "GH-0208", approve: true }).state; const r = s.renewals.find((x) => x.id === "GH-0208"); - assert.equal(s.units.find((u) => u.code === "C-208").end, r.to); + assert.equal(s.units.find((u) => u.code === "K02").end, r.to); }); test("phân công việc hỗ trợ cho nhân viên → yêu cầu chuyển sang đang xử lý", () => { 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 866afad..1ad6ab1 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js @@ -44,8 +44,11 @@ test("đặt chỗ: kiểm tra đầu vào", () => { const s = createSeedData(T); assert.match(book(s, { start_date: "2026-09-20" }).error.message, /quá khứ/); assert.match(book(s, { months: 2 }).error.message, /1, 3 hoặc 6/); - assert.match(book(s, { facility_id: 8, type: "climate" }).error.message, /chưa có loại kho/); + // Figma 14/10: cơ sở nào cũng có kho lạnh → giả lập một cơ sở thiếu loại kho để kiểm tra thông báo + const noCold = { ...s, facilities: s.facilities.map((f) => (f.facility_id === 8 ? { ...f, has_climate: false, offers: f.offers.filter((o) => o.type !== "climate") } : f)) }; + assert.match(book(noCold, { facility_id: 8, type: "climate" }).error.message, /chưa có loại kho/); assert.match(book(s, { band: "X" }).error.message, /diện tích/); + assert.match(book(s, { band: "S" }).error.message, /diện tích/); // cỡ S đã bỏ, chỉ còn M và L }); test("chuyển khoản trong hạn: chờ đối soát, sinh 2 khoản thu, thông báo", () => { @@ -84,7 +87,7 @@ test("gia hạn: chỉ 1 yêu cầu chờ duyệt, chặn trả kho song song, h assert.equal(a.state.renewals[0].status, "PENDING"); assert.equal(a.state.renewals[0].new_end, addMonths(s.contracts[1].end_date, 3)); assert.equal(a.state.ledger.at(-1).status, "RENEWAL_PENDING"); - assert.equal(a.state.ledger.at(-1).amount, 3 * 500000); + assert.equal(a.state.ledger.at(-1).amount, 3 * 1380000); // B-015: kho lạnh cỡ M tại Nguyễn Lương Bằng assert.match(run(a.state, "REQUEST_RENEWAL", { contract_id: "HĐ-2026-0086", months: 1 }).error.message, /đang chờ/); assert.match(run(a.state, "REQUEST_RETURN", { contract_id: "HĐ-2026-0086", date: T, slot: "09:00–09:30" }).error.message, /gia hạn/); assert.match(run(s, "REQUEST_RENEWAL", { contract_id: "HĐ-2026-0086", months: 2 }).error.message, /1, 3 hoặc 6/); @@ -138,12 +141,12 @@ test("nhân viên đối soát: tạo hợp đồng + lịch nhận kho, khoản assert.deepEqual(mine, ["DEPOSIT_HELD", "RECONCILED"]); }); -test("tìm cơ sở: lọc khu vực Quận 7 → 3 cơ sở; kho lạnh loại bỏ cơ sở không có; sắp xếp giá", () => { +test("tìm cơ sở: lọc khu vực Quận 7 → 5 cơ sở; cả 12 cơ sở có kho lạnh; sắp xếp giá", () => { const s = createSeedData(T); const q7 = searchFacilities(s.facilities, { area: "Quận 7, TP. Hồ Chí Minh" }); - assert.deepEqual(q7.map((f) => f.facility_id), [1, 2, 3]); + assert.deepEqual(q7.map((f) => f.facility_id), [1, 2, 3, 4, 5]); const cold = searchFacilities(s.facilities, { type: "climate" }); - assert.ok(cold.every((f) => f.has_climate) && cold.length === 9); + assert.ok(cold.every((f) => f.has_climate) && cold.length === 12); const cheap = searchFacilities(s.facilities, { sort: "price" }); assert.equal(cheap[0].facility_id, 8); // Bình Chánh 790.000 assert.equal(rateFor(s.facilities[0], "normal", "M"), 1150000); 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 072583d..c5c7945 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/render.test.mjs @@ -20,7 +20,7 @@ try { const { OPS_ACCOUNTS } = await vite.ssrLoadModule("/src/ops/data.js"); const seed = (authed, opsUser = null) => memory.set(STORAGE_KEY, JSON.stringify({ version: 5, authed, data: createSeedData(), opsUser })); - const publicRoutes = ["home", "login", "register", "pricing", "guide", "find", "find?type=climate&band=S", "find/map", "find/map?type=climate", "find/map?area=Kh%C3%B4ng%20c%C3%B3", "find/1", "find/1?view=map&unit=K02", "find/8?type=climate&view=map", "find/999", "nope"]; + const publicRoutes = ["home", "login", "register", "pricing", "guide", "find", "find?type=climate&band=M", "find/map", "find/map?type=climate", "find/map?area=Kh%C3%B4ng%20c%C3%B3", "find/1", "find/1?view=map&unit=K02", "find/8?type=climate&view=map", "find/999", "nope"]; const privateRoutes = [ "overview", "units", "units/HĐ-2026-0142", "units/HĐ-2026-0086/renew", "units/HĐ-2026-0142/return", "units/unknown", "sent?type=renew&contract=HĐ-2026-0086", "reservations", "reservations/SS-20260914-0142", "reservations/none", diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/units.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/units.test.js index a7e4a36..6852081 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/units.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/units.test.js @@ -1,38 +1,57 @@ -// Sơ đồ tình trạng ô kho (src/lib/units.js) +// Sơ đồ tình trạng ô kho (src/lib/units.js) — Figma 14/10: 12 ô mỗi cơ sở import test from "node:test"; import assert from "node:assert/strict"; import { createFacilities } from "../src/data/seed.js"; import { countBy, unitsFor } from "../src/lib/units.js"; -test("mỗi cơ sở có 10 ô, giá khớp gói kho, cơ sở đầu theo đúng Figma", () => { +const kinds = (units) => units.map((u) => `${u.row}:${u.type}`); + +test("mỗi cơ sở có 12 ô: dãy A cỡ M (4 thường + 2 lạnh), dãy B cỡ L (4 thường + 2 lạnh), giá khớp gói kho", () => { const facilities = createFacilities(); for (const f of facilities) { const units = unitsFor(f); - assert.equal(units.length, 10); + assert.equal(units.length, 12); + assert.deepEqual(kinds(units), [ + "A:normal", "A:normal", "A:normal", "A:normal", "A:climate", "A:climate", + "B:normal", "B:normal", "B:normal", "B:normal", "B:climate", "B:climate", + ]); + assert.ok(units.filter((u) => u.row === "A").every((u) => u.area === 15)); + assert.ok(units.filter((u) => u.row === "B").every((u) => u.area === 30)); for (const u of units) assert.equal(u.monthly_rate, f.offers.find((o) => o.key === u.offer_key).monthly_rate); - if (!f.has_climate) assert.ok(units.every((u) => u.type === "normal")); } const nlb = unitsFor(facilities[0]); - assert.deepEqual(countBy(nlb), { FREE: 5, RENTED: 3, HELD: 1, SERVICE: 1 }); + assert.deepEqual(countBy(nlb), { FREE: 6, RENTED: 4, HELD: 1, SERVICE: 1 }); assert.equal(nlb.find((u) => u.code === "K02").status, "RENTED"); + assert.equal(nlb.find((u) => u.code === "K12").position, "Tầng trệt · Dãy B"); }); -test("dữ liệu backend: ô kho lấy loại kho từ bảng giá, số ô trống khớp /api/availability/check", async () => { +test("dữ liệu backend: ô kho lấy đúng loại + cỡ từ bảng giá, số ô trống khớp /api/availability/check", async () => { const { mapCatalog } = await import("../src/api/mappers.js"); const unitTypes = [ - { unitTypeId: 1, typeName: "Kho Mini S", area: 1, climateControlled: false, status: "ACTIVE" }, - { unitTypeId: 2, typeName: "Kho M", area: 4, climateControlled: true, status: "ACTIVE" }, - { unitTypeId: 3, typeName: "Kho L", area: 9, climateControlled: true, status: "ACTIVE" }, + { unitTypeId: 1, typeName: "Kho thường M", area: 15, climateControlled: false, status: "ACTIVE" }, + { unitTypeId: 2, typeName: "Kho thường L", area: 30, climateControlled: false, status: "ACTIVE" }, + { unitTypeId: 3, typeName: "Kho lạnh M", area: 15, climateControlled: true, status: "ACTIVE" }, + { unitTypeId: 4, typeName: "Kho lạnh L", area: 30, climateControlled: true, status: "ACTIVE" }, ]; - const rates = [1, 2, 3].map((id) => ({ facilityId: 7, unitTypeId: id, monthlyRate: id * 500000 })); + const rates = [1, 2, 3, 4].map((id) => ({ facilityId: 7, unitTypeId: id, monthlyRate: id * 500000 })); const { facilities } = mapCatalog({ facilities: [{ facilityId: 7, name: "SafeSpace Nhà Bè", address: "Nhà Bè, TP. Hồ Chí Minh", status: "ACTIVE" }], unitTypes, rates }); const f = facilities[0]; - const units = unitsFor(f, { "ut-1": 2, "ut-2": 0, "ut-3": 1 }); - assert.equal(units.length, 10); - assert.ok(units.every((u) => f.offers.some((o) => o.key === u.offer_key)), "mỗi ô gắn với một loại kho thật"); + const units = unitsFor(f, { "ut-1": 2, "ut-2": 0, "ut-3": 1, "ut-4": 2 }); + assert.equal(units.length, 12); + assert.deepEqual(units.map((u) => u.offer_key), ["ut-1", "ut-1", "ut-1", "ut-1", "ut-3", "ut-3", "ut-2", "ut-2", "ut-2", "ut-2", "ut-4", "ut-4"]); const free = (key) => units.filter((u) => u.offer_key === key && u.status === "FREE").length; assert.equal(free("ut-1"), 2); assert.equal(free("ut-2"), 0); assert.equal(free("ut-3"), 1); - assert.equal(units.find((u) => u.offer_key === "ut-1").area_label, "1 m²"); + assert.equal(free("ut-4"), 2); + assert.equal(units.find((u) => u.offer_key === "ut-2").area_label, "30 m²"); +}); + +test("dữ liệu backend thiếu loại kho: ô vẫn gắn với một gói có thật", async () => { + const { mapCatalog } = await import("../src/api/mappers.js"); + const unitTypes = [{ unitTypeId: 9, typeName: "Kho thường M", area: 15, climateControlled: false, status: "ACTIVE" }]; + const { facilities } = mapCatalog({ facilities: [{ facilityId: 3, name: "SafeSpace Phú Xuân", address: "Quận 7, TP. Hồ Chí Minh", status: "ACTIVE" }], unitTypes, rates: [{ facilityId: 3, unitTypeId: 9, monthlyRate: 890000 }] }); + const units = unitsFor(facilities[0]); + assert.equal(units.length, 12); + assert.ok(units.every((u) => u.offer_key === "ut-9" && u.monthly_rate === 890000)); }); diff --git a/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs new file mode 100644 index 0000000..979eb0e --- /dev/null +++ b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs @@ -0,0 +1,129 @@ +using System.Security.Claims; +using StorageProject.Api.Extensions; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Interfaces; + +namespace StorageProject.Api.Endpoints; + +/// +/// Khu Nhân viên cơ sở (Figma S01–S09) và Quản lý cơ sở (M01–M08) — BACKEND-TODO.md mục A2, A3. +/// Role STAFF hoặc MANAGER; thao tác của quản lý trả 403 với nhân viên. Chỉ dữ liệu cơ sở được phân công (SRS A06). +/// Lỗi: 400 { error } · 403 { error } · 404 { error }. +/// +public static class FacilityOpsEndpoints +{ + public static void MapFacilityOpsEndpoints(this IEndpointRouteBuilder routes) + { + var group = routes.MapGroup("/api/ops") + .WithTags("Facility Operations") + .RequireAuthorization(policy => policy.RequireRole("STAFF", "MANAGER")); + + group.MapGet("/board", (ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => Results.Ok(ToJson(await ops.GetBoardAsync(Actor(user), ct))))) + .WithSummary("Dữ liệu vận hành của cơ sở được phân công (nhân viên: S01–S09; quản lý: thêm M01–M08)"); + + // ---- Nhân viên (quản lý cũng làm được) + group.MapPost("/payments/{id}/confirm", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.ConfirmPaymentAsync(Actor(user), id, ct); return Done(); })) + .WithSummary("S09 · Xác nhận đã thu: đơn PENDING_VERIFICATION → CONFIRMED, chuyển quản lý phân bổ ô"); + + group.MapPost("/payments/{id}/mismatch", (string id, OpsNoteRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.ReportMismatchAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S09 · Báo sai lệch chuyển khoản (note bắt buộc)"); + + group.MapPost("/verifications/{id}", (string id, OpsVerifyRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.VerifyCustomerAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S02 · Xác minh khách nhận kho; chỉ lưu 4 số cuối giấy tờ"); + + group.MapPost("/handovers/{id}/complete", (string id, OpsHandoverRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.CompleteHandoverAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S03 · Bàn giao kho (CARD / PIN / FINGER): hợp đồng ACTIVE, ô OCCUPIED, cấp phương thức mở khoá"); + + group.MapPost("/returns/{id}/inspection", (string id, OpsReturnInspectionRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.SubmitReturnInspectionAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S04 · Biên bản kiểm tra trả kho; ô → INSPECTION, chờ quản lý hoàn cọc"); + + group.MapPost("/tickets/{id}/responses", (string id, OpsTicketResponseRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.RespondTicketAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("S05 · Phản hồi yêu cầu hỗ trợ: IN_PROGRESS / WAITING_CUSTOMER / DONE"); + + // ---- Chỉ quản lý cơ sở + group.MapPost("/allocations/{id}", (string id, OpsAllocateRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.AllocateAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("M05 · Phân bổ ô trống đúng loại cho đơn đã đối soát → hợp đồng nháp + lịch bàn giao"); + + group.MapPut("/assignments/{id}", (string id, OpsAssignRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.AssignAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("M06 · Giao việc bàn giao / trả kho / hỗ trợ cho nhân viên cùng cơ sở"); + + group.MapPost("/renewals/{id}/approve", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.ApproveRenewalAsync(Actor(user), id, ct); return Done(); })) + .WithSummary("M03 · Duyệt gia hạn: cập nhật ngày hết hạn, tạo khoản gia hạn chờ thanh toán"); + + group.MapPost("/renewals/{id}/reject", (string id, OpsRejectRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.RejectRenewalAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("M03 · Từ chối gia hạn (reason bắt buộc)"); + + group.MapPost("/contracts/{id}/reminders", (string id, OpsNoteRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => { await ops.RemindAsync(Actor(user), id, request, ct); return Done(); })) + .WithSummary("M07 · Ghi lần nhắc khách (quá hạn / còn nợ)"); + + group.MapPost("/contracts/{id}/refund", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => + { + var refund = await ops.ConfirmRefundAsync(Actor(user), id, ct); + return Results.Ok(new { message = "Đã cập nhật.", refund }); + })) + .WithSummary("M07 · Xác nhận hoàn cọc sau biên bản trả kho: cọc − khoản còn nợ, đóng hợp đồng, ô trống lại"); + } + + private static OpsActor Actor(ClaimsPrincipal user) => new(user.GetUserId(), user.IsInRole("MANAGER")); + + private static IResult Done() => Results.Ok(new { message = "Đã cập nhật." }); + + /// + /// Nhân viên không nhận các phần của quản lý — bỏ hẳn khoá thay vì trả null, + /// vì giao diện gộp kết quả vào giá trị mặc định (src/ops/api.js loadBoard). + /// + private static Dictionary ToJson(OpsBoardDto b) + { + var json = new Dictionary + { + ["facility"] = b.Facility, + ["me"] = b.Me, + ["staff"] = b.Staff, + ["units"] = b.Units, + ["payments"] = b.Payments, + ["verifications"] = b.Verifications, + ["handovers"] = b.Handovers, + ["returns"] = b.Returns, + ["tickets"] = b.Tickets, + }; + if (b.Allocations != null) json["allocations"] = b.Allocations; + if (b.Renewals != null) json["renewals"] = b.Renewals; + if (b.Contracts != null) json["contracts"] = b.Contracts; + if (b.Assignments != null) json["assignments"] = b.Assignments; + if (b.Revenue != null) json["revenue"] = b.Revenue; + return json; + } + + private static async Task Run(Func> action) + { + try + { + return await action(); + } + catch (UnauthorizedAccessException ex) + { + return Results.Json(new { error = ex.Message }, statusCode: StatusCodes.Status403Forbidden); + } + catch (KeyNotFoundException ex) + { + return Results.NotFound(new { error = ex.Message }); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + return Results.BadRequest(new { error = ex.Message }); + } + } +} diff --git a/StorageProject.Api/Endpoints/ReservationEndpoints.cs b/StorageProject.Api/Endpoints/ReservationEndpoints.cs index 4a57382..696c95b 100644 --- a/StorageProject.Api/Endpoints/ReservationEndpoints.cs +++ b/StorageProject.Api/Endpoints/ReservationEndpoints.cs @@ -1,6 +1,7 @@ using System.Security.Claims; using StorageProject.Api.Extensions; using StorageProject.Core.DTOs.Reservation; +using StorageProject.Core.Exceptions; using StorageProject.Core.Interfaces; namespace StorageProject.Api.Endpoints; @@ -57,6 +58,29 @@ public static RouteGroupBuilder MapReservationEndpoints(this IEndpointRouteBuild } }); + // C04 / F03: khách báo đã chuyển khoản → PENDING_VERIFICATION (nhân viên đối soát ở S09) + group.MapPost("/{id:long}/confirm-transfer", async (long id, ClaimsPrincipal user, IReservationService reservationService, CancellationToken ct) => + { + try + { + var reservation = await reservationService.ConfirmTransferAsync(user.GetUserId(), id, ct); + return Results.Ok(reservation); + } + catch (KeyNotFoundException ex) + { + return Results.NotFound(new { error = ex.Message }); + } + catch (ReservationExpiredException ex) + { + return Results.BadRequest(new { error = ex.Message, code = "EXPIRED" }); + } + catch (InvalidOperationException ex) + { + return Results.BadRequest(new { error = ex.Message }); + } + }) + .WithSummary("Khách báo đã chuyển khoản: đơn chuyển sang chờ nhân viên đối soát (PENDING_VERIFICATION)"); + return group; } } diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs index eaa3f52..75acbe2 100644 --- a/StorageProject.Api/Program.cs +++ b/StorageProject.Api/Program.cs @@ -90,6 +90,7 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); var app = builder.Build(); @@ -120,6 +121,7 @@ app.MapSupportTicketEndpoints(); app.MapAdminEndpoints(); app.MapOperationsEndpoints(); +app.MapFacilityOpsEndpoints(); // Root status check app.MapGet("/health", () => Results.Ok(new diff --git a/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs b/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs new file mode 100644 index 0000000..0ce72e3 --- /dev/null +++ b/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs @@ -0,0 +1,88 @@ +namespace StorageProject.Core.DTOs.FacilityOps; + +// Khu Nhân viên cơ sở (Figma S01–S09) và Quản lý cơ sở (M01–M08) — GET /api/ops/board và các thao tác. +// Hình dạng JSON khớp src/ops/api.js + mẫu trong BACKEND-TODO.md (camelCase, id dạng chuỗi). +// Ngày "yyyy-MM-dd"; ngày giờ là giờ Việt Nam dạng "yyyy-MM-ddTHH:mm:ss" (giao diện hiển thị nguyên giờ). + +/// Người đang gọi API: STAFF hoặc MANAGER (quản lý làm được mọi việc của nhân viên). +public record OpsActor(long UserId, bool IsManager); + +public record OpsFacilityInfoDto(long FacilityId, string Name, string Address); + +public record OpsStaffDto(string StaffId, string FullName, string Shift); + +public record OpsUnitDto(string Code, string? Tenant, decimal Area, string Floor, string Type, string Status, DateOnly? End); + +public record OpsPaymentDto( + string Id, string Customer, decimal Amount, string Method, string ReportedAt, string Memo, string Offer, + DateOnly Start, DateOnly End, string Pickup, string Status, string? Note, string? HandledAt); + +public record OpsAllocationDto( + string Id, string Customer, string Type, string Offer, decimal MinArea, decimal MaxArea, + DateOnly Start, DateOnly End, string Pickup, string Status, string? Unit); + +public record OpsVerificationDto( + string Id, string ReservationId, string Customer, string Unit, string Appointment, string Status, + string? DocType, string? DocLast4, string? VerifiedAt); + +public record OpsHandoverDto(string Id, string VerificationId, string Unit, string Customer, string Status, string? Method, string? DoneAt); + +public record OpsReturnReportDto(string Items, string Walls, string Keys, string Proposal); + +public record OpsReturnDto( + string Id, string Contract, string Unit, string Customer, string Appointment, decimal Deposit, decimal Unpaid, + string Status, OpsReturnReportDto? Report, string? SubmittedAt); + +public record OpsNoteDto(string Text, string At, string? Staff); + +public record OpsTicketDto( + string Id, string Unit, string Customer, string Title, string CreatedAt, string Schedule, string Status, + string? Assignee, IReadOnlyList Notes); + +public record OpsRenewalDto( + string Id, string Contract, string Customer, string Unit, DateOnly From, DateOnly To, int Months, + string Requested, string Status, string? Reason, string? DecidedAt); + +public record OpsReminderDto(string Text, string At); + +public record OpsContractDto( + string Id, string Customer, string Unit, DateOnly End, string Due, decimal Amount, string State, + IReadOnlyList Reminders); + +public record OpsAssignmentDto(string Id, string Title, string When, string? Staff, string Status, string Ref); + +public record OpsRevenueMonthDto(string Label, int Month, int Year, decimal Value); + +public record OpsRevenueTypeDto(string Label, decimal Value); + +public record OpsRevenueDto(IReadOnlyList Months, IReadOnlyList ByType, DateOnly AsOf); + +/// +/// Dữ liệu vận hành của cơ sở được phân công. Nhân viên chỉ nhận phần S01–S09; +/// các phần của quản lý (allocations … revenue) để null và không được trả về. +/// +public record OpsBoardDto( + OpsFacilityInfoDto Facility, + OpsStaffDto? Me, + IReadOnlyList Staff, + IReadOnlyList Units, + IReadOnlyList Payments, + IReadOnlyList Verifications, + IReadOnlyList Handovers, + IReadOnlyList Returns, + IReadOnlyList Tickets, + IReadOnlyList? Allocations, + IReadOnlyList? Renewals, + IReadOnlyList? Contracts, + IReadOnlyList? Assignments, + OpsRevenueDto? Revenue); + +// ---- Thân request (BACKEND-TODO A2, A3) +public record OpsNoteRequest(string? Note); +public record OpsVerifyRequest(string? DocType, string? DocNumber, bool PhotoMatched, bool InfoMatched); +public record OpsHandoverRequest(string? UnlockMethod); +public record OpsReturnInspectionRequest(string? Items, string? Walls, string? Keys, string? Proposal); +public record OpsTicketResponseRequest(string? Note, string? NextStatus); +public record OpsRejectRequest(string? Reason); +public record OpsAllocateRequest(string? UnitCode); +public record OpsAssignRequest(string? StaffId); diff --git a/StorageProject.Core/Entities/Reservation.cs b/StorageProject.Core/Entities/Reservation.cs index ff0e9f0..e941755 100644 --- a/StorageProject.Core/Entities/Reservation.cs +++ b/StorageProject.Core/Entities/Reservation.cs @@ -13,7 +13,7 @@ public class Reservation public decimal QuotedMonthlyRate { get; set; } public decimal EstimatedAmount { get; set; } public decimal RequiredDeposit { get; set; } - // PENDING_PAYMENT, CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW + // PENDING_PAYMENT, PENDING_VERIFICATION (khách báo đã chuyển khoản, chờ đối soát), CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW public string Status { get; set; } = "PENDING_PAYMENT"; public string? CancellationReason { get; set; } public DateTime CreatedAt { get; set; } diff --git a/StorageProject.Core/Exceptions/ReservationExpiredException.cs b/StorageProject.Core/Exceptions/ReservationExpiredException.cs new file mode 100644 index 0000000..7e124c0 --- /dev/null +++ b/StorageProject.Core/Exceptions/ReservationExpiredException.cs @@ -0,0 +1,4 @@ +namespace StorageProject.Core.Exceptions; + +/// Đơn đặt chỗ đã quá thời gian giữ chỗ. Endpoint trả 400 kèm code = "EXPIRED" (BE-CONTRACT C04). +public class ReservationExpiredException(string message) : InvalidOperationException(message); diff --git a/StorageProject.Core/Interfaces/IFacilityOpsService.cs b/StorageProject.Core/Interfaces/IFacilityOpsService.cs new file mode 100644 index 0000000..ac9cd6f --- /dev/null +++ b/StorageProject.Core/Interfaces/IFacilityOpsService.cs @@ -0,0 +1,30 @@ +using StorageProject.Core.DTOs.FacilityOps; + +namespace StorageProject.Core.Interfaces; + +/// +/// Khu Nhân viên cơ sở (UC07–UC12) và Quản lý cơ sở (UC13–UC18), chỉ trong cơ sở được phân công (SRS A06). +/// Lỗi: KeyNotFoundException → 404 · InvalidOperationException/ArgumentException → 400 · +/// UnauthorizedAccessException → 403 (chưa được phân công cơ sở / không đủ quyền). +/// Id trong đường dẫn là mã hiển thị ("SS-20261014-0012", "BG-0007", "HĐ-2026-0003"…). +/// +public interface IFacilityOpsService +{ + Task GetBoardAsync(OpsActor actor, CancellationToken ct = default); + + // Nhân viên (và quản lý) + Task ConfirmPaymentAsync(OpsActor actor, string id, CancellationToken ct = default); + Task ReportMismatchAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default); + Task VerifyCustomerAsync(OpsActor actor, string id, OpsVerifyRequest request, CancellationToken ct = default); + Task CompleteHandoverAsync(OpsActor actor, string id, OpsHandoverRequest request, CancellationToken ct = default); + Task SubmitReturnInspectionAsync(OpsActor actor, string id, OpsReturnInspectionRequest request, CancellationToken ct = default); + Task RespondTicketAsync(OpsActor actor, string id, OpsTicketResponseRequest request, CancellationToken ct = default); + + // Chỉ quản lý + Task AllocateAsync(OpsActor actor, string id, OpsAllocateRequest request, CancellationToken ct = default); + Task AssignAsync(OpsActor actor, string id, OpsAssignRequest request, CancellationToken ct = default); + Task ApproveRenewalAsync(OpsActor actor, string id, CancellationToken ct = default); + Task RejectRenewalAsync(OpsActor actor, string id, OpsRejectRequest request, CancellationToken ct = default); + Task RemindAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default); + Task ConfirmRefundAsync(OpsActor actor, string id, CancellationToken ct = default); +} diff --git a/StorageProject.Core/Interfaces/IServices.cs b/StorageProject.Core/Interfaces/IServices.cs index 9571868..16a198c 100644 --- a/StorageProject.Core/Interfaces/IServices.cs +++ b/StorageProject.Core/Interfaces/IServices.cs @@ -31,6 +31,7 @@ public interface IReservationService Task GetReservationDetailAsync(long customerId, long reservationId, CancellationToken ct = default); Task CreateReservationAsync(long customerId, CreateReservationRequest request, CancellationToken ct = default); Task CancelReservationAsync(long customerId, long reservationId, string reason, CancellationToken ct = default); + Task ConfirmTransferAsync(long customerId, long reservationId, CancellationToken ct = default); } public interface IContractService diff --git a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs index b4be776..a482679 100644 --- a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs +++ b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs @@ -15,7 +15,7 @@ public void Configure(EntityTypeBuilder b) t.HasCheckConstraint("CK_reservations_estimated_amount", "[EstimatedAmount] >= 0"); t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); t.HasCheckConstraint("CK_reservations_status", - "[Status] IN ('PENDING_PAYMENT','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); }); b.HasKey(r => r.ReservationId); b.Property(r => r.ReservationId).UseIdentityColumn(); diff --git a/StorageProject.Infrastructure/Data/DbSeeder.Catalog.cs b/StorageProject.Infrastructure/Data/DbSeeder.Catalog.cs new file mode 100644 index 0000000..4d50dac --- /dev/null +++ b/StorageProject.Infrastructure/Data/DbSeeder.Catalog.cs @@ -0,0 +1,197 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Data; + +/// +/// Danh mục kho theo D17 (Figma 14/10): +/// - 4 loại kho: thường / lạnh × cỡ M (15 m²) / cỡ L (30 m²). +/// - 12 cơ sở SafeSpace (khớp src/data/seed.js của giao diện), cơ sở nào cũng có kho lạnh. +/// - Mỗi cơ sở 12 ô: dãy A cỡ M (K01–K04 thường, K05–K06 lạnh), dãy B cỡ L (K07–K10 thường, K11–K12 lạnh). +/// - Giá = giá gốc cơ sở × hệ số cỡ (M 1, L 1,75) × hệ số loại (thường 1, lạnh 1,2), làm tròn 10.000 đ +/// — cùng công thức với src/lib/catalog.js. +/// Dữ liệu cũ (cỡ S/M/L/XL, cơ sở "Quận 7") được ngừng dùng, không xoá để giữ lịch sử. +/// +public static partial class DbSeeder +{ + public sealed record SeedCatalog(Facility Home, UnitType NormalM, UnitType NormalL, UnitType ColdM, UnitType ColdL); + + private sealed record SeedFacility(string Name, string District, decimal BasePrice, string Street, string Phone, string? OldAddress = null); + + // Thứ tự và giá gốc giống src/data/seed.js. Cơ sở đầu tiên là nơi staff01 / manager01 phụ trách. + private static readonly SeedFacility[] SafeSpaceFacilities = + [ + new("SafeSpace Nguyễn Lương Bằng", "Quận 7", 1150000m, "Số 12 Nguyễn Lương Bằng, Tân Phú", "02837001012", + "12 Nguyễn Lương Bằng, Phường Tân Phú, Quận 7, TP. Hồ Chí Minh"), + new("SafeSpace Him Lam", "Quận 7", 1050000m, "Khu dân cư Him Lam, Tân Hưng", "02837001013", + "Khu dân cư Him Lam, Phường Tân Hưng, Quận 7, TP. Hồ Chí Minh"), + new("SafeSpace Phú Xuân", "Quận 7", 890000m, "Đường Nguyễn Hữu Thọ, Phú Xuân", "02837001014", + "Đường Nguyễn Hữu Thọ, Xã Phú Xuân, Huyện Nhà Bè, TP. Hồ Chí Minh"), + new("SafeSpace Tân Thuận", "Quận 7", 1100000m, "Đường Huỳnh Tấn Phát, Tân Thuận", "02837001015", + "Đường Huỳnh Tấn Phát, Phường Tân Thuận Đông, Quận 7, TP. Hồ Chí Minh"), + new("SafeSpace Phú Mỹ Hưng", "Quận 7", 1250000m, "Đường Nguyễn Lương Bằng, Tân Phong", "02837001016", + "Đường Nguyễn Văn Linh, Phường Tân Phong, Quận 7, TP. Hồ Chí Minh"), + new("SafeSpace Bình Thạnh", "Quận Bình Thạnh", 980000m, "Đường Nguyễn Xí, Phường 26", "02837001017", + "Đường Nguyễn Xí, Phường 26, Quận Bình Thạnh, TP. Hồ Chí Minh"), + new("SafeSpace Nhà Bè", "Huyện Nhà Bè", 850000m, "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè", "02837001018", + "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè, Huyện Nhà Bè, TP. Hồ Chí Minh"), + new("SafeSpace Bình Chánh", "Huyện Bình Chánh", 790000m, "Quốc lộ 50, Bình Hưng", "02837001019", + "Quốc lộ 50, Xã Bình Hưng, Huyện Bình Chánh, TP. Hồ Chí Minh"), + new("SafeSpace Thủ Đức", "TP. Thủ Đức", 920000m, "Đường Võ Văn Ngân, Linh Chiểu", "02837001020", + "Đường Võ Văn Ngân, Phường Linh Chiểu, TP. Thủ Đức, TP. Hồ Chí Minh"), + new("SafeSpace Gò Vấp", "Quận Gò Vấp", 930000m, "Đường Quang Trung, Phường 10", "02837001021", + "Đường Quang Trung, Phường 10, Quận Gò Vấp, TP. Hồ Chí Minh"), + new("SafeSpace Tân Bình", "Quận Tân Bình", 1020000m, "Đường Cộng Hòa, Phường 13", "02838112233", + "123 Hoàng Hoa Thám, Phường 13, Quận Tân Bình, TP. Hồ Chí Minh"), + new("SafeSpace Bình Tân", "Quận Bình Tân", 820000m, "Đường Kinh Dương Vương, An Lạc", "02837001023"), + ]; + + // (mã ô, dãy, lạnh?, cỡ L?) + private static readonly (string Code, string Row, bool Cold, bool Large)[] UnitLayout = + [ + ("K01", "A", false, false), ("K02", "A", false, false), ("K03", "A", false, false), ("K04", "A", false, false), + ("K05", "A", true, false), ("K06", "A", true, false), + ("K07", "B", false, true), ("K08", "B", false, true), ("K09", "B", false, true), ("K10", "B", false, true), + ("K11", "B", true, true), ("K12", "B", true, true), + ]; + + private static readonly string[] LegacyUnitTypeNames = + ["Kho Mini S (1m x 1m)", "Kho Tiêu Chuẩn M (2m x 2m)", "Kho Lớn L (3m x 3m)", "Kho Doanh Nghiệp XL (4m x 4m)"]; + + private static readonly string[] LegacyFacilityNames = ["SafeSpace Quận 7", "SSFRMS Chi nhánh Quận 7"]; + + public static decimal SeedRate(decimal basePrice, bool cold, bool large) => + Math.Round(basePrice * (large ? 1.75m : 1m) * (cold ? 1.2m : 1m) / 10000m, MidpointRounding.AwayFromZero) * 10000m; + + private static async Task EnsureCatalogAsync(AppDbContext context, long adminId) + { + var now = DateTime.UtcNow; + + // --- 4 loại kho + async Task TypeAsync(string name, decimal area, decimal length, decimal width, bool cold, string description) + { + var type = await context.UnitTypes.FirstOrDefaultAsync(t => t.TypeName == name); + if (type != null) return type; + type = new UnitType + { + TypeName = name, Area = area, Length = length, Width = width, Height = 3.0m, ClimateControlled = cold, + Description = description, Status = "ACTIVE", CreatedAt = now, UpdatedAt = now + }; + context.UnitTypes.Add(type); + await context.SaveChangesAsync(); + return type; + } + + var normalM = await TypeAsync("Kho thường M", 15m, 5m, 3m, false, "Đồ đạc một phòng, hàng shop online, hồ sơ giấy tờ."); + var normalL = await TypeAsync("Kho thường L", 30m, 6m, 5m, false, "Đồ chuyển nhà 2–3 phòng ngủ, hàng tồn kho số lượng lớn."); + var coldM = await TypeAsync("Kho lạnh M", 15m, 5m, 3m, true, "Thiết bị điện tử, tài liệu, đồ gỗ cần tránh ẩm."); + var coldL = await TypeAsync("Kho lạnh L", 30m, 6m, 5m, true, "Hàng hoá cần giữ nhiệt độ ổn định, kho hàng cho cửa hàng."); + + await RetireLegacyCatalogAsync(context); + + // --- Đổi tên cơ sở seed đời đầu (chỉ khi còn tên cũ) + var oldTanBinh = await context.Facilities.FirstOrDefaultAsync(f => f.Name == "SSFRMS Chi nhánh Tân Bình"); + if (oldTanBinh != null && !await context.Facilities.AnyAsync(f => f.Name == "SafeSpace Tân Bình")) + { + oldTanBinh.Name = "SafeSpace Tân Bình"; + oldTanBinh.UpdatedAt = now; + await context.SaveChangesAsync(); + } + + // --- 12 cơ sở, bảng giá, 12 ô mỗi cơ sở + var effectiveFrom = DateOnly.FromDateTime(now.AddHours(7)).AddDays(-30); + Facility? home = null; + foreach (var seed in SafeSpaceFacilities) + { + var address = $"{seed.Street}, {seed.District}, TP. Hồ Chí Minh"; + var facility = await context.Facilities.FirstOrDefaultAsync(f => f.Name == seed.Name); + if (facility == null) + { + facility = new Facility + { + Name = seed.Name, Address = address, ContactPhone = seed.Phone, + OpeningTime = new TimeOnly(6, 0), ClosingTime = new TimeOnly(22, 0), + Status = "ACTIVE", CreatedAt = now, UpdatedAt = now + }; + context.Facilities.Add(facility); + await context.SaveChangesAsync(); + } + else if (seed.OldAddress != null && facility.Address == seed.OldAddress) + { + // Địa chỉ seed cũ → địa chỉ theo Figma 14/10 (không đụng địa chỉ Vận hành KD đã tự sửa) + facility.Address = address; + facility.UpdatedAt = now; + } + home ??= facility; + + foreach (var (type, cold, large) in new[] { (normalM, false, false), (normalL, false, true), (coldM, true, false), (coldL, true, true) }) + { + var hasRate = await context.RentalRates.AnyAsync(r => r.FacilityId == facility.FacilityId && r.UnitTypeId == type.UnitTypeId); + if (!hasRate) + { + context.RentalRates.Add(new RentalRate + { + FacilityId = facility.FacilityId, UnitTypeId = type.UnitTypeId, SetBy = adminId, + MonthlyRate = SeedRate(seed.BasePrice, cold, large), EffectiveFrom = effectiveFrom, + Status = "ACTIVE", CreatedAt = now + }); + } + } + + var existingCodes = await context.StorageUnits + .Where(u => u.FacilityId == facility.FacilityId) + .Select(u => u.UnitNumber) + .ToListAsync(); + foreach (var (code, row, cold, large) in UnitLayout) + { + if (existingCodes.Contains(code)) continue; + var type = cold ? (large ? coldL : coldM) : (large ? normalL : normalM); + context.StorageUnits.Add(new StorageUnit + { + FacilityId = facility.FacilityId, UnitTypeId = type.UnitTypeId, UnitNumber = code, + Floor = "Tầng trệt", Zone = $"Dãy {row}", + LocationDescription = $"Tầng trệt · Dãy {row} · {(cold ? "Kho lạnh" : "Kho thường")} cỡ {(large ? "L" : "M")}", + Status = "AVAILABLE", CreatedAt = now, UpdatedAt = now + }); + } + await context.SaveChangesAsync(); + } + + return new SeedCatalog(home!, normalM, normalL, coldM, coldL); + } + + /// Ngừng dùng loại kho cỡ S/M/L/XL và cơ sở "Quận 7" của bản seed cũ — giữ lại để không mất lịch sử. + private static async Task RetireLegacyCatalogAsync(AppDbContext context) + { + var now = DateTime.UtcNow; + var legacyTypes = await context.UnitTypes.Where(t => LegacyUnitTypeNames.Contains(t.TypeName)).ToListAsync(); + if (legacyTypes.Count > 0) + { + var ids = legacyTypes.Select(t => t.UnitTypeId).ToList(); + foreach (var t in legacyTypes.Where(t => t.Status == "ACTIVE")) + { + t.Status = "INACTIVE"; + t.UpdatedAt = now; + } + var rates = await context.RentalRates.Where(r => ids.Contains(r.UnitTypeId) && r.Status == "ACTIVE").ToListAsync(); + foreach (var r in rates) r.Status = "INACTIVE"; + // Ô trống của loại cũ không nhận khách mới; ô đang có khách giữ nguyên tới khi trả kho + var units = await context.StorageUnits.Where(u => ids.Contains(u.UnitTypeId) && u.Status == "AVAILABLE").ToListAsync(); + foreach (var u in units) + { + u.Status = "OUT_OF_SERVICE"; + u.UpdatedAt = now; + } + } + + var legacyFacilities = await context.Facilities.Where(f => LegacyFacilityNames.Contains(f.Name) && f.Status == "ACTIVE").ToListAsync(); + foreach (var f in legacyFacilities) + { + var busy = await context.RentalContracts.AnyAsync(c => c.Unit.FacilityId == f.FacilityId && (c.Status == "ACTIVE" || c.Status == "EXPIRING" || c.Status == "OVERDUE" || c.Status == "RETURN_PENDING" || c.Status == "DRAFT")) + || await context.Reservations.AnyAsync(r => r.FacilityId == f.FacilityId && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED" || r.Status == "UNIT_ASSIGNED")); + f.Status = busy ? "TEMPORARILY_CLOSED" : "INACTIVE"; + f.UpdatedAt = now; + } + await context.SaveChangesAsync(); + } +} diff --git a/StorageProject.Infrastructure/Data/DbSeeder.FacilityOps.cs b/StorageProject.Infrastructure/Data/DbSeeder.FacilityOps.cs new file mode 100644 index 0000000..46c98f9 --- /dev/null +++ b/StorageProject.Infrastructure/Data/DbSeeder.FacilityOps.cs @@ -0,0 +1,274 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Data; + +/// +/// Khu Nhân viên cơ sở / Quản lý cơ sở (BACKEND-TODO A1): +/// - Quyền của role STAFF, MANAGER; tài khoản manager01 / Manager@123 và staff02 / Staff@123. +/// - Phân công cơ sở: staff01, staff02, manager01 → SafeSpace Nguyễn Lương Bằng (SRS A06: mỗi người 1 cơ sở). +/// - Dữ liệu vận hành mẫu tại cơ sở đó để màn S01–S09, M01–M08 có việc để xử lý ngay sau khi tạo DB. +/// +public static partial class DbSeeder +{ + private static readonly string[] StaffPermissionCodes = ["HANDOVER_MANAGE", "RETURN_MANAGE", "TICKET_MANAGE", "PAYMENT_CONFIRM"]; + + private static readonly string[] ManagerPermissionCodes = + ["HANDOVER_MANAGE", "RETURN_MANAGE", "TICKET_MANAGE", "PAYMENT_CONFIRM", "UNIT_MANAGE", "ASSIGNMENT_MANAGE", "RENEWAL_MANAGE", "REPORT_VIEW"]; + + private static async Task EnsureUserAsync(AppDbContext context, string username, string email, string password, string fullName, string phone, string roleName) + { + var user = await context.Users.FirstOrDefaultAsync(u => u.Username == username); + if (user == null) + { + user = new User + { + Username = username, Email = email, PasswordHash = BCrypt.Net.BCrypt.HashPassword(password), + FullName = fullName, Phone = phone, Status = "ACTIVE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow + }; + context.Users.Add(user); + await context.SaveChangesAsync(); + } + var role = await context.Roles.FirstAsync(r => r.RoleName == roleName); + if (!await context.UserRoles.AnyAsync(ur => ur.UserId == user.UserId && ur.RoleId == role.RoleId)) + { + context.UserRoles.Add(new UserRole { UserId = user.UserId, RoleId = role.RoleId, AssignedAt = DateTime.UtcNow }); + await context.SaveChangesAsync(); + } + return user; + } + + private static async Task EnsureFacilityRolesAsync(AppDbContext context) + { + var staffRole = await context.Roles.FirstAsync(r => r.RoleName == "STAFF"); + var managerRole = await context.Roles.FirstAsync(r => r.RoleName == "MANAGER"); + var permissions = await context.Permissions.ToListAsync(); + var pairs = await context.RolePermissions.Select(rp => new { rp.RoleId, rp.PermissionId }).ToListAsync(); + + foreach (var perm in permissions) + { + if (StaffPermissionCodes.Contains(perm.PermissionCode) && !pairs.Any(x => x.RoleId == staffRole.RoleId && x.PermissionId == perm.PermissionId)) + { + context.RolePermissions.Add(new RolePermission { RoleId = staffRole.RoleId, PermissionId = perm.PermissionId }); + } + if (ManagerPermissionCodes.Contains(perm.PermissionCode) && !pairs.Any(x => x.RoleId == managerRole.RoleId && x.PermissionId == perm.PermissionId)) + { + context.RolePermissions.Add(new RolePermission { RoleId = managerRole.RoleId, PermissionId = perm.PermissionId }); + } + } + await context.SaveChangesAsync(); + + await EnsureUserAsync(context, "manager01", "manager01@storage.vn", "Manager@123", "Phạm Thu Hà", "0900000005", "MANAGER"); + await EnsureUserAsync(context, "staff02", "staff02@storage.vn", "Staff@123", "Nguyễn Minh Tâm", "0900000006", "STAFF"); + } + + /// Gán cơ sở cho tài khoản chưa có cơ sở nào đang hiệu lực (không ghi đè phân công do quản trị đặt). + private static async Task EnsureFacilityAssignmentsAsync(AppDbContext context, long facilityId, long adminId) + { + var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + foreach (var username in new[] { "staff01", "staff02", "manager01" }) + { + var user = await context.Users.FirstOrDefaultAsync(u => u.Username == username); + if (user == null) continue; + var hasActive = await context.UserFacilities.AnyAsync(uf => uf.UserId == user.UserId && uf.Status == "ACTIVE"); + if (hasActive) continue; + context.UserFacilities.Add(new UserFacility + { + UserId = user.UserId, FacilityId = facilityId, AssignedBy = adminId, + AssignedFrom = today.AddDays(-30), Status = "ACTIVE", CreatedAt = DateTime.UtcNow + }); + } + await context.SaveChangesAsync(); + } + + /// + /// Dữ liệu vận hành mẫu tại cơ sở đầu tiên. Chỉ chạy khi cơ sở này chưa có đơn đặt chỗ nào. + /// Ô kho: K01, K09 đang thuê · K02 sắp hết hạn + chờ duyệt gia hạn · K03 quá hạn · K05 chờ bàn giao · + /// K07 chờ kiểm tra trả kho · K10 bảo trì · còn lại trống. Thêm 2 khoản chờ đối soát, 1 đơn chờ phân bổ, + /// 1 đơn chờ chuyển khoản (để khách thử "Tôi đã chuyển khoản"). + /// + private static async Task SeedFacilityOperationsAsync(AppDbContext context, SeedCatalog catalog) + { + var home = catalog.Home; + if (await context.Reservations.AnyAsync(r => r.FacilityId == home.FacilityId)) return; + + var nowUtc = DateTime.UtcNow; + var today = DateOnly.FromDateTime(nowUtc.AddHours(7)); + DateTime Utc(DateOnly d, int hour, int minute = 0) => + DateTime.SpecifyKind(d.ToDateTime(new TimeOnly(hour, minute)).AddHours(-7), DateTimeKind.Utc); + + var staff01 = await context.Users.FirstAsync(u => u.Username == "staff01"); + var manager = await context.Users.FirstAsync(u => u.Username == "manager01"); + var cust01 = await context.Users.FirstAsync(u => u.Username == "customer01"); + var cust02 = await context.Users.FirstAsync(u => u.Username == "customer02"); + var cust03 = await EnsureUserAsync(context, "customer03", "tung.le@example.com", "Customer@123", "Lê Văn Tùng", "0903000003", "CUSTOMER"); + var cust04 = await EnsureUserAsync(context, "customer04", "lan.hoang@example.com", "Customer@123", "Hoàng Thị Lan", "0903000004", "CUSTOMER"); + var cust05 = await EnsureUserAsync(context, "customer05", "huy.phan@example.com", "Customer@123", "Phan Quốc Huy", "0903000005", "CUSTOMER"); + var cust06 = await EnsureUserAsync(context, "customer06", "trang.dang@example.com", "Customer@123", "Đặng Thu Trang", "0903000006", "CUSTOMER"); + + var units = await context.StorageUnits.Where(u => u.FacilityId == home.FacilityId).ToDictionaryAsync(u => u.UnitNumber); + // Giá đang áp dụng của từng loại kho (có thể có nhiều bản ACTIVE nếu Vận hành KD đã lên lịch giá mới) + var rates = (await context.RentalRates + .Where(r => r.FacilityId == home.FacilityId && r.Status == "ACTIVE" && r.EffectiveFrom <= today) + .ToListAsync()) + .GroupBy(r => r.UnitTypeId) + .ToDictionary(g => g.Key, g => g.OrderByDescending(r => r.EffectiveFrom).First().MonthlyRate); + + void Log(long? userId, string action, string entityType, long entityId, object value, DateTime at) => + context.ActivityLogs.Add(new ActivityLog + { + UserId = userId, Action = action, EntityType = entityType, EntityId = entityId, + NewValue = JsonSerializer.Serialize(value), LoggedAt = at + }); + + async Task ReserveAsync(User customer, UnitType type, DateOnly start, int months, string status, DateTime createdAt) + { + var rate = rates[type.UnitTypeId]; + var r = new Reservation + { + CustomerId = customer.UserId, FacilityId = home.FacilityId, UnitTypeId = type.UnitTypeId, + StartDate = start, RentalPeriodMonths = months, ExpectedEndDate = start.AddMonths(months), + CheckInAppointmentAt = Utc(start, 9), QuotedMonthlyRate = rate, EstimatedAmount = rate * months, + RequiredDeposit = rate, Status = status, CreatedAt = createdAt, + ExpiresAt = status == "PENDING_PAYMENT" ? nowUtc.AddHours(24) : createdAt.AddHours(24) + }; + context.Reservations.Add(r); + await context.SaveChangesAsync(); + return r; + } + + // Thuê một ô: đơn đặt chỗ + phân bổ + hợp đồng + cọc và tiền thuê đã thu + biên bản bàn giao + async Task RentAsync(User customer, string code, UnitType type, DateOnly start, int months, + string contractStatus, string unitStatus, User handoverStaff, bool handedOver) + { + var unit = units[code]; + var paidAt = Utc(start.AddDays(-2), 10); + var reservation = await ReserveAsync(customer, type, start, months, handedOver ? "CHECKED_IN" : "UNIT_ASSIGNED", paidAt.AddHours(-1)); + context.UnitAssignments.Add(new UnitAssignment + { + ReservationId = reservation.ReservationId, UnitId = unit.UnitId, AssignedBy = manager.UserId, + Status = "ACTIVE", AssignedAt = paidAt.AddHours(2) + }); + var contract = new RentalContract + { + ReservationId = reservation.ReservationId, CustomerId = customer.UserId, UnitId = unit.UnitId, + StartDate = start, EndDate = start.AddMonths(months), AgreedMonthlyRate = reservation.QuotedMonthlyRate, + DepositAmount = reservation.RequiredDeposit, Status = contractStatus, CreatedAt = paidAt.AddHours(2), + ActivatedAt = handedOver ? Utc(start, 9) : null + }; + context.RentalContracts.Add(contract); + await context.SaveChangesAsync(); + + var reference = $"SS-{reservation.CreatedAt.AddHours(7):yyyyMMdd}-{reservation.ReservationId:0000}"; + foreach (var (kind, amount) in new[] { ("DEPOSIT", reservation.RequiredDeposit), ("RENT", reservation.EstimatedAmount) }) + { + context.Payments.Add(new Payment + { + ContractId = contract.ContractId, PaymentType = kind, Amount = amount, Currency = "VND", + PaymentMethod = "BANK_TRANSFER", TransactionReference = reference, DueDate = start, + PaidAt = paidAt, Status = "PAID", CreatedAt = paidAt, UpdatedAt = paidAt + }); + } + Log(staff01.UserId, "PAYMENT_CONFIRMED", "RESERVATION", reservation.ReservationId, + new { amount = reservation.EstimatedAmount + reservation.RequiredDeposit }, paidAt); + + context.HandoverRecords.Add(new HandoverRecord + { + ContractId = contract.ContractId, StaffId = handoverStaff.UserId, ScheduledAt = Utc(start, 9), + VerifiedAt = handedOver ? Utc(start, 9) : null, HandoverAt = handedOver ? Utc(start, 9, 15) : null, + InitialCondition = "Kho sạch, cửa cuốn và khoá hoạt động tốt", + CustomerConfirmed = handedOver, StaffConfirmed = handedOver, + Status = handedOver ? "HANDED_OVER" : "SCHEDULED", CreatedAt = paidAt.AddHours(2) + }); + if (handedOver) + { + context.AccessCredentials.Add(new AccessCredential + { + ContractId = contract.ContractId, UnitId = unit.UnitId, IssuedBy = handoverStaff.UserId, + CredentialType = "ACCESS_CARD", CredentialReference = $"CARD-{code}-{start:yyMMdd}", + IssuedAt = Utc(start, 9, 15), Status = "ACTIVE" + }); + } + unit.Status = unitStatus; + unit.UpdatedAt = paidAt; + await context.SaveChangesAsync(); + return contract; + } + + // K01 · customer01 đang thuê + 1 yêu cầu hỗ trợ chưa phân công + var k01 = await RentAsync(cust01, "K01", catalog.NormalM, today.AddDays(-15), 3, "ACTIVE", "OCCUPIED", staff01, true); + context.SupportTickets.Add(new SupportTicket + { + CustomerId = cust01.UserId, ContractId = k01.ContractId, UnitId = units["K01"].UnitId, IssueType = "UNIT", + Title = "Cửa cuốn kho kẹt khi mở", Description = "Cửa cuốn ô K01 kéo lên được nửa thì kẹt, nhờ cơ sở kiểm tra.", + Priority = "NORMAL", Status = "OPEN", CreatedAt = Utc(today.AddDays(-1), 16, 20) + }); + + // K02 · sắp hết hạn, khách xin gia hạn 3 tháng + var k02Start = today.AddDays(10).AddMonths(-3); + var k02 = await RentAsync(cust03, "K02", catalog.NormalM, k02Start, 3, "ACTIVE", "OCCUPIED", staff01, true); + context.ContractRenewals.Add(new ContractRenewal + { + ContractId = k02.ContractId, OldEndDate = k02.EndDate, NewEndDate = k02.EndDate.AddMonths(3), RenewalPeriodMonths = 3, + OldMonthlyRate = k02.AgreedMonthlyRate, NewMonthlyRate = k02.AgreedMonthlyRate, RenewalAmount = k02.AgreedMonthlyRate * 3, + Status = "PENDING", RequestedAt = Utc(today.AddDays(-1), 10, 5), CreatedAt = Utc(today.AddDays(-1), 10, 5) + }); + + // K03 · quá hạn 3 ngày, chưa thanh toán kỳ mới + var k03Start = today.AddDays(-3).AddMonths(-1); + var k03 = await RentAsync(cust04, "K03", catalog.NormalM, k03Start, 1, "OVERDUE", "OCCUPIED", staff01, true); + context.Payments.Add(new Payment + { + ContractId = k03.ContractId, PaymentType = "RENT", Amount = k03.AgreedMonthlyRate, Currency = "VND", + PaymentMethod = "BANK_TRANSFER", DueDate = k03.EndDate, Status = "PENDING", + CreatedAt = Utc(k03.EndDate.AddDays(-7), 8), UpdatedAt = Utc(k03.EndDate.AddDays(-7), 8) + }); + context.OverdueCases.Add(new OverdueCase + { + ContractId = k03.ContractId, OverdueFrom = k03.EndDate.AddDays(1), GraceDeadline = k03.EndDate.AddDays(8), + OutstandingAmount = k03.AgreedMonthlyRate, Status = "OPEN", OpenedAt = Utc(k03.EndDate.AddDays(1), 8) + }); + + // K05 · kho lạnh M đã phân bổ, chờ khách đến xác minh + nhận kho (giao cho staff01) + await RentAsync(cust05, "K05", catalog.ColdM, today.AddDays(1), 3, "DRAFT", "RESERVED", staff01, false); + + // K07 · khách đã đăng ký trả kho, chờ kiểm tra (chưa phân công nhân viên) + còn nợ phí vệ sinh + var k07Start = today.AddDays(1).AddMonths(-3); + var k07 = await RentAsync(cust06, "K07", catalog.NormalL, k07Start, 3, "RETURN_PENDING", "RETURN_PENDING", staff01, true); + context.ReturnInspections.Add(new ReturnInspection + { + ContractId = k07.ContractId, StaffId = manager.UserId, ScheduledAt = Utc(today.AddDays(1), 10), + Status = "SCHEDULED", CreatedAt = Utc(today.AddDays(-2), 9) + }); + context.Payments.Add(new Payment + { + ContractId = k07.ContractId, PaymentType = "CLEANING_FEE", Amount = 200000m, Currency = "VND", + PaymentMethod = "BANK_TRANSFER", DueDate = k07.EndDate, Status = "PENDING", + CreatedAt = Utc(today.AddDays(-2), 9), UpdatedAt = Utc(today.AddDays(-2), 9) + }); + + // K09 · customer02 đang thuê dài hạn + await RentAsync(cust02, "K09", catalog.NormalL, today.AddDays(-40), 6, "ACTIVE", "OCCUPIED", staff01, true); + + // K10 · bảo trì + units["K10"].Status = "MAINTENANCE"; + units["K10"].UpdatedAt = nowUtc; + + // Khoản chờ đối soát (S09): khách đã bấm "Tôi đã chuyển khoản" + var pv1 = await ReserveAsync(cust02, catalog.NormalM, today.AddDays(5), 3, "PENDING_VERIFICATION", nowUtc.AddMinutes(-50)); + Log(cust02.UserId, "TRANSFER_REPORTED", "RESERVATION", pv1.ReservationId, new { amount = pv1.EstimatedAmount + pv1.RequiredDeposit }, nowUtc.AddMinutes(-45)); + var pv2 = await ReserveAsync(cust01, catalog.ColdL, today.AddDays(3), 1, "PENDING_VERIFICATION", nowUtc.AddHours(-14)); + Log(cust01.UserId, "TRANSFER_REPORTED", "RESERVATION", pv2.ReservationId, new { amount = pv2.EstimatedAmount + pv2.RequiredDeposit }, nowUtc.AddHours(-13.9)); + + // Đơn đã đối soát, chờ quản lý phân bổ ô (M05) — ô phù hợp: K06 + var confirmed = await ReserveAsync(cust06, catalog.ColdM, today.AddDays(6), 3, "CONFIRMED", nowUtc.AddDays(-1).AddHours(-3)); + Log(staff01.UserId, "PAYMENT_CONFIRMED", "RESERVATION", confirmed.ReservationId, + new { amount = confirmed.EstimatedAmount + confirmed.RequiredDeposit }, nowUtc.AddDays(-1)); + + // Đơn chờ chuyển khoản của customer01 — dùng để thử nút "Tôi đã chuyển khoản" + await ReserveAsync(cust01, catalog.NormalL, today.AddDays(5), 1, "PENDING_PAYMENT", nowUtc); + + await context.SaveChangesAsync(); + } +} diff --git a/StorageProject.Infrastructure/Data/DbSeeder.cs b/StorageProject.Infrastructure/Data/DbSeeder.cs index 3e54a99..23351f6 100644 --- a/StorageProject.Infrastructure/Data/DbSeeder.cs +++ b/StorageProject.Infrastructure/Data/DbSeeder.cs @@ -3,7 +3,13 @@ namespace StorageProject.Infrastructure.Data; -public static class DbSeeder +/// +/// Dữ liệu khởi tạo. Mọi bước đều "chỉ thêm phần còn thiếu", nên chạy lại nhiều lần vẫn an toàn và +/// database tạo từ trước cũng được bổ sung khi khởi động lại API. +/// - Danh mục kho theo D17 (Figma 14/10): xem DbSeeder.Catalog.cs +/// - Tài khoản nhân viên / quản lý cơ sở và dữ liệu vận hành mẫu: xem DbSeeder.FacilityOps.cs +/// +public static partial class DbSeeder { public static async Task SeedAsync(AppDbContext context) { @@ -60,7 +66,6 @@ public static async Task SeedAsync(AppDbContext context) await context.SaveChangesAsync(); } - // 2. Users if (!await context.Users.AnyAsync()) { @@ -125,135 +130,18 @@ public static async Task SeedAsync(AppDbContext context) await context.SaveChangesAsync(); } - // 2b. Vai trò Quản lý vận hành KD (OPERATIONS) + tài khoản ops01 — chạy lại được với DB đã có + // 2b. Vai trò Quản lý vận hành KD (OPERATIONS) + tài khoản ops01 await EnsureOperationsRoleAsync(context); - var admin = await context.Users.FirstAsync(u => u.Username == "admin"); - var staff = await context.Users.FirstAsync(u => u.Username == "staff01"); - var cust1 = await context.Users.FirstAsync(u => u.Username == "customer01"); - - // 3. Facilities - if (!await context.Facilities.AnyAsync()) - { - var fac1 = new Facility - { - Name = "SSFRMS Chi nhánh Tân Bình", - Address = "123 Hoàng Hoa Thám, Phường 13, Quận Tân Bình, TP. Hồ Chí Minh", - ContactPhone = "02838112233", - OpeningTime = new TimeOnly(7, 0), - ClosingTime = new TimeOnly(22, 0), - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }; - - var fac2 = new Facility - { - Name = "SSFRMS Chi nhánh Quận 7", - Address = "456 Nguyễn Thị Thập, Phường Tân Quy, Quận 7, TP. Hồ Chí Minh", - ContactPhone = "02837778899", - OpeningTime = new TimeOnly(6, 0), - ClosingTime = new TimeOnly(23, 0), - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }; - - context.Facilities.AddRange(fac1, fac2); - await context.SaveChangesAsync(); - } - - var tanBinhFac = await context.Facilities.FirstAsync(f => f.Name.Contains("Tân Bình")); - var quan7Fac = await context.Facilities.FirstAsync(f => f.Name.Contains("Quận 7")); - - // 4. Unit Types - if (!await context.UnitTypes.AnyAsync()) - { - var types = new List - { - new() - { - TypeName = "Kho Mini S (1m x 1m)", - Length = 1.0m, - Width = 1.0m, - Height = 2.5m, - Area = 1.0m, - ClimateControlled = false, - Description = "Kho nhỏ tiết kiệm, phù hợp cất giữ vali, tài liệu, phụ kiện gia đình", - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }, - new() - { - TypeName = "Kho Tiêu Chuẩn M (2m x 2m)", - Length = 2.0m, - Width = 2.0m, - Height = 2.8m, - Area = 4.0m, - ClimateControlled = true, - Description = "Kho điều hòa mát mẻ, phù hợp đồ nội thất, thiết bị điện tử, hàng shop online", - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }, - new() - { - TypeName = "Kho Lớn L (3m x 3m)", - Length = 3.0m, - Width = 3.0m, - Height = 3.0m, - Area = 9.0m, - ClimateControlled = true, - Description = "Kho điều hòa sức chứa lớn, phù hợp lưu trữ đồ chuyển nhà 2-3 phòng ngủ", - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }, - new() - { - TypeName = "Kho Doanh Nghiệp XL (4m x 4m)", - Length = 4.0m, - Width = 4.0m, - Height = 3.2m, - Area = 16.0m, - ClimateControlled = true, - Description = "Kho chuyên biệt cho doanh nghiệp lưu trữ tài liệu chứng từ hoặc kiện hàng thương mại", - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - } - }; - - context.UnitTypes.AddRange(types); - await context.SaveChangesAsync(); - } + // 2c. Quyền của STAFF / MANAGER + tài khoản manager01, staff02 (BACKEND-TODO A1) + await EnsureFacilityRolesAsync(context); - var typeS = await context.UnitTypes.FirstAsync(t => t.TypeName.Contains("Kho Mini S")); - var typeM = await context.UnitTypes.FirstAsync(t => t.TypeName.Contains("Kho Tiêu Chuẩn M")); - var typeL = await context.UnitTypes.FirstAsync(t => t.TypeName.Contains("Kho Lớn L")); - var typeXL = await context.UnitTypes.FirstAsync(t => t.TypeName.Contains("Kho Doanh Nghiệp XL")); - - // 5. Rental Rates - if (!await context.RentalRates.AnyAsync()) - { - var today = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-30)); - var rates = new List - { - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeS.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 500000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeM.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 1500000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeL.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 3000000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeS.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 550000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeM.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 1600000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeL.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 3200000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeXL.UnitTypeId, SetBy = admin.UserId, MonthlyRate = 5500000m, EffectiveFrom = today, Status = "ACTIVE", CreatedAt = DateTime.UtcNow }, - }; + var admin = await context.Users.FirstAsync(u => u.Username == "admin"); - context.RentalRates.AddRange(rates); - await context.SaveChangesAsync(); - } + // 3. Danh mục kho theo D17: 4 loại kho, 12 cơ sở, mỗi cơ sở 12 ô + bảng giá + var catalog = await EnsureCatalogAsync(context, admin.UserId); - // 6. Policies + // 4. Policies if (!await context.Policies.AnyAsync()) { var policies = new List @@ -290,170 +178,13 @@ public static async Task SeedAsync(AppDbContext context) await context.SaveChangesAsync(); } - // 7. Storage Units - if (!await context.StorageUnits.AnyAsync()) - { - var units = new List - { - // Tân Bình - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeS.UnitTypeId, UnitNumber = "TB-S-101", Floor = "Tầng 1", Zone = "Khu A", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeS.UnitTypeId, UnitNumber = "TB-S-102", Floor = "Tầng 1", Zone = "Khu A", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeM.UnitTypeId, UnitNumber = "TB-M-103", Floor = "Tầng 1", Zone = "Khu B", Status = "OCCUPIED", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeM.UnitTypeId, UnitNumber = "TB-M-104", Floor = "Tầng 1", Zone = "Khu B", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeL.UnitTypeId, UnitNumber = "TB-L-201", Floor = "Tầng 2", Zone = "Khu C", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = tanBinhFac.FacilityId, UnitTypeId = typeL.UnitTypeId, UnitNumber = "TB-L-202", Floor = "Tầng 2", Zone = "Khu C", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - - // Quận 7 - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeS.UnitTypeId, UnitNumber = "Q7-S-101", Floor = "Tầng 1", Zone = "Khu 1", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeS.UnitTypeId, UnitNumber = "Q7-S-102", Floor = "Tầng 1", Zone = "Khu 1", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeM.UnitTypeId, UnitNumber = "Q7-M-103", Floor = "Tầng 1", Zone = "Khu 2", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeM.UnitTypeId, UnitNumber = "Q7-M-104", Floor = "Tầng 1", Zone = "Khu 2", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeL.UnitTypeId, UnitNumber = "Q7-L-201", Floor = "Tầng 2", Zone = "Khu 3", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - new() { FacilityId = quan7Fac.FacilityId, UnitTypeId = typeXL.UnitTypeId, UnitNumber = "Q7-XL-301", Floor = "Tầng 3", Zone = "Khu VIP", Status = "AVAILABLE", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }, - }; - - context.StorageUnits.AddRange(units); - await context.SaveChangesAsync(); - } - - // 7b. Mạng lưới 12 cơ sở SafeSpace theo thiết kế Figma. - // Chạy lại nhiều lần vẫn an toàn: chỉ thêm cơ sở / bảng giá / phòng kho còn thiếu, - // nên database đã tạo từ trước cũng được bổ sung khi khởi động lại API. - await SeedSafeSpaceNetworkAsync(context, admin.UserId, typeS, typeM, typeL, typeXL); - - // 8. Sample Customer Data (Reservation, Contract, Payment, SupportTicket for customer01) - if (!await context.Reservations.AnyAsync()) - { - var occupiedUnit = await context.StorageUnits.FirstAsync(u => u.UnitNumber == "TB-M-103"); - - // Reservation 1: Converted to Contract - var startDate1 = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-15)); - var endDate1 = startDate1.AddMonths(3); - - var res1 = new Reservation - { - CustomerId = cust1.UserId, - FacilityId = tanBinhFac.FacilityId, - UnitTypeId = typeM.UnitTypeId, - StartDate = startDate1, - ExpectedEndDate = endDate1, - RentalPeriodMonths = 3, - QuotedMonthlyRate = 1500000m, - EstimatedAmount = 4500000m, - RequiredDeposit = 1500000m, - Status = "CHECKED_IN", - CreatedAt = DateTime.UtcNow.AddDays(-16), - ExpiresAt = DateTime.UtcNow.AddDays(-15) - }; - context.Reservations.Add(res1); - await context.SaveChangesAsync(); - - // Contract for Reservation 1 - var contract = new RentalContract - { - ReservationId = res1.ReservationId, - CustomerId = cust1.UserId, - UnitId = occupiedUnit.UnitId, - StartDate = startDate1, - EndDate = endDate1, - AgreedMonthlyRate = 1500000m, - DepositAmount = 1500000m, - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow.AddDays(-15), - ActivatedAt = DateTime.UtcNow.AddDays(-15) - }; - context.RentalContracts.Add(contract); - await context.SaveChangesAsync(); - - // Handover Record - var handover = new HandoverRecord - { - ContractId = contract.ContractId, - StaffId = staff.UserId, - InitialCondition = "Kho sạch sẽ, hệ thống điều hòa hoạt động tốt, đã bàn giao khóa", - ScheduledAt = DateTime.UtcNow.AddDays(-15), - HandoverAt = DateTime.UtcNow.AddDays(-15), - CustomerConfirmed = true, - StaffConfirmed = true, - Status = "HANDED_OVER", - CreatedAt = DateTime.UtcNow.AddDays(-15) - }; - context.HandoverRecords.Add(handover); - - // Payments (Deposit + Rent) - var depositPayment = new Payment - { - ContractId = contract.ContractId, - PaymentType = "DEPOSIT", - Amount = 1500000m, - Currency = "VND", - PaymentMethod = "BANK_TRANSFER", - TransactionReference = "VNPAY-DEP-10001", - DueDate = startDate1, - PaidAt = DateTime.UtcNow.AddDays(-15), - Status = "PAID", - CreatedAt = DateTime.UtcNow.AddDays(-15), - UpdatedAt = DateTime.UtcNow.AddDays(-15) - }; - - var rentPayment = new Payment - { - ContractId = contract.ContractId, - PaymentType = "RENT", - Amount = 1500000m, - Currency = "VND", - PaymentMethod = "BANK_TRANSFER", - TransactionReference = "VNPAY-RENT-10002", - DueDate = startDate1, - PaidAt = DateTime.UtcNow.AddDays(-15), - Status = "PAID", - CreatedAt = DateTime.UtcNow.AddDays(-15), - UpdatedAt = DateTime.UtcNow.AddDays(-15) - }; - - context.Payments.AddRange(depositPayment, rentPayment); - - // Support Ticket - var ticket = new SupportTicket - { - CustomerId = cust1.UserId, - ContractId = contract.ContractId, - UnitId = occupiedUnit.UnitId, - IssueType = "UNIT", - Title = "Kiểm tra nhiệt độ phòng kho", - Description = "Nhờ nhân viên kiểm tra lại nhiệt độ kho TB-M-103 vào buổi trưa", - Priority = "NORMAL", - Status = "OPEN", - CreatedAt = DateTime.UtcNow.AddDays(-2) - }; - context.SupportTickets.Add(ticket); - - // Reservation 2: Pending payment for customer01 - var startDate2 = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(5)); - var res2 = new Reservation - { - CustomerId = cust1.UserId, - FacilityId = tanBinhFac.FacilityId, - UnitTypeId = typeS.UnitTypeId, - StartDate = startDate2, - ExpectedEndDate = startDate2.AddMonths(1), - RentalPeriodMonths = 1, - QuotedMonthlyRate = 500000m, - EstimatedAmount = 500000m, - RequiredDeposit = 500000m, - Status = "PENDING_PAYMENT", - CreatedAt = DateTime.UtcNow, - ExpiresAt = DateTime.UtcNow.AddHours(24) - }; - context.Reservations.Add(res2); - - await context.SaveChangesAsync(); - } + // 5. Phân công cơ sở (SRS A06: mỗi nhân viên / quản lý 1 cơ sở) + dữ liệu vận hành mẫu tại cơ sở đó + await EnsureFacilityAssignmentsAsync(context, catalog.Home.FacilityId, admin.UserId); + await SeedFacilityOperationsAsync(context, catalog); } // ------------------------------------------------------------------------------------------ // Quản lý vận hành kinh doanh (SRS: Business Operations Manager — UC19–UC23) - // Chỉ thêm phần còn thiếu nên DB tạo từ trước cũng được bổ sung khi khởi động lại API. // ------------------------------------------------------------------------------------------ private static async Task EnsureOperationsRoleAsync(AppDbContext context) { @@ -523,113 +254,4 @@ private static async Task EnsureOperationsRoleAsync(AppDbContext context) await context.SaveChangesAsync(); } } - - // ------------------------------------------------------------------------------------------ - // Mạng lưới cơ sở SafeSpace (Figma C02 / Trang chủ) - // RateM = giá kho Tiêu Chuẩn M; các loại khác tính theo tỉ lệ (S ≈ 40%, L = 2×, XL = 3,5×). - // ------------------------------------------------------------------------------------------ - private sealed record SeedFacility(string Code, string Name, string Address, string Phone, int OpenHour, int CloseHour, decimal RateM, bool HasXL); - - private static readonly SeedFacility[] SafeSpaceNetwork = - [ - new("NLB", "SafeSpace Nguyễn Lương Bằng", "12 Nguyễn Lương Bằng, Phường Tân Phú, Quận 7, TP. Hồ Chí Minh", "02837001012", 6, 22, 1150000m, true), - new("HL", "SafeSpace Him Lam", "Khu dân cư Him Lam, Phường Tân Hưng, Quận 7, TP. Hồ Chí Minh", "02837001013", 6, 22, 1050000m, false), - new("PX", "SafeSpace Phú Xuân", "Đường Nguyễn Hữu Thọ, Xã Phú Xuân, Huyện Nhà Bè, TP. Hồ Chí Minh", "02837001014", 6, 22, 890000m, false), - new("TT", "SafeSpace Tân Thuận", "Đường Huỳnh Tấn Phát, Phường Tân Thuận Đông, Quận 7, TP. Hồ Chí Minh", "02837001015", 6, 22, 1100000m, true), - new("PMH", "SafeSpace Phú Mỹ Hưng", "Đường Nguyễn Văn Linh, Phường Tân Phong, Quận 7, TP. Hồ Chí Minh", "02837001016", 6, 22, 1250000m, true), - new("BT", "SafeSpace Bình Thạnh", "Đường Nguyễn Xí, Phường 26, Quận Bình Thạnh, TP. Hồ Chí Minh", "02837001017", 6, 22, 980000m, false), - new("NB", "SafeSpace Nhà Bè", "Đường Huỳnh Tấn Phát, Thị trấn Nhà Bè, Huyện Nhà Bè, TP. Hồ Chí Minh", "02837001018", 6, 22, 850000m, false), - new("BC", "SafeSpace Bình Chánh", "Quốc lộ 50, Xã Bình Hưng, Huyện Bình Chánh, TP. Hồ Chí Minh", "02837001019", 6, 22, 790000m, true), - new("TD", "SafeSpace Thủ Đức", "Đường Võ Văn Ngân, Phường Linh Chiểu, TP. Thủ Đức, TP. Hồ Chí Minh", "02837001020", 6, 22, 920000m, false), - new("GV", "SafeSpace Gò Vấp", "Đường Quang Trung, Phường 10, Quận Gò Vấp, TP. Hồ Chí Minh", "02837001021", 6, 22, 930000m, false), - ]; - - private static decimal RoundRate(decimal value) => Math.Round(value / 10000m, MidpointRounding.AwayFromZero) * 10000m; - - private static async Task SeedSafeSpaceNetworkAsync(AppDbContext context, long adminId, UnitType typeS, UnitType typeM, UnitType typeL, UnitType typeXL) - { - // Đổi tên 2 cơ sở seed ban đầu sang thương hiệu SafeSpace (chỉ đổi khi còn tên cũ) - var renames = new Dictionary - { - ["SSFRMS Chi nhánh Tân Bình"] = "SafeSpace Tân Bình", - ["SSFRMS Chi nhánh Quận 7"] = "SafeSpace Quận 7", - }; - var oldNames = renames.Keys.ToList(); - var toRename = await context.Facilities.Where(f => oldNames.Contains(f.Name)).ToListAsync(); - foreach (var f in toRename) - { - f.Name = renames[f.Name]; - f.UpdatedAt = DateTime.UtcNow; - } - if (toRename.Count > 0) await context.SaveChangesAsync(); - - var effectiveFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-30)); - - foreach (var seed in SafeSpaceNetwork) - { - var facility = await context.Facilities.FirstOrDefaultAsync(f => f.Name == seed.Name); - if (facility == null) - { - facility = new Facility - { - Name = seed.Name, - Address = seed.Address, - ContactPhone = seed.Phone, - OpeningTime = new TimeOnly(seed.OpenHour, 0), - ClosingTime = new TimeOnly(seed.CloseHour, 0), - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }; - context.Facilities.Add(facility); - await context.SaveChangesAsync(); - } - - // (loại kho, giá/tháng, số phòng, ký hiệu, số phòng bắt đầu, tầng, khu) - var plan = new List<(UnitType Type, decimal Rate, int Count, string Size, int FirstNo, string Floor, string Zone)> - { - (typeS, RoundRate(seed.RateM * 0.4m), 2, "S", 101, "Tầng 1", "Khu A"), - (typeM, seed.RateM, 2, "M", 111, "Tầng 1", "Khu B"), - (typeL, RoundRate(seed.RateM * 2m), 1, "L", 201, "Tầng 2", "Khu C"), - }; - if (seed.HasXL) plan.Add((typeXL, RoundRate(seed.RateM * 3.5m), 1, "XL", 301, "Tầng 3", "Khu D")); - - foreach (var item in plan) - { - var hasRate = await context.RentalRates.AnyAsync(r => r.FacilityId == facility.FacilityId && r.UnitTypeId == item.Type.UnitTypeId); - if (!hasRate) - { - context.RentalRates.Add(new RentalRate - { - FacilityId = facility.FacilityId, - UnitTypeId = item.Type.UnitTypeId, - SetBy = adminId, - MonthlyRate = item.Rate, - EffectiveFrom = effectiveFrom, - Status = "ACTIVE", - CreatedAt = DateTime.UtcNow - }); - } - - for (var i = 0; i < item.Count; i++) - { - var unitNumber = $"{seed.Code}-{item.Size}-{item.FirstNo + i}"; - var exists = await context.StorageUnits.AnyAsync(u => u.FacilityId == facility.FacilityId && u.UnitNumber == unitNumber); - if (exists) continue; - context.StorageUnits.Add(new StorageUnit - { - FacilityId = facility.FacilityId, - UnitTypeId = item.Type.UnitTypeId, - UnitNumber = unitNumber, - Floor = item.Floor, - Zone = item.Zone, - Status = "AVAILABLE", - CreatedAt = DateTime.UtcNow, - UpdatedAt = DateTime.UtcNow - }); - } - } - await context.SaveChangesAsync(); - } - } } diff --git a/StorageProject.Infrastructure/Migrations/20261014150000_ReservationPendingVerification.cs b/StorageProject.Infrastructure/Migrations/20261014150000_ReservationPendingVerification.cs new file mode 100644 index 0000000..e6752ba --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261014150000_ReservationPendingVerification.cs @@ -0,0 +1,47 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using StorageProject.Infrastructure.Data; + +#nullable disable + +namespace StorageProject.Infrastructure.Migrations +{ + /// + /// F03 / BACKEND-TODO A4: đơn đặt chỗ có thêm trạng thái PENDING_VERIFICATION + /// (khách đã bấm "Tôi đã chuyển khoản", chờ nhân viên đối soát). + /// Viết tay vì chỉ đổi một ràng buộc CHECK; AppDbContextModelSnapshot đã cập nhật tương ứng. + /// + [DbContext(typeof(AppDbContext))] + [Migration("20261014150000_ReservationPendingVerification")] + public partial class ReservationPendingVerification : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropCheckConstraint( + name: "CK_reservations_status", + table: "reservations"); + + migrationBuilder.AddCheckConstraint( + name: "CK_reservations_status", + table: "reservations", + sql: "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + // Đơn đang chờ đối soát quay về chờ chuyển khoản trước khi bỏ trạng thái + migrationBuilder.Sql("UPDATE [reservations] SET [Status] = 'PENDING_PAYMENT' WHERE [Status] = 'PENDING_VERIFICATION'"); + + migrationBuilder.DropCheckConstraint( + name: "CK_reservations_status", + table: "reservations"); + + migrationBuilder.AddCheckConstraint( + name: "CK_reservations_status", + table: "reservations", + sql: "[Status] IN ('PENDING_PAYMENT','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index a2c6714..f8886b4 100644 --- a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -865,7 +865,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); - t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); }); }); diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs new file mode 100644 index 0000000..0bafe6c --- /dev/null +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs @@ -0,0 +1,498 @@ +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Services; + +/// +/// Thao tác của nhân viên (S02–S05, S09) và quản lý (M03, M05–M07). Mỗi thao tác lưu trong một lần SaveChanges +/// (một giao dịch) và ghi activity_logs. Điều kiện chặn giống src/ops/reducer.js (có test ở giao diện). +/// +public partial class FacilityOpsService +{ + private static readonly Regex DocNumberPattern = new(@"^\d{9}$|^\d{12}$|^[A-Z]\d{7}$", RegexOptions.IgnoreCase); + private static readonly string[] UnlockMethods = ["CARD", "PIN", "FINGER"]; + private static readonly string[] TicketNextStates = ["IN_PROGRESS", "WAITING_CUSTOMER", "DONE"]; + + // ------------------------------------------------------------------ + // Tải thực thể trong cơ sở được phân công (khác cơ sở → 404, không lộ dữ liệu) + // ------------------------------------------------------------------ + private async Task ReservationAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "SS-", "đơn đặt chỗ"); + return await dbContext.Reservations + .Include(r => r.UnitType) + .Include(r => r.UnitAssignments) + .FirstOrDefaultAsync(r => r.ReservationId == id && r.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy đơn đặt chỗ tại cơ sở của bạn."); + } + + private async Task HandoverAsync(long facilityId, string code, string prefix, CancellationToken ct) + { + var id = ParseCode(code, prefix, prefix == "XM-" ? "lịch xác minh" : "phiếu bàn giao"); + return await dbContext.HandoverRecords + .Include(h => h.Contract).ThenInclude(c => c.Unit) + .Include(h => h.Contract).ThenInclude(c => c.Reservation) + .Include(h => h.Contract).ThenInclude(c => c.AccessCredentials) + .FirstOrDefaultAsync(h => h.HandoverId == id && h.Contract.Unit.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy lịch bàn giao tại cơ sở của bạn."); + } + + private async Task InspectionAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "TK-", "lịch trả kho"); + return await dbContext.ReturnInspections + .Include(i => i.Contract).ThenInclude(c => c.Unit) + .Include(i => i.Contract).ThenInclude(c => c.AccessCredentials) + .FirstOrDefaultAsync(i => i.InspectionId == id && i.Contract.Unit.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy lịch trả kho tại cơ sở của bạn."); + } + + private async Task TicketAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "HT-", "yêu cầu hỗ trợ"); + return await dbContext.SupportTickets + .FirstOrDefaultAsync(t => t.TicketId == id + && ((t.Unit != null && t.Unit.FacilityId == facilityId) + || (t.Contract != null && t.Contract.Unit.FacilityId == facilityId)), ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu hỗ trợ tại cơ sở của bạn."); + } + + private async Task ContractAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "HĐ-", "hợp đồng"); + return await dbContext.RentalContracts + .Include(c => c.Unit) + .Include(c => c.Payments) + .Include(c => c.ReturnInspections) + .Include(c => c.OverdueCases) + .Include(c => c.AccessCredentials) + .FirstOrDefaultAsync(c => c.ContractId == id && c.Unit.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy hợp đồng tại cơ sở của bạn."); + } + + // ===================================================================== + // S09 · Đối soát chuyển khoản + // ===================================================================== + public async Task ConfirmPaymentAsync(OpsActor actor, string id, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var r = await ReservationAsync(facility.FacilityId, id, ct); + if (r.Status != "PENDING_VERIFICATION") throw new InvalidOperationException("Khoản này đã được xử lý."); + + // Chưa có ô kho → vào hàng chờ phân bổ của quản lý (M05) + r.Status = "CONFIRMED"; + Log(actor.UserId, LogAction.PaymentConfirmed, LogEntity.Reservation, r.ReservationId, new { amount = r.EstimatedAmount + r.RequiredDeposit }); + await dbContext.SaveChangesAsync(ct); + } + + public async Task ReportMismatchAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var r = await ReservationAsync(facility.FacilityId, id, ct); + if (r.Status != "PENDING_VERIFICATION") throw new InvalidOperationException("Khoản này đã được xử lý."); + var note = Clip(request.Note, 500); + if (note.Length == 0) throw new ArgumentException("Vui lòng ghi rõ sai lệch (số tiền, nội dung hoặc thời gian)."); + + var last = await dbContext.ActivityLogs + .Where(l => l.EntityType == LogEntity.Reservation && l.EntityId == r.ReservationId + && (l.Action == LogAction.PaymentMismatch || l.Action == LogAction.TransferReported)) + .OrderByDescending(l => l.LoggedAt) + .FirstOrDefaultAsync(ct); + if (last?.Action == LogAction.PaymentMismatch) throw new InvalidOperationException("Khoản này đã được xử lý."); + + // Đơn vẫn chờ đối soát; quản lý liên hệ khách rồi nhân viên xác nhận lại khi đã khớp + Log(actor.UserId, LogAction.PaymentMismatch, LogEntity.Reservation, r.ReservationId, new { note }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // S02 · Xác minh khách khi đến nhận kho — chỉ lưu 4 số cuối giấy tờ + // ===================================================================== + public async Task VerifyCustomerAsync(OpsActor actor, string id, OpsVerifyRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var h = await HandoverAsync(facility.FacilityId, id, "XM-", ct); + if (h.Status != "SCHEDULED") throw new InvalidOperationException("Khách hàng này đã được xác minh."); + + var docNumber = (request.DocNumber ?? string.Empty).Trim(); + if (!DocNumberPattern.IsMatch(docNumber)) + { + throw new ArgumentException("Số giấy tờ gồm 9 hoặc 12 chữ số (CCCD/CMND) hoặc 1 chữ + 7 số (hộ chiếu)."); + } + if (!request.PhotoMatched || !request.InfoMatched) + { + throw new ArgumentException("Đánh dấu cả hai mục đối chiếu trước khi xác minh."); + } + + var docType = Clip(request.DocType, 50); + h.Status = "VERIFIED"; + h.VerifiedAt = NowUtc; + if (!actor.IsManager) h.StaffId = actor.UserId; + Log(actor.UserId, LogAction.CustomerVerified, LogEntity.Handover, h.HandoverId, + new { docType = docType.Length > 0 ? docType : "Căn cước công dân", docLast4 = docNumber[^4..] }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // S03 · Bàn giao kho + cấp phương thức mở khoá + // ===================================================================== + public async Task CompleteHandoverAsync(OpsActor actor, string id, OpsHandoverRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var h = await HandoverAsync(facility.FacilityId, id, "BG-", ct); + if (h.Status == "HANDED_OVER") throw new InvalidOperationException("Kho này đã được bàn giao."); + if (h.Status != "VERIFIED") throw new InvalidOperationException("Cần xác minh khách hàng trước khi bàn giao kho."); + var method = (request.UnlockMethod ?? string.Empty).Trim().ToUpperInvariant(); + if (!UnlockMethods.Contains(method)) throw new ArgumentException("Chọn phương thức mở khoá."); + + var contract = h.Contract; + if (contract.Status != "DRAFT") throw new InvalidOperationException("Hợp đồng không ở trạng thái chờ bàn giao."); + + var now = NowUtc; + h.Status = "HANDED_OVER"; + h.HandoverAt = now; + h.StaffConfirmed = true; + h.CustomerConfirmed = true; // khách có mặt và ký nhận tại quầy + if (!actor.IsManager) h.StaffId = actor.UserId; + + contract.Status = "ACTIVE"; + contract.ActivatedAt = now; + contract.Reservation.Status = "CHECKED_IN"; + SetUnitStatus(contract.Unit, "OCCUPIED", actor.UserId, $"Bàn giao cho khách · {HandoverCode(h.HandoverId)}"); + + foreach (var old in contract.AccessCredentials.Where(a => a.Status == "ACTIVE")) + { + old.Status = "REPLACED"; + old.ReturnedAt = now; + } + // Thẻ từ → ACCESS_CARD; mã PIN và vân tay đăng ký tại máy → ACCESS_CODE (không lưu bí mật) + dbContext.AccessCredentials.Add(new AccessCredential + { + ContractId = contract.ContractId, + UnitId = contract.UnitId, + IssuedBy = actor.UserId, + CredentialType = method == "CARD" ? "ACCESS_CARD" : "ACCESS_CODE", + CredentialReference = $"{method}-{contract.Unit.UnitNumber}-{now + VnOffset:yyMMdd}", + IssuedAt = now, + Status = "ACTIVE" + }); + Log(actor.UserId, LogAction.HandoverCompleted, LogEntity.Handover, h.HandoverId, new { method }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // S04 · Kiểm tra trả kho → chờ quản lý xác nhận hoàn cọc + // ===================================================================== + public async Task SubmitReturnInspectionAsync(OpsActor actor, string id, OpsReturnInspectionRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var i = await InspectionAsync(facility.FacilityId, id, ct); + if (i.Status == "COMPLETED") throw new InvalidOperationException("Biên bản trả kho đã được gửi."); + if (i.Status == "CANCELLED") throw new InvalidOperationException("Lịch trả kho đã huỷ."); + + var items = Clip(request.Items, 500); + var walls = Clip(request.Walls, 500); + var keys = Clip(request.Keys, 500); + var proposal = Clip(request.Proposal, 500); + if (items.Length == 0 || walls.Length == 0 || keys.Length == 0 || proposal.Length == 0) + { + throw new ArgumentException("Điền đủ 4 mục kiểm tra trước khi gửi biên bản."); + } + + var now = NowUtc; + i.Status = "COMPLETED"; + i.InspectedAt = now; + i.DamageDescription = walls; + i.Notes = $"Đồ đạc còn lại: {items}\nTường, sàn, cửa: {walls}\nChìa khoá, thẻ: {keys}\nĐề xuất: {proposal}"; + if (!actor.IsManager) i.StaffId = actor.UserId; + + var contract = i.Contract; + if (contract.Status is "ACTIVE" or "EXPIRING" or "OVERDUE") contract.Status = "RETURN_PENDING"; + SetUnitStatus(contract.Unit, "INSPECTION", actor.UserId, $"Khách trả kho · {ReturnCode(i.InspectionId)}"); + foreach (var cred in contract.AccessCredentials.Where(a => a.Status == "ACTIVE")) + { + cred.Status = "RETURNED"; + cred.ReturnedAt = now; + } + Log(actor.UserId, LogAction.ReturnInspected, LogEntity.Return, i.InspectionId, new { items, walls, keys, proposal }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // S05 · Phản hồi yêu cầu hỗ trợ + // ===================================================================== + public async Task RespondTicketAsync(OpsActor actor, string id, OpsTicketResponseRequest request, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var t = await TicketAsync(facility.FacilityId, id, ct); + if (t.Status is "CLOSED" or "CANCELLED") throw new InvalidOperationException("Yêu cầu đã đóng."); + var note = Clip(request.Note, 1000); + if (note.Length == 0) throw new ArgumentException("Ghi nhận nội dung xử lý trước khi lưu."); + var next = (request.NextStatus ?? string.Empty).Trim().ToUpperInvariant(); + if (!TicketNextStates.Contains(next)) throw new ArgumentException("Chọn trạng thái tiếp theo."); + + var now = NowUtc; + if (t.AssignedStaffId == null) + { + t.AssignedStaffId = actor.UserId; + t.AssignedAt = now; + } + switch (next) + { + case "IN_PROGRESS": + t.Status = "IN_PROGRESS"; + break; + case "WAITING_CUSTOMER": // đã xử lý, chờ khách xác nhận + t.Status = "RESOLVED"; + t.ResolvedAt = now; + break; + default: // DONE + t.Status = "CLOSED"; + t.ResolvedAt ??= now; + t.ClosedAt = now; + break; + } + Log(actor.UserId, LogAction.TicketResponse, LogEntity.Ticket, t.TicketId, new { note, status = next, staff = StaffCode(actor.UserId) }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // M05 · Phân bổ ô cho đơn đã đối soát → hợp đồng nháp + lịch xác minh / bàn giao + // ===================================================================== + public async Task AllocateAsync(OpsActor actor, string id, OpsAllocateRequest request, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var r = await ReservationAsync(facility.FacilityId, id, ct); + if (r.Status == "UNIT_ASSIGNED" || r.UnitAssignments.Any(a => a.Status == "ACTIVE")) + { + throw new InvalidOperationException("Đơn này đã được phân bổ kho."); + } + if (r.Status != "CONFIRMED") throw new InvalidOperationException("Đơn chưa được xác nhận thanh toán nên chưa phân bổ được."); + + var unitCode = (request.UnitCode ?? string.Empty).Trim(); + var unit = await dbContext.StorageUnits + .FirstOrDefaultAsync(u => u.FacilityId == facility.FacilityId && u.UnitNumber == unitCode, ct); + if (unit == null || unit.Status != "AVAILABLE" || unit.UnitTypeId != r.UnitTypeId) + { + throw new InvalidOperationException("Kho đã chọn không còn trống hoặc không khớp đơn đặt chỗ."); + } + var busy = await dbContext.RentalContracts.AnyAsync(c => c.UnitId == unit.UnitId + && HeldContractStatuses.Contains(c.Status) + && c.StartDate < r.ExpectedEndDate && c.EndDate > r.StartDate, ct); + if (busy) throw new InvalidOperationException("Kho đã chọn không còn trống hoặc không khớp đơn đặt chỗ."); + + var now = NowUtc; + var code = ReservationCode(r); + var confirmedAt = await dbContext.ActivityLogs + .Where(l => l.EntityType == LogEntity.Reservation && l.EntityId == r.ReservationId && l.Action == LogAction.PaymentConfirmed) + .OrderByDescending(l => l.LoggedAt) + .Select(l => (DateTime?)l.LoggedAt) + .FirstOrDefaultAsync(ct) ?? now; + + dbContext.UnitAssignments.Add(new UnitAssignment + { + ReservationId = r.ReservationId, UnitId = unit.UnitId, AssignedBy = actor.UserId, Status = "ACTIVE", AssignedAt = now + }); + r.Status = "UNIT_ASSIGNED"; + SetUnitStatus(unit, "RESERVED", actor.UserId, $"Phân bổ cho đơn {code}"); + + var contract = new RentalContract + { + ReservationId = r.ReservationId, CustomerId = r.CustomerId, UnitId = unit.UnitId, + StartDate = r.StartDate, EndDate = r.ExpectedEndDate, AgreedMonthlyRate = r.QuotedMonthlyRate, + DepositAmount = r.RequiredDeposit, Status = "DRAFT", CreatedAt = now + }; + // Khoản khách đã chuyển (nhân viên đã đối soát ở S09): cọc + tiền thuê cả kỳ + foreach (var (kind, amount) in new[] { ("DEPOSIT", r.RequiredDeposit), ("RENT", r.EstimatedAmount) }) + { + contract.Payments.Add(new Payment + { + PaymentType = kind, Amount = amount, Currency = "VND", PaymentMethod = "BANK_TRANSFER", + TransactionReference = code, DueDate = r.StartDate, PaidAt = confirmedAt, Status = "PAID", + CreatedAt = now, UpdatedAt = now + }); + } + // Chưa giao cho nhân viên nào: người phụ trách tạm là quản lý (bảng M06 hiện "Cần xử lý") + contract.HandoverRecord = new HandoverRecord + { + StaffId = actor.UserId, + ScheduledAt = r.CheckInAppointmentAt ?? UtcFromLocal(r.StartDate, 9), + Status = "SCHEDULED", + CreatedAt = now + }; + dbContext.RentalContracts.Add(contract); + Log(actor.UserId, LogAction.UnitAllocated, LogEntity.Reservation, r.ReservationId, new { unit = unit.UnitNumber }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // M06 · Giao việc bàn giao / trả kho / hỗ trợ cho nhân viên cùng cơ sở + // ===================================================================== + public async Task AssignAsync(OpsActor actor, string id, OpsAssignRequest request, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var staff = await FacilityStaffAsync(facility.FacilityId, ct); + var staffUser = staff.FirstOrDefault(u => StaffCode(u.UserId) == (request.StaffId ?? string.Empty).Trim()) + ?? throw new ArgumentException("Chọn nhân viên phụ trách."); + + var reference = (id ?? string.Empty).Trim(); + if (reference.StartsWith("PC-", StringComparison.OrdinalIgnoreCase)) reference = reference[3..]; + + if (reference.StartsWith("BG-", StringComparison.OrdinalIgnoreCase)) + { + var h = await HandoverAsync(facility.FacilityId, reference, "BG-", ct); + if (h.Status is "HANDED_OVER" or "CANCELLED") throw new InvalidOperationException("Công việc đã hoàn tất."); + h.StaffId = staffUser.UserId; + Log(actor.UserId, LogAction.TaskAssigned, LogEntity.Handover, h.HandoverId, new { staff = StaffCode(staffUser.UserId) }); + } + else if (reference.StartsWith("TK-", StringComparison.OrdinalIgnoreCase)) + { + var i = await InspectionAsync(facility.FacilityId, reference, ct); + if (i.Status is "COMPLETED" or "CANCELLED") throw new InvalidOperationException("Công việc đã hoàn tất."); + i.StaffId = staffUser.UserId; + Log(actor.UserId, LogAction.TaskAssigned, LogEntity.Return, i.InspectionId, new { staff = StaffCode(staffUser.UserId) }); + } + else if (reference.StartsWith("HT-", StringComparison.OrdinalIgnoreCase)) + { + var t = await TicketAsync(facility.FacilityId, reference, ct); + if (t.Status is "RESOLVED" or "CLOSED" or "CANCELLED") throw new InvalidOperationException("Công việc đã hoàn tất."); + t.AssignedStaffId = staffUser.UserId; + t.AssignedAt = NowUtc; + if (t.Status == "OPEN") t.Status = "ASSIGNED"; + Log(actor.UserId, LogAction.TaskAssigned, LogEntity.Ticket, t.TicketId, new { staff = StaffCode(staffUser.UserId) }); + } + else + { + throw new KeyNotFoundException("Không tìm thấy công việc."); + } + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // M03 · Duyệt / từ chối gia hạn + // ===================================================================== + private async Task RenewalAsync(long facilityId, string code, CancellationToken ct) + { + var id = ParseCode(code, "GH-", "yêu cầu gia hạn"); + return await dbContext.ContractRenewals + .Include(r => r.Contract).ThenInclude(c => c.Unit) + .FirstOrDefaultAsync(r => r.RenewalId == id && r.Contract.Unit.FacilityId == facilityId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu gia hạn tại cơ sở của bạn."); + } + + public async Task ApproveRenewalAsync(OpsActor actor, string id, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var r = await RenewalAsync(facility.FacilityId, id, ct); + if (r.Status != "PENDING") throw new InvalidOperationException("Yêu cầu này đã được xử lý."); + var contract = r.Contract; + if (contract.Status is not ("ACTIVE" or "EXPIRING" or "OVERDUE")) + { + throw new InvalidOperationException("Hợp đồng không còn hiệu lực để gia hạn."); + } + + var now = NowUtc; + r.Status = "APPROVED"; + r.ApprovedBy = actor.UserId; + r.ApprovedAt = now; + contract.EndDate = r.NewEndDate; + if (contract.Status is "EXPIRING" or "OVERDUE") contract.Status = "ACTIVE"; + + // Khoản gia hạn khách cần thanh toán (hiện ở "Thanh toán" của khách) + dbContext.Payments.Add(new Payment + { + ContractId = contract.ContractId, RenewalId = r.RenewalId, PaymentType = "RENEWAL", Amount = r.RenewalAmount, + Currency = "VND", PaymentMethod = "BANK_TRANSFER", DueDate = r.OldEndDate, Status = "PENDING", + CreatedAt = now, UpdatedAt = now + }); + Log(actor.UserId, LogAction.RenewalApproved, LogEntity.Renewal, r.RenewalId, new { newEndDate = r.NewEndDate.ToString("yyyy-MM-dd") }); + await dbContext.SaveChangesAsync(ct); + } + + public async Task RejectRenewalAsync(OpsActor actor, string id, OpsRejectRequest request, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var r = await RenewalAsync(facility.FacilityId, id, ct); + if (r.Status != "PENDING") throw new InvalidOperationException("Yêu cầu này đã được xử lý."); + var reason = Clip(request.Reason, 500); + if (reason.Length == 0) throw new ArgumentException("Nhập lý do từ chối để gửi cho khách hàng."); + + r.Status = "REJECTED"; + r.ApprovedBy = actor.UserId; // người quyết định + r.ApprovedAt = NowUtc; + Log(actor.UserId, LogAction.RenewalRejected, LogEntity.Renewal, r.RenewalId, new { reason }); + await dbContext.SaveChangesAsync(ct); + } + + // ===================================================================== + // M07 · Nhắc khách / xác nhận hoàn cọc sau trả kho + // ===================================================================== + public async Task RemindAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var contract = await ContractAsync(facility.FacilityId, id, ct); + var note = Clip(request.Note, 500); + if (note.Length == 0) note = "Đã liên hệ nhắc khách thanh toán / xử lý hợp đồng."; + + var stamp = (NowUtc + VnOffset).ToString("dd/MM/yyyy HH:mm", Invariant); + foreach (var oc in contract.OverdueCases.Where(o => o.Status is not ("RESOLVED" or "ESCALATED"))) + { + oc.Status = "CONTACTED"; + oc.Notes = string.IsNullOrWhiteSpace(oc.Notes) ? $"{stamp}: {note}" : $"{oc.Notes}\n{stamp}: {note}"; + } + Log(actor.UserId, LogAction.OverdueReminder, LogEntity.Contract, contract.ContractId, new { note }); + await dbContext.SaveChangesAsync(ct); + } + + public async Task ConfirmRefundAsync(OpsActor actor, string id, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var contract = await ContractAsync(facility.FacilityId, id, ct); + if (contract.Status != "RETURN_PENDING" || !contract.ReturnInspections.Any(i => i.Status == "COMPLETED")) + { + throw new InvalidOperationException("Hợp đồng chưa có biên bản trả kho."); + } + + var now = NowUtc; + var unpaidPayments = contract.Payments.Where(p => (p.Status == "PENDING" || p.Status == "FAILED") && p.PaymentType != "REFUND").ToList(); + var unpaid = unpaidPayments.Sum(p => p.Amount); + var refund = Math.Max(0, contract.DepositAmount - unpaid); + + // Khoản còn nợ được trừ vào tiền cọc + foreach (var p in unpaidPayments) + { + p.Status = "PAID"; + p.PaidAt = now; + p.TransactionReference = "Trừ vào tiền cọc"; + p.UpdatedAt = now; + } + if (refund > 0) + { + dbContext.Payments.Add(new Payment + { + ContractId = contract.ContractId, PaymentType = "REFUND", Amount = refund, Currency = "VND", + PaymentMethod = "BANK_TRANSFER", TransactionReference = $"Hoàn cọc {ContractCode(contract)}", + PaidAt = now, Status = "PAID", CreatedAt = now, UpdatedAt = now + }); + } + contract.Status = "COMPLETED"; + contract.CompletedAt = now; + foreach (var oc in contract.OverdueCases.Where(o => o.Status != "RESOLVED")) + { + oc.Status = "RESOLVED"; + oc.ResolvedAt = now; + } + SetUnitStatus(contract.Unit, "AVAILABLE", actor.UserId, $"Đã trả kho, hoàn cọc · {ContractCode(contract)}"); + Log(actor.UserId, LogAction.DepositRefunded, LogEntity.Contract, contract.ContractId, new { refund, deducted = unpaid }); + await dbContext.SaveChangesAsync(ct); + return refund; + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs new file mode 100644 index 0000000..d599f22 --- /dev/null +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs @@ -0,0 +1,386 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Services; + +/// GET /api/ops/board — toàn bộ dữ liệu màn S01–S09 (và M01–M08 nếu là quản lý) của cơ sở được phân công. +public partial class FacilityOpsService +{ + public async Task GetBoardAsync(OpsActor actor, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var fid = facility.FacilityId; + var now = NowUtc; + var today = VnToday; + var recent = now.AddDays(-RecentDays); + + var staffUsers = await FacilityStaffAsync(fid, ct); + var staffIds = staffUsers.Select(u => u.UserId).ToHashSet(); + string? StaffOf(long? userId) => userId.HasValue && staffIds.Contains(userId.Value) ? StaffCode(userId.Value) : null; + var shift = Shift(facility); + + var meUser = await dbContext.Users.AsNoTracking().FirstAsync(u => u.UserId == actor.UserId, ct); + var me = new OpsStaffDto(StaffCode(meUser.UserId), meUser.FullName, shift); + var staff = staffUsers.Select(u => new OpsStaffDto(StaffCode(u.UserId), u.FullName, shift)).ToList(); + + // ---- Dữ liệu gốc của cơ sở + var units = await dbContext.StorageUnits + .AsNoTracking() + .Include(u => u.UnitType) + .Where(u => u.FacilityId == fid) + .OrderBy(u => u.UnitNumber) + .ToListAsync(ct); + + var contracts = await dbContext.RentalContracts + .AsNoTracking() + .AsSplitQuery() + .Include(c => c.Customer) + .Include(c => c.Reservation) + .Include(c => c.Unit).ThenInclude(u => u.UnitType) + .Include(c => c.HandoverRecord) + .Include(c => c.ReturnInspections) + .Include(c => c.ContractRenewals) + .Include(c => c.Payments) + .Include(c => c.AccessCredentials) + .Where(c => c.Unit.FacilityId == fid + && (HeldContractStatuses.Contains(c.Status) + || (c.Status == "COMPLETED" && c.CompletedAt >= recent))) + .ToListAsync(ct); + + var reservations = await dbContext.Reservations + .AsNoTracking() + .Include(r => r.Customer) + .Include(r => r.UnitType) + .Include(r => r.UnitAssignments).ThenInclude(a => a.Unit) + .Where(r => r.FacilityId == fid + && (r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED" + || ((r.Status == "UNIT_ASSIGNED" || r.Status == "CHECKED_IN") && r.CreatedAt >= now.AddDays(-60)))) + .ToListAsync(ct); + + var tickets = await dbContext.SupportTickets + .AsNoTracking() + .Include(t => t.Customer) + .Include(t => t.Unit) + .Include(t => t.Contract).ThenInclude(c => c!.Unit) + .Where(t => ((t.Unit != null && t.Unit.FacilityId == fid) || (t.Contract != null && t.Contract.Unit.FacilityId == fid)) + && t.Status != "CANCELLED" + && ((t.Status != "RESOLVED" && t.Status != "CLOSED") + || (t.ClosedAt ?? t.ResolvedAt ?? t.CreatedAt) >= recent)) + .OrderByDescending(t => t.CreatedAt) + .ToListAsync(ct); + + var reservationLogs = await LogsAsync(LogEntity.Reservation, reservations.Select(r => r.ReservationId).ToList(), ct); + var handoverLogs = await LogsAsync(LogEntity.Handover, contracts.Where(c => c.HandoverRecord != null).Select(c => c.HandoverRecord!.HandoverId).ToList(), ct); + var returnLogs = await LogsAsync(LogEntity.Return, contracts.SelectMany(c => c.ReturnInspections).Select(i => i.InspectionId).ToList(), ct); + var ticketLogs = await LogsAsync(LogEntity.Ticket, tickets.Select(t => t.TicketId).ToList(), ct); + var renewalLogs = await LogsAsync(LogEntity.Renewal, contracts.SelectMany(c => c.ContractRenewals).Select(r => r.RenewalId).ToList(), ct); + var contractLogs = await LogsAsync(LogEntity.Contract, contracts.Select(c => c.ContractId).ToList(), ct); + + ActivityLog? Last(List logs, long id, params string[] actions) => + logs.LastOrDefault(l => l.EntityId == id && actions.Contains(l.Action)); + + // ---- M01/M02 · Ô kho + var heldByUnit = contracts + .Where(c => HeldContractStatuses.Contains(c.Status)) + .GroupBy(c => c.UnitId) + .ToDictionary(g => g.Key, g => g.OrderByDescending(c => c.CreatedAt).First()); + + string UnitState(StorageUnit u) + { + heldByUnit.TryGetValue(u.UnitId, out var c); + switch (u.Status) + { + case "AVAILABLE": return "EMPTY"; + case "RESERVED": + case "ASSIGNED": return "WAITING_HANDOVER"; + case "INSPECTION": return "INSPECTION"; + case "MAINTENANCE": + case "OUT_OF_SERVICE": return "MAINTENANCE"; + } + 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"; + return "ACTIVE"; + } + + var unitDtos = units.Select(u => + { + heldByUnit.TryGetValue(u.UnitId, out var c); + var floor = (u.Floor ?? string.Empty).Replace("Tầng", string.Empty).Trim(); + return new OpsUnitDto(u.UnitNumber, c?.Customer.FullName, u.UnitType.Area, floor.Length > 0 ? floor : "trệt", + TypeKey(u.UnitType), UnitState(u), c?.EndDate); + }).ToList(); + + // ---- S09 · Đối soát chuyển khoản + var payments = new List(); + foreach (var r in reservations) + { + var reported = Last(reservationLogs, r.ReservationId, LogAction.TransferReported); + var decision = Last(reservationLogs, r.ReservationId, LogAction.PaymentConfirmed, LogAction.PaymentMismatch); + string status; + if (r.Status == "PENDING_VERIFICATION") + { + status = decision?.Action == LogAction.PaymentMismatch && (reported == null || decision.LoggedAt >= reported.LoggedAt) ? "MISMATCH" : "PENDING"; + } + else if (decision?.Action == LogAction.PaymentConfirmed && decision.LoggedAt >= now.AddDays(-3)) + { + status = "CONFIRMED"; + } + else continue; + + var code = ReservationCode(r); + payments.Add(new OpsPaymentDto( + code, r.Customer.FullName, r.EstimatedAmount + r.RequiredDeposit, "Chuyển khoản ngân hàng", + Local(reported?.LoggedAt ?? r.CreatedAt)!, code, OfferLabel(r.UnitType), r.StartDate, r.ExpectedEndDate, + LocalOrDate(r.CheckInAppointmentAt, r.StartDate), status, + status == "MISMATCH" ? Read(decision!, "note") : null, + status == "PENDING" ? null : Local(decision?.LoggedAt))); + } + payments = payments.OrderBy(p => p.Status == "PENDING" ? 0 : 1).ThenByDescending(p => p.ReportedAt).ToList(); + + // ---- S02 / S03 · Xác minh khách + bàn giao + var handoverContracts = contracts + .Where(c => c.HandoverRecord != null + && c.HandoverRecord.Status != "CANCELLED" + && (c.HandoverRecord.Status != "HANDED_OVER" || c.HandoverRecord.HandoverAt >= now.AddDays(-3))) + .OrderBy(c => c.HandoverRecord!.ScheduledAt) + .ToList(); + + var verifications = handoverContracts.Select(c => + { + var h = c.HandoverRecord!; + var verified = Last(handoverLogs, h.HandoverId, LogAction.CustomerVerified); + return new OpsVerificationDto( + VerificationCode(h.HandoverId), ReservationCode(c.Reservation), c.Customer.FullName, c.Unit.UnitNumber, + LocalOrDate(h.ScheduledAt, c.StartDate), h.Status == "SCHEDULED" ? "TODO" : "DONE", + verified != null ? Read(verified, "docType") : null, + verified != null ? Read(verified, "docLast4") : null, + Local(h.VerifiedAt)); + }).ToList(); + + var handovers = handoverContracts.Select(c => + { + var h = c.HandoverRecord!; + var done = Last(handoverLogs, h.HandoverId, LogAction.HandoverCompleted); + var method = done != null ? Read(done, "method") : h.Status == "HANDED_OVER" ? MethodOf(c.AccessCredentials) : null; + return new OpsHandoverDto(HandoverCode(h.HandoverId), VerificationCode(h.HandoverId), c.Unit.UnitNumber, c.Customer.FullName, + h.Status == "HANDED_OVER" ? "DONE" : "WAITING", method, Local(h.HandoverAt)); + }).ToList(); + + // ---- S04 · Kiểm tra trả kho + var inspections = contracts + .SelectMany(c => c.ReturnInspections.Select(i => (Contract: c, Inspection: i))) + .Where(x => x.Inspection.Status != "CANCELLED" + && (x.Inspection.Status != "COMPLETED" || x.Inspection.InspectedAt >= recent)) + .OrderBy(x => x.Inspection.ScheduledAt) + .ToList(); + + var returns = inspections.Select(x => + { + var (c, i) = x; + var submitted = Last(returnLogs, i.InspectionId, LogAction.ReturnInspected); + OpsReturnReportDto? report = submitted == null ? null : new OpsReturnReportDto( + Read(submitted, "items") ?? "", Read(submitted, "walls") ?? "", Read(submitted, "keys") ?? "", Read(submitted, "proposal") ?? ""); + return new OpsReturnDto(ReturnCode(i.InspectionId), ContractCode(c), c.Unit.UnitNumber, c.Customer.FullName, + LocalOrDate(i.ScheduledAt, c.EndDate), c.DepositAmount, Unpaid(c), i.Status == "COMPLETED" ? "SUBMITTED" : "SCHEDULED", + report, Local(i.InspectedAt)); + }).ToList(); + + // ---- S05 · Yêu cầu hỗ trợ + var ticketDtos = tickets.Select(t => + { + var notes = ticketLogs + .Where(l => l.EntityId == t.TicketId && l.Action == LogAction.TicketResponse) + .Select(l => new OpsNoteDto(Read(l, "note") ?? "", Local(l.LoggedAt)!, Read(l, "staff"))) + .ToList(); + var unitCode = t.Unit?.UnitNumber ?? t.Contract?.Unit.UnitNumber ?? "—"; + return new OpsTicketDto(TicketCode(t.TicketId), unitCode, t.Customer.FullName, t.Title, Local(t.CreatedAt)!, + Local(t.AssignedAt ?? t.CreatedAt)!, TicketState(t), t.AssignedStaffId.HasValue ? StaffCode(t.AssignedStaffId.Value) : null, notes); + }).ToList(); + + if (!actor.IsManager) + { + return new OpsBoardDto(new OpsFacilityInfoDto(fid, facility.Name, facility.Address), me, staff, unitDtos, + payments, verifications, handovers, returns, ticketDtos, null, null, null, null, null); + } + + // ---- M05 · Đơn chờ phân bổ ô + var allocations = new List(); + foreach (var r in reservations) + { + var allocated = Last(reservationLogs, r.ReservationId, LogAction.UnitAllocated); + string status; + string? unit = null; + if (r.Status == "CONFIRMED" && !r.UnitAssignments.Any(a => a.Status == "ACTIVE")) status = "PENDING"; + else if (r.Status == "UNIT_ASSIGNED" && allocated != null && allocated.LoggedAt >= now.AddDays(-3)) + { + status = "DONE"; + unit = r.UnitAssignments.Where(a => a.Status == "ACTIVE").OrderByDescending(a => a.AssignedAt).FirstOrDefault()?.Unit.UnitNumber; + } + else continue; + allocations.Add(new OpsAllocationDto(ReservationCode(r), r.Customer.FullName, TypeKey(r.UnitType), OfferLabel(r.UnitType), + r.UnitType.Area, r.UnitType.Area, r.StartDate, r.ExpectedEndDate, LocalOrDate(r.CheckInAppointmentAt, r.StartDate), status, unit)); + } + allocations = allocations.OrderBy(a => a.Status == "PENDING" ? 0 : 1).ThenBy(a => a.Start).ToList(); + + // ---- M03 · Gia hạn + var renewals = contracts + .SelectMany(c => c.ContractRenewals.Select(r => (Contract: c, Renewal: r))) + .Where(x => x.Renewal.Status == "PENDING" || (x.Renewal.ApprovedAt.HasValue && x.Renewal.ApprovedAt >= recent)) + .OrderBy(x => x.Renewal.Status == "PENDING" ? 0 : 1).ThenBy(x => x.Renewal.RequestedAt) + .Select(x => + { + var (c, r) = x; + var rejected = Last(renewalLogs, r.RenewalId, LogAction.RenewalRejected); + var status = r.Status switch { "PAID" => "APPROVED", "CANCELLED" => "REJECTED", _ => r.Status }; + return new OpsRenewalDto(RenewalCode(r.RenewalId), ContractCode(c), c.Customer.FullName, c.Unit.UnitNumber, + r.OldEndDate, r.NewEndDate, r.RenewalPeriodMonths, Local(r.RequestedAt)!, status, + status == "REJECTED" && rejected != null ? Read(rejected, "reason") : null, Local(r.ApprovedAt)); + }) + .ToList(); + + // ---- M07 · Hợp đồng cần xử lý + var contractDtos = new List(); + foreach (var c in contracts.OrderBy(c => c.EndDate)) + { + var unpaid = Unpaid(c); + var inspected = c.ReturnInspections.Any(i => i.Status == "COMPLETED"); + var lastRenewal = c.ContractRenewals.OrderByDescending(r => r.RequestedAt).FirstOrDefault(); + string state, due; + decimal amount = 0; + + if (c.Status == "COMPLETED") + { + var refunded = Last(contractLogs, c.ContractId, LogAction.DepositRefunded); + if (refunded == null) continue; + state = "CLOSED"; + due = $"Hoàn cọc {Money(decimal.TryParse(Read(refunded, "refund"), System.Globalization.NumberStyles.Number, Invariant, out var rf) ? rf : 0)} sau khi trừ khoản còn nợ"; + } + else if (c.Status == "RETURN_PENDING" && inspected) + { + state = "RETURNED"; + due = $"{Money(unpaid)} · Chờ quản lý xác nhận hoàn cọc"; + amount = unpaid; + } + else if (lastRenewal?.Status == "PENDING") + { + state = "RENEWAL"; + due = "Yêu cầu gia hạn"; + } + else if (c.Status == "OVERDUE" || (c.Status is "ACTIVE" or "EXPIRING" && c.EndDate < today)) + { + state = "OVERDUE"; + due = unpaid > 0 ? "Tiền thuê kỳ mới · Chưa thanh toán" : "Đã hết hạn · Chưa gia hạn hoặc trả kho"; + amount = unpaid; + } + else if (lastRenewal is { ApprovedAt: not null } && lastRenewal.ApprovedAt >= recent) + { + state = "RESOLVED"; + var reason = Read(Last(renewalLogs, lastRenewal.RenewalId, LogAction.RenewalRejected) ?? new ActivityLog(), "reason"); + due = lastRenewal.Status == "REJECTED" + ? $"Từ chối gia hạn · {reason}" + : $"Đã duyệt gia hạn đến {lastRenewal.NewEndDate:dd/MM/yyyy}"; + } + else continue; + + var reminders = contractLogs + .Where(l => l.EntityId == c.ContractId && l.Action == LogAction.OverdueReminder) + .Select(l => new OpsReminderDto(Read(l, "note") ?? "", Local(l.LoggedAt)!)) + .ToList(); + contractDtos.Add(new OpsContractDto(ContractCode(c), c.Customer.FullName, c.Unit.UnitNumber, c.EndDate, due, amount, state, reminders)); + } + + // ---- M06 · Phân công công việc + var assignments = new List(); + foreach (var c in handoverContracts) + { + var h = c.HandoverRecord!; + var done = h.Status == "HANDED_OVER"; + var who = StaffOf(h.StaffId); + assignments.Add(new OpsAssignmentDto($"PC-{HandoverCode(h.HandoverId)}", $"Bàn giao {c.Unit.UnitNumber} · {c.Customer.FullName}", + LocalOrDate(h.ScheduledAt, c.StartDate), who, done ? "DONE" : who == null ? "OPEN" : h.Status == "VERIFIED" ? "ACCEPTED" : "WAITING", + HandoverCode(h.HandoverId))); + } + foreach (var (c, i) in inspections) + { + var who = StaffOf(i.StaffId); + assignments.Add(new OpsAssignmentDto($"PC-{ReturnCode(i.InspectionId)}", $"Kiểm tra trả kho {c.Unit.UnitNumber} · {c.Customer.FullName}", + LocalOrDate(i.ScheduledAt, c.EndDate), who, i.Status == "COMPLETED" ? "DONE" : who == null ? "OPEN" : i.Status == "IN_PROGRESS" ? "ACCEPTED" : "WAITING", + ReturnCode(i.InspectionId))); + } + foreach (var t in tickets) + { + var who = StaffOf(t.AssignedStaffId); + var state = TicketState(t); + assignments.Add(new OpsAssignmentDto($"PC-{TicketCode(t.TicketId)}", $"{TicketCode(t.TicketId)} · {t.Title}", + Local(t.AssignedAt ?? t.CreatedAt), who, + state == "DONE" || state == "WAITING_CUSTOMER" ? "DONE" : who == null ? "OPEN" : state == "IN_PROGRESS" && t.Status == "IN_PROGRESS" ? "ACCEPTED" : "WAITING", + TicketCode(t.TicketId))); + } + assignments = assignments.OrderBy(a => a.Status == "DONE" ? 1 : 0).ThenBy(a => a.When).ToList(); + + var revenue = await RevenueAsync(fid, ct); + + return new OpsBoardDto(new OpsFacilityInfoDto(fid, facility.Name, facility.Address), me, staff, unitDtos, + payments, verifications, handovers, returns, ticketDtos, allocations, renewals, contractDtos, assignments, revenue); + } + + /// + /// Trạng thái hỗ trợ theo giao diện: OPEN (chưa phân công) · IN_PROGRESS · WAITING_CUSTOMER (đã xử lý, chờ khách xác nhận) · DONE. + /// + private static string TicketState(SupportTicket t) => t.Status switch + { + "OPEN" => t.AssignedStaffId.HasValue ? "IN_PROGRESS" : "OPEN", + "ASSIGNED" or "IN_PROGRESS" => "IN_PROGRESS", + "RESOLVED" => "WAITING_CUSTOMER", + _ => "DONE", + }; + + private static string? MethodOf(IEnumerable credentials) + { + var cred = credentials.OrderByDescending(a => a.IssuedAt).FirstOrDefault(); + if (cred == null) return null; + if (cred.CredentialType == "ACCESS_CARD") return "CARD"; + return (cred.CredentialReference ?? string.Empty).StartsWith("FINGER", StringComparison.Ordinal) ? "FINGER" : "PIN"; + } + + /// + /// M04 · Doanh thu thuê và phí 6 tháng gần nhất (triệu đồng, theo ngày thu giờ Việt Nam) — không gồm tiền cọc + /// và hoàn tiền (cùng định nghĩa "rentalAndFeeRevenue" của báo cáo Vận hành KD, SRS 10.2). + /// Cơ cấu theo loại kho là của tháng hiện tại. + /// + private async Task RevenueAsync(long facilityId, CancellationToken ct) + { + var today = VnToday; + var firstMonth = new DateOnly(today.Year, today.Month, 1).AddMonths(-5); + var fromUtc = UtcFromLocal(firstMonth, 0); + + var rows = await dbContext.Payments + .AsNoTracking() + .Where(p => p.Contract.Unit.FacilityId == facilityId + && p.PaidAt != null && p.PaidAt >= fromUtc + && (p.Status == "PAID" || p.Status == "REFUNDED" || p.Status == "PARTIALLY_REFUNDED") + && p.PaymentType != "DEPOSIT" && p.PaymentType != "REFUND") + .Select(p => new { p.Amount, p.PaidAt, Cold = p.Contract.Unit.UnitType.ClimateControlled }) + .ToListAsync(ct); + + static decimal Million(decimal v) => Math.Round(v / 1_000_000m, 1, MidpointRounding.AwayFromZero); + + var months = Enumerable.Range(0, 6).Select(i => + { + var m = firstMonth.AddMonths(i); + var sum = rows.Where(r => { var d = r.PaidAt!.Value + VnOffset; return d.Year == m.Year && d.Month == m.Month; }).Sum(r => r.Amount); + return new OpsRevenueMonthDto($"Tháng {m.Month}", m.Month, m.Year, Million(sum)); + }).ToList(); + + var current = rows.Where(r => { var d = r.PaidAt!.Value + VnOffset; return d.Year == today.Year && d.Month == today.Month; }).ToList(); + var byType = new List + { + new("Kho thường", Million(current.Where(r => !r.Cold).Sum(r => r.Amount))), + new("Kho lạnh", Million(current.Where(r => r.Cold).Sum(r => r.Amount))), + }; + + return new OpsRevenueDto(months, byType, today); + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.cs new file mode 100644 index 0000000..849caf9 --- /dev/null +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.cs @@ -0,0 +1,220 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Entities; +using StorageProject.Core.Interfaces; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +/// +/// Khu Nhân viên cơ sở (S01–S09) và Quản lý cơ sở (M01–M08) — /api/ops/*. +/// Mọi truy vấn và thao tác chỉ trong cơ sở đang được phân công cho tài khoản (SRS A06). +/// Phần dùng chung: xác định cơ sở, mã hiển thị, giờ Việt Nam, nhật ký. Màn hình: FacilityOpsService.Board.cs; +/// thao tác: FacilityOpsService.Actions.cs. Nghiệp vụ khớp src/ops/reducer.js của giao diện. +/// +public partial class FacilityOpsService(AppDbContext dbContext) : IFacilityOpsService +{ + private static readonly TimeSpan VnOffset = TimeSpan.FromHours(7); + private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; + + // Hợp đồng còn gắn với ô kho (ô đang có khách hoặc đã giữ cho khách) + private static readonly string[] HeldContractStatuses = ["DRAFT", "ACTIVE", "EXPIRING", "OVERDUE", "RETURN_PENDING"]; + + // Khoảng thời gian còn hiện việc đã xong trên bảng (để nhân viên / quản lý thấy kết quả vừa xử lý) + private const int RecentDays = 14; + + private static DateTime NowUtc => DateTime.UtcNow; + private static DateOnly VnToday => DateOnly.FromDateTime(DateTime.UtcNow + VnOffset); + + /// Giờ Việt Nam "yyyy-MM-ddTHH:mm:ss" (DB lưu UTC — D10). + private static string? Local(DateTime? utc) => + utc.HasValue ? (utc.Value + VnOffset).ToString("yyyy-MM-dd'T'HH:mm:ss", Invariant) : null; + + private static string LocalOrDate(DateTime? utc, DateOnly fallback, int hour = 9) => + Local(utc) ?? fallback.ToDateTime(new TimeOnly(hour, 0)).ToString("yyyy-MM-dd'T'HH:mm:ss", Invariant); + + private static DateTime UtcFromLocal(DateOnly date, int hour) => + DateTime.SpecifyKind(date.ToDateTime(new TimeOnly(hour, 0)) - VnOffset, DateTimeKind.Utc); + + private static string Money(decimal amount) => + string.Format(CultureInfo.GetCultureInfo("vi-VN"), "{0:#,0} đ", amount); + + // ------------------------------------------------------------------ + // Mã hiển thị — giống mã khách hàng thấy (src/api/mappers.js) + // ------------------------------------------------------------------ + internal static string ReservationCode(Reservation r) => + $"SS-{(r.CreatedAt + VnOffset):yyyyMMdd}-{r.ReservationId:0000}"; + internal static string ContractCode(RentalContract c) => $"HĐ-{c.StartDate.Year}-{c.ContractId:0000}"; + internal static string VerificationCode(long handoverId) => $"XM-{handoverId:0000}"; + internal static string HandoverCode(long handoverId) => $"BG-{handoverId:0000}"; + internal static string ReturnCode(long inspectionId) => $"TK-{inspectionId:0000}"; + internal static string TicketCode(long ticketId) => $"HT-{ticketId:0000}"; + internal static string RenewalCode(long renewalId) => $"GH-{renewalId:0000}"; + internal static string StaffCode(long userId) => $"NV-{userId:00}"; + + /// Đọc số cuối của mã ("SS-20261014-0012" → 12). Sai tiền tố / không có số → 404. + internal static long ParseCode(string? code, string prefix, string what) + { + var text = (code ?? string.Empty).Trim(); + if (!text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + throw new KeyNotFoundException($"Không tìm thấy {what}."); + } + var m = Regex.Match(text, @"(\d+)$"); + if (!m.Success || !long.TryParse(m.Groups[1].Value, out var id) || id <= 0) + { + throw new KeyNotFoundException($"Không tìm thấy {what}."); + } + return id; + } + + private static string OfferLabel(UnitType type) => + $"{(type.ClimateControlled ? "Kho lạnh" : "Kho thường")} · Cỡ {(type.Area <= 20 ? "M" : "L")} · {type.Area.ToString("0.#", Invariant)} m²"; + + private static string TypeKey(UnitType type) => type.ClimateControlled ? "climate" : "normal"; + + // ------------------------------------------------------------------ + // Cơ sở được phân công + nhân viên của cơ sở + // ------------------------------------------------------------------ + private async Task FacilityOfAsync(OpsActor actor, CancellationToken ct) + { + var today = VnToday; + var assignment = await dbContext.UserFacilities + .AsNoTracking() + .Include(uf => uf.Facility) + .Where(uf => uf.UserId == actor.UserId + && uf.Status == "ACTIVE" + && uf.AssignedFrom <= today + && (uf.AssignedTo == null || uf.AssignedTo >= today)) + .OrderByDescending(uf => uf.AssignedFrom) + .FirstOrDefaultAsync(ct); + + return assignment?.Facility + ?? throw new UnauthorizedAccessException("Tài khoản chưa được phân công cơ sở. Liên hệ quản trị hệ thống."); + } + + private static void RequireManager(OpsActor actor) + { + if (!actor.IsManager) + { + throw new UnauthorizedAccessException("Chỉ quản lý cơ sở được thực hiện thao tác này."); + } + } + + /// Nhân viên (role STAFF) đang được phân công cùng cơ sở. + private async Task> FacilityStaffAsync(long facilityId, CancellationToken ct) + { + var today = VnToday; + return await dbContext.Users + .AsNoTracking() + .Where(u => u.Status == "ACTIVE" + && u.UserRoles.Any(ur => ur.Role.RoleName == "STAFF") + && u.UserFacilities.Any(uf => uf.FacilityId == facilityId + && uf.Status == "ACTIVE" + && uf.AssignedFrom <= today + && (uf.AssignedTo == null || uf.AssignedTo >= today))) + .OrderBy(u => u.FullName) + .ToListAsync(ct); + } + + private static string Shift(Facility f) => + f.OpeningTime.HasValue && f.ClosingTime.HasValue + ? $"{f.OpeningTime.Value:HH\\:mm}–{f.ClosingTime.Value:HH\\:mm}" + : "Theo giờ cơ sở"; + + // ------------------------------------------------------------------ + // Nhật ký (activity_logs, BR13) — cũng là nơi lưu phần giao diện cần mà bảng chưa có cột + // (giấy tờ đã xác minh, biên bản trả kho, phản hồi hỗ trợ, lý do từ chối, lần nhắc khách) + // ------------------------------------------------------------------ + private static class LogAction + { + public const string TransferReported = "TRANSFER_REPORTED"; + public const string PaymentConfirmed = "PAYMENT_CONFIRMED"; + public const string PaymentMismatch = "PAYMENT_MISMATCH"; + public const string CustomerVerified = "CUSTOMER_VERIFIED"; + public const string HandoverCompleted = "HANDOVER_COMPLETED"; + public const string ReturnInspected = "RETURN_INSPECTED"; + public const string TicketResponse = "TICKET_RESPONSE"; + public const string UnitAllocated = "UNIT_ALLOCATED"; + public const string TaskAssigned = "TASK_ASSIGNED"; + public const string RenewalApproved = "RENEWAL_APPROVED"; + public const string RenewalRejected = "RENEWAL_REJECTED"; + public const string OverdueReminder = "OVERDUE_REMINDER"; + public const string DepositRefunded = "DEPOSIT_REFUNDED"; + } + + private static class LogEntity + { + public const string Reservation = "RESERVATION"; + public const string Handover = "HANDOVER_RECORD"; + public const string Return = "RETURN_INSPECTION"; + public const string Ticket = "SUPPORT_TICKET"; + public const string Renewal = "CONTRACT_RENEWAL"; + public const string Contract = "RENTAL_CONTRACT"; + } + + private void Log(long userId, string action, string entityType, long entityId, object value) => + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = userId, + Action = action, + EntityType = entityType, + EntityId = entityId, + NewValue = JsonSerializer.Serialize(value), + LoggedAt = NowUtc + }); + + private static string? Read(ActivityLog log, string field) + { + if (string.IsNullOrWhiteSpace(log.NewValue)) return null; + try + { + using var doc = JsonDocument.Parse(log.NewValue); + return doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty(field, out var v) + ? v.ValueKind == JsonValueKind.String ? v.GetString() : v.ToString() + : null; + } + catch (JsonException) + { + return null; + } + } + + private async Task> LogsAsync(string entityType, ICollection ids, CancellationToken ct) + { + if (ids.Count == 0) return []; + return await dbContext.ActivityLogs + .AsNoTracking() + .Where(l => l.EntityType == entityType && l.EntityId != null && ids.Contains(l.EntityId.Value)) + .OrderBy(l => l.LoggedAt) + .ToListAsync(ct); + } + + private void SetUnitStatus(StorageUnit unit, string status, long userId, string reason) + { + if (unit.Status == status) return; + dbContext.UnitStatusHistories.Add(new UnitStatusHistory + { + UnitId = unit.UnitId, + ChangedBy = userId, + OldStatus = unit.Status, + NewStatus = status, + Reason = reason.Length > 255 ? reason[..255] : reason, + ChangedAt = NowUtc + }); + unit.Status = status; + unit.UpdatedAt = NowUtc; + } + + private static decimal Unpaid(RentalContract c) => + c.Payments.Where(p => (p.Status == "PENDING" || p.Status == "FAILED") && p.PaymentType != "REFUND").Sum(p => p.Amount); + + private static string Clip(string? text, int max = 1000) + { + var t = (text ?? string.Empty).Trim(); + return t.Length > max ? t[..max] : t; + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityService.cs b/StorageProject.Infrastructure/Services/FacilityService.cs index 8ea92c3..9cf044b 100644 --- a/StorageProject.Infrastructure/Services/FacilityService.cs +++ b/StorageProject.Infrastructure/Services/FacilityService.cs @@ -153,7 +153,7 @@ public async Task> GetActiveRatesAsync(long? facili var reservedUnitsCount = await dbContext.Reservations .CountAsync(r => r.FacilityId == request.FacilityId && r.UnitTypeId == request.UnitTypeId - && (r.Status == "PENDING_PAYMENT" || r.Status == "CONFIRMED") + && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED") && r.StartDate < expectedEndDate && r.ExpectedEndDate > request.StartDate, ct); diff --git a/StorageProject.Infrastructure/Services/HandoverService.cs b/StorageProject.Infrastructure/Services/HandoverService.cs index 77da152..9be444e 100644 --- a/StorageProject.Infrastructure/Services/HandoverService.cs +++ b/StorageProject.Infrastructure/Services/HandoverService.cs @@ -19,7 +19,7 @@ public async Task ConfirmCustomerHandoverAsync(long customerId, long handoverId, // If staff already confirmed, or now both confirmed, complete handover if (handover.StaffConfirmed) { - handover.Status = "COMPLETED"; + handover.Status = "HANDED_OVER"; // CHECK chỉ cho SCHEDULED/VERIFIED/HANDED_OVER/CANCELLED handover.HandoverAt = DateTime.UtcNow; // Activate contract diff --git a/StorageProject.Infrastructure/Services/RenewalService.cs b/StorageProject.Infrastructure/Services/RenewalService.cs index 4dc73ff..de0d153 100644 --- a/StorageProject.Infrastructure/Services/RenewalService.cs +++ b/StorageProject.Infrastructure/Services/RenewalService.cs @@ -51,14 +51,14 @@ public async Task RequestRenewalAsync(long customerId, long contract .FirstOrDefaultAsync(ct) ?? throw new InvalidOperationException("Không tìm thấy hợp đồng hợp lệ."); - if (contract.Status != "ACTIVE") + if (contract.Status != "ACTIVE" && contract.Status != "EXPIRING") { throw new InvalidOperationException($"Chỉ hợp đồng ở trạng thái 'ACTIVE' mới có thể gia hạn. Trạng thái hiện tại: {contract.Status}"); } // Check if there is already a pending renewal var hasPendingRenewal = await dbContext.ContractRenewals - .AnyAsync(r => r.ContractId == contractId && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_APPROVAL"), ct); + .AnyAsync(r => r.ContractId == contractId && r.Status == "PENDING", ct); if (hasPendingRenewal) { @@ -88,7 +88,7 @@ public async Task RequestRenewalAsync(long customerId, long contract OldMonthlyRate = contract.AgreedMonthlyRate, NewMonthlyRate = newRate, RenewalAmount = renewalAmount, - Status = "PENDING_PAYMENT", + Status = "PENDING", // chờ quản lý cơ sở duyệt (M03); CHECK chỉ cho PENDING/APPROVED/REJECTED/PAID/CANCELLED RequestedAt = DateTime.UtcNow, CreatedAt = DateTime.UtcNow }; diff --git a/StorageProject.Infrastructure/Services/ReservationService.cs b/StorageProject.Infrastructure/Services/ReservationService.cs index 564c456..f40105f 100644 --- a/StorageProject.Infrastructure/Services/ReservationService.cs +++ b/StorageProject.Infrastructure/Services/ReservationService.cs @@ -1,6 +1,8 @@ +using System.Text.Json; using Microsoft.EntityFrameworkCore; using StorageProject.Core.DTOs.Reservation; using StorageProject.Core.Entities; +using StorageProject.Core.Exceptions; using StorageProject.Core.Interfaces; using StorageProject.Infrastructure.Data; @@ -121,7 +123,7 @@ public async Task CreateReservationAsync(long customerId, Create var existingReservationsCount = await dbContext.Reservations .CountAsync(r => r.FacilityId == request.FacilityId && r.UnitTypeId == request.UnitTypeId - && (r.Status == "PENDING_PAYMENT" || r.Status == "CONFIRMED") + && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED") && r.StartDate < expectedEndDate && r.ExpectedEndDate > request.StartDate, ct); @@ -195,4 +197,65 @@ public async Task CancelReservationAsync(long customerId, long reservationId, st await dbContext.SaveChangesAsync(ct); } + + /// + /// C04 / F03: khách bấm "Tôi đã chuyển khoản" → đơn chờ nhân viên đối soát (S09). + /// Gọi lại khi đơn đã chờ đối soát thì trả về đơn như cũ (an toàn khi bấm hai lần). + /// + public async Task ConfirmTransferAsync(long customerId, long reservationId, CancellationToken ct = default) + { + var reservation = await dbContext.Reservations + .Include(r => r.Facility) + .Include(r => r.UnitType) + .FirstOrDefaultAsync(r => r.ReservationId == reservationId && r.CustomerId == customerId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy đơn đặt chỗ."); + + if (reservation.Status == "PENDING_VERIFICATION") return ToDto(reservation); + if (reservation.Status != "PENDING_PAYMENT") + { + throw new InvalidOperationException("Đơn đặt chỗ này không còn chờ chuyển khoản."); + } + + var now = DateTime.UtcNow; + if (reservation.ExpiresAt.HasValue && reservation.ExpiresAt.Value <= now) + { + reservation.Status = "EXPIRED"; + reservation.CancelledAt = now; + reservation.CancellationReason = "Quá thời gian giữ chỗ chưa xác nhận chuyển khoản"; + await dbContext.SaveChangesAsync(ct); + throw new ReservationExpiredException("Đơn đặt chỗ đã hết thời gian giữ chỗ."); + } + + reservation.Status = "PENDING_VERIFICATION"; + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = customerId, + Action = "TRANSFER_REPORTED", + EntityType = "RESERVATION", + EntityId = reservation.ReservationId, + NewValue = JsonSerializer.Serialize(new { amount = reservation.EstimatedAmount + reservation.RequiredDeposit }), + LoggedAt = now + }); + await dbContext.SaveChangesAsync(ct); + return ToDto(reservation); + } + + private static ReservationDto ToDto(Reservation r) => new( + r.ReservationId, + r.FacilityId, + r.Facility.Name, + r.UnitTypeId, + r.UnitType.TypeName, + r.StartDate, + r.ExpectedEndDate, + r.RentalPeriodMonths, + r.QuotedMonthlyRate, + r.EstimatedAmount, + r.RequiredDeposit, + r.Status, + r.ExpiresAt, + r.CancelledAt, + r.CancellationReason, + r.CreatedAt + ); } diff --git a/docs/facility-ops-api.md b/docs/facility-ops-api.md new file mode 100644 index 0000000..5a3b441 --- /dev/null +++ b/docs/facility-ops-api.md @@ -0,0 +1,78 @@ +# API Nhân viên cơ sở & Quản lý cơ sở (`/api/ops/*`) + +Dành cho role **STAFF** (Figma S01–S09) và **MANAGER** (M01–M08). Code: `StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs`, +`StorageProject.Infrastructure/Services/FacilityOpsService*.cs`. Giao diện gọi ở `src/ops/api.js`. + +Tài khoản seed (cùng cơ sở **SafeSpace Nguyễn Lương Bằng**): `staff01` / `Staff@123`, `staff02` / `Staff@123`, +`manager01` / `Manager@123`. + +Quy ước chung: + +- Mỗi tài khoản chỉ thấy và sửa dữ liệu của **cơ sở đang được phân công** (SRS A06, bảng `user_facilities`). + Chưa được phân công → **403**. Dữ liệu cơ sở khác → **404**. +- Thao tác của quản lý gọi bằng tài khoản nhân viên → **403**. Quản lý làm được mọi thao tác của nhân viên. +- Lỗi: `400 { error }` dữ liệu sai / sai trạng thái · `403 { error }` · `404 { error }`. Thành công: `200 { message }`. +- `id` trong đường dẫn là **mã hiển thị**, giống mã khách thấy: `SS-20261014-0012` (đơn đặt chỗ), `XM-0007` / `BG-0007` + (xác minh / bàn giao), `TK-0003` (trả kho), `HT-0005` (hỗ trợ), `GH-0002` (gia hạn), `HĐ-2026-0004` (hợp đồng), + `PC-BG-0007` (công việc), `NV-02` (nhân viên). +- Ngày `yyyy-MM-dd`; ngày giờ là **giờ Việt Nam** `yyyy-MM-ddTHH:mm:ss` (DB vẫn lưu UTC). Tiền là số VND. +- Mọi thao tác ghi `activity_logs`. Những thông tin bảng chưa có cột (giấy tờ đã xác minh, biên bản trả kho, + phản hồi hỗ trợ, lý do từ chối gia hạn, lần nhắc khách) cũng đọc lại từ đây — D18. + +## 1. Bảng dữ liệu — `GET /api/ops/board` + +Mẫu JSON ở cuối `BACKEND-TODO.md`. Nhân viên nhận: `facility, me, staff, units, payments, verifications, handovers, +returns, tickets`. Quản lý nhận thêm: `allocations, renewals, contracts, assignments, revenue`. + +| Phần | Lấy từ | Ghi chú | +|---|---|---| +| `units` | `storage_units` + hợp đồng đang giữ ô | `EMPTY` · `WAITING_HANDOVER` (RESERVED) · `ACTIVE` · `EXPIRING` (hết hạn trong 14 ngày) · `OVERDUE` · `INSPECTION` · `MAINTENANCE` | +| `payments` (S09) | đơn `PENDING_VERIFICATION` | `PENDING`; `MISMATCH` nếu nhân viên đã báo sai lệch; `CONFIRMED` hiện thêm 3 ngày | +| `verifications`, `handovers` (S02, S03) | `handover_records` | `SCHEDULED` → `TODO`/`WAITING`; `VERIFIED` → xác minh `DONE`; `HANDED_OVER` → bàn giao `DONE` | +| `returns` (S04) | `return_inspections` | `unpaid` = khoản PENDING/FAILED của hợp đồng | +| `tickets` (S05) | `support_tickets` của ô / hợp đồng tại cơ sở | `OPEN` · `IN_PROGRESS` · `WAITING_CUSTOMER` (DB `RESOLVED`) · `DONE` (DB `CLOSED`) | +| `allocations` (M05) | đơn `CONFIRMED` chưa có ô | `minArea = maxArea` = diện tích loại kho | +| `renewals` (M03) | `contract_renewals` `PENDING` (+ đã quyết trong 14 ngày) | | +| `contracts` (M07) | hợp đồng `OVERDUE` / chờ gia hạn / đã có biên bản trả kho | `state`: `OVERDUE` · `RENEWAL` · `RETURNED` · `RESOLVED` · `CLOSED` | +| `assignments` (M06) | bàn giao, trả kho, hỗ trợ chưa xong | `staff = null` → `OPEN` (chưa giao ai) | +| `revenue` (M04) | `payments` đã thu 6 tháng, theo giờ VN | Triệu đồng; không gồm cọc và hoàn tiền; `byType` là của tháng này | + +## 2. Nhân viên (STAFF, MANAGER) + +| Màn | Endpoint | Body | Kết quả | +|---|---|---|---| +| S09 | `POST /api/ops/payments/{id}/confirm` | — | Đơn `PENDING_VERIFICATION` → `CONFIRMED`, vào hàng phân bổ của quản lý | +| S09 | `POST /api/ops/payments/{id}/mismatch` | `{ note }` | Ghi sai lệch; đơn vẫn chờ đối soát. `note` rỗng → 400 | +| S02 | `POST /api/ops/verifications/{id}` | `{ docType, docNumber, photoMatched, infoMatched }` | Số giấy tờ 9/12 số hoặc hộ chiếu 1 chữ + 7 số; hai ô đối chiếu phải `true`. **Chỉ lưu 4 số cuối.** → `VERIFIED` | +| S03 | `POST /api/ops/handovers/{id}/complete` | `{ unlockMethod: "CARD" \| "PIN" \| "FINGER" }` | Chưa xác minh → 400. Hợp đồng `ACTIVE`, ô `OCCUPIED`, đơn `CHECKED_IN`, cấp `access_credentials` | +| S04 | `POST /api/ops/returns/{id}/inspection` | `{ items, walls, keys, proposal }` | Đủ 4 mục. Hợp đồng `RETURN_PENDING`, ô `INSPECTION`, thu hồi thẻ / mã | +| S05 | `POST /api/ops/tickets/{id}/responses` | `{ note, nextStatus: "IN_PROGRESS" \| "WAITING_CUSTOMER" \| "DONE" }` | Ghi phản hồi; chưa có người nhận thì giao cho người phản hồi | + +## 3. Quản lý cơ sở (MANAGER) + +| Màn | Endpoint | Body | Kết quả | +|---|---|---|---| +| M05 | `POST /api/ops/allocations/{id}` | `{ unitCode }` | Ô phải `AVAILABLE` và **đúng loại kho** của đơn. Tạo `unit_assignments`, hợp đồng `DRAFT`, khoản cọc + thuê `PAID`, lịch bàn giao; ô `RESERVED` | +| M06 | `PUT /api/ops/assignments/{id}` | `{ staffId }` | `id` = `PC-BG-…` / `PC-TK-…` / `PC-HT-…`; nhân viên phải cùng cơ sở | +| M03 | `POST /api/ops/renewals/{id}/approve` | — | `APPROVED`, đổi ngày hết hạn hợp đồng, tạo khoản `RENEWAL` chờ thanh toán | +| M03 | `POST /api/ops/renewals/{id}/reject` | `{ reason }` | `reason` rỗng → 400 | +| M07 | `POST /api/ops/contracts/{id}/reminders` | `{ note }` | Ghi lần nhắc; ca quá hạn → `CONTACTED` | +| M07 | `POST /api/ops/contracts/{id}/refund` | — | Chỉ sau biên bản trả kho. Hoàn = cọc − khoản còn nợ (khoản nợ được trừ vào cọc). Hợp đồng `COMPLETED`, ô `AVAILABLE`. Trả `{ message, refund }` | + +## 4. Khách báo đã chuyển khoản (F03) + +`POST /api/reservations/{id}/confirm-transfer` (tài khoản khách, chủ đơn): + +- `PENDING_PAYMENT` → `PENDING_VERIFICATION` (trạng thái mới, migration `20261014150000_ReservationPendingVerification`). +- Gọi lại khi đã chờ đối soát → 200, không đổi gì. Đơn ở trạng thái khác → 400. +- Quá `expiresAt` → đơn `EXPIRED`, trả `400 { error, code: "EXPIRED" }`. +- Đơn chờ đối soát vẫn giữ chỗ khi tính số ô trống (`/api/availability/check`, tạo đơn mới). + +## 5. Chạy thử nhanh + +1. Xoá database cũ cho sạch (seed D17 chỉ thêm phần thiếu, không xoá dữ liệu cũ): trong SSMS xoá database + `SSFRMS` (tên trong chuỗi kết nối `appsettings.json`), rồi chạy API — migration + seed tự chạy. +2. `dotnet run --project StorageProject.Api --launch-profile http`, rồi `npm run dev` ở thư mục giao diện. +3. Khách `customer01` → "Đơn đặt chỗ" → đơn chờ chuyển khoản → "Tôi đã chuyển khoản". +4. `staff01` → Đối soát → xác nhận đơn vừa báo. `manager01` → Phân bổ → chọn ô trống đúng loại → Phân công cho `staff01`. +5. `staff01` → Xác minh khách → Bàn giao. Ô chuyển "Đang hoạt động" ở `manager01` → Ô kho. diff --git a/feature_list.json b/feature_list.json index a61b8e9..cda0983 100644 --- a/feature_list.json +++ b/feature_list.json @@ -2,7 +2,7 @@ "_readme": "Danh sách tính năng = ranh giới phạm vi cho AI agent. Mỗi mục: behavior (hành vi), verification (lệnh/cách kiểm chứng), state. state: not_started -> active -> passing | blocked. Chỉ đổi sang passing khi verification pass và ghi evidence. Mỗi phiên chỉ một mục active.", "_fe": "cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm test && npm run test:render && npm run build", "_be": "dotnet build StorageProject.slnx", - "updated": "2026-10-01", + "updated": "2026-10-14", "features": [ { "id": "F01", "flow": 1, "uc": ["UC01"], "actor": "Khách hàng", @@ -23,7 +23,7 @@ "behavior": "Khách bấm 'Tôi đã chuyển khoản' → đơn chuyển PENDING_VERIFICATION trên backend", "verification": "_be; POST /api/reservations/{id}/confirm-transfer trả 200, sau expiresAt trả lỗi EXPIRED; _fe", "state": "blocked", - "blocked_reason": "Backend chưa có endpoint confirm-transfer và đối soát (luồng đã chốt theo Figma, DECISIONS D02); phía nhân viên đối soát (S09) đã có giao diện, chờ /api/ops/payments/{id}/confirm", + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing.", "evidence": null }, { @@ -86,7 +86,7 @@ "state": "blocked", "depends_on": ["F21"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F12", "flow": 5, "uc": ["UC09"], "actor": "Nhân viên cơ sở", @@ -95,7 +95,7 @@ "state": "blocked", "depends_on": ["F21"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F13", "flow": 3, "uc": ["UC10"], "actor": "Nhân viên cơ sở", @@ -104,7 +104,7 @@ "state": "blocked", "depends_on": ["F06", "F12"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F14", "flow": 7, "uc": ["UC11"], "actor": "Nhân viên cơ sở", @@ -113,7 +113,7 @@ "state": "blocked", "depends_on": ["F21"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F15", "flow": 5, "uc": ["UC12"], "actor": "Nhân viên cơ sở", @@ -122,7 +122,7 @@ "state": "blocked", "depends_on": ["F11", "F14"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F16", "flow": 5, "uc": ["UC13"], "actor": "Quản lý cơ sở", @@ -131,7 +131,7 @@ "state": "blocked", "depends_on": ["F21"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F17", "flow": 1, "uc": ["UC14"], "actor": "Quản lý cơ sở", @@ -140,7 +140,7 @@ "state": "blocked", "depends_on": ["F16"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F18", "flow": 3, "uc": ["UC15", "UC16"], "actor": "Quản lý cơ sở", @@ -149,7 +149,7 @@ "state": "blocked", "depends_on": ["F17"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F19", "flow": 5, "uc": ["UC17"], "actor": "Quản lý cơ sở", @@ -158,7 +158,7 @@ "state": "blocked", "depends_on": ["F11", "F14"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F20", "flow": 4, "uc": ["UC18"], "actor": "Quản lý cơ sở", @@ -167,7 +167,7 @@ "state": "blocked", "depends_on": ["F18"], "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật.", - "blocked_reason": "FE đã xong (khu #/staff, #/manager); chờ backend làm /api/ops/* theo BACKEND-TODO.md mục A. Trong lúc chờ, thao tác lưu trên trình duyệt (D04, D15)." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F21", "flow": null, "uc": ["UC24", "UC26"], "actor": "Chung", @@ -175,7 +175,7 @@ "verification": "_be; _fe; staff01 đăng nhập vào được khu nhân viên", "state": "blocked", "evidence": "2026-10-01: FE xong trên nhánh feature/figma-3009-staff-manager (npm test 38/38, test:render 76 route PASS, build OK; chạy luồng với mock MOCK_OPS=1). Chưa chạy với backend thật. staff01 vào #/staff.", - "blocked_reason": "FE đã xong (đăng nhập STAFF → #/staff, MANAGER → #/manager); backend chưa có tài khoản seed vai trò MANAGER và chưa lọc dữ liệu theo cơ sở được phân công (UserFacility) — BACKEND-TODO.md mục A." + "blocked_reason": "Code backend đã có trên nhánh feature/ops-backend (D18, docs/facility-ops-api.md); chưa chạy với SQL Server. Chạy luồng ở docs/facility-ops-api.md mục 5 rồi đổi passing." }, { "id": "F22", "flow": 4, "uc": ["UC19", "UC20", "UC21"], "actor": "Quản lý vận hành KD", diff --git a/progress.md b/progress.md index 5d72e25..e378158 100644 --- a/progress.md +++ b/progress.md @@ -17,6 +17,48 @@ --- +## Phiên 5 — 2026-10-14 — Backend khu Nhân viên / Quản lý cơ sở + seed D17 (Claude) + +- Tính năng: F03, F11–F21 (phần backend) + seed theo D17. Nhánh `feature/ops-backend` (tách từ `feature/figma-1410-sync`). Quyết định D18. +- Đã xong: + - `DbSeeder` tách 3 file: 4 loại kho (thường/lạnh × M 15 m²/L 30 m²), 12 cơ sở, 12 ô K01–K12 mỗi cơ sở, giá theo + `lib/catalog.js`; loại kho / cơ sở đời cũ chuyển ngừng dùng. Quyền STAFF, MANAGER; tài khoản `manager01`, `staff02`, + `customer03`–`customer06`; gán cơ sở Nguyễn Lương Bằng; dữ liệu vận hành mẫu (2 khoản chờ đối soát, 1 đơn chờ phân bổ, + 1 khách chờ bàn giao, 1 gia hạn chờ duyệt, 1 hợp đồng quá hạn, 1 lịch trả kho, 1 yêu cầu hỗ trợ). + - `/api/ops/*` (`FacilityOpsEndpoints.cs`, `FacilityOpsService*.cs`): board + 12 thao tác đúng `src/ops/api.js`. + - `POST /api/reservations/{id}/confirm-transfer` + trạng thái `PENDING_VERIFICATION` (migration viết tay). + - Sửa lỗi CHECK cũ: `HandoverService` (`COMPLETED` → `HANDED_OVER`), `RenewalService` (`PENDING_PAYMENT` → `PENDING`). + - Giao diện: "Tôi đã chuyển khoản" gọi API thật; `ops/data.js` còn 12 ô; bỏ chữ "dữ liệu mẫu" trên banner khu vận hành. + - Tài liệu: `docs/facility-ops-api.md`, `BACKEND-TODO.md` mục A, README / AGENTS (tài khoản). +- Kiểm chứng: + - `npm test` → 41/41 pass (thêm test confirm-transfer qua mock, test mapper PENDING_VERIFICATION, test 12 ô) + - `npm run test:render` → 76 route PASS · `npm run build` → OK + - Backend: máy làm không tải được NuGet → **chưa chạy `dotnet build` thật**; đã biên dịch kiểm kiểu các file sửa + với bản giả lập EF Core → 0 lỗi. **Chưa chạy với SQL Server.** +- Bị chặn / rủi ro: cần một bạn chạy `dotnet build` + chạy API trên máy có SQL Server, đi luồng ở + `docs/facility-ops-api.md` mục 5. Nên xoá database cũ trước (seed chỉ thêm phần thiếu). +- Phiên sau nên: chạy thử luồng trên; pass thì đổi F03, F11–F21 sang `passing`. Sau đó giao diện B01–B05 (Vận hành KD). + +## Phiên 4 — 2026-10-14 — Đồng bộ giao diện với Figma 14/10 (Claude) + +- Tính năng: F30 (sơ đồ ô kho) + trang chủ, danh mục kho, header khu vận hành. Nhánh `feature/figma-1410-sync`. Quyết định D17. +- Đã xong (chỉ frontend): + - Trang chủ mới (`pages/Home.jsx`): hero ảnh + tìm theo khu vực / loại / cỡ, dải số liệu, 4 loại kho, 3 bước, + cơ sở theo chip khu vực, khối kêu gọi, footer. Bỏ CSS trang chủ cũ không còn dùng. + - Sơ đồ 12 ô (`lib/units.js`, `UnitMap.jsx`): dãy A cỡ M, dãy B cỡ L; dữ liệu backend gắn ô theo loại + cỡ. + - Bỏ cỡ S (`lib/catalog.js`), 2 cỡ M 15 m² / L 30 m²; bảng giá P01 còn 2 thẻ, có giá kho lạnh. + - Bỏ "Gần bạn nhất", "Cách bạn … km", `distance_km`, `distanceLabel`. + - 12 cơ sở đều có kho lạnh; sửa quận Tân Thuận, Phú Mỹ Hưng về Quận 7; đơn mẫu B-015 đổi sang kho lạnh cỡ M. + - Header khu Nhân viên / Quản lý hiện tên cơ sở phụ trách dưới vai trò. +- Test đã sửa theo quy tắc mới (không phải để cho pass): `units.test.js` (10 → 12 ô), `reducer.test.js` + (Quận 7 có 5 cơ sở, cả 12 có kho lạnh, giá B-015 mới, thêm kiểm tra cỡ S bị từ chối), `api-mappers.test.js` + (loại kho ≤ 20 m² là cỡ M), `render.test.mjs` (lọc cỡ M thay cỡ S). +- Kiểm chứng: `npm test` → 39/39 pass; `npm run test:render` → 76 route PASS; `npm run build` → OK; + chụp màn hình trang chủ (1440 px và 390 px), sơ đồ 12 ô, header quản lý / nhân viên ở chế độ không backend. +- Chưa làm: dữ liệu khu vận hành (`ops/data.js`) vẫn dùng diện tích cũ và 86 ô; backend chưa đổi seed (D17); + dòng thông báo trong `OpsShell.jsx` còn chữ "dữ liệu mẫu" (trái D07/D15). +- Phiên sau nên: cập nhật `DbSeeder` theo D17, rồi chạy giao diện với backend thật. + ## Phiên 3 — 2026-10-14 — Backend khu Quản lý vận hành KD (Claude) - Tính năng: F24 (role OPERATIONS), F22 (cơ sở, chính sách, bảng giá), F23 (báo cáo + xuất CSV) — phía backend.