Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:

Expand All @@ -341,4 +341,12 @@ 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.
- Đườ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`.
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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/);
});
10 changes: 9 additions & 1 deletion StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down
20 changes: 12 additions & 8 deletions StorageProject.Api/Endpoints/ManagerEndpoints.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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)
{
Expand Down
16 changes: 16 additions & 0 deletions StorageProject.Api/Endpoints/ReservationEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion StorageProject.Api/Workers/ExpiredCashHoldWorker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
do {
try {
using var scope = scopes.CreateScope();
await CashHoldExpiry.ExpireAsync(scope.ServiceProvider.GetRequiredService<AppDbContext>(), stoppingToken);
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
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));
Expand Down
12 changes: 11 additions & 1 deletion StorageProject.Core/DTOs/Reservation/ReservationDtos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
);

/// <summary>C14a · Ước tính khi huỷ đơn đã thanh toán trước ngày bắt đầu (D27).</summary>
public record CancelPreviewDto(
decimal PaidAmount,
decimal CancellationFee,
decimal RefundAmount,
string PolicyName
);

public record ReservationDetailDto(
Expand Down
2 changes: 2 additions & 0 deletions StorageProject.Core/Interfaces/IFacilityOpsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<decimal> ConfirmRefundAsync(OpsActor actor, string id, CancellationToken ct = default);
/// <summary>M07 · Xác nhận đã chuyển khoản hoàn tiền cho đơn đã huỷ (D27).</summary>
Task<decimal> ConfirmReservationRefundAsync(OpsActor actor, string id, CancellationToken ct = default);
}
1 change: 0 additions & 1 deletion StorageProject.Core/Interfaces/IManagerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IReadOnlyList<OpsUnitDto>> GetFacilityUnitsAsync(long userId, CancellationToken ct = default);
Expand Down
1 change: 1 addition & 0 deletions StorageProject.Core/Interfaces/IServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public interface IReservationService
Task<IReadOnlyList<ReservationDto>> GetMyReservationsAsync(long customerId, CancellationToken ct = default);
Task<ReservationDetailDto?> GetReservationDetailAsync(long customerId, long reservationId, CancellationToken ct = default);
Task<ReservationDto> CreateReservationAsync(long customerId, CreateReservationRequest request, CancellationToken ct = default);
Task<CancelPreviewDto> GetCancelPreviewAsync(long customerId, long reservationId, CancellationToken ct = default);
Task CancelReservationAsync(long customerId, long reservationId, string reason, CancellationToken ct = default);
Task<ReservationDto> ConfirmTransferAsync(long customerId, long reservationId, CancellationToken ct = default);
}
Expand Down
Loading