diff --git a/DECISIONS.md b/DECISIONS.md
index 07e50ff..8602875 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -327,3 +327,15 @@ Bổ sung @playwright/test trong devDependencies để kiểm thao tác biểu m
- Tên đăng nhập bắt buộc, tối đa 50 ký tự theo cột User.Username, không chứa khoảng trắng hoặc @ để tránh nhầm định danh email; trùng username/email trả đúng lỗi từ backend. Tài khoản cũ giữ nguyên.
- B03 chọn cơ sở trước → B03a bốn loại kho (15/30 m², thường/lạnh), có ảnh và sửa giá cho đúng cơ sở/loại kho/ngày áp dụng. Giá đọc API; không chép số minh họa Figma. Không sửa ngược giá hợp đồng. B02 giữ quản lý chính sách/phí toàn hệ thống theo D32.
- Chỉ sửa FE, ghi nhận hợp đồng T20 backend đã merge trên main c1a9b05. Không xác nhận tích hợp SQL Server/PayOS thật và không đổi trạng thái feature.
+
+## D34 — 29/10/2026: Cách backend triển khai T05/T07/T08/T13 và cờ khả năng — Chờ nhóm xác nhận
+
+> Người dùng (FE) yêu cầu ngày 29/10 làm hộ phần BE: sự cố cơ sở (T13, kế hoạch giao Tiến) và cờ hỗ trợ Batch08 kèm T05/T07/T08 (giao Ngọc Mai). Không đổi quy tắc tiền của D27/D32; chỉ ghi các lựa chọn kỹ thuật cần nhóm biết. Nhánh `feature/be-t05-t07-t08-t13-flags`, chưa build/kiểm SQL Server.
+
+- **Ảnh bằng chứng** (trả kho, kiểm kê, sự cố): gửi JSON base64 theo hợp đồng FE, tối đa 5 ảnh JPG/PNG mỗi lần, ≤ 5 MiB/ảnh, server tự kiểm chữ ký tệp. Lưu trong bảng `evidence_photos` của SQL Server (không để thư mục web công khai). Đọc qua URL có chữ ký HMAC hết hạn 1 giờ (khoá dẫn từ `JwtSettings:Secret`).
+- **Tài khoản chính chủ** lưu cột riêng trên `reservations` (huỷ đơn), `return_inspections` (gửi trả kho) và `facility_incidents` (kết thúc do sự cố) — không ghi vào nhật ký vì admin đọc được nhật ký.
+- **Huỷ đơn đã thanh toán trước StartDate** áp dụng cả đơn đã được tự cấp hợp đồng sau thanh toán (D26, `UNIT_ASSIGNED`) khi khách chưa nhận chìa khóa: hợp đồng chuyển `CANCELLED`, ô `RESERVED` về `AVAILABLE`, mã QR/PIN do hệ thống vô hiệu (`REVOKED`) — không phải API thu hồi thủ công (giữ D32).
+- **Hoàn tiền hai bước**: khoản hoàn cọc sau trả kho và khoản hoàn do sự cố cơ sở dùng chung màn/API hoàn cọc (`/api/ops/deposit-refunds`); phiên bản khoản hoàn = 1 khi chờ hoàn, 2 khi đã hoàn. Mã giao dịch không được trùng giữa các khoản.
+- **Cờ khả năng** được bật cố định trên `GET /api/ops/board` và `GET /api/rental-policy` của nhánh này vì server đã lưu đủ dữ liệu tương ứng. `returns[].damageWorkflowResolved = true` vì BE chưa có luồng phản hồi/khắc phục hư hỏng (Batch06) nên không hồ sơ nào có thể đang mở; khi làm Batch06 phải tính lại cờ này.
+- **Sự cố cơ sở (T13)**: mã hồ sơ `SC-{mã hợp đồng}-{lần}` cấp từ lúc còn nháp; ô tương đương = cùng cơ sở + cùng loại kho (loại và diện tích), trống, không bảo trì, không trùng hợp đồng khác; ô được giữ (`RESERVED`) từ lúc gửi phương án tới khi khách chọn. Khoản hoàn khi kết thúc = tiền tháng đang thuê + các tháng nguyên chưa bắt đầu (theo giá `AgreedMonthlyRate`) + 100% cọc, chốt tại ngày quản lý xác nhận kết thúc.
+- Cần nhóm xác nhận: (1) Tiến / Ngọc Mai review vì chạm phần việc đã giao; (2) giá dùng cho tháng chưa dùng khi hợp đồng đã gia hạn với giá khác; (3) giữ ảnh trong DB hay chuyển sang lưu trữ tệp riêng sau 31/10.
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
index 0359133..e1e9ab9 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
@@ -35,6 +35,21 @@ Mã việc khớp kế hoạch "SafeSpace — Kế hoạch hoàn thiện cập n
Không làm: thu hồi QR/PIN thủ công; công nợ sau trả kho; thanh toán phí phát sinh sau trả kho qua PayOS hoặc tại quầy (`POST /api/payments/{id}/at-facility`, `feeCollections`, `POST /api/ops/fees/{id}/confirm`).
+### Cập nhật BE 29/10 — nhánh `feature/be-t05-t07-t08-t13-flags` (xếp chồng trên PR #53)
+
+Đã viết code BE, **chưa build / chưa chạy test / chưa tạo migration** (môi trường AI không có .NET), chưa kiểm SQL Server. Người nhận chạy `dotnet ef migrations add AddRefundEvidenceAndIncidents`, `dotnet build`, `dotnet test` rồi kiểm tích hợp với FE PR #53.
+
+| Mã | Đã có trên nhánh | Còn lại |
+|---|---|---|
+| T05 | `POST /api/ops/returns/{id}/inspection` lưu `damageFee`, `cleaningRequired` (vệ sinh = 10% cọc do server tính), `damageItem`, `feeReason`, ảnh (`photos[]` JSON base64, bắt buộc khi có hư hỏng); board trả `report` đủ phí/ảnh, `requestedAt`, `overdueFee` | Route cũ `/api/staff/returns/{id}/inspection` chưa nhận phí/ảnh |
+| T07 | M07 chỉ tạo `REFUND` `PENDING` (trả `{refund, refundStatus}`), ô cần vệ sinh/sửa giữ `MAINTENANCE`; `GET /api/ops/deposit-refunds`, `POST /api/ops/deposit-refunds/actions` (`CONFIRM_DEPOSIT_REFUND`, `expectedVersion` cũ → 409); khách `GET /api/deposit-refunds` | Khoản `DAMAGE_FEE/OVERDUE_FEE` cũ còn PENDING trên dữ liệu cũ (T06) chưa dọn |
+| T08 | Huỷ đơn đã thanh toán bắt buộc tài khoản chính chủ (kể cả đơn `UNIT_ASSIGNED` trước StartDate, mã QR/PIN hết hiệu lực); gửi trả kho bắt buộc ảnh kho trống + tài khoản + `emptied`, nhận cả hợp đồng `OVERDUE`, chặn gửi trùng; M08 lưu `transactionRef`/`transferredAt`; `GET /api/rental-policy` trả `cancellationBankSupported`, `returnRequestSupported` | — |
+| S02 | `POST /api/ops/verifications/{id}` nhận checklist 4 mục, không cần số giấy tờ; `POST /api/ops/keys/{id}/receipt` nhận checklist 3 mục | — |
+| Cờ | Board trả `verificationChecklistSupported`, `inspectionEvidenceSupported`, `refundEvidenceSupported`, `returnPolicyVersion: "D32"`, `returns[].damageWorkflowResolved`, `refunds[]` (M08) | `damageWorkflowResolved` luôn `true` vì BE chưa có luồng phản hồi hư hỏng Batch06 (không hồ sơ nào đang mở) |
+| T13 | Toàn bộ hợp đồng Batch07: `GET /api/ops/incidents`, `POST /api/ops/incidents`, `/complete-transfer`, `/terminate`, khách `GET /api/incidents`, `POST /api/contracts/{contractId}/incident-choice`; khoản hoàn sự cố xác nhận chuyển tiền ở màn hoàn cọc | Chưa có idempotency key riêng (dựa `expectedVersion` + khoá giao dịch) |
+
+Ảnh lưu trong bảng `evidence_photos` (riêng tư), đọc qua `GET /api/evidence-photos/{id}?exp=&sig=` (chữ ký HMAC, hết hạn 1 giờ). Dev FE :5173 + API :5151: link ảnh dùng `EvidencePhotos:PublicBaseUrl` (mặc định `http://localhost:5151` khi Development). Nginx `/api/` nâng `client_max_body_size 40m`.
+
### Bàn giao FE T10 / T15 — 26/10
FE đã ẩn phí trả kho đang chờ thu ở C11, bỏ route S09f/queue/badge và adapter thu phí, gỡ adapter `REVOKE_CREDENTIAL`; vẫn giữ luồng tiền thuê/gia hạn và cấp lại mã.
@@ -62,7 +77,7 @@ tên route + tên trường JSON là giao diện chạy ngay, không phải sử
| 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 | **Đã 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 | — |
+| 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ập nhật 29/10: main đã kiểm chuyển tiếp qua `UnitStatusRules.Validate`, bắt buộc lý do, chặn ô đang giữ/có hợp đồng và ghi `unit_status_history` — dòng "còn thiếu" cũ không còn đúng | Thắng | Đã có |
### P · PayOS (D19) và thanh toán tại cửa hàng
```json
@@ -512,6 +527,8 @@ Khi cho khắc phục vẫn giữ deduction đến inspection PASS; bỏ đúng
## Batch07 — T13 sự cố cơ sở: API ĐỀ XUẤT, chưa có trên main c1a9b05
+> 29/10: đã viết BE theo đúng hợp đồng dưới đây trên nhánh `feature/be-t05-t07-t08-t13-flags` (xem "Cập nhật BE 29/10" ở đầu tệp); chưa build/kiểm SQL Server.
+
FE có D30-10/16/16b; không triển khai BE/schema và chưa chứng minh tích hợp thật. Cần BE owner thống nhất contract dưới đây; giữ các đường T13 đề xuất trước, bổ sung GET/save/send/terminate/version/evidence.
### Đọc và khởi tạo nháp
@@ -544,6 +561,8 @@ Contract đã ENDED/RETURN_PENDING/OVERDUE hoặc đang có xử lý xung đột
## Batch08 — T05–T08/T11–T12, S02/M07/M08: contract FE bổ sung, chưa có đầy đủ trên main c1a9b05
+> 29/10: S02, S04/T05, M07/T07, M08/T08 và các cờ đã viết BE trên nhánh `feature/be-t05-t07-t08-t13-flags`; T11/T12 (quá hạn ngày 20) **chưa làm**. Cờ chỉ được giữ `true` sau khi nhóm build và kiểm luồng trên SQL Server.
+
Không sửa BE/schema trong task này. Các marker bên dưới là đề xuất tích hợp, **server chỉ công bố sau khi đã triển khai và kiểm chứng**; không bật từ FE/env hoặc mock để giả hỗ trợ. Cờ không thay server authorization/validation/transaction.
| Phần | JSON / yêu cầu server |
diff --git a/StorageProject.Api/Endpoints/ContractEndpoints.cs b/StorageProject.Api/Endpoints/ContractEndpoints.cs
index 9faf095..0e7d8e2 100644
--- a/StorageProject.Api/Endpoints/ContractEndpoints.cs
+++ b/StorageProject.Api/Endpoints/ContractEndpoints.cs
@@ -52,11 +52,12 @@ public static RouteGroupBuilder MapContractEndpoints(this IEndpointRouteBuilder
{
return Results.NotFound(new { error = ex.Message });
}
- catch (InvalidOperationException ex)
+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
return Results.BadRequest(new { error = ex.Message });
}
- });
+ })
+ .WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(StorageProject.Infrastructure.Services.EvidencePhotos.RequestBodyLimit));
return group;
}
diff --git a/StorageProject.Api/Endpoints/EvidenceEndpoints.cs b/StorageProject.Api/Endpoints/EvidenceEndpoints.cs
new file mode 100644
index 0000000..8b83a8e
--- /dev/null
+++ b/StorageProject.Api/Endpoints/EvidenceEndpoints.cs
@@ -0,0 +1,32 @@
+using Microsoft.EntityFrameworkCore;
+using StorageProject.Infrastructure.Data;
+using StorageProject.Infrastructure.Services;
+
+namespace StorageProject.Api.Endpoints;
+
+///
+/// Ảnh bằng chứng (trả kho, kiểm kê). Không cần token vì link mở trong tab mới; thay vào đó URL do server cấp
+/// kèm chữ ký HMAC và hạn 1 giờ (EvidencePhotos.Url) — chỉ người vừa được API trả link (đúng quyền) mới có.
+/// Sai chữ ký / hết hạn → 404 để không lộ ảnh có tồn tại hay không.
+///
+public static class EvidenceEndpoints
+{
+ public static void MapEvidenceEndpoints(this IEndpointRouteBuilder routes)
+ {
+ routes.MapGet("/api/evidence-photos/{id:long}", async (long id, long? exp, string? sig, AppDbContext db, HttpContext http, CancellationToken ct) =>
+ {
+ if (exp is not long expires || !EvidencePhotos.Verify(id, expires, sig)) return Results.NotFound();
+ var photo = await db.EvidencePhotos.AsNoTracking()
+ .Where(p => p.PhotoId == id)
+ .Select(p => new { p.Data, p.ContentType })
+ .FirstOrDefaultAsync(ct);
+ if (photo == null) return Results.NotFound();
+ http.Response.Headers.CacheControl = "private, max-age=600";
+ http.Response.Headers["X-Content-Type-Options"] = "nosniff";
+ return Results.File(photo.Data, photo.ContentType);
+ })
+ .AllowAnonymous()
+ .WithTags("Evidence")
+ .WithSummary("Ảnh bằng chứng qua URL có chữ ký, hết hạn sau 1 giờ");
+ }
+}
diff --git a/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs
index f19284c..f5e17a8 100644
--- a/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs
+++ b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs
@@ -2,6 +2,7 @@
using StorageProject.Api.Extensions;
using StorageProject.Core.DTOs.FacilityOps;
using StorageProject.Core.Interfaces;
+using StorageProject.Infrastructure.Services;
namespace StorageProject.Api.Endpoints;
@@ -35,13 +36,14 @@ public static void MapFacilityOpsEndpoints(this IEndpointRouteBuilder routes)
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("/keys/{id}/receipt", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
- Run(async () => { await ops.RecordKeyReceiptAsync(Actor(user), id, ct); return Done(); }))
- .WithSummary("Ghi nhận khách nhận chìa khóa vật lý; không kích hoạt hợp đồng");
+ group.MapPost("/keys/{id}/receipt", (string id, OpsKeyReceiptRequest? request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => { await ops.RecordKeyReceiptAsync(Actor(user), id, request, ct); return Done(); }))
+ .WithSummary("Ghi nhận khách nhận chìa khóa vật lý (checklist 3 mục nếu gửi); không kích hoạt hợp đồng");
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");
+ .WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(EvidencePhotos.RequestBodyLimit))
+ .WithSummary("S04 · Biên bản kiểm kê trả kho: 4 mục, phí hư hỏng, vệ sinh 10% cọc, lý do, ảnh (D32 / T05)");
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(); }))
@@ -68,21 +70,68 @@ public static void MapFacilityOpsEndpoints(this IEndpointRouteBuilder routes)
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) =>
+ group.MapPost("/contracts/{id}/refund", (string id, OpsNoteRequest? request, 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 });
+ var result = await ops.ConfirmRefundAsync(Actor(user), id, request?.Note, ct);
+ return Results.Ok(new { message = "Đã cập nhật.", refund = result.Refund, refundStatus = result.RefundStatus });
}))
- .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");
+ .WithSummary("M07 · Chốt quyết toán trả kho (D32): tạo khoản hoàn PENDING, đóng hợp đồng; ô cần vệ sinh giữ MAINTENANCE");
- group.MapPost("/reservations/{id}/refund", (string id, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ group.MapPost("/reservations/{id}/refund", (string id, OpsReservationRefundRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
Run(async () =>
{
- var refund = await ops.ConfirmReservationRefundAsync(Actor(user), id, ct);
+ var refund = await ops.ConfirmReservationRefundAsync(Actor(user), id, request, 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)");
+ .WithSummary("M08 · Ghi bằng chứng đã chuyển khoản hoàn cho đơn huỷ: mã giao dịch, thời điểm chuyển, xác nhận (D32)");
+
+ // ---- Hoàn cọc sau trả kho (D32 / T07)
+ group.MapGet("/deposit-refunds", (ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.GetDepositRefundsAsync(Actor(user), ct))))
+ .WithSummary("Danh sách khoản hoàn cọc của cơ sở: chờ hoàn và đã hoàn gần đây");
+
+ group.MapPost("/deposit-refunds/actions", (DepositRefundActionRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(new { item = await ops.ConfirmDepositRefundAsync(Actor(user), request, ct) })))
+ .WithSummary("CONFIRM_DEPOSIT_REFUND: quản lý ghi mã giao dịch → PAID; expectedVersion cũ trả 409");
+
+ // ---- T13 · Sự cố do cơ sở (quản lý)
+ group.MapGet("/incidents", (ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.GetIncidentsAsync(Actor(user), ct))))
+ .WithSummary("Hồ sơ sự cố của cơ sở + nháp cho hợp đồng đủ điều kiện (mã/phiên bản do server cấp) và ô tương đương");
+
+ group.MapPost("/incidents", (IncidentActionRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.SaveIncidentAsync(Actor(user), request, ct))))
+ .WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(EvidencePhotos.RequestBodyLimit))
+ .WithSummary("SAVE_INCIDENT (giữ nháp) / SEND_INCIDENT_PROPOSAL (gửi khách, giữ ô thay thế); expectedVersion cũ trả 409");
+
+ group.MapPost("/incidents/{id}/complete-transfer", (string id, IncidentActionRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.CompleteIncidentTransferAsync(Actor(user), id, request, ct))))
+ .WithSummary("Hoàn tất chuyển ô: ô cũ MAINTENANCE, ô mới OCCUPIED, mã ô cũ hết hiệu lực, cấp QR/PIN ô mới, không phụ phí");
+
+ group.MapPost("/incidents/{id}/terminate", (string id, IncidentActionRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.FinalizeIncidentTerminationAsync(Actor(user), id, request, ct))))
+ .WithSummary("Chốt kết thúc theo lựa chọn khách: hợp đồng kết thúc, khoản hoàn PENDING = tháng đang thuê + tháng chưa dùng + 100% cọc");
+
+ // ---- T13 · Khách xem và tự chọn phương án
+ routes.MapGet("/api/incidents", (ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.GetCustomerIncidentsAsync(user.GetUserId(), ct))))
+ .WithTags("Facility Operations")
+ .RequireAuthorization(policy => policy.RequireRole("CUSTOMER"))
+ .WithSummary("Khách xem hồ sơ sự cố đã gửi của hợp đồng mình");
+
+ routes.MapPost("/api/contracts/{contractId}/incident-choice", (string contractId, IncidentActionRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.ChooseIncidentOptionAsync(user.GetUserId(), contractId, request, ct))))
+ .WithTags("Facility Operations")
+ .RequireAuthorization(policy => policy.RequireRole("CUSTOMER"))
+ .WithSummary("CHOOSE_INCIDENT_OPTION: khách tự chọn đổi ô (TRANSFER) hoặc kết thúc + tài khoản chính chủ (TERMINATE)");
+
+ // ---- Khách xem khoản hoàn cọc của chính mình
+ routes.MapGet("/api/deposit-refunds", (ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.GetCustomerDepositRefundsAsync(user.GetUserId(), ct))))
+ .WithTags("Facility Operations")
+ .RequireAuthorization(policy => policy.RequireRole("CUSTOMER"))
+ .WithSummary("Khách theo dõi hoàn cọc sau trả kho (chỉ hồ sơ của mình)");
}
private static OpsActor Actor(ClaimsPrincipal user) => new(user.GetUserId(), user.IsInRole("MANAGER"));
@@ -112,6 +161,13 @@ public static void MapFacilityOpsEndpoints(this IEndpointRouteBuilder routes)
if (b.Contracts != null) json["contracts"] = b.Contracts;
if (b.Assignments != null) json["assignments"] = b.Assignments;
if (b.Revenue != null) json["revenue"] = b.Revenue;
+ if (b.Refunds != null) json["refunds"] = b.Refunds;
+
+ // Khả năng server đã triển khai thật (BACKEND-TODO Batch08). Giao diện chỉ mở thao tác khi cờ = true.
+ json["verificationChecklistSupported"] = true; // S02: lưu checklist 4 mục, không cần số giấy tờ
+ json["inspectionEvidenceSupported"] = true; // S04: lưu phí, vệ sinh 10% cọc, lý do, hạng mục, ảnh (T05)
+ json["refundEvidenceSupported"] = true; // M08: tài khoản chính chủ + mã giao dịch/thời điểm chuyển (T08)
+ json["returnPolicyVersion"] = "D32"; // M07: khấu trừ tối đa bằng cọc, hoàn hai bước (T06, T07, T09)
return json;
}
@@ -129,6 +185,10 @@ private static async Task Run(Func> action)
{
return Results.NotFound(new { error = ex.Message });
}
+ catch (OpsConflictException ex)
+ {
+ return Results.Conflict(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/ManagerEndpoints.cs b/StorageProject.Api/Endpoints/ManagerEndpoints.cs
index 7d1d570..0e31070 100644
--- a/StorageProject.Api/Endpoints/ManagerEndpoints.cs
+++ b/StorageProject.Api/Endpoints/ManagerEndpoints.cs
@@ -138,8 +138,8 @@ public static RouteGroupBuilder MapManagerEndpoints(this IEndpointRouteBuilder a
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 });
+ var result = await ops.ConfirmRefundAsync(actor, id, null, ct);
+ return Results.Ok(new { message = "Đã chốt quyết toán trả kho.", refund = result.Refund, refundStatus = result.RefundStatus });
}
catch (UnauthorizedAccessException)
{
diff --git a/StorageProject.Api/Endpoints/ReservationEndpoints.cs b/StorageProject.Api/Endpoints/ReservationEndpoints.cs
index 35c6bb7..de4f8b8 100644
--- a/StorageProject.Api/Endpoints/ReservationEndpoints.cs
+++ b/StorageProject.Api/Endpoints/ReservationEndpoints.cs
@@ -7,7 +7,7 @@
namespace StorageProject.Api.Endpoints;
-public record CancelReservationRequest(string Reason);
+public record CancelReservationRequest(string Reason, string? BankName = null, string? AccountNumber = null, string? AccountHolder = null);
public static class ReservationEndpoints
{
@@ -66,10 +66,13 @@ public static RouteGroupBuilder MapReservationEndpoints(this IEndpointRouteBuild
try
{
var customerId = user.GetUserId();
- await reservationService.CancelReservationAsync(customerId, id, request.Reason, ct);
+ var bank = request.BankName != null || request.AccountNumber != null || request.AccountHolder != null
+ ? new StorageProject.Core.DTOs.Evidence.RefundBankInput(request.BankName, request.AccountNumber, request.AccountHolder)
+ : null;
+ await reservationService.CancelReservationAsync(customerId, id, request.Reason, bank, ct);
return Results.Ok(new { message = "Đã hủy đơn đặt chỗ thành công." });
}
- catch (InvalidOperationException ex)
+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
return Results.BadRequest(new { error = ex.Message });
}
diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs
index dbc86a5..2b9817e 100644
--- a/StorageProject.Api/Program.cs
+++ b/StorageProject.Api/Program.cs
@@ -50,6 +50,11 @@
jwtSecret = defaultDevSecret;
}
+// Ảnh bằng chứng (D32 / T05, T08): khoá ký URL dẫn từ JWT secret. EvidencePhotos:PublicBaseUrl để trống khi FE và API
+// cùng origin (nginx /api); khi chạy dev FE :5173 + API :5151 thì đặt "http://localhost:5151" để link ảnh mở đúng API.
+StorageProject.Infrastructure.Services.EvidencePhotos.Configure(jwtSecret,
+ builder.Configuration["EvidencePhotos:PublicBaseUrl"] ?? (builder.Environment.IsDevelopment() ? "http://localhost:5151" : ""));
+
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
@@ -231,6 +236,7 @@
app.MapStaffEndpoints();
app.MapManagerEndpoints();
app.MapAccessEndpoints();
+app.MapEvidenceEndpoints();
// 8. Health & Readiness Endpoints
// Liveness endpoint (lightweight check, no external DB dependencies)
diff --git a/StorageProject.Api/StorageProject.Api.http b/StorageProject.Api/StorageProject.Api.http
index 55c0f96..a6fc507 100644
--- a/StorageProject.Api/StorageProject.Api.http
+++ b/StorageProject.Api/StorageProject.Api.http
@@ -93,3 +93,52 @@ Authorization: Bearer {{managerToken}}
Content-Type: application/json
{ "status": "MAINTENANCE", "reason": "Sửa cửa kho" }
+
+### ==== D32 / T05, T07, T08, T13 (29/10) — thay token, mã và ảnh base64 thật trước khi chạy ====
+@contractId = 1
+@contractCode = HĐ-2026-0001
+@returnCode = TK-0001
+@jpegBase64 = /9j/4AAQSkZJRgABAQ==
+
+### Khách gửi trả kho: ảnh kho trống + tài khoản chính chủ (bắt buộc)
+POST {{StorageProject.Api_HostAddress}}/api/contracts/{{contractId}}/move-out
+Authorization: Bearer {{customerToken}}
+Content-Type: application/json
+
+{ "date": "2026-10-30", "slot": "09:00–09:30", "note": "Đã dọn sạch", "bankName": "Vietcombank", "accountNumber": "0123456789", "accountHolder": "NGUYEN VAN AN", "emptied": true, "photos": [ { "fileName": "kho-trong.jpg", "contentType": "image/jpeg", "dataBase64": "{{jpegBase64}}" } ] }
+
+### Nhân viên kiểm kê (vệ sinh = 10% cọc do server tính)
+POST {{StorageProject.Api_HostAddress}}/api/ops/returns/{{returnCode}}/inspection
+Authorization: Bearer {{staffToken}}
+Content-Type: application/json
+
+{ "items": "Trống", "walls": "Trầy cửa", "keys": "Đã nhận", "proposal": "Cần bảo trì trước khi cho thuê lại", "damageFee": 200000, "cleaningRequired": true, "damageItem": "Cửa cuốn", "feeReason": "Trầy sơn", "photos": [ { "fileName": "cua.jpg", "contentType": "image/jpeg", "dataBase64": "{{jpegBase64}}" } ] }
+
+### Quản lý chốt quyết toán → khoản hoàn PENDING
+POST {{StorageProject.Api_HostAddress}}/api/ops/contracts/{{contractCode}}/refund
+Authorization: Bearer {{managerToken}}
+Content-Type: application/json
+
+{ "note": "Đối chiếu đủ ảnh" }
+
+### Danh sách hoàn cọc / ghi đã chuyển (expectedVersion lấy từ danh sách)
+GET {{StorageProject.Api_HostAddress}}/api/ops/deposit-refunds
+Authorization: Bearer {{managerToken}}
+
+###
+POST {{StorageProject.Api_HostAddress}}/api/ops/deposit-refunds/actions
+Authorization: Bearer {{managerToken}}
+Content-Type: application/json
+
+{ "action": "CONFIRM_DEPOSIT_REFUND", "id": "HC-0001", "expectedVersion": 1, "transactionRef": "FT26302000001", "transferredAt": "2026-10-29T03:00:00.000Z", "confirmed": true }
+
+### T13 · Sự cố: danh sách (có nháp + ô tương đương) và gửi phương án
+GET {{StorageProject.Api_HostAddress}}/api/ops/incidents
+Authorization: Bearer {{managerToken}}
+
+###
+POST {{StorageProject.Api_HostAddress}}/api/ops/incidents
+Authorization: Bearer {{managerToken}}
+Content-Type: application/json
+
+{ "action": "SEND_INCIDENT_PROPOSAL", "id": "SC-0001-1", "expectedVersion": 1, "description": "Thấm nước mái kho", "affectedAt": "2026-10-29T01:00:00.000Z", "confirmed": true, "proposal": "TERMINATE" }
diff --git a/StorageProject.Core/DTOs/Contract/ContractDtos.cs b/StorageProject.Core/DTOs/Contract/ContractDtos.cs
index 5bd5ccb..2cc37a6 100644
--- a/StorageProject.Core/DTOs/Contract/ContractDtos.cs
+++ b/StorageProject.Core/DTOs/Contract/ContractDtos.cs
@@ -49,10 +49,19 @@ public record HandoverSummaryDto(
bool StaffConfirmed
);
+///
+/// Gửi trả kho (D32 / T08). Bắt buộc: ảnh kho trống (1–5 ảnh JPG/PNG), xác nhận đã chuyển hết đồ,
+/// tài khoản ngân hàng chính chủ nhận hoàn cọc. Gửi thành công thì QR/PIN hết hiệu lực, dừng tính phí quá hạn.
+///
public record MoveOutRequest(
DateOnly Date,
string? Slot,
- string? Note
+ string? Note,
+ string? BankName = null,
+ string? AccountNumber = null,
+ string? AccountHolder = null,
+ bool? Emptied = null,
+ IReadOnlyList? Photos = null
);
public record MoveOutResponseDto(
diff --git a/StorageProject.Core/DTOs/Evidence/EvidenceDtos.cs b/StorageProject.Core/DTOs/Evidence/EvidenceDtos.cs
new file mode 100644
index 0000000..a459825
--- /dev/null
+++ b/StorageProject.Core/DTOs/Evidence/EvidenceDtos.cs
@@ -0,0 +1,14 @@
+namespace StorageProject.Core.DTOs.Evidence;
+
+// Ảnh bằng chứng (trả kho, kiểm kê) và tài khoản nhận hoàn chính chủ (D32).
+// Ảnh gửi dạng JSON base64 theo hợp đồng FE (BACKEND-TODO "Figma–FE đợt03", Batch08):
+// tối đa 5 ảnh JPG/PNG, mỗi ảnh ≤ 5 MiB sau giải mã; server tự kiểm chữ ký tệp, không tin MIME/đuôi tệp.
+
+/// Một ảnh khách / nhân viên tải lên.
+public record EvidencePhotoUpload(string? FileName, string? ContentType, string? DataBase64);
+
+/// Ảnh đã lưu: URL có chữ ký, hết hạn sau một thời gian (không công khai vĩnh viễn).
+public record EvidencePhotoDto(string Url, string? Caption);
+
+/// Tài khoản ngân hàng nhận hoàn tiền; tên chủ tài khoản phải trùng tên trên hợp đồng.
+public record RefundBankInput(string? BankName, string? AccountNumber, string? AccountHolder);
diff --git a/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs b/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs
index 0ce72e3..da38238 100644
--- a/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs
+++ b/StorageProject.Core/DTOs/FacilityOps/FacilityOpsDtos.cs
@@ -1,3 +1,5 @@
+using StorageProject.Core.DTOs.Evidence;
+
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.
@@ -27,11 +29,31 @@ public record OpsVerificationDto(
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);
+///
+/// Biên bản kiểm kê S04 (D32 / T05). Vệ sinh = 10% cọc cố định do server tính; ảnh là URL có chữ ký.
+/// DamageItem/FeeReason trả "" khi không có để giao diện đối chiếu đúng giá trị đã gửi.
+///
+public record OpsReturnReportDto(
+ string Items, string Walls, string Keys, string Proposal,
+ decimal DamageFee = 0, decimal CleaningFee = 0, bool CleaningRequired = false,
+ string DamageItem = "", string FeeReason = "", decimal OverdueFee = 0,
+ IReadOnlyList? Photos = null);
+///
+/// RequestedAt: lúc khách gửi trả kho (ISO UTC) — mốc dừng phí quá hạn (D32). OverdueFee tính tại mốc đó.
+/// DamageWorkflowResolved: không còn phản hồi/khắc phục hư hỏng chờ xử lý (backend chưa có luồng phản hồi hư hỏng
+/// Batch06 nên không hồ sơ nào có thể đang mở).
+///
public record OpsReturnDto(
string Id, string Contract, string Unit, string Customer, string Appointment, decimal Deposit, decimal Unpaid,
- string Status, OpsReturnReportDto? Report, string? SubmittedAt);
+ string Status, OpsReturnReportDto? Report, string? SubmittedAt,
+ DateTime? RequestedAt = null, decimal OverdueFee = 0, bool DamageWorkflowResolved = true,
+ IReadOnlyList? MoveOutPhotos = null);
+
+/// M08 · Đơn huỷ chờ hoàn / đã hoàn (D27, D32). Tài khoản là tài khoản chính chủ khách khai khi huỷ.
+public record OpsRefundDto(
+ string Id, string Customer, string CancelledAt, decimal Rent, decimal Deposit, decimal Paid, decimal Fee, decimal Amount,
+ string Status, string? PaidAt, string? TransactionRef, string? BankName, string? AccountNumber, string? AccountHolder);
public record OpsNoteDto(string Text, string At, string? Staff);
@@ -75,13 +97,48 @@ public record OpsBoardDto(
IReadOnlyList? Renewals,
IReadOnlyList? Contracts,
IReadOnlyList? Assignments,
- OpsRevenueDto? Revenue);
+ OpsRevenueDto? Revenue,
+ IReadOnlyList? Refunds = null);
+
+/// Kết quả M07: khoản hoàn cọc chờ chuyển (PENDING) hoặc không có khoản hoàn (NO_REFUND); chưa bao giờ PAID ở bước này.
+public record OpsSettlementResult(decimal Refund, string RefundStatus);
// ---- Thân request (BACKEND-TODO A2, A3)
public record OpsNoteRequest(string? Note);
-public record OpsVerifyRequest(string? DocType, string? DocNumber, bool PhotoMatched, bool InfoMatched);
+
+///
+/// S02. Màn mới gửi checklist 4 mục (OriginalDocumentValid, PhotoMatched, InfoMatched, BookingMatched), không gửi số giấy tờ.
+/// Thiếu OriginalDocumentValid → luồng cũ (bắt buộc DocNumber) cho client cũ.
+///
+public record OpsVerifyRequest(string? DocType, string? DocNumber, bool PhotoMatched, bool InfoMatched,
+ bool? OriginalDocumentValid = null, bool? BookingMatched = null);
+
+/// Nhận chìa khóa: nếu client gửi checklist thì cả ba mục phải được đánh dấu.
+public record OpsKeyReceiptRequest(bool? IdentityChecked, bool? ConditionChecked, bool? KeyDelivered);
+
public record OpsHandoverRequest(string? UnlockMethod);
-public record OpsReturnInspectionRequest(string? Items, string? Walls, string? Keys, string? Proposal);
+
+///
+/// S04 (D32 / T05): 4 mục kiểm kê + phí hư hỏng, có cần vệ sinh không, hạng mục, lý do và ảnh.
+/// Phí vệ sinh không nhận từ client: server tính 10% cọc khi CleaningRequired.
+///
+public record OpsReturnInspectionRequest(string? Items, string? Walls, string? Keys, string? Proposal,
+ decimal? DamageFee = null, bool? CleaningRequired = null, string? DamageItem = null, string? FeeReason = null,
+ IReadOnlyList? Photos = null);
+
+/// M08: quản lý ghi bằng chứng đã chuyển khoản hoàn cho đơn huỷ.
+public record OpsReservationRefundRequest(string? Method, string? TransactionRef, DateTime? TransferredAt, bool Confirmed);
+
+/// Hoàn cọc sau trả kho (T07). Version: 1 khi chờ hoàn, 2 khi đã hoàn (khoản chỉ đổi trạng thái một lần).
+public record DepositRefundDto(
+ string Id, long FacilityId, long OwnerId, string ContractId, string Unit, string Customer, int Version,
+ decimal Deposit, decimal Overdue, decimal Cleaning, decimal Damage, decimal Amount, string Status,
+ DateTime? RequestedAt, DateTime? InspectedAt, DateTime? ApprovedAt, DateTime? PaidAt, DateOnly? RefundDueDate,
+ string? TransactionRef, string? BankName, string? AccountNumber, string? AccountHolder,
+ string? InspectionNote, IReadOnlyList Photos);
+
+public record DepositRefundActionRequest(string? Action, string? Id, int? ExpectedVersion, string? TransactionRef,
+ DateTime? TransferredAt, bool Confirmed);
public record OpsTicketResponseRequest(string? Note, string? NextStatus);
public record OpsRejectRequest(string? Reason);
public record OpsAllocateRequest(string? UnitCode);
diff --git a/StorageProject.Core/DTOs/FacilityOps/IncidentDtos.cs b/StorageProject.Core/DTOs/FacilityOps/IncidentDtos.cs
new file mode 100644
index 0000000..1187348
--- /dev/null
+++ b/StorageProject.Core/DTOs/FacilityOps/IncidentDtos.cs
@@ -0,0 +1,42 @@
+using StorageProject.Core.DTOs.Evidence;
+
+namespace StorageProject.Core.DTOs.FacilityOps;
+
+// T13 · Sự cố cơ sở — hình dạng JSON khớp incidentApi.js (normalizeIncident / validateIncidentReceipt).
+// Mốc thời gian là chuỗi ISO UTC có mili giây ("2026-10-28T03:00:00.000Z") để so trùng giá trị giao diện gửi lên.
+
+public record IncidentUnitDto(string Id, string Code, long FacilityId, string Type, int SizeM2, string Status, int Version, string? ReservedFor);
+
+public record IncidentChoiceDto(string Choice, string Note, string At);
+
+public record IncidentBankDto(string BankName, string AccountNumber, string AccountHolder);
+
+public record IncidentAccessDto(string OldUnit, string NewUnit);
+
+public record IncidentRefundDto(string Id, decimal Amount, string Status, string? TransactionRef, string? PaidAt);
+
+public record IncidentFileDto(string FileName, string ContentType, int Size);
+
+public record IncidentCaseDto(
+ string Id, string ContractId, long OwnerId, long FacilityId, int Version, string Status, string ContractStatus,
+ string OldUnitId, string OldUnit, string CurrentUnit, string UnitType, int SizeM2, string Customer,
+ string StartDate, string EndDate, decimal MonthlyRate, decimal Deposit, decimal CurrentMonthRent, decimal UnusedRent,
+ string? Description, string? AffectedAt, bool Confirmed, string? Proposal,
+ IReadOnlyList Photos, IReadOnlyList Files,
+ IReadOnlyList Candidates, IncidentUnitDto? TargetUnit,
+ IncidentChoiceDto? Choice, IncidentBankDto? RefundBank, string? MovedAt,
+ string OldUnitStatus, IncidentAccessDto Access, decimal Surcharge, IncidentRefundDto? Refund);
+
+public record IncidentListDto(IReadOnlyList Items);
+
+public record IncidentReceiptDto(IncidentCaseDto Incident);
+
+///
+/// Một thân request cho mọi thao tác T13. Server không nhận tiền/owner/cơ sở/giá từ client.
+/// AffectedAt, MovedAt: chuỗi ISO có múi giờ (giao diện gửi toISOString).
+///
+public record IncidentActionRequest(
+ string? Action, string? Id, int? ExpectedVersion,
+ string? Description = null, string? AffectedAt = null, bool? Confirmed = null, string? Proposal = null,
+ string? TargetUnitId = null, int? ExpectedTargetVersion = null, IReadOnlyList? Photos = null,
+ string? Choice = null, string? Note = null, RefundBankInput? RefundBank = null, string? MovedAt = null);
diff --git a/StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs b/StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs
index f3850f6..28cac65 100644
--- a/StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs
+++ b/StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs
@@ -1,11 +1,17 @@
namespace StorageProject.Core.DTOs.Policy;
+///
+/// CancellationBankSupported / ReturnRequestSupported: server đã lưu tài khoản chính chủ khi huỷ đơn và
+/// ảnh kho trống + tài khoản khi gửi trả kho (D32 / T08); giao diện chỉ mở hai luồng này khi cờ = true.
+///
public record RentalPolicyDto(
decimal Rate,
Dictionary Sections,
int Version,
string DisplayVersion,
- DateTime UpdatedAt
+ DateTime UpdatedAt,
+ bool CancellationBankSupported = true,
+ bool ReturnRequestSupported = true
);
public record SaveRentalPolicyRequest(
diff --git a/StorageProject.Core/Entities/EvidencePhoto.cs b/StorageProject.Core/Entities/EvidencePhoto.cs
new file mode 100644
index 0000000..d32f4d2
--- /dev/null
+++ b/StorageProject.Core/Entities/EvidencePhoto.cs
@@ -0,0 +1,22 @@
+namespace StorageProject.Core.Entities;
+
+///
+/// Ảnh bằng chứng lưu riêng tư trong database (không để trong thư mục web công khai).
+/// Chỉ đọc qua URL có chữ ký do server cấp (EvidencePhotos.Url).
+///
+public class EvidencePhoto
+{
+ public long PhotoId { get; set; }
+ // MOVE_OUT (khách gửi trả kho, ownerId = InspectionId), RETURN_INSPECTION (nhân viên kiểm kê, ownerId = InspectionId),
+ // INCIDENT (quản lý ghi nhận sự cố cơ sở, ownerId = IncidentId)
+ public string OwnerType { get; set; } = null!;
+ public long OwnerId { get; set; }
+ public string FileName { get; set; } = null!;
+ public string ContentType { get; set; } = null!; // image/jpeg, image/png
+ public int SizeBytes { get; set; }
+ public byte[] Data { get; set; } = [];
+ public long UploadedBy { get; set; }
+ public DateTime CreatedAt { get; set; }
+
+ public User UploadedByUser { get; set; } = null!;
+}
diff --git a/StorageProject.Core/Entities/FacilityIncident.cs b/StorageProject.Core/Entities/FacilityIncident.cs
new file mode 100644
index 0000000..4b67d35
--- /dev/null
+++ b/StorageProject.Core/Entities/FacilityIncident.cs
@@ -0,0 +1,41 @@
+namespace StorageProject.Core.Entities;
+
+///
+/// T13 · Sự cố do cơ sở làm khách không sử dụng được ô (D32). Quản lý ghi nhận và đề xuất phương án;
+/// khách tự chọn đổi sang ô tương đương (không phụ phí, giữ kỳ thuê/giá/cọc) hoặc kết thúc hợp đồng
+/// (hoàn 100% tháng đang thuê + 100% tháng chưa dùng + 100% cọc, không phạt dừng sớm).
+///
+public class FacilityIncident
+{
+ public long IncidentId { get; set; }
+ /// Mã hồ sơ ổn định từ lúc còn là nháp: "SC-{ContractId:0000}-{n}".
+ public string CaseCode { get; set; } = null!;
+ public long ContractId { get; set; }
+ public long FacilityId { get; set; }
+ public long OldUnitId { get; set; }
+ public long? TargetUnitId { get; set; }
+ // DRAFT, PROPOSED, TRANSFER_PENDING, TRANSFERRED, TERMINATION_PENDING, TERMINATED
+ public string Status { get; set; } = "DRAFT";
+ public int Version { get; set; } = 1;
+ public string? Description { get; set; }
+ public DateTime? AffectedAt { get; set; }
+ public bool Confirmed { get; set; }
+ public string? Proposal { get; set; } // TRANSFER, TERMINATE
+ public string? ChoiceOption { get; set; } // TRANSFER, TERMINATE — khách tự chọn
+ public string? ChoiceNote { get; set; }
+ public DateTime? ChoiceAt { get; set; }
+ public string? RefundBankName { get; set; }
+ public string? RefundAccountNumber { get; set; }
+ public string? RefundAccountHolder { get; set; }
+ public DateTime? MovedAt { get; set; }
+ public long? RefundPaymentId { get; set; }
+ public decimal? CurrentMonthRent { get; set; } // chốt khi kết thúc
+ public decimal? UnusedRent { get; set; } // chốt khi kết thúc
+ public long CreatedBy { get; set; }
+ public DateTime CreatedAt { get; set; }
+ public DateTime UpdatedAt { get; set; }
+
+ public RentalContract Contract { get; set; } = null!;
+ public StorageUnit OldUnit { get; set; } = null!;
+ public StorageUnit? TargetUnit { get; set; }
+}
diff --git a/StorageProject.Core/Entities/Reservation.cs b/StorageProject.Core/Entities/Reservation.cs
index 0c62118..3fafb27 100644
--- a/StorageProject.Core/Entities/Reservation.cs
+++ b/StorageProject.Core/Entities/Reservation.cs
@@ -24,6 +24,10 @@ public class Reservation
public DateTime CreatedAt { get; set; }
public DateTime? ExpiresAt { get; set; }
public DateTime? CancelledAt { get; set; }
+ // D32 / T08: tài khoản chính chủ nhận hoàn khi huỷ đơn đã thanh toán
+ public string? RefundBankName { get; set; }
+ public string? RefundAccountNumber { get; set; }
+ public string? RefundAccountHolder { get; set; }
public User Customer { get; set; } = null!;
public Facility Facility { get; set; } = null!;
diff --git a/StorageProject.Core/Entities/ReturnInspection.cs b/StorageProject.Core/Entities/ReturnInspection.cs
index fc8da5a..c728adb 100644
--- a/StorageProject.Core/Entities/ReturnInspection.cs
+++ b/StorageProject.Core/Entities/ReturnInspection.cs
@@ -14,6 +14,13 @@ public class ReturnInspection
public decimal DamageFee { get; set; } = 0;
public decimal CleaningFee { get; set; } = 0;
public string? Notes { get; set; }
+ // D32 / T05: hạng mục hư hỏng và lý do khấu trừ trên biên bản kiểm kê
+ public string? DamageItem { get; set; }
+ public string? FeeReason { get; set; }
+ // D32 / T08: tài khoản chính chủ nhận hoàn cọc, khách khai khi gửi trả kho
+ public string? RefundBankName { get; set; }
+ public string? RefundAccountNumber { get; set; }
+ public string? RefundAccountHolder { get; set; }
public string Status { get; set; } = "SCHEDULED"; // SCHEDULED, IN_PROGRESS, COMPLETED, CANCELLED
public DateTime CreatedAt { get; set; }
diff --git a/StorageProject.Core/Interfaces/IFacilityOpsService.cs b/StorageProject.Core/Interfaces/IFacilityOpsService.cs
index 1afe0e2..6c8527d 100644
--- a/StorageProject.Core/Interfaces/IFacilityOpsService.cs
+++ b/StorageProject.Core/Interfaces/IFacilityOpsService.cs
@@ -17,6 +17,7 @@ public interface IFacilityOpsService
Task ReportMismatchAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default);
Task VerifyCustomerAsync(OpsActor actor, string id, OpsVerifyRequest request, CancellationToken ct = default);
Task RecordKeyReceiptAsync(OpsActor actor, string id, CancellationToken ct = default);
+ Task RecordKeyReceiptAsync(OpsActor actor, string id, OpsKeyReceiptRequest? 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);
@@ -27,7 +28,22 @@ public interface IFacilityOpsService
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);
- /// 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);
+ /// M07 · Chốt quyết toán trả kho: tạo khoản hoàn PENDING ("Chờ hoàn"), chưa ghi đã chuyển tiền (D32 / T07).
+ Task ConfirmRefundAsync(OpsActor actor, string id, string? note = null, CancellationToken ct = default);
+ /// M08 · Ghi bằng chứng đã chuyển khoản hoàn cho đơn đã huỷ vào tài khoản chính chủ (D27, D32).
+ Task ConfirmReservationRefundAsync(OpsActor actor, string id, OpsReservationRefundRequest request, CancellationToken ct = default);
+
+ // Hoàn cọc sau trả kho (D32 / T07)
+ Task> GetDepositRefundsAsync(OpsActor actor, CancellationToken ct = default);
+ Task ConfirmDepositRefundAsync(OpsActor actor, DepositRefundActionRequest request, CancellationToken ct = default);
+ /// Khách xem khoản hoàn cọc của chính mình (GET /api/deposit-refunds).
+ Task> GetCustomerDepositRefundsAsync(long customerId, CancellationToken ct = default);
+
+ // T13 · Sự cố do cơ sở (D32)
+ Task GetIncidentsAsync(OpsActor actor, CancellationToken ct = default);
+ Task GetCustomerIncidentsAsync(long customerId, CancellationToken ct = default);
+ Task SaveIncidentAsync(OpsActor actor, IncidentActionRequest request, CancellationToken ct = default);
+ Task ChooseIncidentOptionAsync(long customerId, string contractCode, IncidentActionRequest request, CancellationToken ct = default);
+ Task CompleteIncidentTransferAsync(OpsActor actor, string id, IncidentActionRequest request, CancellationToken ct = default);
+ Task FinalizeIncidentTerminationAsync(OpsActor actor, string id, IncidentActionRequest request, CancellationToken ct = default);
}
diff --git a/StorageProject.Core/Interfaces/IServices.cs b/StorageProject.Core/Interfaces/IServices.cs
index 5eef9d9..8e8cd9a 100644
--- a/StorageProject.Core/Interfaces/IServices.cs
+++ b/StorageProject.Core/Interfaces/IServices.cs
@@ -38,6 +38,8 @@ public interface IReservationService
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);
+ /// Huỷ đơn kèm tài khoản chính chủ nhận hoàn (bắt buộc khi đơn đã thanh toán — D32 / T08).
+ Task CancelReservationAsync(long customerId, long reservationId, string reason, StorageProject.Core.DTOs.Evidence.RefundBankInput? bank, CancellationToken ct = default);
Task ConfirmTransferAsync(long customerId, long reservationId, CancellationToken ct = default);
}
diff --git a/StorageProject.Core/Policies/IncidentRefundPolicy.cs b/StorageProject.Core/Policies/IncidentRefundPolicy.cs
new file mode 100644
index 0000000..5aa348c
--- /dev/null
+++ b/StorageProject.Core/Policies/IncidentRefundPolicy.cs
@@ -0,0 +1,24 @@
+namespace StorageProject.Core.Policies;
+
+///
+/// D32 · Sự cố do cơ sở, khách chọn kết thúc hợp đồng: hoàn 100% tiền tháng đang thuê + 100% các tháng chưa dùng
+/// + 100% cọc; không chia theo ngày, không phạt dừng sớm. Tháng tính từ StartDate như .
+///
+public static class IncidentRefundPolicy
+{
+ public sealed record Result(decimal CurrentMonthRent, decimal UnusedRent, decimal Deposit)
+ {
+ public decimal Total => CurrentMonthRent + UnusedRent + Deposit;
+ }
+
+ public static Result Calculate(DateOnly start, DateOnly end, decimal monthlyRate, decimal deposit, DateOnly today)
+ {
+ if (monthlyRate < 0 || deposit < 0) throw new ArgumentException("Số tiền không được âm.");
+ var total = RefundPolicy.TotalMonths(start, end);
+ var begun = 0;
+ while (begun < total && start.AddMonths(begun) <= today) begun++;
+ var current = begun > 0 ? monthlyRate : 0m; // tháng đang thuê (đã bắt đầu) hoàn đủ 100%
+ var unused = monthlyRate * (total - begun); // các tháng nguyên chưa bắt đầu
+ return new Result(current, unused, deposit);
+ }
+}
diff --git a/StorageProject.Infrastructure/Data/AppDbContext.cs b/StorageProject.Infrastructure/Data/AppDbContext.cs
index 7721a82..a1f3337 100644
--- a/StorageProject.Infrastructure/Data/AppDbContext.cs
+++ b/StorageProject.Infrastructure/Data/AppDbContext.cs
@@ -51,9 +51,11 @@ public class AppDbContext(DbContextOptions options) : DbContext(op
// XI. Return & Inspection
public DbSet ReturnInspections => Set();
+ public DbSet EvidencePhotos => Set();
// XII. Overdue Handling
public DbSet OverdueCases => Set();
+ public DbSet FacilityIncidents => Set();
// XIII. Support & Issue Handling
public DbSet SupportTickets => Set();
diff --git a/StorageProject.Infrastructure/Data/Configurations/EvidenceConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/EvidenceConfigurations.cs
new file mode 100644
index 0000000..5ff86d6
--- /dev/null
+++ b/StorageProject.Infrastructure/Data/Configurations/EvidenceConfigurations.cs
@@ -0,0 +1,29 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using StorageProject.Core.Entities;
+
+namespace StorageProject.Infrastructure.Data.Configurations;
+
+public class EvidencePhotoConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder b)
+ {
+ b.ToTable("evidence_photos", t =>
+ {
+ t.HasCheckConstraint("CK_evidence_photos_owner_type", "[OwnerType] IN ('MOVE_OUT','RETURN_INSPECTION','INCIDENT')");
+ t.HasCheckConstraint("CK_evidence_photos_content_type", "[ContentType] IN ('image/jpeg','image/png')");
+ t.HasCheckConstraint("CK_evidence_photos_size", "[SizeBytes] > 0 AND [SizeBytes] <= 5242880");
+ });
+ b.HasKey(p => p.PhotoId);
+ b.Property(p => p.PhotoId).UseIdentityColumn();
+ b.Property(p => p.OwnerType).IsRequired().HasMaxLength(30).IsUnicode(false);
+ b.Property(p => p.FileName).IsRequired().HasMaxLength(200);
+ b.Property(p => p.ContentType).IsRequired().HasMaxLength(20).IsUnicode(false);
+ b.Property(p => p.Data).IsRequired();
+ b.Property(p => p.CreatedAt).IsRequired();
+ b.HasIndex(p => new { p.OwnerType, p.OwnerId });
+
+ b.HasOne(p => p.UploadedByUser).WithMany()
+ .HasForeignKey(p => p.UploadedBy).OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/StorageProject.Infrastructure/Data/Configurations/IncidentConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/IncidentConfigurations.cs
new file mode 100644
index 0000000..fe19f8d
--- /dev/null
+++ b/StorageProject.Infrastructure/Data/Configurations/IncidentConfigurations.cs
@@ -0,0 +1,51 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using StorageProject.Core.Entities;
+
+namespace StorageProject.Infrastructure.Data.Configurations;
+
+public class FacilityIncidentConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder b)
+ {
+ b.ToTable("facility_incidents", t =>
+ {
+ t.HasCheckConstraint("CK_facility_incidents_status",
+ "[Status] IN ('DRAFT','PROPOSED','TRANSFER_PENDING','TRANSFERRED','TERMINATION_PENDING','TERMINATED')");
+ t.HasCheckConstraint("CK_facility_incidents_proposal", "[Proposal] IS NULL OR [Proposal] IN ('TRANSFER','TERMINATE')");
+ t.HasCheckConstraint("CK_facility_incidents_choice", "[ChoiceOption] IS NULL OR [ChoiceOption] IN ('TRANSFER','TERMINATE')");
+ t.HasCheckConstraint("CK_facility_incidents_version", "[Version] > 0");
+ });
+ b.HasKey(i => i.IncidentId);
+ b.Property(i => i.IncidentId).UseIdentityColumn();
+ b.Property(i => i.CaseCode).IsRequired().HasMaxLength(40).IsUnicode(false);
+ b.HasIndex(i => i.CaseCode).IsUnique();
+ b.Property(i => i.Status).IsRequired().HasMaxLength(30).HasDefaultValue("DRAFT");
+ b.Property(i => i.Version).IsRequired().HasDefaultValue(1);
+ b.Property(i => i.Description).HasMaxLength(1000);
+ b.Property(i => i.Proposal).HasMaxLength(20);
+ b.Property(i => i.ChoiceOption).HasMaxLength(20);
+ b.Property(i => i.ChoiceNote).HasMaxLength(1000);
+ b.Property(i => i.RefundBankName).HasMaxLength(100);
+ b.Property(i => i.RefundAccountNumber).HasMaxLength(19).IsUnicode(false);
+ b.Property(i => i.RefundAccountHolder).HasMaxLength(150);
+ b.Property(i => i.CurrentMonthRent).HasColumnType("decimal(15,2)");
+ b.Property(i => i.UnusedRent).HasColumnType("decimal(15,2)");
+ b.Property(i => i.CreatedAt).IsRequired();
+ b.Property(i => i.UpdatedAt).IsRequired();
+
+ // Mỗi hợp đồng chỉ một hồ sơ đang mở; một ô thay thế chỉ được giữ cho một hồ sơ (chống hai khách giữ cùng ô).
+ b.HasIndex(i => i.ContractId).IsUnique()
+ .HasFilter("[Status] IN ('DRAFT','PROPOSED','TRANSFER_PENDING','TERMINATION_PENDING')");
+ b.HasIndex(i => i.TargetUnitId).IsUnique()
+ .HasFilter("[TargetUnitId] IS NOT NULL AND [Status] IN ('PROPOSED','TRANSFER_PENDING')");
+ b.HasIndex(i => new { i.FacilityId, i.Status });
+
+ b.HasOne(i => i.Contract).WithMany()
+ .HasForeignKey(i => i.ContractId).OnDelete(DeleteBehavior.Restrict);
+ b.HasOne(i => i.OldUnit).WithMany()
+ .HasForeignKey(i => i.OldUnitId).OnDelete(DeleteBehavior.Restrict);
+ b.HasOne(i => i.TargetUnit).WithMany()
+ .HasForeignKey(i => i.TargetUnitId).OnDelete(DeleteBehavior.Restrict);
+ }
+}
diff --git a/StorageProject.Infrastructure/Data/Configurations/OperationsConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/OperationsConfigurations.cs
index daffe9b..ad9f114 100644
--- a/StorageProject.Infrastructure/Data/Configurations/OperationsConfigurations.cs
+++ b/StorageProject.Infrastructure/Data/Configurations/OperationsConfigurations.cs
@@ -78,6 +78,11 @@ public void Configure(EntityTypeBuilder b)
b.Property(ri => ri.CleaningFee).IsRequired().HasColumnType("decimal(15,2)").HasDefaultValue(0m);
b.Property(ri => ri.Status).IsRequired().HasMaxLength(20).HasDefaultValue("SCHEDULED");
b.Property(ri => ri.CreatedAt).IsRequired();
+ b.Property(ri => ri.DamageItem).HasMaxLength(200);
+ b.Property(ri => ri.FeeReason).HasMaxLength(500);
+ b.Property(ri => ri.RefundBankName).HasMaxLength(100);
+ b.Property(ri => ri.RefundAccountNumber).HasMaxLength(19).IsUnicode(false);
+ b.Property(ri => ri.RefundAccountHolder).HasMaxLength(150);
b.HasOne(ri => ri.Contract).WithMany(rc => rc.ReturnInspections)
.HasForeignKey(ri => ri.ContractId).OnDelete(DeleteBehavior.Restrict);
diff --git a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs
index ac84046..7b4195a 100644
--- a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs
+++ b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs
@@ -27,6 +27,9 @@ public void Configure(EntityTypeBuilder b)
b.Property(r => r.RequiredDeposit).IsRequired().HasColumnType("decimal(15,2)");
b.Property(r => r.Status).IsRequired().HasMaxLength(30).HasDefaultValue("PENDING_PAYMENT");
b.Property(r => r.CancellationReason).HasMaxLength(500);
+ b.Property(r => r.RefundBankName).HasMaxLength(100);
+ b.Property(r => r.RefundAccountNumber).HasMaxLength(19).IsUnicode(false);
+ b.Property(r => r.RefundAccountHolder).HasMaxLength(150);
b.Property(r => r.PaymentMethod).IsRequired().HasMaxLength(20).HasDefaultValue("PAYOS");
b.Property(r => r.OrderCode);
b.HasIndex(r => r.OrderCode).IsUnique().HasFilter("[OrderCode] IS NOT NULL");
diff --git a/StorageProject.Infrastructure/Migrations/20261029054804_AddRefundEvidenceAndIncidents.Designer.cs b/StorageProject.Infrastructure/Migrations/20261029054804_AddRefundEvidenceAndIncidents.Designer.cs
new file mode 100644
index 0000000..4db1f10
--- /dev/null
+++ b/StorageProject.Infrastructure/Migrations/20261029054804_AddRefundEvidenceAndIncidents.Designer.cs
@@ -0,0 +1,2520 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using StorageProject.Infrastructure.Data;
+
+#nullable disable
+
+namespace StorageProject.Infrastructure.Migrations
+{
+ [DbContext(typeof(AppDbContext))]
+ [Migration("20261029054804_AddRefundEvidenceAndIncidents")]
+ partial class AddRefundEvidenceAndIncidents
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.12")
+ .HasAnnotation("Relational:MaxIdentifierLength", 128);
+
+ SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
+
+ modelBuilder.Entity("StorageProject.Core.Entities.AccessCredential", b =>
+ {
+ b.Property("CredentialId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("CredentialId"));
+
+ b.Property("ContractId")
+ .HasColumnType("bigint");
+
+ b.Property("CredentialReference")
+ .HasMaxLength(100)
+ .HasColumnType("nvarchar(100)");
+
+ b.Property("CredentialType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)");
+
+ b.Property("IssuedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("IssuedBy")
+ .HasColumnType("bigint");
+
+ b.Property("ReturnedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("SecretHash")
+ .HasMaxLength(255)
+ .HasColumnType("nvarchar(255)");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)")
+ .HasDefaultValue("ACTIVE");
+
+ b.Property("UnitId")
+ .HasColumnType("bigint");
+
+ b.HasKey("CredentialId");
+
+ b.HasIndex("ContractId");
+
+ b.HasIndex("IssuedBy");
+
+ b.HasIndex("UnitId");
+
+ b.ToTable("access_credentials", null, t =>
+ {
+ t.HasCheckConstraint("CK_access_credentials_status", "[Status] IN ('ACTIVE','RETURNED','LOST','REVOKED','REPLACED')");
+
+ t.HasCheckConstraint("CK_access_credentials_type", "[CredentialType] IN ('KEY','LOCK','ACCESS_CARD','ACCESS_CODE')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.ActivityLog", b =>
+ {
+ b.Property("LogId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("LogId"));
+
+ b.Property("Action")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("nvarchar(100)");
+
+ b.Property("EntityId")
+ .HasColumnType("bigint");
+
+ b.Property("EntityType")
+ .IsRequired()
+ .HasMaxLength(80)
+ .HasColumnType("nvarchar(80)");
+
+ b.Property("IpAddress")
+ .HasMaxLength(45)
+ .HasColumnType("nvarchar(45)");
+
+ b.Property("LoggedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("NewValue")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("OldValue")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("UserId")
+ .HasColumnType("bigint");
+
+ b.HasKey("LogId");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("activity_logs", (string)null);
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b =>
+ {
+ b.Property("RenewalId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RenewalId"));
+
+ b.Property("AcceptedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("AppliedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("ApprovedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("ApprovedBy")
+ .HasColumnType("bigint");
+
+ b.Property("ContractId")
+ .HasColumnType("bigint");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("ExpiredAt")
+ .HasColumnType("datetime2");
+
+ b.Property("NewEndDate")
+ .HasColumnType("date");
+
+ b.Property("NewMonthlyRate")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("OldEndDate")
+ .HasColumnType("date");
+
+ b.Property("OldMonthlyRate")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("PaymentDeadlineAt")
+ .HasColumnType("datetime2");
+
+ b.Property("PolicyVersion")
+ .HasColumnType("int");
+
+ b.Property("RenewalAmount")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("RenewalPeriodMonths")
+ .HasColumnType("int");
+
+ b.Property("RequestedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)")
+ .HasDefaultValue("PENDING");
+
+ b.HasKey("RenewalId");
+
+ b.HasIndex("ApprovedBy");
+
+ b.HasIndex("ContractId")
+ .IsUnique()
+ .HasFilter("[Status] IN ('PENDING','APPROVED')");
+
+ b.ToTable("contract_renewals", null, t =>
+ {
+ t.HasCheckConstraint("CK_contract_renewals_amount", "[RenewalAmount] >= 0");
+
+ t.HasCheckConstraint("CK_contract_renewals_period", "[RenewalPeriodMonths] > 0");
+
+ t.HasCheckConstraint("CK_contract_renewals_status", "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED','EXPIRED')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.EvidencePhoto", b =>
+ {
+ b.Property("PhotoId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PhotoId"));
+
+ b.Property("ContentType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("varchar(20)");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Data")
+ .IsRequired()
+ .HasColumnType("varbinary(max)");
+
+ b.Property("FileName")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("nvarchar(200)");
+
+ b.Property("OwnerId")
+ .HasColumnType("bigint");
+
+ b.Property("OwnerType")
+ .IsRequired()
+ .HasMaxLength(30)
+ .IsUnicode(false)
+ .HasColumnType("varchar(30)");
+
+ b.Property("SizeBytes")
+ .HasColumnType("int");
+
+ b.Property("UploadedBy")
+ .HasColumnType("bigint");
+
+ b.HasKey("PhotoId");
+
+ b.HasIndex("UploadedBy");
+
+ b.HasIndex("OwnerType", "OwnerId");
+
+ b.ToTable("evidence_photos", null, t =>
+ {
+ t.HasCheckConstraint("CK_evidence_photos_content_type", "[ContentType] IN ('image/jpeg','image/png')");
+
+ t.HasCheckConstraint("CK_evidence_photos_owner_type", "[OwnerType] IN ('MOVE_OUT','RETURN_INSPECTION','INCIDENT')");
+
+ t.HasCheckConstraint("CK_evidence_photos_size", "[SizeBytes] > 0 AND [SizeBytes] <= 5242880");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.Facility", b =>
+ {
+ b.Property("FacilityId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("FacilityId"));
+
+ b.Property("Address")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("nvarchar(255)");
+
+ b.Property("ClosingTime")
+ .HasColumnType("time");
+
+ b.Property("ContactPhone")
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Latitude")
+ .HasPrecision(9, 6)
+ .HasColumnType("decimal(9,6)");
+
+ b.Property("Longitude")
+ .HasPrecision(9, 6)
+ .HasColumnType("decimal(9,6)");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(150)
+ .HasColumnType("nvarchar(150)");
+
+ b.Property("OpeningTime")
+ .HasColumnType("time");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)")
+ .HasDefaultValue("ACTIVE");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("datetime2");
+
+ b.HasKey("FacilityId");
+
+ b.ToTable("facilities", null, t =>
+ {
+ t.HasCheckConstraint("CK_facilities_coordinates", "([Latitude] IS NULL AND [Longitude] IS NULL) OR ([Latitude] BETWEEN -90 AND 90 AND [Longitude] BETWEEN -180 AND 180)");
+
+ t.HasCheckConstraint("CK_facilities_status", "[Status] IN ('ACTIVE','INACTIVE','TEMPORARILY_CLOSED')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.FacilityIncident", b =>
+ {
+ b.Property("IncidentId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("IncidentId"));
+
+ b.Property("AffectedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("CaseCode")
+ .IsRequired()
+ .HasMaxLength(40)
+ .IsUnicode(false)
+ .HasColumnType("varchar(40)");
+
+ b.Property("ChoiceAt")
+ .HasColumnType("datetime2");
+
+ b.Property("ChoiceNote")
+ .HasMaxLength(1000)
+ .HasColumnType("nvarchar(1000)");
+
+ b.Property("ChoiceOption")
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)");
+
+ b.Property("Confirmed")
+ .HasColumnType("bit");
+
+ b.Property("ContractId")
+ .HasColumnType("bigint");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("CreatedBy")
+ .HasColumnType("bigint");
+
+ b.Property("CurrentMonthRent")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("Description")
+ .HasMaxLength(1000)
+ .HasColumnType("nvarchar(1000)");
+
+ b.Property("FacilityId")
+ .HasColumnType("bigint");
+
+ b.Property("MovedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("OldUnitId")
+ .HasColumnType("bigint");
+
+ b.Property("Proposal")
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)");
+
+ b.Property("RefundAccountHolder")
+ .HasMaxLength(150)
+ .HasColumnType("nvarchar(150)");
+
+ b.Property("RefundAccountNumber")
+ .HasMaxLength(19)
+ .IsUnicode(false)
+ .HasColumnType("varchar(19)");
+
+ b.Property("RefundBankName")
+ .HasMaxLength(100)
+ .HasColumnType("nvarchar(100)");
+
+ b.Property("RefundPaymentId")
+ .HasColumnType("bigint");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)")
+ .HasDefaultValue("DRAFT");
+
+ b.Property("TargetUnitId")
+ .HasColumnType("bigint");
+
+ b.Property("UnusedRent")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Version")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("int")
+ .HasDefaultValue(1);
+
+ b.HasKey("IncidentId");
+
+ b.HasIndex("CaseCode")
+ .IsUnique();
+
+ b.HasIndex("ContractId")
+ .IsUnique()
+ .HasFilter("[Status] IN ('DRAFT','PROPOSED','TRANSFER_PENDING','TERMINATION_PENDING')");
+
+ b.HasIndex("OldUnitId");
+
+ b.HasIndex("TargetUnitId")
+ .IsUnique()
+ .HasFilter("[TargetUnitId] IS NOT NULL AND [Status] IN ('PROPOSED','TRANSFER_PENDING')");
+
+ b.HasIndex("FacilityId", "Status");
+
+ b.ToTable("facility_incidents", null, t =>
+ {
+ t.HasCheckConstraint("CK_facility_incidents_choice", "[ChoiceOption] IS NULL OR [ChoiceOption] IN ('TRANSFER','TERMINATE')");
+
+ t.HasCheckConstraint("CK_facility_incidents_proposal", "[Proposal] IS NULL OR [Proposal] IN ('TRANSFER','TERMINATE')");
+
+ t.HasCheckConstraint("CK_facility_incidents_status", "[Status] IN ('DRAFT','PROPOSED','TRANSFER_PENDING','TRANSFERRED','TERMINATION_PENDING','TERMINATED')");
+
+ t.HasCheckConstraint("CK_facility_incidents_version", "[Version] > 0");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.HandoverRecord", b =>
+ {
+ b.Property("HandoverId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("HandoverId"));
+
+ b.Property("ContractId")
+ .HasColumnType("bigint");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("CustomerConfirmed")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bit")
+ .HasDefaultValue(false);
+
+ b.Property("HandoverAt")
+ .HasColumnType("datetime2");
+
+ b.Property("InitialCondition")
+ .HasMaxLength(500)
+ .HasColumnType("nvarchar(500)");
+
+ b.Property("Notes")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("ScheduledAt")
+ .HasColumnType("datetime2");
+
+ b.Property("StaffConfirmed")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bit")
+ .HasDefaultValue(false);
+
+ b.Property("StaffId")
+ .HasColumnType("bigint");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)")
+ .HasDefaultValue("SCHEDULED");
+
+ b.Property("VerifiedAt")
+ .HasColumnType("datetime2");
+
+ b.HasKey("HandoverId");
+
+ b.HasIndex("ContractId")
+ .IsUnique();
+
+ b.HasIndex("StaffId");
+
+ b.ToTable("handover_records", null, t =>
+ {
+ t.HasCheckConstraint("CK_handover_records_status", "[Status] IN ('SCHEDULED','VERIFIED','HANDED_OVER','CANCELLED')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.LoginHistory", b =>
+ {
+ b.Property("LoginHistoryId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("LoginHistoryId"));
+
+ b.Property("DeviceInfo")
+ .HasMaxLength(255)
+ .HasColumnType("nvarchar(255)");
+
+ b.Property("IpAddress")
+ .HasMaxLength(45)
+ .HasColumnType("nvarchar(45)");
+
+ b.Property("LoginAt")
+ .HasColumnType("datetime2");
+
+ b.Property("LoginStatus")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)");
+
+ b.Property("LogoutAt")
+ .HasColumnType("datetime2");
+
+ b.Property("UserId")
+ .HasColumnType("bigint");
+
+ b.HasKey("LoginHistoryId");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("login_history", null, t =>
+ {
+ t.HasCheckConstraint("CK_login_history_status", "[LoginStatus] IN ('SUCCESS','FAILED','BLOCKED')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.MaintenanceRequest", b =>
+ {
+ b.Property("MaintenanceId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("MaintenanceId"));
+
+ b.Property("AssignedStaffId")
+ .HasColumnType("bigint");
+
+ b.Property("CompletedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Cost")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("decimal(15,2)")
+ .HasDefaultValue(0m);
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("IssueDescription")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("MaintenanceType")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)");
+
+ b.Property("Notes")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Priority")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)")
+ .HasDefaultValue("NORMAL");
+
+ b.Property("ReportedBy")
+ .HasColumnType("bigint");
+
+ b.Property("ScheduledAt")
+ .HasColumnType("datetime2");
+
+ b.Property("StartedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)")
+ .HasDefaultValue("OPEN");
+
+ b.Property("SupportTicketId")
+ .HasColumnType("bigint");
+
+ b.Property("UnitId")
+ .HasColumnType("bigint");
+
+ b.HasKey("MaintenanceId");
+
+ b.HasIndex("AssignedStaffId");
+
+ b.HasIndex("ReportedBy");
+
+ b.HasIndex("SupportTicketId");
+
+ b.HasIndex("UnitId");
+
+ b.ToTable("maintenance_requests", null, t =>
+ {
+ t.HasCheckConstraint("CK_maintenance_requests_priority", "[Priority] IN ('LOW','NORMAL','HIGH','URGENT')");
+
+ t.HasCheckConstraint("CK_maintenance_requests_status", "[Status] IN ('OPEN','SCHEDULED','IN_PROGRESS','COMPLETED','CANCELLED')");
+
+ t.HasCheckConstraint("CK_maintenance_requests_type", "[MaintenanceType] IN ('INSPECTION','REPAIR','CLEANING','LOCK','ACCESS_SYSTEM','OTHER')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.OverdueCase", b =>
+ {
+ b.Property("OverdueCaseId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("OverdueCaseId"));
+
+ b.Property("AssignedStaffId")
+ .HasColumnType("bigint");
+
+ b.Property("ContractId")
+ .HasColumnType("bigint");
+
+ b.Property("GraceDeadline")
+ .HasColumnType("date");
+
+ b.Property("Notes")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("OpenedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("OutstandingAmount")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("decimal(15,2)")
+ .HasDefaultValue(0m);
+
+ b.Property("OverdueFrom")
+ .HasColumnType("date");
+
+ b.Property("ResolvedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)")
+ .HasDefaultValue("OPEN");
+
+ b.HasKey("OverdueCaseId");
+
+ b.HasIndex("AssignedStaffId");
+
+ b.HasIndex("ContractId");
+
+ b.ToTable("overdue_cases", null, t =>
+ {
+ t.HasCheckConstraint("CK_overdue_cases_status", "[Status] IN ('OPEN','CONTACTED','PAYMENT_PENDING','RETURN_PENDING','RESOLVED','ESCALATED')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.Payment", b =>
+ {
+ b.Property("PaymentId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PaymentId"));
+
+ b.Property("Amount")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("ContractId")
+ .HasColumnType("bigint");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Currency")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(3)
+ .HasColumnType("nvarchar(3)")
+ .HasDefaultValue("VND");
+
+ b.Property("DueDate")
+ .HasColumnType("date");
+
+ b.Property("PaidAt")
+ .HasColumnType("datetime2");
+
+ b.Property("PaymentMethod")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)");
+
+ b.Property("PaymentType")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)");
+
+ b.Property("RenewalId")
+ .HasColumnType("bigint");
+
+ b.Property("ReservationId")
+ .HasColumnType("bigint");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)")
+ .HasDefaultValue("PENDING");
+
+ b.Property("TransactionReference")
+ .HasMaxLength(150)
+ .HasColumnType("nvarchar(150)");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("datetime2");
+
+ b.HasKey("PaymentId");
+
+ b.HasIndex("ContractId");
+
+ b.HasIndex("RenewalId")
+ .IsUnique()
+ .HasFilter("[PaymentType] = 'RENEWAL' AND [RenewalId] IS NOT NULL");
+
+ b.HasIndex("TransactionReference")
+ .IsUnique()
+ .HasFilter("[TransactionReference] IS NOT NULL");
+
+ b.HasIndex("ReservationId", "PaymentType")
+ .IsUnique()
+ .HasFilter("[ReservationId] IS NOT NULL AND [PaymentType] IN ('RENT','DEPOSIT')");
+
+ b.ToTable("payments", null, t =>
+ {
+ t.HasCheckConstraint("CK_payments_amount", "[Amount] >= 0");
+
+ t.HasCheckConstraint("CK_payments_payment_method", "[PaymentMethod] IN ('CASH','BANK_TRANSFER','CARD','E_WALLET','PAYMENT_GATEWAY')");
+
+ t.HasCheckConstraint("CK_payments_payment_type", "[PaymentType] IN ('DEPOSIT','RENT','RENEWAL','EXTRA_FEE','OVERDUE_FEE','DAMAGE_FEE','CLEANING_FEE','LOST_KEY_FEE','ACCESS_CARD_FEE','REFUND')");
+
+ t.HasCheckConstraint("CK_payments_status", "[Status] IN ('PENDING','PAID','FAILED','REFUNDED','PARTIALLY_REFUNDED')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.PaymentCheckout", b =>
+ {
+ b.Property("CheckoutId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("CheckoutId"));
+
+ b.Property("Amount")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("CheckoutUrl")
+ .HasMaxLength(2000)
+ .HasColumnType("nvarchar(2000)");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("ExpiresAt")
+ .HasColumnType("datetime2");
+
+ b.Property("OrderCode")
+ .HasColumnType("bigint");
+
+ b.Property("PaymentId")
+ .HasColumnType("bigint");
+
+ b.Property("Provider")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)")
+ .HasDefaultValue("PAYOS");
+
+ b.Property("QrCode")
+ .HasMaxLength(2000)
+ .HasColumnType("nvarchar(2000)");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)")
+ .HasDefaultValue("PENDING");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("datetime2");
+
+ b.HasKey("CheckoutId");
+
+ b.HasIndex("OrderCode")
+ .IsUnique();
+
+ b.HasIndex("PaymentId");
+
+ b.ToTable("payment_checkouts", null, t =>
+ {
+ t.HasCheckConstraint("CK_payment_checkouts_amount", "[Amount] >= 0");
+
+ t.HasCheckConstraint("CK_payment_checkouts_status", "[Status] IN ('PENDING','PAID','CANCELLED','EXPIRED')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.Permission", b =>
+ {
+ b.Property("PermissionId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PermissionId"));
+
+ b.Property("Description")
+ .HasMaxLength(255)
+ .HasColumnType("nvarchar(255)");
+
+ b.Property("PermissionCode")
+ .IsRequired()
+ .HasMaxLength(80)
+ .HasColumnType("nvarchar(80)");
+
+ b.Property("PermissionName")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("nvarchar(100)");
+
+ b.HasKey("PermissionId");
+
+ b.HasIndex("PermissionCode")
+ .IsUnique();
+
+ b.ToTable("permissions", (string)null);
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.Policy", b =>
+ {
+ b.Property("PolicyId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PolicyId"));
+
+ b.Property("CalculationType")
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("CreatedBy")
+ .HasColumnType("bigint");
+
+ b.Property("EffectiveFrom")
+ .HasColumnType("date");
+
+ b.Property("EffectiveTo")
+ .HasColumnType("date");
+
+ b.Property("FacilityId")
+ .HasColumnType("bigint");
+
+ b.Property("MaxValue")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("MinValue")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("PolicyName")
+ .IsRequired()
+ .HasMaxLength(150)
+ .HasColumnType("nvarchar(150)");
+
+ b.Property("PolicyType")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)");
+
+ b.Property("RuleDescription")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Status")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .HasColumnType("nvarchar(20)")
+ .HasDefaultValue("DRAFT");
+
+ b.Property("UnitTypeId")
+ .HasColumnType("bigint");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Value")
+ .HasColumnType("decimal(15,2)");
+
+ b.HasKey("PolicyId");
+
+ b.HasIndex("CreatedBy");
+
+ b.HasIndex("FacilityId");
+
+ b.HasIndex("UnitTypeId");
+
+ b.ToTable("policies", null, t =>
+ {
+ t.HasCheckConstraint("CK_policies_calculation_type", "[CalculationType] IS NULL OR [CalculationType] IN ('FIXED','PERCENTAGE','RANGE','RULE','DEPOSIT_PERCENT_PER_DAY')");
+
+ t.HasCheckConstraint("CK_policies_policy_type", "[PolicyType] IN ('DEPOSIT','RENEWAL','CANCELLATION','RETURN','OVERDUE','EXTRA_FEE','DISCOUNT','FEE_WAIVER','PRICE_RANGE')");
+
+ t.HasCheckConstraint("CK_policies_status", "[Status] IN ('DRAFT','ACTIVE','INACTIVE','EXPIRED')");
+ });
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.PolicyConsent", b =>
+ {
+ b.Property("ConsentId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ConsentId"));
+
+ b.Property("AcceptedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("Channel")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("nvarchar(30)")
+ .HasDefaultValue("WEB_CUSTOMER");
+
+ b.Property("ContractId")
+ .HasColumnType("bigint");
+
+ b.Property("CustomerId")
+ .HasColumnType("bigint");
+
+ b.Property("PolicyVersionId")
+ .HasColumnType("bigint");
+
+ b.Property("RenewalId")
+ .HasColumnType("bigint");
+
+ b.Property("ReservationId")
+ .HasColumnType("bigint");
+
+ b.HasKey("ConsentId");
+
+ b.HasIndex("ContractId");
+
+ b.HasIndex("PolicyVersionId");
+
+ b.HasIndex("RenewalId")
+ .HasFilter("[RenewalId] IS NOT NULL");
+
+ b.HasIndex("ReservationId")
+ .HasFilter("[ReservationId] IS NOT NULL");
+
+ b.HasIndex("CustomerId", "PolicyVersionId");
+
+ b.ToTable("policy_consents", (string)null);
+ });
+
+ modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b =>
+ {
+ b.Property("ContractId")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ContractId"));
+
+ b.Property("ActivatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("AgreedMonthlyRate")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("CompletedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("CustomerId")
+ .HasColumnType("bigint");
+
+ b.Property("DepositAmount")
+ .HasColumnType("decimal(15,2)");
+
+ b.Property("EndDate")
+ .HasColumnType("date");
+
+ b.Property("ReservationId")
+ .HasColumnType("bigint");
+
+ b.Property