From c3257212b9c0de7b2f50ba35d95b98b284ef08ec Mon Sep 17 00:00:00 2001 From: Vector Date: Thu, 22 Oct 2026 23:58:22 +0700 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20t=C3=ADnh=20ho=C3=A0n=20c=E1=BB=8Dc?= =?UTF-8?q?=20v=C3=A0=20ho=C3=A0n=20ti=E1=BB=81n=20hu=E1=BB=B7=20=C4=91?= =?UTF-8?q?=C6=A1n=20theo=20ch=C3=ADnh=20s=C3=A1ch=20D27?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Thêm RefundPolicy tính hoàn tiền cho 3 tình huống: huỷ trước ngày bắt đầu (phí 10% cọc), dừng thuê sớm (giữ 30% cọc), trả kho (trừ vệ sinh, hư hỏng, quá hạn) - Thêm API xem trước phí huỷ và ghi một khoản hoàn tiền khi khách huỷ đơn đã thanh toán - Quản lý xác nhận đã chuyển khoản hoàn tiền cho đơn huỷ và hợp đồng trả kho - Cập nhật màn huỷ đơn C14a: phí huỷ 10% tiền cọc thay vì 10% tiền thuê - Đồng bộ BACKEND-TODO, progress và feature_list; thêm test cho công thức hoàn tiền --- .../SafeSpace-Customer-UI/BACKEND-TODO.md | 17 ++- .../src/app/state/appReducer.js | 11 +- .../tests/reducer.test.js | 4 +- .../Endpoints/FacilityOpsEndpoints.cs | 10 +- .../Endpoints/ReservationEndpoints.cs | 16 +++ .../DTOs/Reservation/ReservationDtos.cs | 12 +- .../Interfaces/IFacilityOpsService.cs | 2 + StorageProject.Core/Interfaces/IServices.cs | 1 + StorageProject.Core/Policies/RefundPolicy.cs | 113 +++++++++++++++++ .../Data/DbSeeder.cs | 4 +- .../Services/FacilityOpsService.Actions.cs | 93 ++++++++++++-- .../Services/ReservationService.cs | 59 ++++++++- StorageProject.Tests/RefundPolicyTests.cs | 117 ++++++++++++++++++ feature_list.json | 15 ++- progress.md | 10 ++ 15 files changed, 453 insertions(+), 31 deletions(-) create mode 100644 StorageProject.Core/Policies/RefundPolicy.cs create mode 100644 StorageProject.Tests/RefundPolicyTests.cs diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index 7a3691a..b2b32d0 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -23,7 +23,7 @@ tên route + tên trường JSON là giao diện chạy ngay, không phải sử | Q1 | `GET /api/contracts/{id}/access-qr` → `AccessQrDto` | Tiến | Popup C07q báo "Mã QR đang được cơ sở kích hoạt" | | Q2 | `POST /api/access/scan` `{ code }` → `ScanResultDto` (cho phép không đăng nhập — máy quét ở cửa) | Tiến | Màn `#/door` báo "Máy quét chưa kết nối được hệ thống" | | R1 | `GET /api/tickets/{id}` trả thêm `responses[]` | Ngọc Mai | C12 không hiện dòng phản hồi | -| H1 | `GET /api/reservations/{id}/cancel-preview` → `CancelPreviewDto`; `ReservationDto` thêm `refundAmount`, `refundStatus` | Ngọc Mai | C14a ghi "Theo chính sách hiện hành / Cơ sở xác nhận sau khi huỷ" | +| H1 | **Đã viết (D27)** `GET /api/reservations/{id}/cancel-preview` → `CancelPreviewDto`; `ReservationDto` thêm `refundAmount`, `refundStatus` (`PENDING` / `COMPLETED`). Chờ nhóm build và kiểm thử | Ngọc Mai, Đạt, Thắng | C14a ghi "Theo chính sách hiện hành / Cơ sở xác nhận sau khi huỷ" | | U1 | **Đã nối** `PUT /api/staff/units/{mã}/status` `{ status, reason }` có sẵn trên main (nhân viên + quản lý). Còn thiếu: kiểm chuyển tiếp hợp lệ, bắt buộc lý do, trạng thái `INSPECTION` | Thắng | — | ### P · PayOS (D19) và thanh toán tại cửa hàng @@ -66,10 +66,10 @@ Hợp đồng quá hạn có khoá QR hay không: nhóm chốt (giao diện ch ### H · Huỷ đơn đã thanh toán (Ngọc Mai) ```json -// CancelPreviewDto — theo chính sách CANCELLATION đang hiệu lực ở B02 -{ "paidAmount": 4600000, "cancellationFee": 345000, "refundAmount": 4255000, "policyName": "Huỷ trước ngày nhận kho: phí 10% tiền thuê" } +// CancelPreviewDto — theo D27 (ví dụ: cọc 1.150.000 đ, tiền thuê 3.450.000 đ) +{ "paidAmount": 4600000, "cancellationFee": 115000, "refundAmount": 4485000, "policyName": "Huỷ trước ngày bắt đầu: phí 10% tiền cọc, hoàn đủ tiền thuê và 90% tiền cọc" } ``` -`POST /api/reservations/{id}/cancel` (đã có, nhận `PENDING_PAYMENT` / `CONFIRMED`) với đơn đã trả: ghi khoản `REFUND`, trả +`POST /api/reservations/{id}/cancel` (đã có, nhận `PENDING_PAYMENT` / `CONFIRMED`) với đơn đã trả: ghi một khoản `REFUND` (`PENDING`, `BANK_TRANSFER`), trả `refundAmount` + `refundStatus: "PENDING"` trong `ReservationDto` để C14b hiện "Đã huỷ · Đang hoàn tiền". ### U · Đổi trạng thái ô kho — F12 (Thắng) @@ -329,7 +329,7 @@ Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái) } ``` -## D27 — Hoàn tiền và cọc (chốt 22/10/2026, chưa code) +## D27 — Hoàn tiền và cọc (chốt 22/10/2026; code đã viết, chờ nhóm build và kiểm thử) Nguồn: DECISIONS.md D27. Các việc backend cần làm: @@ -341,4 +341,11 @@ Nguồn: DECISIONS.md D27. Các việc backend cần làm: - Ghi trạng thái hoàn khi Quản lý xác nhận ở M07; chuyển khoản thủ công. - Đồng bộ FE: appReducer.js `CANCEL_FEE_RATE` và màn C14a phải theo công thức trên. +Trạng thái triển khai D27 (22/10/2026): +- `StorageProject.Core/Policies/RefundPolicy.cs`: hàm thuần tính 3 tình huống (huỷ trước StartDate, dừng sớm, trả kho) kèm `OverdueFeeFor` đọc tham số `OVERDUE`; thiếu hoặc không hỗ trợ cấu hình thì báo lỗi, không tự đặt mức phí. Phí quá hạn: `PERCENTAGE` = % tiền thuê tháng mỗi ngày trễ, `FIXED` = số tiền cố định mỗi ngày trễ. +- `GET /api/reservations/{id}/cancel-preview` và `POST /api/reservations/{id}/cancel`: đơn đã thanh toán chỉ huỷ được trước StartDate (giờ Việt Nam); ghi đúng một khoản `REFUND` trạng thái `PENDING`. +- `POST /api/ops/reservations/{id}/refund` (M07, chỉ quản lý): xác nhận đã chuyển khoản hoàn cho đơn đã huỷ, `PENDING` → `PAID`, chỉ chạy được một lần. +- `POST /api/ops/contracts/{id}/refund` (M07): tính theo D27 từ biên bản trả kho. Trả trước EndDate = dừng sớm; trễ so với EndDate = quá hạn. Ghi một khoản `REFUND` gồm hoàn thuê + hoàn cọc; hư hỏng/quá hạn chỉ trừ trong phạm vi cọc, phần thiếu giữ trạng thái chưa thanh toán (công nợ). +- Giao diện: `cancelPreviewOf` (appReducer.js) tính 10% tiền cọc; C14a hiển thị phí và số hoàn theo đó. Còn thiếu: nút xác nhận hoàn cho đơn đã huỷ ở màn M07. +- Chưa làm: `ManagerService.ConfirmRefundAsync` (đường cũ `POST /api/manager/contracts/{id}/refund`) vẫn đặt trạng thái `ENDED` và không theo D27; cần gộp với `FacilityOpsService.ConfirmRefundAsync` (liên quan T02). diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js index 4e81a8d..1121ad2 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js @@ -69,13 +69,14 @@ const hasPending = (state, contract_id) => ({ ret: state.returns.some((r) => r.contract_id === contract_id && ["PENDING", "SCHEDULED"].includes(r.status)), }); -// C14a · Ước tính hoàn tiền khi huỷ đơn đã thanh toán (chế độ trình duyệt). Chế độ API lấy từ -// GET /api/reservations/{id}/cancel-preview theo chính sách CANCELLATION ở B02. -export const CANCEL_FEE_RATE = 0.1; // 10% tiền thuê, hoàn đủ tiền cọc (Figma C14a) +// C14a · Ước tính hoàn tiền khi huỷ đơn đã thanh toán trước ngày bắt đầu thuê (chế độ trình duyệt). +// Chính sách D27: phí huỷ cố định 10% tiền cọc; hoàn 100% tiền thuê + 90% tiền cọc. +// Chế độ API lấy từ GET /api/reservations/{id}/cancel-preview. +export const CANCEL_DEPOSIT_FEE_RATE = 0.1; export function cancelPreviewOf(r) { const paid = r.initial_total || 0; - const fee = Math.round((r.rent_total || 0) * CANCEL_FEE_RATE); - return { paid, fee, refund: Math.max(0, paid - fee), policy: null }; + const fee = Math.round((r.deposit || 0) * CANCEL_DEPOSIT_FEE_RATE); + return { paid, fee, refund: Math.max(0, paid - fee), policy: "Huỷ trước ngày bắt đầu: phí 10% tiền cọc" }; } const handlers = { 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 838a0bc..1348c09 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/reducer.test.js @@ -225,13 +225,13 @@ test("PayOS gia hạn (C11q → C11b): khoản gia hạn đã duyệt chuyển assert.equal(out.state.contracts.find((c) => c.contract_id === row.contract_id).end_date, row.period.to); }); -test("huỷ đơn (C14a): đơn đã thanh toán chưa nhận kho được huỷ và hoàn tiền trừ phí; đơn đã nhận kho thì không", () => { +test("huỷ đơn (C14a, D27): đơn đã thanh toán chưa nhận kho được huỷ và hoàn tiền trừ phí 10% tiền cọc; đơn đã nhận kho thì không", () => { const s = createSeedData(T); const out = run(s, "CANCEL_RESERVATION", { reservation_id: "SS-20260914-0142", reason: "Đổi kế hoạch chuyển nhà" }); const r = out.state.reservations.find((x) => x.reservation_id === "SS-20260914-0142"); assert.equal(r.status, "CANCELLED"); assert.equal(r.refund_status, "PENDING"); - assert.equal(r.refund_amount, 4600000 - 345000); // Figma C14a: phí huỷ 10% tiền thuê + assert.equal(r.refund_amount, 4600000 - 115000); // D27: phí huỷ 10% tiền cọc (cọc 1.150.000), hoàn đủ tiền thuê assert.equal(out.state.contracts.find((c) => c.reservation_id === r.reservation_id).status, "ENDED"); assert.match(run(s, "CANCEL_RESERVATION", { reservation_id: "SS-20260615-0086" }).error.message, /nhận kho/); }); diff --git a/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs index 6a21a03..f19284c 100644 --- a/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs +++ b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs @@ -74,7 +74,15 @@ public static void MapFacilityOpsEndpoints(this IEndpointRouteBuilder routes) 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"); + .WithSummary("M07 · Xác nhận hoàn cọc sau biên bản trả kho theo chính sách D27, đóng hợp đồng, ô trống lại"); + + group.MapPost("/reservations/{id}/refund", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => + Run(async () => + { + var refund = await ops.ConfirmReservationRefundAsync(Actor(user), id, ct); + return Results.Ok(new { message = "Đã cập nhật.", refund }); + })) + .WithSummary("M07 · Xác nhận đã chuyển khoản hoàn tiền cho đơn đã huỷ (D27)"); } private static OpsActor Actor(ClaimsPrincipal user) => new(user.GetUserId(), user.IsInRole("MANAGER")); diff --git a/StorageProject.Api/Endpoints/ReservationEndpoints.cs b/StorageProject.Api/Endpoints/ReservationEndpoints.cs index d189fc9..35c6bb7 100644 --- a/StorageProject.Api/Endpoints/ReservationEndpoints.cs +++ b/StorageProject.Api/Endpoints/ReservationEndpoints.cs @@ -45,6 +45,22 @@ public static RouteGroupBuilder MapReservationEndpoints(this IEndpointRouteBuild } }); + group.MapGet("/{id:long}/cancel-preview", async (long id, ClaimsPrincipal user, IReservationService reservationService, CancellationToken ct) => + { + try + { + return Results.Ok(await reservationService.GetCancelPreviewAsync(user.GetUserId(), id, ct)); + } + catch (KeyNotFoundException ex) + { + return Results.NotFound(new { error = ex.Message }); + } + catch (InvalidOperationException ex) + { + return Results.BadRequest(new { error = ex.Message }); + } + }); + group.MapPost("/{id:long}/cancel", async (long id, CancelReservationRequest request, ClaimsPrincipal user, IReservationService reservationService, CancellationToken ct) => { try diff --git a/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs b/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs index 3187422..1fa1283 100644 --- a/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs +++ b/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs @@ -24,7 +24,17 @@ public record ReservationDto( DateTime? CancelledAt, string? CancellationReason, DateTime CreatedAt, - string PaymentMethod = "PAYOS" + string PaymentMethod = "PAYOS", + decimal? RefundAmount = null, + string? RefundStatus = null // PENDING (chờ quản lý chuyển khoản) | COMPLETED +); + +/// C14a · Ước tính khi huỷ đơn đã thanh toán trước ngày bắt đầu (D27). +public record CancelPreviewDto( + decimal PaidAmount, + decimal CancellationFee, + decimal RefundAmount, + string PolicyName ); public record ReservationDetailDto( diff --git a/StorageProject.Core/Interfaces/IFacilityOpsService.cs b/StorageProject.Core/Interfaces/IFacilityOpsService.cs index b97c4b8..1afe0e2 100644 --- a/StorageProject.Core/Interfaces/IFacilityOpsService.cs +++ b/StorageProject.Core/Interfaces/IFacilityOpsService.cs @@ -28,4 +28,6 @@ public interface IFacilityOpsService 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); + /// M07 · Xác nhận đã chuyển khoản hoàn tiền cho đơn đã huỷ (D27). + Task ConfirmReservationRefundAsync(OpsActor actor, string id, CancellationToken ct = default); } diff --git a/StorageProject.Core/Interfaces/IServices.cs b/StorageProject.Core/Interfaces/IServices.cs index cfe3b58..a2fdc40 100644 --- a/StorageProject.Core/Interfaces/IServices.cs +++ b/StorageProject.Core/Interfaces/IServices.cs @@ -36,6 +36,7 @@ public interface IReservationService Task> GetMyReservationsAsync(long customerId, CancellationToken ct = default); Task GetReservationDetailAsync(long customerId, long reservationId, CancellationToken ct = default); Task CreateReservationAsync(long customerId, CreateReservationRequest request, CancellationToken ct = default); + Task GetCancelPreviewAsync(long customerId, long reservationId, CancellationToken ct = default); Task CancelReservationAsync(long customerId, long reservationId, string reason, CancellationToken ct = default); Task ConfirmTransferAsync(long customerId, long reservationId, CancellationToken ct = default); } diff --git a/StorageProject.Core/Policies/RefundPolicy.cs b/StorageProject.Core/Policies/RefundPolicy.cs new file mode 100644 index 0000000..0b3d74c --- /dev/null +++ b/StorageProject.Core/Policies/RefundPolicy.cs @@ -0,0 +1,113 @@ +namespace StorageProject.Core.Policies; + +/// Tình huống tính hoàn tiền theo chính sách cọc D27. +public enum RefundScenario +{ + /// Huỷ đơn đã thanh toán trước ngày bắt đầu thuê. + CancelBeforeStart, + /// Dừng thuê sau ngày bắt đầu, trước ngày kết thúc hợp đồng (Move-out). + EarlyStop, + /// Trả kho khi hết hạn hợp đồng. + NormalReturn +} + +public sealed record RefundInput( + RefundScenario Scenario, + decimal Deposit, + decimal RentPaid, + DateOnly StartDate, + DateOnly EndDate, + DateOnly Today, + bool HygieneViolation = false, + bool Overdue = false, + decimal DamageFee = 0, + decimal OverdueFee = 0); + +public sealed record RefundResult( + decimal RentRefund, + decimal DepositRefund, + decimal FixedDeduction, + decimal DamageDeduction, + decimal OverdueDeduction, + decimal Debt) +{ + public decimal Total => RentRefund + DepositRefund; +} + +/// +/// D27 — công thức hoàn cọc và hoàn thuê. Hàm thuần, không đọc cơ sở dữ liệu. +/// Huỷ trước StartDate: phí 10% cọc, hoàn 100% tiền thuê + 90% cọc. +/// Dừng sớm sau StartDate: giữ 30% cọc; tháng đang chạy tính đủ, tháng chưa bắt đầu được hoàn tiền thuê. +/// Trả kho bình thường: hoàn đủ cọc; vi phạm vệ sinh hoặc quá hạn trừ cố định 10% cọc. +/// Hư hỏng và phí quá hạn trừ thêm vào cọc còn lại; không đủ thì hoàn 0 và phần thiếu ghi thành công nợ. +/// +public static class RefundPolicy +{ + public const decimal CancelFeeRate = 0.10m; + public const decimal EarlyStopKeepRate = 0.30m; + public const decimal HygieneFeeRate = 0.10m; + + public static RefundResult Calculate(RefundInput i) + { + if (i.Deposit < 0 || i.RentPaid < 0 || i.DamageFee < 0 || i.OverdueFee < 0) + throw new ArgumentException("Số tiền không được âm."); + + if (i.Scenario == RefundScenario.CancelBeforeStart) + { + var fee = Money(i.Deposit * CancelFeeRate); + return new RefundResult(i.RentPaid, i.Deposit - fee, fee, 0, 0, 0); + } + + var fixedDeduction = i.Scenario == RefundScenario.EarlyStop + ? Money(i.Deposit * EarlyStopKeepRate) + : i.HygieneViolation || i.Overdue ? Money(i.Deposit * HygieneFeeRate) : 0m; + + var rentRefund = i.Scenario == RefundScenario.EarlyStop + ? UnusedRent(i.RentPaid, i.StartDate, i.EndDate, i.Today) + : 0m; + + var remaining = i.Deposit - fixedDeduction; + var damage = Math.Min(remaining, i.DamageFee); + remaining -= damage; + var overdue = Math.Min(remaining, i.OverdueFee); + remaining -= overdue; + var debt = (i.DamageFee - damage) + (i.OverdueFee - overdue); + return new RefundResult(rentRefund, remaining, fixedDeduction, damage, overdue, debt); + } + + /// Số tháng thuê (làm tròn lên) giữa hai ngày; tối thiểu 1. + public static int TotalMonths(DateOnly start, DateOnly end) + { + var m = 0; + while (start.AddMonths(m) < end) m++; + return Math.Max(1, m); + } + + /// Hoàn tiền thuê của các tháng chưa bắt đầu (tháng hiện tại tính đủ, không hoàn). + public static decimal UnusedRent(decimal rentPaid, DateOnly start, DateOnly end, DateOnly today) + { + var total = TotalMonths(start, end); + var begun = 0; + while (begun < total && start.AddMonths(begun) <= today) begun++; + return Money(rentPaid * (total - begun) / total); + } + + /// + /// Phí quá hạn theo tham số chính sách OVERDUE (B02): PERCENTAGE = % tiền thuê tháng mỗi ngày trễ, + /// FIXED = số tiền cố định mỗi ngày trễ. Thiếu hoặc không hỗ trợ cách tính thì báo lỗi, không tự đặt mức phí. + /// + public static decimal OverdueFeeFor(string? calculationType, decimal? value, decimal monthlyRate, int overdueDays) + { + if (overdueDays <= 0) return 0; + if (value is not decimal v || v < 0) + throw new InvalidOperationException("Chưa cấu hình chính sách phí quá hạn (B02). Cần cấu hình trước khi tính hoàn cọc."); + return calculationType switch + { + "PERCENTAGE" => Money(monthlyRate * v / 100m * overdueDays), + "FIXED" => Money(v * overdueDays), + _ => throw new InvalidOperationException("Chính sách phí quá hạn (B02) phải tính theo % tiền thuê tháng hoặc số tiền cố định mỗi ngày.") + }; + } + + private static decimal Money(decimal v) => Math.Round(v, 0, MidpointRounding.AwayFromZero); +} diff --git a/StorageProject.Infrastructure/Data/DbSeeder.cs b/StorageProject.Infrastructure/Data/DbSeeder.cs index d05a1d9..5bf64b9 100644 --- a/StorageProject.Infrastructure/Data/DbSeeder.cs +++ b/StorageProject.Infrastructure/Data/DbSeeder.cs @@ -194,8 +194,8 @@ async Task EnsureUserAsync(string username, string email, string fullName, PolicyName = "Phí phạt quá hạn thanh toán", PolicyType = "OVERDUE", CalculationType = "PERCENTAGE", - Value = 5.0m, // 5% mỗi tuần trễ hạn - RuleDescription = "Tính phí phạt 5% trên số tiền nợ cho mỗi tuần quá hạn", + Value = 5.0m, // 5% tiền thuê tháng mỗi ngày trả kho trễ (D27) + RuleDescription = "Phí quá hạn: 5% tiền thuê tháng cho mỗi ngày trả kho trễ, trừ vào tiền cọc", EffectiveFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-30)), Status = "ACTIVE", CreatedAt = DateTime.UtcNow, diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs index 7d0219f..06bb6a0 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs @@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore; using StorageProject.Core.DTOs.FacilityOps; using StorageProject.Core.Entities; +using StorageProject.Core.Policies; namespace StorageProject.Infrastructure.Services; @@ -373,29 +374,50 @@ public async Task RemindAsync(OpsActor actor, string id, OpsNoteRequest request, await dbContext.SaveChangesAsync(ct); } + /// + /// M07 · Hoàn cọc sau biên bản trả kho theo chính sách D27 (xem ). + /// Ghi đúng một khoản REFUND; khoản hư hỏng / quá hạn chỉ được trừ trong phạm vi tiền cọc còn lại, + /// phần thiếu giữ nguyên trạng thái chưa thanh toán (công nợ của khách). + /// 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")) + var inspection = contract.ReturnInspections.Where(i => i.Status == "COMPLETED") + .OrderByDescending(i => i.InspectedAt ?? i.CreatedAt).FirstOrDefault(); + if (contract.Status != "RETURN_PENDING" || inspection == null) { throw new InvalidOperationException("Hợp đồng chưa có biên bản trả kho."); } + if (contract.Payments.Any(p => p.PaymentType == "REFUND")) + { + throw new InvalidOperationException("Hợp đồng đã ghi nhận hoàn tiền."); + } 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) + var returnDate = DateOnly.FromDateTime((inspection.InspectedAt ?? now) + VnOffset); + var scenario = returnDate < contract.EndDate ? RefundScenario.EarlyStop : RefundScenario.NormalReturn; + var overdueDays = Math.Max(0, returnDate.DayNumber - contract.EndDate.DayNumber); + decimal overdueFee = 0; + if (overdueDays > 0) { - p.Status = "PAID"; - p.PaidAt = now; - p.TransactionReference = "Trừ vào tiền cọc"; - p.UpdatedAt = now; + var policy = await OpsRules.FindApplicablePolicyAsync(dbContext, "OVERDUE", facility.FacilityId, + contract.Unit.UnitTypeId, returnDate, ct); + overdueFee = RefundPolicy.OverdueFeeFor(policy?.CalculationType, policy?.Value, contract.AgreedMonthlyRate, overdueDays); } + var rentPaid = contract.Payments.Where(p => p.PaymentType == "RENT" && p.Status == "PAID").Sum(p => p.Amount); + var result = RefundPolicy.Calculate(new RefundInput(scenario, contract.DepositAmount, rentPaid, + contract.StartDate, contract.EndDate, returnDate, + HygieneViolation: inspection.CleaningRequired || inspection.CleaningFee > 0 || inspection.ConditionStatus == "DIRTY", + Overdue: overdueDays > 0, DamageFee: inspection.DamageFee, OverdueFee: overdueFee)); + + // Khoản đã phát sinh trên hợp đồng được bù trừ bằng đúng phần đã trừ vào cọc; phần còn lại vẫn là nợ. + SettleFromDeposit(contract, "DAMAGE_FEE", result.DamageDeduction, now); + SettleFromDeposit(contract, "OVERDUE_FEE", result.OverdueDeduction, now); + if (result.FixedDeduction > 0) SettleFromDeposit(contract, "CLEANING_FEE", decimal.MaxValue, now); + + var refund = result.Total; if (refund > 0) { dbContext.Payments.Add(new Payment @@ -413,8 +435,55 @@ public async Task ConfirmRefundAsync(OpsActor actor, string id, Cancell 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 }); + Log(actor.UserId, LogAction.DepositRefunded, LogEntity.Contract, contract.ContractId, new + { + refund, scenario = scenario.ToString(), rentRefund = result.RentRefund, depositRefund = result.DepositRefund, + fixedDeduction = result.FixedDeduction, damage = result.DamageDeduction, overdue = result.OverdueDeduction, + debt = result.Debt, overdueDays + }); await dbContext.SaveChangesAsync(ct); return refund; } + + // Đánh dấu khoản chưa thanh toán loại `type` là đã trừ vào cọc tới tối đa `budget`; khoản trả một phần được tách đôi. + private void SettleFromDeposit(RentalContract contract, string type, decimal budget, DateTime now) + { + foreach (var p in contract.Payments.Where(p => p.PaymentType == type && (p.Status == "PENDING" || p.Status == "FAILED")) + .OrderBy(p => p.PaymentId).ToList()) + { + if (budget <= 0) break; + if (p.Amount <= budget) + { + budget -= p.Amount; + p.Status = "PAID"; p.PaidAt = now; p.UpdatedAt = now; p.TransactionReference = "Trừ vào tiền cọc"; + continue; + } + dbContext.Payments.Add(new Payment + { + ContractId = p.ContractId, PaymentType = p.PaymentType, Amount = budget, Currency = p.Currency, + PaymentMethod = p.PaymentMethod, TransactionReference = "Trừ vào tiền cọc", DueDate = p.DueDate, + PaidAt = now, Status = "PAID", CreatedAt = now, UpdatedAt = now + }); + p.Amount -= budget; p.UpdatedAt = now; + budget = 0; + } + } + + /// M07 · Quản lý xác nhận đã chuyển khoản hoàn tiền cho đơn đã huỷ (khoản REFUND ghi lúc khách huỷ). + public async Task ConfirmReservationRefundAsync(OpsActor actor, string id, CancellationToken ct = default) + { + RequireManager(actor); + var facility = await FacilityOfAsync(actor, ct); + var r = await ReservationAsync(facility.FacilityId, id, ct); + if (r.Status != "CANCELLED") throw new InvalidOperationException("Đơn chưa bị huỷ nên không có khoản hoàn tiền."); + var refunds = await dbContext.Payments.Where(p => p.ReservationId == r.ReservationId && p.PaymentType == "REFUND").ToListAsync(ct); + if (refunds.Count == 0) throw new InvalidOperationException("Đơn này không có khoản hoàn tiền."); + var pending = refunds.FirstOrDefault(p => p.Status == "PENDING") + ?? throw new InvalidOperationException("Khoản hoàn tiền này đã được xác nhận."); + var now = NowUtc; + pending.Status = "PAID"; pending.PaidAt = now; pending.UpdatedAt = now; + Log(actor.UserId, LogAction.DepositRefunded, LogEntity.Reservation, r.ReservationId, new { refund = pending.Amount, reservation = true }); + await dbContext.SaveChangesAsync(ct); + return pending.Amount; + } } diff --git a/StorageProject.Infrastructure/Services/ReservationService.cs b/StorageProject.Infrastructure/Services/ReservationService.cs index 7a8ecc3..4640bc5 100644 --- a/StorageProject.Infrastructure/Services/ReservationService.cs +++ b/StorageProject.Infrastructure/Services/ReservationService.cs @@ -4,6 +4,7 @@ using StorageProject.Core.Entities; using StorageProject.Core.Exceptions; using StorageProject.Core.Interfaces; +using StorageProject.Core.Policies; using StorageProject.Infrastructure.Data; namespace StorageProject.Infrastructure.Services; @@ -12,7 +13,7 @@ public class ReservationService(AppDbContext dbContext) : IReservationService { public async Task> GetMyReservationsAsync(long customerId, CancellationToken ct = default) { - return await dbContext.Reservations + var list = await dbContext.Reservations .AsNoTracking() .Include(r => r.Facility) .Include(r => r.UnitType) @@ -38,6 +39,15 @@ public async Task> GetMyReservationsAsync(long cus r.PaymentMethod )) .ToListAsync(ct); + var ids = list.Select(r => r.ReservationId).ToList(); + var refunds = await dbContext.Payments.AsNoTracking() + .Where(p => p.ReservationId != null && ids.Contains(p.ReservationId.Value) && p.PaymentType == "REFUND") + .ToListAsync(ct); + return list.Select(r => + { + var refund = refunds.FirstOrDefault(p => p.ReservationId == r.ReservationId); + return refund == null ? r : r with { RefundAmount = refund.Amount, RefundStatus = refund.Status == "PAID" ? "COMPLETED" : "PENDING" }; + }).ToList(); } public async Task GetReservationDetailAsync(long customerId, long reservationId, CancellationToken ct = default) @@ -185,6 +195,36 @@ public async Task CreateReservationAsync(long customerId, Create ); } + public async Task GetCancelPreviewAsync(long customerId, long reservationId, CancellationToken ct = default) + { + var reservation = await dbContext.Reservations + .AsNoTracking() + .FirstOrDefaultAsync(r => r.ReservationId == reservationId && r.CustomerId == customerId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy đơn đặt chỗ."); + var quote = await QuoteCancelAsync(reservation, ct); + return new CancelPreviewDto(quote.Paid, quote.Fee, quote.Refund, CancelPolicyName); + } + + private const string CancelPolicyName = "Huỷ trước ngày bắt đầu: phí 10% tiền cọc, hoàn đủ tiền thuê và 90% tiền cọc"; + + // D27: chỉ tính trên khoản đã thu (RENT + DEPOSIT, PAID). Đơn chưa thanh toán thì không phát sinh phí. + private async Task<(decimal Paid, decimal Fee, decimal Refund)> QuoteCancelAsync(Reservation reservation, CancellationToken ct) + { + var paid = await dbContext.Payments.AsNoTracking() + .Where(p => p.ReservationId == reservation.ReservationId && p.Status == "PAID" && + (p.PaymentType == "RENT" || p.PaymentType == "DEPOSIT")) + .ToListAsync(ct); + if (paid.Count == 0) return (0, 0, 0); + if (OpsRules.TodayLocal >= reservation.StartDate) + throw new InvalidOperationException( + "Đã đến ngày bắt đầu thuê nên không huỷ đặt chỗ được. Vui lòng đăng ký trả kho để được xử lý hoàn cọc theo chính sách."); + var rent = paid.Where(p => p.PaymentType == "RENT").Sum(p => p.Amount); + var deposit = paid.Where(p => p.PaymentType == "DEPOSIT").Sum(p => p.Amount); + var result = RefundPolicy.Calculate(new RefundInput(RefundScenario.CancelBeforeStart, deposit, rent, + reservation.StartDate, reservation.ExpectedEndDate, OpsRules.TodayLocal)); + return (rent + deposit, result.FixedDeduction, result.Total); + } + public async Task CancelReservationAsync(long customerId, long reservationId, string reason, CancellationToken ct = default) { await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{reservationId}", ct); @@ -198,8 +238,10 @@ public async Task CancelReservationAsync(long customerId, long reservationId, st throw new InvalidOperationException($"Không thể hủy đơn đặt chỗ ở trạng thái '{reservation.Status}'."); } + var quote = await QuoteCancelAsync(reservation, ct); + var now = DateTime.UtcNow; reservation.Status = "CANCELLED"; - reservation.CancelledAt = DateTime.UtcNow; + reservation.CancelledAt = now; reservation.CancellationReason = reason; foreach (var a in await dbContext.UnitAssignments.Include(a => a.Unit).Where(a => a.ReservationId == reservationId && a.Status == "ACTIVE").ToListAsync(ct)) { @@ -208,6 +250,19 @@ public async Task CancelReservationAsync(long customerId, long reservationId, st } var draft = await dbContext.RentalContracts.SingleOrDefaultAsync(c => c.ReservationId == reservationId && c.Status == "DRAFT", ct); if (draft != null) draft.Status = "CANCELLED"; + + // Ghi khoản hoàn đúng một lần; quản lý xác nhận đã chuyển khoản ở M07 (3–5 ngày làm việc). + if (quote.Refund > 0 && !await dbContext.Payments.AnyAsync(p => p.ReservationId == reservationId && p.PaymentType == "REFUND", ct)) + { + dbContext.Payments.Add(new Payment + { + ReservationId = reservationId, ContractId = draft?.ContractId, PaymentType = "REFUND", Amount = quote.Refund, + Currency = "VND", PaymentMethod = "BANK_TRANSFER", Status = "PENDING", + TransactionReference = $"Hoàn huỷ đơn #{reservationId}", CreatedAt = now, UpdatedAt = now + }); + ReservationSettlement.Audit(dbContext, customerId, "RESERVATION_REFUND_RECORDED", reservationId, + new { paid = quote.Paid, fee = quote.Fee, refund = quote.Refund }); + } await dbContext.SaveChangesAsync(ct); await tx.CommitAsync(ct); } diff --git a/StorageProject.Tests/RefundPolicyTests.cs b/StorageProject.Tests/RefundPolicyTests.cs new file mode 100644 index 0000000..bbfd636 --- /dev/null +++ b/StorageProject.Tests/RefundPolicyTests.cs @@ -0,0 +1,117 @@ +using StorageProject.Core.Policies; +using Xunit; + +namespace StorageProject.Tests; + +// D27 — công thức hoàn cọc và hoàn thuê (hàm thuần, không cần cơ sở dữ liệu). +public sealed class RefundPolicyTests +{ + private static readonly DateOnly Start = new(2026, 11, 1); + private static readonly DateOnly End = new(2027, 2, 1); + private const decimal Deposit = 1_000_000m; + private const decimal Rent = 3_000_000m; // 3 tháng + + private static RefundResult Calc(RefundScenario scenario, DateOnly today, bool hygiene = false, + bool overdue = false, decimal damage = 0, decimal overdueFee = 0) => + RefundPolicy.Calculate(new RefundInput(scenario, Deposit, Rent, Start, End, today, hygiene, overdue, damage, overdueFee)); + + [Fact] + public void Cancel_before_start_charges_10_percent_of_deposit_and_refunds_all_rent() + { + var r = Calc(RefundScenario.CancelBeforeStart, new DateOnly(2026, 10, 25)); + Assert.Equal(100_000m, r.FixedDeduction); + Assert.Equal(900_000m, r.DepositRefund); + Assert.Equal(Rent, r.RentRefund); + Assert.Equal(3_900_000m, r.Total); + Assert.Equal(0m, r.Debt); + } + + [Fact] + public void Early_stop_keeps_30_percent_deposit_and_refunds_months_not_yet_begun() + { + // 15/12: tháng 1 và tháng 2 đã bắt đầu, tháng 3 (từ 01/01) chưa bắt đầu. + var r = Calc(RefundScenario.EarlyStop, new DateOnly(2026, 12, 15)); + Assert.Equal(300_000m, r.FixedDeduction); + Assert.Equal(700_000m, r.DepositRefund); + Assert.Equal(1_000_000m, r.RentRefund); + Assert.Equal(1_700_000m, r.Total); + } + + [Fact] + public void Early_stop_in_last_month_refunds_no_rent() + { + var r = Calc(RefundScenario.EarlyStop, new DateOnly(2027, 1, 10)); + Assert.Equal(0m, r.RentRefund); + Assert.Equal(700_000m, r.DepositRefund); + } + + [Fact] + public void Early_stop_damage_beyond_remaining_deposit_gives_zero_refund_and_records_debt() + { + var r = Calc(RefundScenario.EarlyStop, new DateOnly(2026, 12, 15), damage: 800_000m); + Assert.Equal(700_000m, r.DamageDeduction); + Assert.Equal(0m, r.DepositRefund); + Assert.Equal(100_000m, r.Debt); + Assert.Equal(1_000_000m, r.Total); // vẫn hoàn tiền thuê tháng chưa bắt đầu + } + + [Fact] + public void Clean_on_time_return_refunds_full_deposit() + { + var r = Calc(RefundScenario.NormalReturn, End); + Assert.Equal(Deposit, r.DepositRefund); + Assert.Equal(0m, r.FixedDeduction); + Assert.Equal(0m, r.RentRefund); + } + + [Fact] + public void Hygiene_violation_deducts_fixed_10_percent() + { + var r = Calc(RefundScenario.NormalReturn, End, hygiene: true); + Assert.Equal(100_000m, r.FixedDeduction); + Assert.Equal(900_000m, r.DepositRefund); + } + + [Fact] + public void Overdue_return_deducts_fixed_10_percent_plus_overdue_fee() + { + var r = Calc(RefundScenario.NormalReturn, End.AddDays(3), overdue: true, overdueFee: 150_000m); + Assert.Equal(100_000m, r.FixedDeduction); + Assert.Equal(150_000m, r.OverdueDeduction); + Assert.Equal(750_000m, r.DepositRefund); + } + + [Fact] + public void Damage_and_overdue_are_deducted_from_remaining_deposit() + { + var r = Calc(RefundScenario.NormalReturn, End.AddDays(3), hygiene: true, overdue: true, damage: 200_000m, overdueFee: 150_000m); + Assert.Equal(550_000m, r.DepositRefund); + Assert.Equal(0m, r.Debt); + } + + [Fact] + public void Damage_over_deposit_zero_refund_and_shortfall_is_debt() + { + var r = Calc(RefundScenario.NormalReturn, End, damage: 1_200_000m); + Assert.Equal(0m, r.DepositRefund); + Assert.Equal(200_000m, r.Debt); + } + + [Fact] + public void Total_months_rounds_up_and_unused_rent_is_full_before_start() + { + Assert.Equal(3, RefundPolicy.TotalMonths(Start, End)); + Assert.Equal(3, RefundPolicy.TotalMonths(Start, new DateOnly(2027, 1, 31))); + Assert.Equal(Rent, RefundPolicy.UnusedRent(Rent, Start, End, new DateOnly(2026, 10, 1))); + } + + [Fact] + public void Overdue_fee_follows_policy_parameter_and_never_invents_a_default() + { + Assert.Equal(300_000m, RefundPolicy.OverdueFeeFor("PERCENTAGE", 5m, 2_000_000m, 3)); + Assert.Equal(100_000m, RefundPolicy.OverdueFeeFor("FIXED", 50_000m, 2_000_000m, 2)); + Assert.Equal(0m, RefundPolicy.OverdueFeeFor(null, null, 2_000_000m, 0)); + Assert.Throws(() => RefundPolicy.OverdueFeeFor(null, null, 2_000_000m, 2)); + Assert.Throws(() => RefundPolicy.OverdueFeeFor("RULE", 5m, 2_000_000m, 2)); + } +} diff --git a/feature_list.json b/feature_list.json index 8d766d9..e40e0b2 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-20", + "updated": "2026-10-22", "features": [ { "id": "F01", "flow": 1, "uc": ["UC01"], "actor": "Khách hàng", @@ -303,6 +303,19 @@ "state": "active", "verification": "npm run check:structure; npm test; npm run test:business; npm run test:render; npm run build; dotnet build/test -m:1; ./init.sh; kiểm tra browser và PayOS/SQL Server thật", "evidence": "Bàn giao 22/10: browser 13 nhóm PASS; FE 76/76, business 9/9, SSR 92 route, structure/build đạt; backend build + 40 test SQLite. Chờ nhóm kiểm PayOS/SQL Server/thiết bị cửa thật trước merge." + }, + { + "id": "F39", + "flow": [ + 1, + 3, + 6 + ], + "actor": "Đạt + Thắng", + "behavior": "Chính sách cọc và hoàn tiền D27: RefundPolicy tính 3 tình huống (huỷ trước StartDate, dừng sớm, trả kho), cancel-preview, ghi một khoản REFUND khi huỷ, M07 xác nhận hoàn, C14a/B02 hiển thị theo D27", + "state": "active", + "verification": "dotnet build StorageProject.slnx -m:1; dotnet test StorageProject.slnx --no-build -m:1 (RefundPolicyTests); npm test; npm run test:render; npm run check:structure; npm run build; kiểm tra huỷ đơn, cancel-preview và M07 trên SQL Server của nhóm", + "evidence": "2026-10-22: viết xong code BE (RefundPolicy, GetCancelPreviewAsync, CancelReservationAsync ghi REFUND PENDING, ConfirmRefundAsync theo D27, POST /api/ops/reservations/{id}/refund) và 11 test xUnit cho công thức. Phiên viết code không có .NET SDK nên BE chưa được biên dịch hay chạy test; FE: npm test 76/76, test:render, check:structure, build đạt (xem progress.md). Giữ active đến khi nhóm chạy dotnet build/test và kiểm thử luồng thật." } ] } diff --git a/progress.md b/progress.md index 417d6d6..eafb4af 100644 --- a/progress.md +++ b/progress.md @@ -363,3 +363,13 @@ - Nhóm chốt theo D27 (DECISIONS.md): cọc 1 tháng thuê, hủy trước StartDate giữ 10% cọc, dừng sau StartDate hoàn 70% cọc, phương án B cho tiền thuê khi dừng giữa kỳ, phạt quá hạn theo tham số OVERDUE ở B02, DamageFee và OverdueFee trừ thêm vào cọc. - Chưa có code: feature_list.json không đổi trạng thái vì chưa có bằng chứng chạy. Phần cần làm đã ghi trong BACKEND-TODO.md mục D27. - Cần đổi: H1 cancel-preview và CANCEL_FEE_RATE đang tính 10% tiền thuê, không theo D27. T05 trong doc vẫn để "theo chính sách đã chốt". + +## 2026-10-22 — F39 code chính sách cọc và hoàn tiền D27 (T01, T05, T08) + +- Tính năng phiên này duy nhất F39; nền origin/main 248a083. Làm theo D27, không đổi quyết định. +- Backend: RefundPolicy (hàm thuần), cancel-preview, huỷ đơn đã thanh toán ghi một khoản REFUND PENDING, M07 xác nhận hoàn cho đơn đã huỷ, ConfirmRefundAsync hợp đồng tính theo D27 và chỉ trừ trong phạm vi cọc (phần thiếu giữ thành công nợ). Chính sách OVERDUE seed đổi mô tả thành 5% tiền thuê tháng mỗi ngày trễ. +- Frontend: cancelPreviewOf đổi sang 10% tiền cọc; test huỷ đơn (C14a) cập nhật số mong đợi 4.600.000 − 115.000. Không sửa test nào để cho qua; chỉ đổi số liệu theo D27. +- Kiểm chứng: FE npm test 76/76. Backend: phiên này không có .NET SDK nên chưa biên dịch và chưa chạy test; đã thêm RefundPolicyTests (11 trường hợp) và đối chiếu công thức tháng bằng bản tính độc lập. F39 giữ active, chưa passing. +- Giả định cần nhóm xác nhận: (1) dừng sớm thì khấu trừ cố định 30% đã bao gồm khoản vệ sinh 10%; (2) khoản CLEANING_FEE chờ thanh toán được coi là đã nằm trong khoản khấu trừ cố định; (3) quá hạn tính từ EndDate đến ngày biên bản trả kho; (4) khoản gia hạn (RENEWAL) không nằm trong phần hoàn tiền thuê. +- Không push/PR/merge. + From 306ab772630894fabf4c2c22bcc23127095e1a76 Mon Sep 17 00:00:00 2001 From: Vector Date: Fri, 23 Oct 2026 00:39:44 +0700 Subject: [PATCH 2/2] =?UTF-8?q?feat:=20chuy=E1=BB=83n=20=C3=B4=20kho=20san?= =?UTF-8?q?g=20=C4=91ang=20thu=C3=AA=20khi=20=C4=91=E1=BA=BFn=20ng=C3=A0y?= =?UTF-8?q?=20b=E1=BA=AFt=20=C4=91=E1=BA=A7u=20v=C3=A0=20d=C3=B9ng=20chung?= =?UTF-8?q?=20logic=20ho=C3=A0n=20c=E1=BB=8Dc=20D27?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Thêm UnitStartActivation: ô kho đang giữ chỗ chuyển sang đang thuê khi hợp đồng đến ngày bắt đầu (giờ Việt Nam), ghi lịch sử trạng thái, chạy trong worker mỗi phút - Đường hoàn cọc cũ của quản lý gọi chung logic hoàn cọc D27, bỏ hàm cũ đặt hợp đồng sang trạng thái ENDED không hợp lệ - Thêm test cho việc chuyển trạng thái ô kho; cập nhật BACKEND-TODO, progress và feature_list --- .../SafeSpace-Customer-UI/BACKEND-TODO.md | 3 +- .../Endpoints/ManagerEndpoints.cs | 20 ++++++---- .../Workers/ExpiredCashHoldWorker.cs | 4 +- .../Interfaces/IManagerService.cs | 1 - .../Services/ManagerService.cs | 18 --------- .../Services/UnitStartActivation.cs | 37 +++++++++++++++++++ .../Services/UnitStatusRules.cs | 3 +- StorageProject.Tests/CheckoutTests.cs | 15 ++++++++ feature_list.json | 4 +- progress.md | 2 +- 10 files changed, 74 insertions(+), 33 deletions(-) create mode 100644 StorageProject.Infrastructure/Services/UnitStartActivation.cs diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index b2b32d0..6a6bd55 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -348,4 +348,5 @@ Trạng thái triển khai D27 (22/10/2026): - `POST /api/ops/reservations/{id}/refund` (M07, chỉ quản lý): xác nhận đã chuyển khoản hoàn cho đơn đã huỷ, `PENDING` → `PAID`, chỉ chạy được một lần. - `POST /api/ops/contracts/{id}/refund` (M07): tính theo D27 từ biên bản trả kho. Trả trước EndDate = dừng sớm; trễ so với EndDate = quá hạn. Ghi một khoản `REFUND` gồm hoàn thuê + hoàn cọc; hư hỏng/quá hạn chỉ trừ trong phạm vi cọc, phần thiếu giữ trạng thái chưa thanh toán (công nợ). - Giao diện: `cancelPreviewOf` (appReducer.js) tính 10% tiền cọc; C14a hiển thị phí và số hoàn theo đó. Còn thiếu: nút xác nhận hoàn cho đơn đã huỷ ở màn M07. -- Chưa làm: `ManagerService.ConfirmRefundAsync` (đường cũ `POST /api/manager/contracts/{id}/refund`) vẫn đặt trạng thái `ENDED` và không theo D27; cần gộp với `FacilityOpsService.ConfirmRefundAsync` (liên quan T02). +- Đường cũ `POST /api/manager/contracts/{id}/refund` giờ gọi chung `FacilityOpsService.ConfirmRefundAsync` (D27); đã bỏ `ManagerService.ConfirmRefundAsync` (trước đây đặt trạng thái `ENDED` không hợp lệ). Id phải là mã hiển thị `HĐ-…` như `/api/ops`; tài khoản ADMIN không có cơ sở được phân công nên nhận 403. +- F12 · RESERVED → OCCUPIED: `UnitStartActivation` (chạy cùng worker mỗi phút) chuyển ô đang giữ chỗ sang đang thuê khi hợp đồng ACTIVE/EXPIRING đến `StartDate` (giờ Việt Nam), ghi `unit_status_histories`. Nhận chìa khóa vẫn không đổi trạng thái ô (D26). Chuyển RESERVED/OCCUPIED bằng tay vẫn bị chặn ở `UnitStatusRules`. diff --git a/StorageProject.Api/Endpoints/ManagerEndpoints.cs b/StorageProject.Api/Endpoints/ManagerEndpoints.cs index 4405c4b..7d1d570 100644 --- a/StorageProject.Api/Endpoints/ManagerEndpoints.cs +++ b/StorageProject.Api/Endpoints/ManagerEndpoints.cs @@ -1,5 +1,6 @@ using System.Security.Claims; using StorageProject.Api.Extensions; +using StorageProject.Core.DTOs.FacilityOps; using StorageProject.Core.DTOs.Ops; using StorageProject.Core.Interfaces; @@ -131,19 +132,22 @@ public static RouteGroupBuilder MapManagerEndpoints(this IEndpointRouteBuilder a } }); - group.MapPost("/contracts/{id}/refund", async (string id, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => + // Đường cũ giữ lại cho tương thích: dùng chung logic D27 với POST /api/ops/contracts/{id}/refund. + group.MapPost("/contracts/{id}/refund", async (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) => { - var role = user.GetUserRole(); - if (!role.Equals("MANAGER", StringComparison.OrdinalIgnoreCase) && !role.Equals("ADMIN", StringComparison.OrdinalIgnoreCase)) + try + { + var actor = new OpsActor(user.GetUserId(), user.GetUserRole().Equals("MANAGER", StringComparison.OrdinalIgnoreCase)); + var refund = await ops.ConfirmRefundAsync(actor, id, ct); + return Results.Ok(new { message = "Xác nhận hoàn cọc thành công.", refund }); + } + catch (UnauthorizedAccessException) { return Results.Forbid(); } - - try + catch (KeyNotFoundException ex) { - var userId = user.GetUserId(); - await managerService.ConfirmRefundAsync(userId, id, ct); - return Results.Ok(new { message = "Xác nhận hoàn cọc thành công." }); + return Results.NotFound(new { error = ex.Message }); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { diff --git a/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs b/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs index cde02e5..8989627 100644 --- a/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs +++ b/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs @@ -11,7 +11,9 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) do { try { using var scope = scopes.CreateScope(); - await CashHoldExpiry.ExpireAsync(scope.ServiceProvider.GetRequiredService(), stoppingToken); + var db = scope.ServiceProvider.GetRequiredService(); + await CashHoldExpiry.ExpireAsync(db, stoppingToken); + await UnitStartActivation.ActivateAsync(db, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { return; } catch (Exception ex) { logger.LogError(ex, "Không xử lý được các đơn hết hạn giữ chỗ"); } } while (await timer.WaitForNextTickAsync(stoppingToken)); diff --git a/StorageProject.Core/Interfaces/IManagerService.cs b/StorageProject.Core/Interfaces/IManagerService.cs index 0c1d022..6451900 100644 --- a/StorageProject.Core/Interfaces/IManagerService.cs +++ b/StorageProject.Core/Interfaces/IManagerService.cs @@ -10,7 +10,6 @@ public interface IManagerService Task ApproveRenewalAsync(long userId, string id, CancellationToken ct = default); Task RejectRenewalAsync(long userId, string id, RejectRenewalRequest request, CancellationToken ct = default); Task AddContractReminderAsync(long userId, string id, AddReminderRequest request, CancellationToken ct = default); - Task ConfirmRefundAsync(long userId, string id, CancellationToken ct = default); // Facility storage unit management (UC13) Task> GetFacilityUnitsAsync(long userId, CancellationToken ct = default); diff --git a/StorageProject.Infrastructure/Services/ManagerService.cs b/StorageProject.Infrastructure/Services/ManagerService.cs index 151fce3..d076597 100644 --- a/StorageProject.Infrastructure/Services/ManagerService.cs +++ b/StorageProject.Infrastructure/Services/ManagerService.cs @@ -240,24 +240,6 @@ public async Task AddContractReminderAsync(long userId, string id, AddReminderRe } } - public async Task ConfirmRefundAsync(long userId, string id, CancellationToken ct = default) - { - var num = FacilityOpsStateStore.ParseIdNumber(id); - var contract = await dbContext.RentalContracts - .Include(c => c.Unit) - .FirstOrDefaultAsync(c => c.ContractId == num, ct); - if (contract != null) - { - contract.Status = "ENDED"; - if (contract.Unit != null) - { - contract.Unit.Status = "AVAILABLE"; - contract.Unit.UpdatedAt = DateTime.UtcNow; - } - await dbContext.SaveChangesAsync(ct); - } - } - public async Task> GetFacilityUnitsAsync(long userId, CancellationToken ct = default) { var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); diff --git a/StorageProject.Infrastructure/Services/UnitStartActivation.cs b/StorageProject.Infrastructure/Services/UnitStartActivation.cs new file mode 100644 index 0000000..cf9ff6d --- /dev/null +++ b/StorageProject.Infrastructure/Services/UnitStartActivation.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +/// +/// F12/M02 · Ô kho đang giữ chỗ (RESERVED) chuyển sang đang thuê (OCCUPIED) khi đến ngày bắt đầu của hợp đồng +/// (giờ Việt Nam, D27: "đã sử dụng" tính từ StartDate). Nhận chìa khóa không đổi trạng thái ô (D26). +/// Chạy lặp lại an toàn: ô đã OCCUPIED không bị đụng tới và không ghi lịch sử thêm. +/// +public static class UnitStartActivation +{ + public static async Task ActivateAsync(AppDbContext db, CancellationToken ct = default) + { + var today = OpsRules.TodayLocal; + var contracts = await db.RentalContracts.Include(c => c.Unit) + .Where(c => (c.Status == "ACTIVE" || c.Status == "EXPIRING") && c.StartDate <= today && c.Unit.Status == "RESERVED") + .OrderBy(c => c.ContractId).Take(200).ToListAsync(ct); + if (contracts.Count == 0) return 0; + + var now = DateTime.UtcNow; + foreach (var c in contracts) + { + // Thay đổi tự động ghi theo khách của hợp đồng (khóa ngoại user), giống ContractProvisioning. + db.UnitStatusHistories.Add(new UnitStatusHistory + { + Unit = c.Unit, ChangedBy = c.CustomerId, OldStatus = "RESERVED", NewStatus = "OCCUPIED", + ChangedAt = now, Reason = $"Đến ngày bắt đầu thuê của hợp đồng #{c.ContractId}" + }); + c.Unit.Status = "OCCUPIED"; + c.Unit.UpdatedAt = now; + } + await db.SaveChangesAsync(ct); + return contracts.Count; + } +} diff --git a/StorageProject.Infrastructure/Services/UnitStatusRules.cs b/StorageProject.Infrastructure/Services/UnitStatusRules.cs index 6f3fefc..9ecc8c6 100644 --- a/StorageProject.Infrastructure/Services/UnitStatusRules.cs +++ b/StorageProject.Infrastructure/Services/UnitStatusRules.cs @@ -2,7 +2,8 @@ namespace StorageProject.Infrastructure.Services; public static class UnitStatusRules { - // Lifecycle transitions RESERVED/OCCUPIED/INSPECTION are owned by allocation/handover/return services. + // Lifecycle transitions RESERVED/OCCUPIED/INSPECTION are owned by allocation, UnitStartActivation (RESERVED → OCCUPIED + // khi đến StartDate) and return services. public static string Normalize(string status) => status.Trim().ToUpperInvariant() switch { "EMPTY" => "AVAILABLE", "ACTIVE" => "OCCUPIED", "WAITING_HANDOVER" => "RESERVED", "LOCKED" => "OUT_OF_SERVICE", var value => value diff --git a/StorageProject.Tests/CheckoutTests.cs b/StorageProject.Tests/CheckoutTests.cs index 22174bf..a4397c9 100644 --- a/StorageProject.Tests/CheckoutTests.cs +++ b/StorageProject.Tests/CheckoutTests.cs @@ -109,6 +109,21 @@ [Fact] public async Task OtherCustomerCannotSwitchAndExpiredHoldCannotBeCollecte await Assert.ThrowsAsync(() => new StaffService(f.Db).ConfirmPaymentAsync(1, "SS-0001")); Assert.Empty(await f.Db.Payments.ToListAsync()); } + [Fact] public async Task ReservedUnitBecomesOccupiedOnStartDateOnly() { + await using var f = await Fixture.Create(); + Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); + var unit = await f.Db.StorageUnits.SingleAsync(); + Assert.Equal("RESERVED", unit.Status); + Assert.Equal(0, await UnitStartActivation.ActivateAsync(f.Db)); // chưa đến StartDate + Assert.Equal("RESERVED", unit.Status); + var contract = await f.Db.RentalContracts.SingleAsync(); + contract.StartDate = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + await f.Db.SaveChangesAsync(); + Assert.Equal(1, await UnitStartActivation.ActivateAsync(f.Db)); + Assert.Equal("OCCUPIED", unit.Status); + Assert.Equal(0, await UnitStartActivation.ActivateAsync(f.Db)); // chạy lại không ghi thêm + Assert.Single(await f.Db.UnitStatusHistories.Where(h => h.NewStatus == "OCCUPIED").ToListAsync()); + } [Fact] public async Task UnitMaintenanceWritesHistoryAndRefusesOccupiedUnit() { await using var f = await Fixture.Create(); var staff = new StaffService(f.Db); await Assert.ThrowsAsync(() => staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "MAINTENANCE" })); diff --git a/feature_list.json b/feature_list.json index e40e0b2..35e71e0 100644 --- a/feature_list.json +++ b/feature_list.json @@ -312,10 +312,10 @@ 6 ], "actor": "Đạt + Thắng", - "behavior": "Chính sách cọc và hoàn tiền D27: RefundPolicy tính 3 tình huống (huỷ trước StartDate, dừng sớm, trả kho), cancel-preview, ghi một khoản REFUND khi huỷ, M07 xác nhận hoàn, C14a/B02 hiển thị theo D27", + "behavior": "Chính sách cọc và hoàn tiền D27: RefundPolicy tính 3 tình huống (huỷ trước StartDate, dừng sớm, trả kho), cancel-preview, ghi một khoản REFUND khi huỷ, M07 xác nhận hoàn, C14a/B02 hiển thị theo D27, ô kho RESERVED → OCCUPIED khi đến StartDate (F12), đường hoàn cọc cũ dùng chung logic D27", "state": "active", "verification": "dotnet build StorageProject.slnx -m:1; dotnet test StorageProject.slnx --no-build -m:1 (RefundPolicyTests); npm test; npm run test:render; npm run check:structure; npm run build; kiểm tra huỷ đơn, cancel-preview và M07 trên SQL Server của nhóm", - "evidence": "2026-10-22: viết xong code BE (RefundPolicy, GetCancelPreviewAsync, CancelReservationAsync ghi REFUND PENDING, ConfirmRefundAsync theo D27, POST /api/ops/reservations/{id}/refund) và 11 test xUnit cho công thức. Phiên viết code không có .NET SDK nên BE chưa được biên dịch hay chạy test; FE: npm test 76/76, test:render, check:structure, build đạt (xem progress.md). Giữ active đến khi nhóm chạy dotnet build/test và kiểm thử luồng thật." + "evidence": "2026-10-22: viết xong code BE (RefundPolicy, GetCancelPreviewAsync, CancelReservationAsync ghi REFUND PENDING, ConfirmRefundAsync theo D27, POST /api/ops/reservations/{id}/refund) và 11 test xUnit cho công thức, UnitStartActivation (RESERVED → OCCUPIED) và test ReservedUnitBecomesOccupiedOnStartDateOnly. Lượt đầu đã build + 51 test đạt trên máy nhóm; phần bổ sung F12 và đường hoàn cọc cũ chưa được biên dịch (không có .NET SDK trong phiên); FE: npm test 76/76, test:render, check:structure, build đạt (xem progress.md). Giữ active đến khi nhóm chạy dotnet build/test và kiểm thử luồng thật." } ] } diff --git a/progress.md b/progress.md index eafb4af..3455085 100644 --- a/progress.md +++ b/progress.md @@ -372,4 +372,4 @@ - Kiểm chứng: FE npm test 76/76. Backend: phiên này không có .NET SDK nên chưa biên dịch và chưa chạy test; đã thêm RefundPolicyTests (11 trường hợp) và đối chiếu công thức tháng bằng bản tính độc lập. F39 giữ active, chưa passing. - Giả định cần nhóm xác nhận: (1) dừng sớm thì khấu trừ cố định 30% đã bao gồm khoản vệ sinh 10%; (2) khoản CLEANING_FEE chờ thanh toán được coi là đã nằm trong khoản khấu trừ cố định; (3) quá hạn tính từ EndDate đến ngày biên bản trả kho; (4) khoản gia hạn (RENEWAL) không nằm trong phần hoàn tiền thuê. - Không push/PR/merge. - +- Bổ sung cùng F39 (cùng đợt, trước khi merge): (a) F12 ô kho RESERVED → OCCUPIED khi đến StartDate, qua UnitStartActivation chạy trong worker hiện có, có test ReservedUnitBecomesOccupiedOnStartDateOnly; (b) đường hoàn cọc cũ của quản lý gọi chung logic D27, bỏ ManagerService.ConfirmRefundAsync (lỗi: đặt trạng thái ENDED, không theo D27). Cả hai chưa biên dịch trong phiên viết code; cần dotnet build/test của nhóm. Còn lại: nút xác nhận hoàn đơn huỷ ở M07 trên giao diện.