From b48284065128fc884c88a0264ea9dfa7d3f6d07a Mon Sep 17 00:00:00 2001 From: Vector Date: Tue, 20 Oct 2026 23:31:04 +0700 Subject: [PATCH] fix: reconcile payments, enforce unit transitions and fix policy seeding --- DECISIONS.md | 18 + .../SafeSpace-Customer-UI/BE-CONTRACT.md | 4 + .../SafeSpace-Customer-UI/src/state/store.jsx | 17 +- .../Endpoints/ManagerEndpoints.cs | 65 - .../Endpoints/ReservationEndpoints.cs | 10 + .../Endpoints/StaffEndpoints.cs | 41 +- StorageProject.Api/Program.cs | 3 + StorageProject.Api/StorageProject.Api.http | 28 + .../Workers/ExpiredCashHoldWorker.cs | 19 + .../DTOs/Payment/PaymentDtos.cs | 2 +- .../DTOs/Reservation/ReservationDtos.cs | 6 +- StorageProject.Core/Entities/Payment.cs | 4 +- StorageProject.Core/Entities/Reservation.cs | 1 + .../Interfaces/IPayOSService.cs | 1 + .../ReservationContractConfigurations.cs | 6 +- .../Data/DbSeeder.cs | 5 + ...38_ReservationPaymentIntegrity.Designer.cs | 2004 +++++++++++++++++ ...61020154838_ReservationPaymentIntegrity.cs | 109 + .../Migrations/AppDbContextModelSnapshot.cs | 28 +- .../Services/CashHoldExpiry.cs | 34 + .../Services/CheckoutTransaction.cs | 27 + .../Services/FacilityOpsService.Actions.cs | 72 +- .../Services/FacilityOpsService.Board.cs | 4 +- .../Services/FacilityOpsStateStore.cs | 10 +- .../Services/FacilityService.cs | 3 +- .../Services/ManagerService.cs | 67 +- .../Services/OperationsReportService.cs | 8 +- .../Services/PayOSGateway.cs | 63 + .../Services/PayOSService.cs | 453 +--- .../Services/PaymentService.cs | 2 +- .../Services/ReservationAllocation.cs | 58 + .../Services/ReservationService.cs | 31 +- .../Services/ReservationSettlement.cs | 53 + .../Services/StaffService.cs | 212 +- .../Services/UnitStatusRules.cs | 24 + StorageProject.Tests/CheckoutTests.cs | 187 ++ StorageProject.Tests/RouteTests.cs | 32 + .../StorageProject.Tests.csproj | 10 + StorageProject.slnx | 1 + docs/payment-integrity-2026-10-20.md | 66 + feature_list.json | 15 +- progress.md | 10 + 42 files changed, 3024 insertions(+), 789 deletions(-) create mode 100644 StorageProject.Api/Workers/ExpiredCashHoldWorker.cs create mode 100644 StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.Designer.cs create mode 100644 StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.cs create mode 100644 StorageProject.Infrastructure/Services/CashHoldExpiry.cs create mode 100644 StorageProject.Infrastructure/Services/CheckoutTransaction.cs create mode 100644 StorageProject.Infrastructure/Services/PayOSGateway.cs create mode 100644 StorageProject.Infrastructure/Services/ReservationAllocation.cs create mode 100644 StorageProject.Infrastructure/Services/ReservationSettlement.cs create mode 100644 StorageProject.Infrastructure/Services/UnitStatusRules.cs create mode 100644 StorageProject.Tests/CheckoutTests.cs create mode 100644 StorageProject.Tests/RouteTests.cs create mode 100644 StorageProject.Tests/StorageProject.Tests.csproj create mode 100644 docs/payment-integrity-2026-10-20.md diff --git a/DECISIONS.md b/DECISIONS.md index 05cae7c..7610e57 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -149,3 +149,21 @@ - Ghi nhận lịch sử quét mã vào bảng `activity_logs` với `Action = "ACCESS_SCANNED"`, `EntityType = "CONTRACT"`, `EntityId = ContractId`, `NewValue = { result, unit, reason }`, `IpAddress` của máy quét. - Frontend: kết nối `useAccessQr.js` và `endpoints.js` trực tiếp với API backend khi `VITE_USE_API=true`, giữ nguyên mock offline cho môi trường thử nghiệm khi `VITE_USE_API=false`. + +## D23 — Thu tiền đặt kho và dự phòng thanh toán tại cơ sở (20/10/2026) +- Bổ sung cho D19/D21; không đổi số hoặc xoá nội dung quyết định cũ. Phạm vi được yêu cầu: kiểm tiền PayOS, ghi khoản thu, chống lặp, phân bổ, thanh toán tại kho và F12. +- Giữ cách tính hiện tại: khách trả tiền thuê cả kỳ + tiền cọc; không triển khai bỏ cọc trong gói này. +- PayOS: backend tính số tiền; SDK kiểm chữ ký; đối chiếu chính xác orderCode và số tiền. Không tìm đơn bằng cách tách số từ mô tả. Không dùng VietQR mặc định khi PayOS lỗi. +- Khoản thu RENT và DEPOSIT ghi vào payments ngay khi xác nhận, gắn ReservationId; ContractId được phép trống trước khi quản lý phân bổ. Gắn lại đúng bản ghi vào hợp đồng DRAFT, không tạo khoản PAID mới. +- Webhook chỉ xác nhận thanh toán; quản lý chọn ô ở M05. Đơn trả tại kho cũng được phân bổ trước, nhưng chưa thu đủ thì không được bàn giao. +- Chọn trả tại kho phải còn hạn và chưa trả tiền. Nếu đã khởi tạo orderCode, cần PayOS xác nhận link đã huỷ/không tồn tại; không chuyển nếu không kiểm tra được hoặc PayOS đã nhận tiền (kể cả một phần). +- Đơn trả tại kho có trạng thái PENDING_AT_FACILITY và PaymentMethod AT_FACILITY. Giữ chỗ đến hết ngày hẹn nhận kho theo giờ Việt Nam; worker xử lý hết hạn mỗi phút, huỷ phân bổ/hợp đồng nháp chưa thu và trả ô RESERVED về AVAILABLE. Thu tiền và worker dùng cùng khoá giao dịch. +- S09 chỉ là đơn chờ thu tại kho; nhân viên bấm xác nhận khi đã thực nhận tiền mặt. Ghi CASH. API gọi lại không tạo khoản thu mới. +- Tiền PayOS về sau khi đổi phương thức/đóng đơn: ghi PAYMENT_REVIEW_REQUIRED đúng một lần cho orderCode, không cộng vào khoản thu thuê lần nữa. Quản lý kiểm tra khoản tiền thực về và hoàn thủ công theo nhật ký; không tuyên bố đã tự chuyển tiền hoàn. +- Khoá transaction ở SQL Server bằng sp_getapplock, cùng khoá reservation cho webhook/thu tiền/phân bổ; thêm unique index trên ReservationId + PaymentType cho RENT/DEPOSIT. API /api/ops chỉ đăng ký một lần. +- Migration nối khoản RENT/DEPOSIT cũ vào đơn khi liên kết là duy nhất; không xoá hay tự bịa khoản tiền cho các đơn cũ chỉ có PaidAt. Các đơn cũ thiếu bằng chứng thu cần đối chiếu trước khi bàn giao. + +## D24 — Đổi trạng thái ô bằng tay phải có lý do và lịch sử (20/10/2026) +- AVAILABLE, MAINTENANCE, OUT_OF_SERVICE được chuyển qua lại bằng thao tác quản lý vận hành nếu ô không có giữ chỗ/hợp đồng chưa đóng. Mỗi lần đổi phải có lý do 1–255 ký tự và ghi unit_status_history trong cùng transaction. +- RESERVED/ASSIGNED/OCCUPIED/RETURN_PENDING/INSPECTION thuộc luồng phân bổ, bàn giao, trả kho. Không cho dùng form trạng thái để bỏ qua các bước này. +- LOCKED từ giao diện được ánh xạ thành OUT_OF_SERVICE theo tập trạng thái SQL hiện có. Gọi lại cùng trạng thái với lý do hợp lệ không thêm lịch sử trùng. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md index 21e2e7e..e5945f5 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -108,3 +108,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: Hình dạng dữ liệu giao diện đang dùng nằm ở `src/ops/data.js`; nghiệp vụ (điều kiện chặn, chuyển trạng thái) ở `src/ops/reducer.js` và có test (`tests/ops.test.js`) để backend đối chiếu. + +## Bổ sung 20/10 — thu tiền trước phân bổ và trạng thái ô + +Đã triển khai API chọn trả tại kho, PaymentMethod, ghi khoản thu theo ReservationId rồi gắn ContractId, kiểm chuyển tiếp ô và lịch sử. Xem `docs/payment-integrity-2026-10-20.md` và D23–D24 để biết hợp đồng API, migration, phạm vi test và các ca cần chạy thật. FE không còn dùng confirm-transfer làm fallback cho chọn trả tại kho. Các API /api/ops tương thích được đăng ký duy nhất trong FacilityOpsEndpoints. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx index 4c70b58..21176ec 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx @@ -506,20 +506,9 @@ function ApiProvider({ children }) { } return null; }; - // Ưu tiên endpoint pay-at-facility; backend chưa có → dùng confirm-transfer để đơn vẫn vào hàng chờ thu tiền S09 - const calls = [() => api.payAtFacility(r.api_id), () => api.confirmTransfer(r.api_id)]; - let done = false; - for (const call of calls) { - try { - await call(); - done = true; - break; - } catch (e) { - const exp = await expired(e); - if (exp) return exp; - if (!(e instanceof ApiError && (e.status === 404 || e.status === 405))) throw e; - } - } + try { await api.payAtFacility(r.api_id); } + catch (e) { const exp = await expired(e); if (exp) return exp; throw e; } + const done = true; updateOverlay((o) => ({ ...o, atFacility: { ...o.atFacility, [r.api_id]: Date.now() }, diff --git a/StorageProject.Api/Endpoints/ManagerEndpoints.cs b/StorageProject.Api/Endpoints/ManagerEndpoints.cs index 82c9ebf..4405c4b 100644 --- a/StorageProject.Api/Endpoints/ManagerEndpoints.cs +++ b/StorageProject.Api/Endpoints/ManagerEndpoints.cs @@ -225,71 +225,6 @@ public static RouteGroupBuilder MapManagerEndpoints(this IEndpointRouteBuilder a } }); - // Backward compatibility routes for /api/ops/ - var opsGroup = app.MapGroup("/api/ops").WithTags("Operations (Compatibility)").RequireAuthorization(); - - opsGroup.MapGet("/board", async (ClaimsPrincipal user, IStaffService staffService, IManagerService managerService, CancellationToken ct) => - { - var role = user.GetUserRole(); - if (role.Equals("CUSTOMER", StringComparison.OrdinalIgnoreCase)) return Results.Forbid(); - - var userId = user.GetUserId(); - var isManager = role.Equals("MANAGER", StringComparison.OrdinalIgnoreCase) || role.Equals("ADMIN", StringComparison.OrdinalIgnoreCase); - - if (isManager) - { - var board = await managerService.GetManagerBoardAsync(userId, ct); - return Results.Ok(board); - } - else - { - var board = await staffService.GetStaffBoardAsync(userId, ct); - return Results.Ok(board); - } - }); - - opsGroup.MapPost("/allocations/{id}", async (string id, AllocateUnitRequest request, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.AllocateUnitAsync(userId, id, request, ct); - return Results.Ok(new { message = "Phân bổ kho thành công." }); - }); - - opsGroup.MapPut("/assignments/{id}", async (string id, AssignStaffRequest request, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.AssignStaffAsync(userId, id, request, ct); - return Results.Ok(new { message = "Phân công nhân viên thành công." }); - }); - - opsGroup.MapPost("/renewals/{id}/approve", async (string id, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.ApproveRenewalAsync(userId, id, ct); - return Results.Ok(new { message = "Phê duyệt gia hạn thành công." }); - }); - - opsGroup.MapPost("/renewals/{id}/reject", async (string id, RejectRenewalRequest request, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.RejectRenewalAsync(userId, id, request, ct); - return Results.Ok(new { message = "Từ chối gia hạn thành công." }); - }); - - opsGroup.MapPost("/contracts/{id}/reminders", async (string id, AddReminderRequest request, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.AddContractReminderAsync(userId, id, request, ct); - return Results.Ok(new { message = "Ghi nhận lịch sử nhắc nhở." }); - }); - - opsGroup.MapPost("/contracts/{id}/refund", async (string id, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - 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 group; } } diff --git a/StorageProject.Api/Endpoints/ReservationEndpoints.cs b/StorageProject.Api/Endpoints/ReservationEndpoints.cs index 915c339..d189fc9 100644 --- a/StorageProject.Api/Endpoints/ReservationEndpoints.cs +++ b/StorageProject.Api/Endpoints/ReservationEndpoints.cs @@ -82,6 +82,16 @@ public static RouteGroupBuilder MapReservationEndpoints(this IEndpointRouteBuild }) .WithSummary("Khách báo đã chuyển khoản: đơn chuyển sang chờ nhân viên đối soát (PENDING_VERIFICATION)"); + group.MapPost("/{id:long}/pay-at-facility", async (long id, ClaimsPrincipal user, IPayOSService payOS, CancellationToken ct) => + { + try { + await payOS.PayAtFacilityAsync(user.GetUserId(), id, ct); + return Results.Ok(new { message = "Đã giữ chỗ, thanh toán tại cửa hàng khi nhận kho." }); + } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { + return Results.BadRequest(new { error = ex.Message }); + } + }); + // PayOS integration endpoints: create QR and check payment status group.MapPost("/create-payos-qr", async (CreatePayOSQrRequest request, ClaimsPrincipal user, IPayOSService payOSService, CancellationToken ct) => { diff --git a/StorageProject.Api/Endpoints/StaffEndpoints.cs b/StorageProject.Api/Endpoints/StaffEndpoints.cs index a8b6394..5fda5c0 100644 --- a/StorageProject.Api/Endpoints/StaffEndpoints.cs +++ b/StorageProject.Api/Endpoints/StaffEndpoints.cs @@ -11,7 +11,7 @@ public static RouteGroupBuilder MapStaffEndpoints(this IEndpointRouteBuilder app { var group = app.MapGroup("/api/staff") .WithTags("Staff Operations") - .RequireAuthorization(); + .RequireAuthorization(policy => policy.RequireRole("STAFF", "MANAGER")); // 1. Staff Board group.MapGet("/board", async (ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => @@ -184,45 +184,6 @@ public static RouteGroupBuilder MapStaffEndpoints(this IEndpointRouteBuilder app } }); - // Backward compatibility routes for /api/ops/ - var opsGroup = app.MapGroup("/api/ops").WithTags("Operations (Compatibility)").RequireAuthorization(); - opsGroup.MapPost("/payments/{id}/confirm", async (string id, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.ConfirmPaymentAsync(userId, id, ct); - return Results.Ok(new { message = "Xác nhận thanh toán thành công." }); - }); - opsGroup.MapPost("/payments/{id}/mismatch", async (string id, MismatchPaymentRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.MismatchPaymentAsync(userId, id, request, ct); - return Results.Ok(new { message = "Ghi nhận sai lệch thanh toán." }); - }); - opsGroup.MapPost("/verifications/{id}", async (string id, VerifyCustomerRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.VerifyCustomerAsync(userId, id, request, ct); - return Results.Ok(new { message = "Xác minh thông tin khách hàng thành công." }); - }); - opsGroup.MapPost("/handovers/{id}/complete", async (string id, CompleteHandoverRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.CompleteHandoverAsync(userId, id, request, ct); - return Results.Ok(new { message = "Hoàn tất bàn giao kho." }); - }); - opsGroup.MapPost("/returns/{id}/inspection", async (string id, ReturnInspectionRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.SubmitReturnInspectionAsync(userId, id, request, ct); - return Results.Ok(new { message = "Lưu biên bản kiểm tra trả kho thành công." }); - }); - opsGroup.MapPost("/tickets/{id}/responses", async (string id, TicketResponseRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.AddTicketResponseAsync(userId, id, request, ct); - return Results.Ok(new { message = "Phản hồi yêu cầu hỗ trợ thành công." }); - }); - return group; } } diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs index 23a847c..2056d5d 100644 --- a/StorageProject.Api/Program.cs +++ b/StorageProject.Api/Program.cs @@ -1,4 +1,5 @@ using System.Text; +using StorageProject.Api.Workers; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; @@ -92,6 +93,8 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddSingleton(new AccessQrOptions( builder.Configuration["AccessQr:Secret"] ?? jwtSecret, diff --git a/StorageProject.Api/StorageProject.Api.http b/StorageProject.Api/StorageProject.Api.http index 45c3143..55c0f96 100644 --- a/StorageProject.Api/StorageProject.Api.http +++ b/StorageProject.Api/StorageProject.Api.http @@ -65,3 +65,31 @@ GET {{StorageProject.Api_HostAddress}}/api/operations/reports/export?view=facili Authorization: Bearer {{opsToken}} ### + +### ==== Bản sửa thanh toán 20/10: thay token và id bằng dữ liệu trên máy thử ==== +@customerToken = +@staffToken = +@managerToken = +@reservationId = 1 + +### Chọn trả tại kho (huỷ link PayOS cũ trước khi đổi phương thức) +POST {{StorageProject.Api_HostAddress}}/api/reservations/{{reservationId}}/pay-at-facility +Authorization: Bearer {{customerToken}} + +### Xác nhận đã thu tiền mặt, gửi lại không tạo tiền trùng +POST {{StorageProject.Api_HostAddress}}/api/staff/payments/{{reservationId}}/confirm +Authorization: Bearer {{staffToken}} + +### Phân bổ ô, gắn khoản thu đã có vào hợp đồng +POST {{StorageProject.Api_HostAddress}}/api/manager/allocations/{{reservationId}} +Authorization: Bearer {{managerToken}} +Content-Type: application/json + +{ "unitCode": "K01" } + +### Đổi trạng thái ô trống, bắt buộc lý do +PUT {{StorageProject.Api_HostAddress}}/api/staff/units/K02/status +Authorization: Bearer {{managerToken}} +Content-Type: application/json + +{ "status": "MAINTENANCE", "reason": "Sửa cửa kho" } diff --git a/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs b/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs new file mode 100644 index 0000000..cde02e5 --- /dev/null +++ b/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs @@ -0,0 +1,19 @@ +using StorageProject.Infrastructure.Data; +using StorageProject.Infrastructure.Services; + +namespace StorageProject.Api.Workers; + +public sealed class ExpiredCashHoldWorker(IServiceScopeFactory scopes, ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1)); + do { + try { + using var scope = scopes.CreateScope(); + await CashHoldExpiry.ExpireAsync(scope.ServiceProvider.GetRequiredService(), stoppingToken); + } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { return; } + catch (Exception ex) { logger.LogError(ex, "Không xử lý được các đơn hết hạn giữ chỗ"); } + } while (await timer.WaitForNextTickAsync(stoppingToken)); + } +} diff --git a/StorageProject.Core/DTOs/Payment/PaymentDtos.cs b/StorageProject.Core/DTOs/Payment/PaymentDtos.cs index f73231d..9baf54a 100644 --- a/StorageProject.Core/DTOs/Payment/PaymentDtos.cs +++ b/StorageProject.Core/DTOs/Payment/PaymentDtos.cs @@ -2,7 +2,7 @@ namespace StorageProject.Core.DTOs.Payment; public record PaymentDto( long PaymentId, - long ContractId, + long? ContractId, long? RenewalId, string PaymentType, decimal Amount, diff --git a/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs b/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs index 760c78f..3187422 100644 --- a/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs +++ b/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs @@ -23,7 +23,8 @@ public record ReservationDto( DateTime? ExpiresAt, DateTime? CancelledAt, string? CancellationReason, - DateTime CreatedAt + DateTime CreatedAt, + string PaymentMethod = "PAYOS" ); public record ReservationDetailDto( @@ -44,5 +45,6 @@ public record ReservationDetailDto( string? AssignedUnitNumber, long? ContractId, string? ContractStatus, - DateTime CreatedAt + DateTime CreatedAt, + string PaymentMethod = "PAYOS" ); diff --git a/StorageProject.Core/Entities/Payment.cs b/StorageProject.Core/Entities/Payment.cs index e4d11ea..f8f05f2 100644 --- a/StorageProject.Core/Entities/Payment.cs +++ b/StorageProject.Core/Entities/Payment.cs @@ -3,7 +3,8 @@ namespace StorageProject.Core.Entities; public class Payment { public long PaymentId { get; set; } - public long ContractId { get; set; } + public long? ContractId { get; set; } + public long? ReservationId { get; set; } public long? RenewalId { get; set; } // DEPOSIT, RENT, RENEWAL, EXTRA_FEE, OVERDUE_FEE, DAMAGE_FEE, CLEANING_FEE, // LOST_KEY_FEE, ACCESS_CARD_FEE, REFUND @@ -19,5 +20,6 @@ public class Payment public DateTime UpdatedAt { get; set; } public RentalContract Contract { get; set; } = null!; + public Reservation Reservation { get; set; } = null!; public ContractRenewal? Renewal { get; set; } } diff --git a/StorageProject.Core/Entities/Reservation.cs b/StorageProject.Core/Entities/Reservation.cs index f361ad2..487c83d 100644 --- a/StorageProject.Core/Entities/Reservation.cs +++ b/StorageProject.Core/Entities/Reservation.cs @@ -14,6 +14,7 @@ public class Reservation public decimal EstimatedAmount { get; set; } public decimal RequiredDeposit { get; set; } // PENDING_PAYMENT, PENDING_VERIFICATION (khách báo đã chuyển khoản, chờ đối soát), CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW + public string PaymentMethod { get; set; } = "PAYOS"; // PAYOS / AT_FACILITY public string Status { get; set; } = "PENDING_PAYMENT"; public string? CancellationReason { get; set; } public long? OrderCode { get; set; } diff --git a/StorageProject.Core/Interfaces/IPayOSService.cs b/StorageProject.Core/Interfaces/IPayOSService.cs index 88512cb..9e11fa2 100644 --- a/StorageProject.Core/Interfaces/IPayOSService.cs +++ b/StorageProject.Core/Interfaces/IPayOSService.cs @@ -5,6 +5,7 @@ namespace StorageProject.Core.Interfaces; public interface IPayOSService { Task CreatePaymentQrAsync(long customerId, CreatePayOSQrRequest request, CancellationToken ct = default); + Task PayAtFacilityAsync(long customerId, long reservationId, CancellationToken ct = default); Task ProcessWebhookAsync(string webhookBodyJson, string? signatureHeader, CancellationToken ct = default); Task GetReservationPaymentStatusAsync(long reservationId, CancellationToken ct = default); } diff --git a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs index e0815ce..f1efa1d 100644 --- a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs +++ b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs @@ -15,7 +15,7 @@ public void Configure(EntityTypeBuilder b) t.HasCheckConstraint("CK_reservations_estimated_amount", "[EstimatedAmount] >= 0"); t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); t.HasCheckConstraint("CK_reservations_status", - "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','PENDING_AT_FACILITY','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); }); b.HasKey(r => r.ReservationId); b.Property(r => r.ReservationId).UseIdentityColumn(); @@ -27,6 +27,7 @@ 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.PaymentMethod).IsRequired().HasMaxLength(20).HasDefaultValue("PAYOS"); b.Property(r => r.OrderCode); b.HasIndex(r => r.OrderCode).IsUnique().HasFilter("[OrderCode] IS NOT NULL"); b.Property(r => r.PaymentQrUrl).HasMaxLength(2000); @@ -144,6 +145,9 @@ public void Configure(EntityTypeBuilder b) t.HasCheckConstraint("CK_payments_status", "[Status] IN ('PENDING','PAID','FAILED','REFUNDED','PARTIALLY_REFUNDED')"); }); + b.HasOne(p => p.Reservation).WithMany().HasForeignKey(p => p.ReservationId).OnDelete(DeleteBehavior.Restrict); + b.HasIndex(p => new { p.ReservationId, p.PaymentType }).IsUnique() + .HasFilter("[ReservationId] IS NOT NULL AND [PaymentType] IN ('RENT','DEPOSIT')"); b.HasKey(p => p.PaymentId); b.Property(p => p.PaymentId).UseIdentityColumn(); b.Property(p => p.PaymentType).IsRequired().HasMaxLength(30); diff --git a/StorageProject.Infrastructure/Data/DbSeeder.cs b/StorageProject.Infrastructure/Data/DbSeeder.cs index d3b95d1..d05a1d9 100644 --- a/StorageProject.Infrastructure/Data/DbSeeder.cs +++ b/StorageProject.Infrastructure/Data/DbSeeder.cs @@ -215,6 +215,11 @@ async Task EnsureUserAsync(string username, string email, string fullName, } }; + foreach (var policy in policies) + { + policy.CreatedBy = admin.UserId; + } + context.Policies.AddRange(policies); await context.SaveChangesAsync(); } diff --git a/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.Designer.cs b/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.Designer.cs new file mode 100644 index 0000000..4879d09 --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.Designer.cs @@ -0,0 +1,2004 @@ +// +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("20261020154838_ReservationPaymentIntegrity")] + partial class ReservationPaymentIntegrity + { + /// + 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("ApprovedAt") + .HasColumnType("datetime2"); + + b.Property("ApprovedBy") + .HasColumnType("bigint"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .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("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"); + + 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')"); + }); + }); + + 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.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"); + + 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.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(20) + .HasColumnType("nvarchar(20)"); + + 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')"); + + 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.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("StartDate") + .HasColumnType("date"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("DRAFT"); + + b.Property("TerminationReason") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("ContractId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("ReservationId") + .IsUnique(); + + b.HasIndex("UnitId"); + + b.ToTable("rental_contracts", null, t => + { + t.HasCheckConstraint("CK_rental_contracts_dates", "[EndDate] > [StartDate]"); + + t.HasCheckConstraint("CK_rental_contracts_deposit", "[DepositAmount] >= 0"); + + t.HasCheckConstraint("CK_rental_contracts_rate", "[AgreedMonthlyRate] >= 0"); + + t.HasCheckConstraint("CK_rental_contracts_status", "[Status] IN ('DRAFT','ACTIVE','EXPIRING','OVERDUE','RETURN_PENDING','COMPLETED','TERMINATED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalRate", b => + { + b.Property("RateId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RateId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("EffectiveTo") + .HasColumnType("date"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("MonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("SetBy") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("DRAFT"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.HasKey("RateId"); + + b.HasIndex("FacilityId"); + + b.HasIndex("SetBy"); + + b.HasIndex("UnitTypeId"); + + b.ToTable("rental_rates", null, t => + { + t.HasCheckConstraint("CK_rental_rates_monthly_rate", "[MonthlyRate] > 0"); + + t.HasCheckConstraint("CK_rental_rates_status", "[Status] IN ('DRAFT','ACTIVE','EXPIRED','INACTIVE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.Property("ReservationId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ReservationId")); + + b.Property("CancellationReason") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("CancelledAt") + .HasColumnType("datetime2"); + + b.Property("CheckInAppointmentAt") + .HasColumnType("datetime2"); + + b.Property("CheckoutUrl") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("EstimatedAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("ExpectedEndDate") + .HasColumnType("date"); + + b.Property("ExpiresAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("OrderCode") + .HasColumnType("bigint"); + + b.Property("PaidAt") + .HasColumnType("datetime2"); + + b.Property("PaymentMethod") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PAYOS"); + + b.Property("PaymentQrUrl") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("QuotedMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("RentalPeriodMonths") + .HasColumnType("int"); + + b.Property("RequiredDeposit") + .HasColumnType("decimal(15,2)"); + + b.Property("StartDate") + .HasColumnType("date"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("PENDING_PAYMENT"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.HasKey("ReservationId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("FacilityId"); + + b.HasIndex("OrderCode") + .IsUnique() + .HasFilter("[OrderCode] IS NOT NULL"); + + b.HasIndex("UnitTypeId"); + + b.ToTable("reservations", null, t => + { + t.HasCheckConstraint("CK_reservations_estimated_amount", "[EstimatedAmount] >= 0"); + + t.HasCheckConstraint("CK_reservations_quoted_rate", "[QuotedMonthlyRate] >= 0"); + + t.HasCheckConstraint("CK_reservations_rental_period", "[RentalPeriodMonths] > 0"); + + t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); + + t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','PENDING_AT_FACILITY','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ReturnInspection", b => + { + b.Property("InspectionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("InspectionId")); + + b.Property("CleaningFee") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("CleaningRequired") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("ConditionStatus") + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("DamageDescription") + .HasColumnType("nvarchar(max)"); + + b.Property("DamageFee") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("InspectedAt") + .HasColumnType("datetime2"); + + b.Property("MaintenanceRequired") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("ScheduledAt") + .HasColumnType("datetime2"); + + b.Property("StaffId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("SCHEDULED"); + + b.HasKey("InspectionId"); + + b.HasIndex("ContractId"); + + b.HasIndex("StaffId"); + + b.ToTable("return_inspections", null, t => + { + t.HasCheckConstraint("CK_return_inspections_condition", "[ConditionStatus] IS NULL OR [ConditionStatus] IN ('GOOD','DIRTY','DAMAGED','MAINTENANCE_REQUIRED')"); + + t.HasCheckConstraint("CK_return_inspections_status", "[Status] IN ('SCHEDULED','IN_PROGRESS','COMPLETED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Role", b => + { + b.Property("RoleId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RoleId")); + + b.Property("Description") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("RoleId"); + + b.HasIndex("RoleName") + .IsUnique(); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RolePermission", b => + { + b.Property("RoleId") + .HasColumnType("bigint"); + + b.Property("PermissionId") + .HasColumnType("bigint"); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.ToTable("role_permissions", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.Property("UnitId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UnitId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("Floor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LocationDescription") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("AVAILABLE"); + + b.Property("UnitNumber") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Zone") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("UnitId"); + + b.HasIndex("UnitTypeId"); + + b.HasIndex("FacilityId", "UnitNumber") + .IsUnique(); + + b.ToTable("storage_units", null, t => + { + t.HasCheckConstraint("CK_storage_units_status", "[Status] IN ('AVAILABLE','RESERVED','ASSIGNED','OCCUPIED','RETURN_PENDING','INSPECTION','MAINTENANCE','OUT_OF_SERVICE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.Property("TicketId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("TicketId")); + + b.Property("AssignedAt") + .HasColumnType("datetime2"); + + b.Property("AssignedStaffId") + .HasColumnType("bigint"); + + b.Property("ClosedAt") + .HasColumnType("datetime2"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("Description") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("IssueType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("Priority") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("NORMAL"); + + b.Property("ResolvedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("OPEN"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("TicketId"); + + b.HasIndex("AssignedStaffId"); + + b.HasIndex("ContractId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("UnitId"); + + b.ToTable("support_tickets", null, t => + { + t.HasCheckConstraint("CK_support_tickets_issue_type", "[IssueType] IN ('UNIT','LOCK','ACCESS_CODE','ACCESS_CARD','PAYMENT','STORED_ITEM','OTHER')"); + + t.HasCheckConstraint("CK_support_tickets_priority", "[Priority] IN ('LOW','NORMAL','HIGH','URGENT')"); + + t.HasCheckConstraint("CK_support_tickets_status", "[Status] IN ('OPEN','ASSIGNED','IN_PROGRESS','RESOLVED','CLOSED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitAssignment", b => + { + b.Property("AssignmentId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("AssignmentId")); + + b.Property("AssignedAt") + .HasColumnType("datetime2"); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.Property("Reason") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UnassignedAt") + .HasColumnType("datetime2"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("AssignmentId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("ReservationId"); + + b.HasIndex("UnitId"); + + b.ToTable("unit_assignments", null, t => + { + t.HasCheckConstraint("CK_unit_assignments_status", "[Status] IN ('ACTIVE','REPLACED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitStatusHistory", b => + { + b.Property("StatusHistoryId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("StatusHistoryId")); + + b.Property("ChangedAt") + .HasColumnType("datetime2"); + + b.Property("ChangedBy") + .HasColumnType("bigint"); + + b.Property("NewStatus") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("OldStatus") + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("Reason") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("StatusHistoryId"); + + b.HasIndex("ChangedBy"); + + b.HasIndex("UnitId"); + + b.ToTable("unit_status_history", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitType", b => + { + b.Property("UnitTypeId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UnitTypeId")); + + b.Property("Area") + .HasColumnType("decimal(8,2)"); + + b.Property("ClimateControlled") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Height") + .HasColumnType("decimal(8,2)"); + + b.Property("Length") + .HasColumnType("decimal(8,2)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("TypeName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Width") + .HasColumnType("decimal(8,2)"); + + b.HasKey("UnitTypeId"); + + b.HasIndex("TypeName") + .IsUnique(); + + b.ToTable("unit_types", null, t => + { + t.HasCheckConstraint("CK_unit_types_area", "[Area] > 0"); + + t.HasCheckConstraint("CK_unit_types_height", "[Height] IS NULL OR [Height] > 0"); + + t.HasCheckConstraint("CK_unit_types_length", "[Length] IS NULL OR [Length] > 0"); + + t.HasCheckConstraint("CK_unit_types_status", "[Status] IN ('ACTIVE','INACTIVE')"); + + t.HasCheckConstraint("CK_unit_types_width", "[Width] IS NULL OR [Width] > 0"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.User", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UserId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("FullName") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Phone") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("UserId"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("CK_users_status", "[Status] IN ('ACTIVE','INACTIVE','LOCKED','SUSPENDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserFacility", b => + { + b.Property("UserFacilityId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UserFacilityId")); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.Property("AssignedFrom") + .HasColumnType("date"); + + b.Property("AssignedTo") + .HasColumnType("date"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("UserFacilityId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("FacilityId"); + + b.HasIndex("UserId"); + + b.ToTable("user_facilities", null, t => + { + t.HasCheckConstraint("CK_user_facilities_status", "[Status] IN ('ACTIVE','ENDED','SUSPENDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserRole", b => + { + b.Property("UserId") + .HasColumnType("bigint"); + + b.Property("RoleId") + .HasColumnType("bigint"); + + b.Property("AssignedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2") + .HasDefaultValueSql("GETUTCDATE()"); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.AccessCredential", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("AccessCredentials") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "IssuedByUser") + .WithMany() + .HasForeignKey("IssuedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("AccessCredentials") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("IssuedByUser"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ActivityLog", b => + { + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("ActivityLogs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.HasOne("StorageProject.Core.Entities.User", "ApprovedByUser") + .WithMany() + .HasForeignKey("ApprovedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("ContractRenewals") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByUser"); + + b.Navigation("Contract"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.HandoverRecord", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithOne("HandoverRecord") + .HasForeignKey("StorageProject.Core.Entities.HandoverRecord", "ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "Staff") + .WithMany() + .HasForeignKey("StaffId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("Staff"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.LoginHistory", b => + { + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("LoginHistories") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.MaintenanceRequest", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.User", "ReportedByUser") + .WithMany() + .HasForeignKey("ReportedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.SupportTicket", "SupportTicket") + .WithMany("MaintenanceRequests") + .HasForeignKey("SupportTicketId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("MaintenanceRequests") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedStaff"); + + b.Navigation("ReportedByUser"); + + b.Navigation("SupportTicket"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.OverdueCase", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("OverdueCases") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedStaff"); + + b.Navigation("Contract"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Payment", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("Payments") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("StorageProject.Core.Entities.ContractRenewal", "Renewal") + .WithMany("Payments") + .HasForeignKey("RenewalId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany() + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Contract"); + + b.Navigation("Renewal"); + + b.Navigation("Reservation"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => + { + b.HasOne("StorageProject.Core.Entities.User", "CreatedByUser") + .WithMany() + .HasForeignKey("CreatedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("Policies") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("Policies") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CreatedByUser"); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("RentalContracts") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithOne("RentalContract") + .HasForeignKey("StorageProject.Core.Entities.RentalContract", "ReservationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("RentalContracts") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Customer"); + + b.Navigation("Reservation"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalRate", b => + { + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("RentalRates") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "SetByUser") + .WithMany() + .HasForeignKey("SetBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("RentalRates") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Facility"); + + b.Navigation("SetByUser"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("Reservations") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("Reservations") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("Reservations") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Customer"); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ReturnInspection", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("ReturnInspections") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "Staff") + .WithMany() + .HasForeignKey("StaffId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("Staff"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RolePermission", b => + { + b.HasOne("StorageProject.Core.Entities.Permission", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Role", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("StorageUnits") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("StorageUnits") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("SupportTickets") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("SupportTickets") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("SupportTickets") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("AssignedStaff"); + + b.Navigation("Contract"); + + b.Navigation("Customer"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitAssignment", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedByUser") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany("UnitAssignments") + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("UnitAssignments") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedByUser"); + + b.Navigation("Reservation"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitStatusHistory", b => + { + b.HasOne("StorageProject.Core.Entities.User", "ChangedByUser") + .WithMany() + .HasForeignKey("ChangedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("StatusHistories") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ChangedByUser"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserFacility", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Assigner") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("UserFacilities") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("UserFacilities") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Assigner"); + + b.Navigation("Facility"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserRole", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Assigner") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Assigner"); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.Navigation("Payments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Facility", b => + { + b.Navigation("Policies"); + + b.Navigation("RentalRates"); + + b.Navigation("Reservations"); + + b.Navigation("StorageUnits"); + + b.Navigation("UserFacilities"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Permission", b => + { + b.Navigation("RolePermissions"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.Navigation("AccessCredentials"); + + b.Navigation("ContractRenewals"); + + b.Navigation("HandoverRecord"); + + b.Navigation("OverdueCases"); + + b.Navigation("Payments"); + + b.Navigation("ReturnInspections"); + + b.Navigation("SupportTickets"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.Navigation("RentalContract"); + + b.Navigation("UnitAssignments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Role", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.Navigation("AccessCredentials"); + + b.Navigation("MaintenanceRequests"); + + b.Navigation("RentalContracts"); + + b.Navigation("StatusHistories"); + + b.Navigation("SupportTickets"); + + b.Navigation("UnitAssignments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.Navigation("MaintenanceRequests"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitType", b => + { + b.Navigation("Policies"); + + b.Navigation("RentalRates"); + + b.Navigation("Reservations"); + + b.Navigation("StorageUnits"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.User", b => + { + b.Navigation("ActivityLogs"); + + b.Navigation("LoginHistories"); + + b.Navigation("RentalContracts"); + + b.Navigation("Reservations"); + + b.Navigation("SupportTickets"); + + b.Navigation("UserFacilities"); + + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.cs b/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.cs new file mode 100644 index 0000000..6a60304 --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.cs @@ -0,0 +1,109 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace StorageProject.Infrastructure.Migrations +{ + /// + public partial class ReservationPaymentIntegrity : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropCheckConstraint( + name: "CK_reservations_status", + table: "reservations"); + + migrationBuilder.AddColumn( + name: "PaymentMethod", + table: "reservations", + type: "nvarchar(20)", + maxLength: 20, + nullable: false, + defaultValue: "PAYOS"); + + migrationBuilder.AlterColumn( + name: "ContractId", + table: "payments", + type: "bigint", + nullable: true, + oldClrType: typeof(long), + oldType: "bigint"); + + migrationBuilder.AddColumn( + name: "ReservationId", + table: "payments", + type: "bigint", + nullable: true); + + migrationBuilder.AddCheckConstraint( + name: "CK_reservations_status", + table: "reservations", + sql: "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','PENDING_AT_FACILITY','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + + // Link unambiguous existing receipts to their reservation; never delete or fabricate money. + migrationBuilder.Sql(@"UPDATE p SET ReservationId = c.ReservationId + FROM payments p INNER JOIN rental_contracts c ON p.ContractId = c.ContractId + WHERE p.PaymentType IN ('RENT','DEPOSIT') AND NOT EXISTS + (SELECT 1 FROM payments other WHERE other.ContractId = p.ContractId + AND other.PaymentType = p.PaymentType AND other.PaymentId <> p.PaymentId)"); + + migrationBuilder.CreateIndex( + name: "IX_payments_ReservationId_PaymentType", + table: "payments", + columns: new[] { "ReservationId", "PaymentType" }, + unique: true, + filter: "[ReservationId] IS NOT NULL AND [PaymentType] IN ('RENT','DEPOSIT')"); + + migrationBuilder.AddForeignKey( + name: "FK_payments_reservations_ReservationId", + table: "payments", + column: "ReservationId", + principalTable: "reservations", + principalColumn: "ReservationId", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(@"IF EXISTS (SELECT 1 FROM payments WHERE ContractId IS NULL) + OR EXISTS (SELECT 1 FROM reservations WHERE Status = 'PENDING_AT_FACILITY') + THROW 51000, N'Không thể hạ migration khi còn khoản thu chưa gắn hợp đồng hoặc đơn chờ thu tại kho.', 1;"); + migrationBuilder.DropForeignKey( + name: "FK_payments_reservations_ReservationId", + table: "payments"); + + migrationBuilder.DropCheckConstraint( + name: "CK_reservations_status", + table: "reservations"); + + migrationBuilder.DropIndex( + name: "IX_payments_ReservationId_PaymentType", + table: "payments"); + + migrationBuilder.DropColumn( + name: "PaymentMethod", + table: "reservations"); + + migrationBuilder.DropColumn( + name: "ReservationId", + table: "payments"); + + migrationBuilder.AlterColumn( + name: "ContractId", + table: "payments", + type: "bigint", + nullable: false, + defaultValue: 0L, + oldClrType: typeof(long), + oldType: "bigint", + oldNullable: true); + + migrationBuilder.AddCheckConstraint( + name: "CK_reservations_status", + table: "reservations", + sql: "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 69409e1..c628ab7 100644 --- a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -498,7 +498,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("Amount") .HasColumnType("decimal(15,2)"); - b.Property("ContractId") + b.Property("ContractId") .HasColumnType("bigint"); b.Property("CreatedAt") @@ -530,6 +530,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("RenewalId") .HasColumnType("bigint"); + b.Property("ReservationId") + .HasColumnType("bigint"); + b.Property("Status") .IsRequired() .ValueGeneratedOnAdd() @@ -554,6 +557,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .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"); @@ -845,6 +852,13 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("PaidAt") .HasColumnType("datetime2"); + b.Property("PaymentMethod") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PAYOS"); + b.Property("PaymentQrUrl") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); @@ -893,7 +907,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); - t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','PENDING_AT_FACILITY','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); }); }); @@ -1569,17 +1583,23 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") .WithMany("Payments") .HasForeignKey("ContractId") - .OnDelete(DeleteBehavior.Restrict) - .IsRequired(); + .OnDelete(DeleteBehavior.Restrict); b.HasOne("StorageProject.Core.Entities.ContractRenewal", "Renewal") .WithMany("Payments") .HasForeignKey("RenewalId") .OnDelete(DeleteBehavior.SetNull); + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany() + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.Restrict); + b.Navigation("Contract"); b.Navigation("Renewal"); + + b.Navigation("Reservation"); }); modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => diff --git a/StorageProject.Infrastructure/Services/CashHoldExpiry.cs b/StorageProject.Infrastructure/Services/CashHoldExpiry.cs new file mode 100644 index 0000000..9748be2 --- /dev/null +++ b/StorageProject.Infrastructure/Services/CashHoldExpiry.cs @@ -0,0 +1,34 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +public static class CashHoldExpiry +{ + public static async Task ExpireAsync(AppDbContext db, CancellationToken ct = default) + { + var ids = await db.Reservations.AsNoTracking().Where(r => r.Status == "PENDING_AT_FACILITY" && + r.PaidAt == null && r.ExpiresAt <= DateTime.UtcNow).Select(r => r.ReservationId).Take(100).ToListAsync(ct); + foreach (var id in ids) + { + await using var tx = await CheckoutTransaction.BeginAsync(db, $"reservation:{id}", ct); + var r = await db.Reservations.Include(r => r.UnitAssignments).ThenInclude(a => a.Unit) + .Include(r => r.RentalContract).ThenInclude(c => c!.HandoverRecord).SingleAsync(r => r.ReservationId == id, ct); + await db.Entry(r).ReloadAsync(ct); + if (r.Status != "PENDING_AT_FACILITY" || r.PaidAt != null || r.ExpiresAt > DateTime.UtcNow) continue; + await CheckoutTransaction.LockAsync(db, $"inventory:{r.FacilityId}", ct); + foreach (var a in r.UnitAssignments.Where(a => a.Status == "ACTIVE")) + { + a.Status = "CANCELLED"; + if (a.Unit.Status == "RESERVED") a.Unit.Status = "AVAILABLE"; + } + if (r.RentalContract?.Status == "DRAFT") { + r.RentalContract.Status = "CANCELLED"; + if (r.RentalContract.HandoverRecord != null) r.RentalContract.HandoverRecord.Status = "CANCELLED"; + } + r.Status = "EXPIRED"; + ReservationSettlement.Audit(db, null, "CASH_HOLD_EXPIRED", id, new { r.ExpiresAt }); + await db.SaveChangesAsync(ct); await tx.CommitAsync(ct); + } + } +} diff --git a/StorageProject.Infrastructure/Services/CheckoutTransaction.cs b/StorageProject.Infrastructure/Services/CheckoutTransaction.cs new file mode 100644 index 0000000..a637ff2 --- /dev/null +++ b/StorageProject.Infrastructure/Services/CheckoutTransaction.cs @@ -0,0 +1,27 @@ +using System.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +public static class CheckoutTransaction +{ + public static async Task BeginAsync(AppDbContext db, string resource, CancellationToken ct) + { + var tx = await db.Database.BeginTransactionAsync(IsolationLevel.Serializable, ct); + try { await LockAsync(db, resource, ct); return tx; } + catch { await tx.DisposeAsync(); throw; } + } + + public static async Task LockAsync(AppDbContext db, string resource, CancellationToken ct) + { + // SQL Server transaction-owned lock works across processes, unlike an in-memory semaphore. + if (db.Database.IsSqlServer()) + await db.Database.ExecuteSqlInterpolatedAsync($@" + DECLARE @result int; + EXEC @result = sp_getapplock @Resource={resource}, @LockMode='Exclusive', + @LockOwner='Transaction', @LockTimeout=10000; + IF @result < 0 THROW 51000, N'Không lấy được khoá giao dịch. Vui lòng thử lại.', 1;", ct); + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs index 0bafe6c..69f56eb 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs @@ -77,14 +77,7 @@ private async Task ContractAsync(long facilityId, string code, C // ===================================================================== public async Task ConfirmPaymentAsync(OpsActor actor, string id, CancellationToken ct = default) { - var facility = await FacilityOfAsync(actor, ct); - var r = await ReservationAsync(facility.FacilityId, id, ct); - if (r.Status != "PENDING_VERIFICATION") throw new InvalidOperationException("Khoản này đã được xử lý."); - - // Chưa có ô kho → vào hàng chờ phân bổ của quản lý (M05) - r.Status = "CONFIRMED"; - Log(actor.UserId, LogAction.PaymentConfirmed, LogEntity.Reservation, r.ReservationId, new { amount = r.EstimatedAmount + r.RequiredDeposit }); - await dbContext.SaveChangesAsync(ct); + await new StaffService(dbContext).ConfirmPaymentAsync(actor.UserId, id, ct); } public async Task ReportMismatchAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default) @@ -148,6 +141,8 @@ public async Task CompleteHandoverAsync(OpsActor actor, string id, OpsHandoverRe if (!UnlockMethods.Contains(method)) throw new ArgumentException("Chọn phương thức mở khoá."); var contract = h.Contract; + var reservation = await dbContext.Reservations.SingleAsync(r => r.ReservationId == contract.ReservationId, ct); + await ReservationSettlement.RequirePaidAsync(dbContext, reservation, ct); if (contract.Status != "DRAFT") throw new InvalidOperationException("Hợp đồng không ở trạng thái chờ bàn giao."); var now = NowUtc; @@ -266,66 +261,7 @@ public async Task AllocateAsync(OpsActor actor, string id, OpsAllocateRequest re RequireManager(actor); var facility = await FacilityOfAsync(actor, ct); var r = await ReservationAsync(facility.FacilityId, id, ct); - if (r.Status == "UNIT_ASSIGNED" || r.UnitAssignments.Any(a => a.Status == "ACTIVE")) - { - throw new InvalidOperationException("Đơn này đã được phân bổ kho."); - } - if (r.Status != "CONFIRMED") throw new InvalidOperationException("Đơn chưa được xác nhận thanh toán nên chưa phân bổ được."); - - var unitCode = (request.UnitCode ?? string.Empty).Trim(); - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == facility.FacilityId && u.UnitNumber == unitCode, ct); - if (unit == null || unit.Status != "AVAILABLE" || unit.UnitTypeId != r.UnitTypeId) - { - throw new InvalidOperationException("Kho đã chọn không còn trống hoặc không khớp đơn đặt chỗ."); - } - var busy = await dbContext.RentalContracts.AnyAsync(c => c.UnitId == unit.UnitId - && HeldContractStatuses.Contains(c.Status) - && c.StartDate < r.ExpectedEndDate && c.EndDate > r.StartDate, ct); - if (busy) throw new InvalidOperationException("Kho đã chọn không còn trống hoặc không khớp đơn đặt chỗ."); - - var now = NowUtc; - var code = ReservationCode(r); - var confirmedAt = await dbContext.ActivityLogs - .Where(l => l.EntityType == LogEntity.Reservation && l.EntityId == r.ReservationId && l.Action == LogAction.PaymentConfirmed) - .OrderByDescending(l => l.LoggedAt) - .Select(l => (DateTime?)l.LoggedAt) - .FirstOrDefaultAsync(ct) ?? now; - - dbContext.UnitAssignments.Add(new UnitAssignment - { - ReservationId = r.ReservationId, UnitId = unit.UnitId, AssignedBy = actor.UserId, Status = "ACTIVE", AssignedAt = now - }); - r.Status = "UNIT_ASSIGNED"; - SetUnitStatus(unit, "RESERVED", actor.UserId, $"Phân bổ cho đơn {code}"); - - var contract = new RentalContract - { - ReservationId = r.ReservationId, CustomerId = r.CustomerId, UnitId = unit.UnitId, - StartDate = r.StartDate, EndDate = r.ExpectedEndDate, AgreedMonthlyRate = r.QuotedMonthlyRate, - DepositAmount = r.RequiredDeposit, Status = "DRAFT", CreatedAt = now - }; - // Khoản khách đã chuyển (nhân viên đã đối soát ở S09): cọc + tiền thuê cả kỳ - foreach (var (kind, amount) in new[] { ("DEPOSIT", r.RequiredDeposit), ("RENT", r.EstimatedAmount) }) - { - contract.Payments.Add(new Payment - { - PaymentType = kind, Amount = amount, Currency = "VND", PaymentMethod = "BANK_TRANSFER", - TransactionReference = code, DueDate = r.StartDate, PaidAt = confirmedAt, Status = "PAID", - CreatedAt = now, UpdatedAt = now - }); - } - // Chưa giao cho nhân viên nào: người phụ trách tạm là quản lý (bảng M06 hiện "Cần xử lý") - contract.HandoverRecord = new HandoverRecord - { - StaffId = actor.UserId, - ScheduledAt = r.CheckInAppointmentAt ?? UtcFromLocal(r.StartDate, 9), - Status = "SCHEDULED", - CreatedAt = now - }; - dbContext.RentalContracts.Add(contract); - Log(actor.UserId, LogAction.UnitAllocated, LogEntity.Reservation, r.ReservationId, new { unit = unit.UnitNumber }); - await dbContext.SaveChangesAsync(ct); + await ReservationAllocation.AllocateAsync(dbContext, actor.UserId, facility.FacilityId, r.ReservationId, request.UnitCode ?? "", ct); } // ===================================================================== diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs index d599f22..16953bc 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs @@ -358,11 +358,11 @@ private async Task RevenueAsync(long facilityId, CancellationToke var rows = await dbContext.Payments .AsNoTracking() - .Where(p => p.Contract.Unit.FacilityId == facilityId + .Where(p => (p.ContractId != null ? p.Contract.Unit.FacilityId : p.Reservation.FacilityId) == facilityId && p.PaidAt != null && p.PaidAt >= fromUtc && (p.Status == "PAID" || p.Status == "REFUNDED" || p.Status == "PARTIALLY_REFUNDED") && p.PaymentType != "DEPOSIT" && p.PaymentType != "REFUND") - .Select(p => new { p.Amount, p.PaidAt, Cold = p.Contract.Unit.UnitType.ClimateControlled }) + .Select(p => new { p.Amount, p.PaidAt, Cold = p.ContractId != null ? p.Contract.Unit.UnitType.ClimateControlled : p.Reservation.UnitType.ClimateControlled }) .ToListAsync(ct); static decimal Million(decimal v) => Math.Round(v / 1_000_000m, 1, MidpointRounding.AwayFromZero); diff --git a/StorageProject.Infrastructure/Services/FacilityOpsStateStore.cs b/StorageProject.Infrastructure/Services/FacilityOpsStateStore.cs index d82da80..e0a7c51 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsStateStore.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsStateStore.cs @@ -33,10 +33,6 @@ public static long ParseIdNumber(string id) .AsQueryable(); var res = await q.FirstOrDefaultAsync(r => (ids.Contains(r.ReservationId) || (r.OrderCode.HasValue && ids.Contains(r.OrderCode.Value))) && (facilityId <= 0 || r.FacilityId == facilityId), ct); - if (res == null) - { - res = await q.FirstOrDefaultAsync(r => ids.Contains(r.ReservationId) || (r.OrderCode.HasValue && ids.Contains(r.OrderCode.Value)), ct); - } return res; } @@ -52,10 +48,6 @@ public static async Task GetUserFacilityAsync(AppDbContext dbContext, return userFac.Facility; } - var defaultFac = await dbContext.Facilities.FirstOrDefaultAsync(f => f.Name.Contains("Nguyễn Lương Bằng"), ct) - ?? await dbContext.Facilities.FirstOrDefaultAsync(ct) - ?? throw new InvalidOperationException("Không tìm thấy cơ sở kho."); - - return defaultFac; + throw new InvalidOperationException("Tài khoản chưa được phân công cơ sở đang hoạt động."); } } diff --git a/StorageProject.Infrastructure/Services/FacilityService.cs b/StorageProject.Infrastructure/Services/FacilityService.cs index cfde663..46fbbde 100644 --- a/StorageProject.Infrastructure/Services/FacilityService.cs +++ b/StorageProject.Infrastructure/Services/FacilityService.cs @@ -157,7 +157,8 @@ public async Task> GetActiveRatesAsync(long? facili var reservedUnitsCount = await dbContext.Reservations .CountAsync(r => r.FacilityId == request.FacilityId && r.UnitTypeId == request.UnitTypeId - && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED") + && (r.Status == "CONFIRMED" || ((r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "PENDING_AT_FACILITY") && r.ExpiresAt > DateTime.UtcNow)) + && !r.UnitAssignments.Any(a => a.Status == "ACTIVE") && r.StartDate < expectedEndDate && r.ExpectedEndDate > request.StartDate, ct); diff --git a/StorageProject.Infrastructure/Services/ManagerService.cs b/StorageProject.Infrastructure/Services/ManagerService.cs index a76ee42..1e7aece 100644 --- a/StorageProject.Infrastructure/Services/ManagerService.cs +++ b/StorageProject.Infrastructure/Services/ManagerService.cs @@ -31,7 +31,7 @@ public async Task GetManagerBoardAsync(long userId, CancellationTok .Include(r => r.Customer) .Include(r => r.UnitType) .Include(r => r.UnitAssignments).ThenInclude(ua => ua.Unit) - .Where(r => r.FacilityId == fac.FacilityId && (r.Status == "CONFIRMED" || r.Status == "UNIT_ASSIGNED")) + .Where(r => r.FacilityId == fac.FacilityId && (r.Status == "CONFIRMED" || r.Status == "UNIT_ASSIGNED" || (r.Status == "PENDING_AT_FACILITY" && r.ExpiresAt > DateTime.UtcNow))) .OrderByDescending(r => r.CreatedAt) .ToListAsync(ct); @@ -117,11 +117,12 @@ public async Task GetManagerBoardAsync(long userId, CancellationTok var payments = await dbContext.Payments .AsNoTracking() .Include(p => p.Contract).ThenInclude(c => c.Unit).ThenInclude(u => u.UnitType) - .Where(p => p.Contract.Unit.FacilityId == fac.FacilityId && p.Status == "PAID") + .Include(p => p.Reservation).ThenInclude(r => r.UnitType) + .Where(p => (p.ContractId != null ? p.Contract.Unit.FacilityId : p.Reservation.FacilityId) == fac.FacilityId && p.Status == "PAID" && p.PaymentType == "RENT") .ToListAsync(ct); - var normalTotal = payments.Where(p => !p.Contract.Unit.UnitType.ClimateControlled).Sum(p => p.Amount) / 1_000_000m; - var climateTotal = payments.Where(p => p.Contract.Unit.UnitType.ClimateControlled).Sum(p => p.Amount) / 1_000_000m; + var normalTotal = payments.Where(p => !(p.ContractId != null ? p.Contract.Unit.UnitType.ClimateControlled : p.Reservation.UnitType.ClimateControlled)).Sum(p => p.Amount) / 1_000_000m; + var climateTotal = payments.Where(p => (p.ContractId != null ? p.Contract.Unit.UnitType.ClimateControlled : p.Reservation.UnitType.ClimateControlled)).Sum(p => p.Amount) / 1_000_000m; var revenueMonths = payments .Where(p => p.PaidAt.HasValue) @@ -165,36 +166,9 @@ public async Task GetManagerBoardAsync(long userId, CancellationTok public async Task AllocateUnitAsync(long userId, string id, AllocateUnitRequest request, CancellationToken ct = default) { var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct); - if (r == null) throw new InvalidOperationException("Không tìm thấy đơn phân bổ."); - - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == fac.FacilityId && u.UnitNumber == request.UnitCode, ct); - if (unit == null || unit.Status != "AVAILABLE") - { - throw new InvalidOperationException("Kho không hợp lệ hoặc không trống."); - } - - unit.Status = "RESERVED"; - unit.UpdatedAt = DateTime.UtcNow; - - var existingAssignments = await dbContext.UnitAssignments - .Where(ua => ua.ReservationId == r.ReservationId) - .ToListAsync(ct); - foreach (var a in existingAssignments) a.Status = "INACTIVE"; - - dbContext.UnitAssignments.Add(new UnitAssignment - { - ReservationId = r.ReservationId, - UnitId = unit.UnitId, - AssignedBy = userId, - Status = "ACTIVE", - AssignedAt = DateTime.UtcNow, - Reason = "Quản lý cơ sở phân bổ kho" - }); - - r.Status = "CONFIRMED"; - await dbContext.SaveChangesAsync(ct); + var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn phân bổ."); + await ReservationAllocation.AllocateAsync(dbContext, userId, fac.FacilityId, r.ReservationId, request.UnitCode, ct); } public async Task AssignStaffAsync(long userId, string id, AssignStaffRequest request, CancellationToken ct = default) @@ -362,18 +336,8 @@ public async Task UpdateUnitAsync(long userId, string id, UpdateStor if (!string.IsNullOrWhiteSpace(request.UnitNumber)) unit.UnitNumber = request.UnitNumber; if (!string.IsNullOrWhiteSpace(request.Floor)) unit.Floor = request.Floor; - if (!string.IsNullOrWhiteSpace(request.Status)) - { - unit.Status = request.Status.ToUpperInvariant() switch - { - "EMPTY" => "AVAILABLE", - "ACTIVE" => "OCCUPIED", - "WAITING_HANDOVER" => "RESERVED", - "MAINTENANCE" => "MAINTENANCE", - "LOCKED" => "LOCKED", - _ => request.Status.ToUpperInvariant() - }; - } + if (!string.IsNullOrWhiteSpace(request.Status) && UnitStatusRules.Normalize(request.Status) != unit.Status) + throw new InvalidOperationException("Đổi trạng thái bằng thao tác trạng thái riêng và nhập lý do."); unit.UpdatedAt = DateTime.UtcNow; await dbContext.SaveChangesAsync(ct); @@ -397,15 +361,6 @@ public async Task UpdateUnitAsync(long userId, string id, UpdateStor public async Task LockUnitAsync(long userId, string id, LockUnitRequest request, CancellationToken ct = default) { - var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == fac.FacilityId && u.UnitNumber == id, ct); - if (unit == null) - { - throw new InvalidOperationException($"Không tìm thấy ô kho {id}."); - } - unit.Status = "LOCKED"; - unit.UpdatedAt = DateTime.UtcNow; - await dbContext.SaveChangesAsync(ct); + await staffService.UpdateUnitStatusAsync(userId, id, new UpdateUnitStatusRequest { Status = "OUT_OF_SERVICE", Reason = request.Reason }, ct); } } diff --git a/StorageProject.Infrastructure/Services/OperationsReportService.cs b/StorageProject.Infrastructure/Services/OperationsReportService.cs index 592f1a6..01931aa 100644 --- a/StorageProject.Infrastructure/Services/OperationsReportService.cs +++ b/StorageProject.Infrastructure/Services/OperationsReportService.cs @@ -49,14 +49,14 @@ private async Task LoadAsync(long? facilityId, long? unitTypeId, Cancell if (facilityId.HasValue) { - payments = payments.Where(p => p.Contract.Unit.FacilityId == facilityId); + payments = payments.Where(p => (p.ContractId != null ? p.Contract.Unit.FacilityId : p.Reservation.FacilityId) == facilityId); units = units.Where(u => u.FacilityId == facilityId); contracts = contracts.Where(c => c.Unit.FacilityId == facilityId); overdues = overdues.Where(o => o.Contract.Unit.FacilityId == facilityId); } if (unitTypeId.HasValue) { - payments = payments.Where(p => p.Contract.Unit.UnitTypeId == unitTypeId); + payments = payments.Where(p => (p.ContractId != null ? p.Contract.Unit.UnitTypeId : p.Reservation.UnitTypeId) == unitTypeId); units = units.Where(u => u.UnitTypeId == unitTypeId); contracts = contracts.Where(c => c.Unit.UnitTypeId == unitTypeId); overdues = overdues.Where(o => o.Contract.Unit.UnitTypeId == unitTypeId); @@ -64,7 +64,9 @@ private async Task LoadAsync(long? facilityId, long? unitTypeId, Cancell return new Source( await payments.Select(p => new PayRow(p.PaymentType, p.Amount, p.Status, p.PaidAt, - p.Contract.Unit.FacilityId, p.Contract.Unit.UnitTypeId, p.Contract.Status)).ToListAsync(ct), + p.ContractId != null ? p.Contract.Unit.FacilityId : p.Reservation.FacilityId, + p.ContractId != null ? p.Contract.Unit.UnitTypeId : p.Reservation.UnitTypeId, + p.ContractId != null ? p.Contract.Status : p.Reservation.Status)).ToListAsync(ct), await units.Select(u => new UnitRow(u.FacilityId, u.UnitTypeId, u.Status)).ToListAsync(ct), await contracts.Select(c => new ContractRow(c.ContractId, c.Unit.FacilityId, c.Unit.UnitTypeId, c.Status)).ToListAsync(ct), await overdues.Select(o => new OverdueRow(o.ContractId, o.Contract.Unit.FacilityId, o.Contract.Unit.UnitTypeId)).ToListAsync(ct)); diff --git a/StorageProject.Infrastructure/Services/PayOSGateway.cs b/StorageProject.Infrastructure/Services/PayOSGateway.cs new file mode 100644 index 0000000..4ac4f76 --- /dev/null +++ b/StorageProject.Infrastructure/Services/PayOSGateway.cs @@ -0,0 +1,63 @@ +using System.Text.Json; +using Microsoft.Extensions.Configuration; +using PayOS; +using PayOS.Models.V2.PaymentRequests; +using PayOS.Models.Webhooks; + +namespace StorageProject.Infrastructure.Services; + +public record VerifiedReservationPayment(long OrderCode, decimal Amount); +public record CheckoutLink(string Url, string Qr); +public interface IPayOSGateway +{ + void EnsureConfigured(); + Task CreateAsync(long orderCode, int amount, long reservationId, long expiresAt, string returnUrl, string cancelUrl); + Task CancelAsync(long orderCode); + Task VerifyAsync(string body); +} + +public sealed class SdkPayOSGateway(IConfiguration config) : IPayOSGateway +{ + private PayOSClient Client() + { + var clientId = config["PayOS:ClientId"]; + var apiKey = config["PayOS:ApiKey"]; + var checksum = config["PayOS:ChecksumKey"]; + if (new[] { clientId, apiKey, checksum }.Any(x => string.IsNullOrWhiteSpace(x) || x.StartsWith("YOUR_"))) + throw new InvalidOperationException("PayOS chưa được cấu hình. Vui lòng chọn thanh toán tại cửa hàng."); + return new PayOSClient(new PayOSOptions { ClientId = clientId!, ApiKey = apiKey!, ChecksumKey = checksum! }); + } + + public void EnsureConfigured() => _ = Client(); + + public async Task CreateAsync(long orderCode, int amount, long reservationId, long expiresAt, string returnUrl, string cancelUrl) + { + var result = await Client().PaymentRequests.CreateAsync(new CreatePaymentLinkRequest { + OrderCode = orderCode, Amount = amount, Description = $"Dat kho #{reservationId}", + ReturnUrl = returnUrl, CancelUrl = cancelUrl, ExpiredAt = (int)expiresAt + }); + return new CheckoutLink(result.CheckoutUrl, result.QrCode); + } + + public async Task CancelAsync(long orderCode) + { + var client = Client(); + PayOS.Models.V2.PaymentRequests.PaymentLink existing; + try { existing = await client.PaymentRequests.GetAsync(orderCode); } + catch (PayOS.Exceptions.NotFoundException) { return; } // PayOS confirms that no payable link exists. + if (existing.AmountPaid > 0 || existing.Status.ToString().ToUpperInvariant() == "PAID") + throw new InvalidOperationException("PayOS đã nhận tiền. Hãy chờ cập nhật thanh toán, không chuyển sang trả tại kho."); + if (existing.Status.ToString().ToUpperInvariant() == "CANCELLED") return; + var cancelled = await client.PaymentRequests.CancelAsync(orderCode, "Khach chon thanh toan tai cua hang"); + if (cancelled.Status.ToString().ToUpperInvariant() != "CANCELLED") + throw new InvalidOperationException("Chưa huỷ được link PayOS. Vui lòng thử lại trước khi đổi phương thức."); + } + + public async Task VerifyAsync(string body) + { + var webhook = JsonSerializer.Deserialize(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) + ?? throw new InvalidOperationException("Thông báo PayOS không hợp lệ."); + var data = await Client().Webhooks.VerifyAsync(webhook); + return webhook.Code == "00" && data.Code == "00" ? new VerifiedReservationPayment(data.OrderCode, data.Amount) : null; + } +} diff --git a/StorageProject.Infrastructure/Services/PayOSService.cs b/StorageProject.Infrastructure/Services/PayOSService.cs index c54037f..47f79fc 100644 --- a/StorageProject.Infrastructure/Services/PayOSService.cs +++ b/StorageProject.Infrastructure/Services/PayOSService.cs @@ -1,384 +1,129 @@ using System.Text.Json; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using PayOS; -using PayOS.Models.V2.PaymentRequests; -using PayOS.Models.Webhooks; using StorageProject.Core.DTOs.Payment; +using StorageProject.Core.DTOs.Reservation; using StorageProject.Core.Entities; using StorageProject.Core.Interfaces; using StorageProject.Infrastructure.Data; namespace StorageProject.Infrastructure.Services; -public class PayOSService : IPayOSService +public class PayOSService(AppDbContext dbContext, IPayOSGateway gateway, ILogger logger) : IPayOSService { - private readonly AppDbContext _dbContext; - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - private readonly PayOSClient? _payOSClient; - private readonly string _clientId; - private readonly string _apiKey; - private readonly string _checksumKey; - - public PayOSService(AppDbContext dbContext, IConfiguration configuration, ILogger logger) + public async Task CreatePaymentQrAsync(long customerId, CreatePayOSQrRequest request, CancellationToken ct = default) { - _dbContext = dbContext; - _configuration = configuration; - _logger = logger; - - _clientId = _configuration["PayOS:ClientId"] ?? ""; - _apiKey = _configuration["PayOS:ApiKey"] ?? ""; - _checksumKey = _configuration["PayOS:ChecksumKey"] ?? ""; - - if (!string.IsNullOrWhiteSpace(_clientId) && - !string.IsNullOrWhiteSpace(_apiKey) && - !string.IsNullOrWhiteSpace(_checksumKey) && - !_clientId.StartsWith("YOUR_") && - !_apiKey.StartsWith("YOUR_")) - { - try - { - var options = new PayOSOptions - { - ClientId = _clientId, - ApiKey = _apiKey, - ChecksumKey = _checksumKey - }; - _payOSClient = new PayOSClient(options); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Could not initialize PayOSClient with configured credentials."); - } - } + var id = request.ReservationId; + if (!id.HasValue && request.FacilityId.HasValue && request.UnitTypeId.HasValue) + { + var created = await new ReservationService(dbContext).CreateReservationAsync(customerId, + new CreateReservationRequest(request.FacilityId.Value, request.UnitTypeId.Value, + request.StartDate ?? DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)), request.RentalPeriodMonths ?? 1), ct); + id = created.ReservationId; + } + if (id is null or <= 0) throw new ArgumentException("Cần mã đơn đặt chỗ hợp lệ."); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{id}", ct); + var r = await dbContext.Reservations.SingleOrDefaultAsync(r => r.ReservationId == id && r.CustomerId == customerId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn đặt chỗ của bạn."); + if (r.Status != "PENDING_PAYMENT" || r.PaymentMethod != "PAYOS" || r.PaidAt != null) + throw new InvalidOperationException("Đơn không còn ở trạng thái chờ PayOS."); + if (r.ExpiresAt <= DateTime.UtcNow) throw new InvalidOperationException("Đơn đã hết thời gian giữ chỗ."); + var amount = ReservationSettlement.Amount(r); + if (amount <= 0 || amount != decimal.Truncate(amount) || amount > int.MaxValue) + throw new InvalidOperationException("Số tiền thanh toán VND không hợp lệ."); + if (request.Amount.HasValue && request.Amount != amount) + throw new ArgumentException("Số tiền phải khớp tiền thuê và tiền cọc do máy chủ tính."); + var expiry = r.ExpiresAt ?? DateTime.UtcNow.AddMinutes(15); + if (r.OrderCode != null && !string.IsNullOrEmpty(r.CheckoutUrl) && !string.IsNullOrEmpty(r.PaymentQrUrl)) + return new CreatePayOSQrResponse(r.ReservationId, r.OrderCode.Value, r.CheckoutUrl, r.PaymentQrUrl, amount, expiry); + + gateway.EnsureConfigured(); + // Commit the identifier before calling the external system. A timeout must not create another order code. + if (r.OrderCode == null) { + r.OrderCode = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 100 + Random.Shared.Next(100); + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + await tx.DisposeAsync(); + return await CreatePaymentQrAsync(customerId, request with { ReservationId = id }, ct); + } + CheckoutLink link; + try { + link = await gateway.CreateAsync(r.OrderCode.Value, (int)amount, r.ReservationId, + new DateTimeOffset(DateTime.SpecifyKind(expiry, DateTimeKind.Utc)).ToUnixTimeSeconds(), + request.ReturnUrl ?? $"http://localhost:5173/#/reservations/{r.ReservationId}", + request.CancelUrl ?? $"http://localhost:5173/#/reservations/{r.ReservationId}"); + } catch (Exception ex) { + throw new InvalidOperationException("Không tạo được link PayOS. Kiểm tra cấu hình hoặc chọn thanh toán tại cửa hàng.", ex); + } + r.CheckoutUrl = link.Url; + r.PaymentQrUrl = link.Qr; + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + return new CreatePayOSQrResponse(r.ReservationId, r.OrderCode.Value, link.Url, link.Qr, amount, expiry); } - public async Task CreatePaymentQrAsync(long customerId, CreatePayOSQrRequest request, CancellationToken ct = default) + public async Task PayAtFacilityAsync(long customerId, long reservationId, CancellationToken ct = default) { - Reservation? reservation = null; - - if (request.ReservationId.HasValue && request.ReservationId.Value > 0) - { - reservation = await _dbContext.Reservations - .FirstOrDefaultAsync(r => r.ReservationId == request.ReservationId.Value && r.CustomerId == customerId, ct); - - if (reservation == null) - { - throw new InvalidOperationException("Không tìm thấy đơn đặt chỗ tương ứng với tài khoản."); - } - } - else if (request.FacilityId.HasValue && request.UnitTypeId.HasValue) - { - var facility = await _dbContext.Facilities.FindAsync([request.FacilityId.Value], ct) - ?? throw new InvalidOperationException("Không tìm thấy cơ sở kho."); - - var unitType = await _dbContext.UnitTypes.FindAsync([request.UnitTypeId.Value], ct) - ?? throw new InvalidOperationException("Không tìm thấy loại phòng kho."); - - var today = DateOnly.FromDateTime(DateTime.UtcNow); - var rentalPeriod = request.RentalPeriodMonths.GetValueOrDefault(1); - if (rentalPeriod <= 0) rentalPeriod = 1; - - var activeRate = await _dbContext.RentalRates - .Where(r => r.FacilityId == request.FacilityId.Value - && r.UnitTypeId == request.UnitTypeId.Value - && r.EffectiveFrom <= today - && (r.EffectiveTo == null || r.EffectiveTo >= today)) - .OrderByDescending(r => r.EffectiveFrom) - .FirstOrDefaultAsync(ct) - ?? throw new InvalidOperationException("Chưa có bảng giá áp dụng cho loại kho này."); - - var expectedEndDate = (request.StartDate ?? today).AddMonths(rentalPeriod); - var monthlyRate = activeRate.MonthlyRate; - var estimatedAmount = monthlyRate * rentalPeriod; - var requiredDeposit = monthlyRate; - - reservation = new Reservation - { - CustomerId = customerId, - FacilityId = request.FacilityId.Value, - UnitTypeId = request.UnitTypeId.Value, - StartDate = request.StartDate ?? today, - ExpectedEndDate = expectedEndDate, - RentalPeriodMonths = rentalPeriod, - QuotedMonthlyRate = monthlyRate, - EstimatedAmount = estimatedAmount, - RequiredDeposit = requiredDeposit, - Status = "PENDING_PAYMENT", - ExpiresAt = DateTime.UtcNow.AddHours(24), - CreatedAt = DateTime.UtcNow - }; - - _dbContext.Reservations.Add(reservation); - await _dbContext.SaveChangesAsync(ct); - } - else - { - throw new ArgumentException("Yêu cầu cần có ReservationId hoặc thông tin FacilityId + UnitTypeId."); - } - - if (reservation.Status != "PENDING_PAYMENT" && reservation.Status != "CONFIRMED") - { - throw new InvalidOperationException($"Không thể tạo mã thanh toán cho đơn đặt chỗ có trạng thái '{reservation.Status}'."); - } - - long orderCode = reservation.OrderCode ?? long.Parse(DateTime.UtcNow.ToString("yyMMddHHmmss") + Random.Shared.Next(10, 99)); - int amount = (int)(reservation.EstimatedAmount + (reservation.RequiredDeposit > 0 ? reservation.RequiredDeposit : 0)); - if (request.Amount.HasValue && request.Amount.Value > 0) - { - amount = (int)request.Amount.Value; - } - - string checkoutUrl = reservation.CheckoutUrl ?? ""; - string qrCode = reservation.PaymentQrUrl ?? ""; - bool hasValidPayOS = !string.IsNullOrEmpty(checkoutUrl) && checkoutUrl.StartsWith("https://pay.payos.vn", StringComparison.OrdinalIgnoreCase); - - // Reuse existing valid PayOS link immediately without regenerating - if (hasValidPayOS && !string.IsNullOrEmpty(qrCode)) - { - return new CreatePayOSQrResponse( - reservation.ReservationId, - orderCode, - checkoutUrl, - qrCode, - amount, - reservation.ExpiresAt ?? DateTime.UtcNow.AddMinutes(15) - ); - } - - if (!hasValidPayOS || string.IsNullOrEmpty(qrCode)) - { - if (_payOSClient != null) - { - try - { - // Reuse existing orderCode if already assigned to reservation to prevent link desync - if (!reservation.OrderCode.HasValue || reservation.OrderCode.Value <= 0) - { - orderCode = long.Parse(DateTime.UtcNow.ToString("yyMMddHHmmss") + Random.Shared.Next(10, 99)); - } - else - { - orderCode = reservation.OrderCode.Value; - } - - var items = new List - { - new PaymentLinkItem - { - Name = $"Dat kho #{reservation.ReservationId}", - Quantity = 1, - Price = amount - } - }; - - var paymentLinkRequest = new CreatePaymentLinkRequest - { - OrderCode = orderCode, - Amount = amount, - Description = $"Dat kho #{reservation.ReservationId}", - Items = items, - CancelUrl = request.CancelUrl ?? "http://localhost:5173/checkout/cancel", - ReturnUrl = request.ReturnUrl ?? $"http://localhost:5173/confirmation/{reservation.ReservationId}", - ExpiredAt = (int)DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds() - }; - - var createResult = await _payOSClient.PaymentRequests.CreateAsync(paymentLinkRequest); - checkoutUrl = createResult.CheckoutUrl ?? ""; - qrCode = createResult.QrCode ?? ""; - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to call PayOS SDK createPaymentLink for OrderCode {OrderCode}. Falling back to default QR format.", orderCode); - } - } - - if (string.IsNullOrEmpty(qrCode)) - { - qrCode = $"https://img.vietqr.io/image/MB-0335012345-compact2.png?amount={amount}&addInfo=SSFRMS%20{orderCode}&accountName=SAFE%20SPACE"; - } - if (string.IsNullOrEmpty(checkoutUrl)) - { - checkoutUrl = request.ReturnUrl ?? $"http://localhost:5173/confirmation/{reservation.ReservationId}"; - } - - reservation.OrderCode = orderCode; - reservation.CheckoutUrl = checkoutUrl; - reservation.PaymentQrUrl = qrCode; - await _dbContext.SaveChangesAsync(ct); - } - - return new CreatePayOSQrResponse( - reservation.ReservationId, - orderCode, - checkoutUrl, - qrCode, - amount, - DateTime.UtcNow.AddMinutes(15) - ); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{reservationId}", ct); + var r = await dbContext.Reservations.SingleOrDefaultAsync(r => r.ReservationId == reservationId && r.CustomerId == customerId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn đặt chỗ của bạn."); + if (r.Status == "PENDING_AT_FACILITY" && r.PaymentMethod == "AT_FACILITY") return; + if (r.PaidAt != null || r.Status != "PENDING_PAYMENT") + throw new InvalidOperationException("Đơn đã được xử lý, không thể đổi sang thanh toán tại kho."); + if (r.ExpiresAt <= DateTime.UtcNow) throw new InvalidOperationException("Đơn đã hết thời gian giữ chỗ."); + // Do not announce a switch until PayOS confirms cancellation. Keep OrderCode for delayed webhooks. + if (r.OrderCode.HasValue) + { + try { await gateway.CancelAsync(r.OrderCode.Value); } + catch (Exception ex) { throw new InvalidOperationException("Chưa xác nhận huỷ link PayOS. Đơn vẫn chờ PayOS; vui lòng thử lại.", ex); } + } + r.PaymentMethod = "AT_FACILITY"; + r.Status = "PENDING_AT_FACILITY"; + // Hold until the end of the scheduled check-in day (Vietnam time), never indefinitely. + var checkInDay = r.CheckInAppointmentAt.HasValue + ? DateOnly.FromDateTime(r.CheckInAppointmentAt.Value.AddHours(7)) : r.StartDate; + r.ExpiresAt = checkInDay.AddDays(1).ToDateTime(TimeOnly.MinValue).AddHours(-7); + ReservationSettlement.Audit(dbContext, customerId, "PAY_AT_FACILITY_SELECTED", r.ReservationId, new { r.OrderCode, r.ExpiresAt }); + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); } public async Task ProcessWebhookAsync(string webhookBodyJson, string? signatureHeader, CancellationToken ct = default) { - if (_payOSClient == null) - { - _logger.LogError("PayOSClient is not initialized. Cannot securely verify webhook signature."); - return false; - } - - Webhook? webhookModel; - try - { - webhookModel = JsonSerializer.Deserialize(webhookBodyJson); - } - catch (JsonException ex) - { - _logger.LogWarning(ex, "Failed to parse PayOS webhook payload as JSON."); - return false; - } - - if (webhookModel == null) - { - _logger.LogWarning("PayOS webhook payload deserialized to null."); - return false; - } - - WebhookData verifiedData; - try - { - verifiedData = await _payOSClient.Webhooks.VerifyAsync(webhookModel); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "PayOS webhook signature verification failed."); - return false; - } - - if (verifiedData == null) - { - _logger.LogWarning("PayOS webhook verification returned null data."); - return false; - } - - // Webhook signature verified. Check transaction code. - if (webhookModel.Code != "00") - { - _logger.LogInformation("PayOS webhook verified, but payment code is '{Code}' (Description: {Description}). Skipping database updates.", - webhookModel.Code, webhookModel.Description); - return true; - } - - long orderCode = verifiedData.OrderCode; - if (orderCode <= 0) - { - _logger.LogWarning("Verified PayOS webhook contains invalid OrderCode: {OrderCode}.", orderCode); - return false; - } - - var reservation = await _dbContext.Reservations - .Include(r => r.UnitAssignments) - .FirstOrDefaultAsync(r => r.OrderCode == orderCode, ct); - - // Fallback: If not found by OrderCode, attempt to extract reservationId from description - // (e.g. PayOS description: "Dat kho #25" or "Dat kho 25") - if (reservation == null) - { - long extractedId = 0; - var desc = verifiedData.Description ?? ""; - var match = System.Text.RegularExpressions.Regex.Match(desc, @"(?:Dat kho #?|kho\s*#?|#)(\d+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); - if (match.Success && long.TryParse(match.Groups[1].Value, out var parsedId)) - { - extractedId = parsedId; - } - - if (extractedId > 0) - { - reservation = await _dbContext.Reservations - .Include(r => r.UnitAssignments) - .FirstOrDefaultAsync(r => r.ReservationId == extractedId, ct); - - if (reservation != null) - { - _logger.LogInformation("Matched Reservation {ReservationId} via description '{Description}' for OrderCode {OrderCode}.", - reservation.ReservationId, desc, orderCode); - // Sync OrderCode to the one actually paid on PayOS - reservation.OrderCode = orderCode; - } - } - } - - if (reservation == null) - { - _logger.LogWarning("Verified PayOS webhook received for OrderCode {OrderCode} (Desc: '{Desc}'), but no matching reservation found. Acknowledging webhook.", - orderCode, verifiedData.Description); + VerifiedReservationPayment? verified; + try { verified = await gateway.VerifyAsync(webhookBodyJson); } + catch (Exception ex) { logger.LogWarning(ex, "PayOS signature verification failed"); return false; } + if (verified == null) return true; + var id = await dbContext.Reservations.AsNoTracking().Where(r => r.OrderCode == verified.OrderCode) + .Select(r => (long?)r.ReservationId).SingleOrDefaultAsync(ct); + // Never recover an order by parsing unstructured description text. + if (id == null) { logger.LogWarning("Unknown PayOS order {OrderCode}", verified.OrderCode); return false; } + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{id}", ct); + var r = await dbContext.Reservations.Include(r => r.UnitAssignments).SingleAsync(r => r.ReservationId == id, ct); + if (verified.Amount != ReservationSettlement.Amount(r)) return false; + if (r.PaymentMethod == "PAYOS" && r.PaidAt != null) + { + await tx.CommitAsync(ct); // Re-delivery of the same verified order: no additional money or allocation. return true; } - - // Idempotency: skip if already confirmed or in subsequent status - if (reservation.Status != "PENDING_PAYMENT") + if (r.PaymentMethod == "AT_FACILITY" || r.Status != "PENDING_PAYMENT" || r.ExpiresAt <= DateTime.UtcNow) { - _logger.LogInformation("Reservation {ReservationId} (OrderCode {OrderCode}) is already in status '{Status}'. Skipping duplicate webhook processing.", - reservation.ReservationId, orderCode, reservation.Status); - return true; + var detail = JsonSerializer.Serialize(new { verified.OrderCode, verified.Amount, reason = "Tiền về sau đổi phương thức/đóng đơn; cần kiểm tra hoàn thủ công" }); + if (!await dbContext.ActivityLogs.AnyAsync(l => l.EntityType == "RESERVATION" && l.EntityId == id && + l.Action == "PAYMENT_REVIEW_REQUIRED" && l.NewValue == detail, ct)) + dbContext.ActivityLogs.Add(new ActivityLog { EntityType = "RESERVATION", EntityId = id, + Action = "PAYMENT_REVIEW_REQUIRED", NewValue = detail, LoggedAt = DateTime.UtcNow }); } - - reservation.Status = "CONFIRMED"; - reservation.PaidAt = DateTime.UtcNow; - - // Idempotent assignment: Only assign if no ACTIVE assignment exists - bool hasActiveAssignment = reservation.UnitAssignments.Any(ua => ua.Status == "ACTIVE"); - if (!hasActiveAssignment) - { - var assignedUnit = await _dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == reservation.FacilityId && - u.UnitTypeId == reservation.UnitTypeId && - u.Status == "AVAILABLE", ct); - - if (assignedUnit != null) - { - assignedUnit.Status = "RESERVED"; - assignedUnit.UpdatedAt = DateTime.UtcNow; - - _dbContext.UnitAssignments.Add(new UnitAssignment - { - ReservationId = reservation.ReservationId, - UnitId = assignedUnit.UnitId, - AssignedBy = null, // System automated assignment - Status = "ACTIVE", - AssignedAt = DateTime.UtcNow, - Reason = "Tự động gán kho sau khi thanh toán VietQR thành công" - }); - } - else - { - _logger.LogWarning("No AVAILABLE storage unit found for FacilityId {FacilityId}, UnitTypeId {UnitTypeId} for Reservation {ReservationId}.", - reservation.FacilityId, reservation.UnitTypeId, reservation.ReservationId); - } - } - - await _dbContext.SaveChangesAsync(ct); - _logger.LogInformation("Successfully confirmed reservation {ReservationId} (OrderCode {OrderCode}) via verified PayOS Webhook.", - reservation.ReservationId, orderCode); - + else await ReservationSettlement.RecordAsync(dbContext, r, "PAYMENT_GATEWAY", $"PAYOS:{verified.OrderCode}", null, ct); + // Manager allocates the physical unit. The webhook only settles the reservation. + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); return true; } public async Task GetReservationPaymentStatusAsync(long reservationId, CancellationToken ct = default) { - var reservation = await _dbContext.Reservations - .AsNoTracking() - .FirstOrDefaultAsync(r => r.ReservationId == reservationId, ct); - - if (reservation == null) return null; - - bool isPaid = reservation.Status is "CONFIRMED" or "UNIT_ASSIGNED" or "CHECKED_IN"; - return new ReservationPaymentStatusDto( - reservation.ReservationId, - reservation.Status, - isPaid, - reservation.PaidAt - ); + var r = await dbContext.Reservations.AsNoTracking().SingleOrDefaultAsync(r => r.ReservationId == reservationId, ct); + return r == null ? null : new ReservationPaymentStatusDto(r.ReservationId, r.Status, r.PaidAt != null, r.PaidAt); } } diff --git a/StorageProject.Infrastructure/Services/PaymentService.cs b/StorageProject.Infrastructure/Services/PaymentService.cs index 53f8cc1..46a411d 100644 --- a/StorageProject.Infrastructure/Services/PaymentService.cs +++ b/StorageProject.Infrastructure/Services/PaymentService.cs @@ -44,7 +44,7 @@ public async Task> GetContractPaymentsAsync(long custo var p = await dbContext.Payments .AsNoTracking() .Include(x => x.Contract) - .Where(x => x.PaymentId == paymentId && x.Contract.CustomerId == customerId) + .Where(x => x.PaymentId == paymentId && ((x.ContractId != null && x.Contract.CustomerId == customerId) || (x.ReservationId != null && x.Reservation.CustomerId == customerId))) .FirstOrDefaultAsync(ct); if (p == null) return null; diff --git a/StorageProject.Infrastructure/Services/ReservationAllocation.cs b/StorageProject.Infrastructure/Services/ReservationAllocation.cs new file mode 100644 index 0000000..3f08484 --- /dev/null +++ b/StorageProject.Infrastructure/Services/ReservationAllocation.cs @@ -0,0 +1,58 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +public static class ReservationAllocation +{ + public static async Task AllocateAsync(AppDbContext db, long actor, long facilityId, long reservationId, + string unitCode, CancellationToken ct) + { + await using var tx = await CheckoutTransaction.BeginAsync(db, $"reservation:{reservationId}", ct); + await CheckoutTransaction.LockAsync(db, $"inventory:{facilityId}", ct); + var r = await db.Reservations.Include(r => r.UnitAssignments).Include(r => r.RentalContract) + .SingleOrDefaultAsync(r => r.ReservationId == reservationId && r.FacilityId == facilityId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn tại cơ sở của bạn."); + var atFacility = r.Status == "PENDING_AT_FACILITY" && r.PaymentMethod == "AT_FACILITY"; + if (!atFacility && (r.Status is not ("CONFIRMED" or "UNIT_ASSIGNED"))) + throw new InvalidOperationException("Chỉ phân bổ đơn đã thanh toán hoặc đơn chờ thu tại kho."); + if (atFacility && r.ExpiresAt <= DateTime.UtcNow) throw new InvalidOperationException("Đơn chờ thu đã hết hạn giữ chỗ."); + if (!atFacility) await ReservationSettlement.RequirePaidAsync(db, r, ct); + var unit = await db.StorageUnits.SingleOrDefaultAsync(u => u.FacilityId == facilityId && u.UnitNumber == unitCode, ct) + ?? throw new InvalidOperationException("Không tìm thấy ô kho tại cơ sở."); + if (unit.UnitTypeId != r.UnitTypeId) throw new InvalidOperationException("Ô kho không đúng loại khách đã đặt."); + var current = r.UnitAssignments.SingleOrDefault(a => a.Status == "ACTIVE"); + if (current != null) + { + if (current.UnitId != unit.UnitId) throw new InvalidOperationException("Đơn đã phân bổ ô khác, không được phân bổ thêm."); + await tx.CommitAsync(ct); + return; + } + if (unit.Status != "AVAILABLE" || await db.RentalContracts.AnyAsync(c => c.UnitId == unit.UnitId && + c.Status != "CANCELLED" && c.Status != "COMPLETED" && c.Status != "TERMINATED" && + c.StartDate < r.ExpectedEndDate && c.EndDate > r.StartDate, ct)) + throw new InvalidOperationException("Ô kho không còn trống trong kỳ thuê."); + var contract = r.RentalContract; + if (contract != null) throw new InvalidOperationException("Đơn đã có hợp đồng, cần kiểm tra phân bổ cũ."); + var now = DateTime.UtcNow; + contract = new RentalContract { ReservationId = r.ReservationId, CustomerId = r.CustomerId, + UnitId = unit.UnitId, StartDate = r.StartDate, EndDate = r.ExpectedEndDate, + AgreedMonthlyRate = r.QuotedMonthlyRate, DepositAmount = r.RequiredDeposit, Status = "DRAFT", CreatedAt = now, + HandoverRecord = new HandoverRecord { StaffId = actor, ScheduledAt = r.CheckInAppointmentAt ?? + r.StartDate.ToDateTime(new TimeOnly(9, 0)).AddHours(-7), Status = "SCHEDULED", CreatedAt = now } }; + db.RentalContracts.Add(contract); + foreach (var payment in await db.Payments.Where(p => p.ReservationId == r.ReservationId).ToListAsync(ct)) + payment.Contract = contract; + db.UnitAssignments.Add(new UnitAssignment { ReservationId = r.ReservationId, UnitId = unit.UnitId, + AssignedBy = actor, AssignedAt = now, Status = "ACTIVE", Reason = "Quản lý phân bổ ô" }); + db.UnitStatusHistories.Add(new UnitStatusHistory { UnitId = unit.UnitId, ChangedBy = actor, + OldStatus = unit.Status, NewStatus = "RESERVED", ChangedAt = now, Reason = $"Phân bổ đơn {r.ReservationId}" }); + unit.Status = "RESERVED"; + unit.UpdatedAt = now; + if (!atFacility) r.Status = "UNIT_ASSIGNED"; + ReservationSettlement.Audit(db, actor, "UNIT_ALLOCATED", r.ReservationId, new { unit.UnitNumber }); + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + } +} diff --git a/StorageProject.Infrastructure/Services/ReservationService.cs b/StorageProject.Infrastructure/Services/ReservationService.cs index f40105f..7a8ecc3 100644 --- a/StorageProject.Infrastructure/Services/ReservationService.cs +++ b/StorageProject.Infrastructure/Services/ReservationService.cs @@ -34,7 +34,8 @@ public async Task> GetMyReservationsAsync(long cus r.ExpiresAt, r.CancelledAt, r.CancellationReason, - r.CreatedAt + r.CreatedAt, + r.PaymentMethod )) .ToListAsync(ct); } @@ -74,7 +75,8 @@ public async Task> GetMyReservationsAsync(long cus assignedUnit, contract?.ContractId, contract?.Status, - r.CreatedAt + r.CreatedAt, + r.PaymentMethod ); } @@ -113,6 +115,7 @@ public async Task CreateReservationAsync(long customerId, Create .FirstOrDefaultAsync(ct) ?? throw new InvalidOperationException("Chưa có bảng giá áp dụng cho cơ sở và loại kho này."); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"inventory:{request.FacilityId}", ct); // Check availability var expectedEndDate = request.StartDate.AddMonths(request.RentalPeriodMonths); var availableUnitsCount = await dbContext.StorageUnits @@ -123,7 +126,8 @@ public async Task CreateReservationAsync(long customerId, Create var existingReservationsCount = await dbContext.Reservations .CountAsync(r => r.FacilityId == request.FacilityId && r.UnitTypeId == request.UnitTypeId - && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED") + && (r.Status == "CONFIRMED" || ((r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "PENDING_AT_FACILITY") && r.ExpiresAt > DateTime.UtcNow)) + && !r.UnitAssignments.Any(a => a.Status == "ACTIVE") && r.StartDate < expectedEndDate && r.ExpectedEndDate > request.StartDate, ct); @@ -152,12 +156,13 @@ public async Task CreateReservationAsync(long customerId, Create EstimatedAmount = estimatedAmount, RequiredDeposit = requiredDeposit, Status = "PENDING_PAYMENT", - ExpiresAt = DateTime.UtcNow.AddHours(24), + ExpiresAt = DateTime.UtcNow.AddMinutes(15), CreatedAt = DateTime.UtcNow }; dbContext.Reservations.Add(reservation); await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); return new ReservationDto( reservation.ReservationId, @@ -175,18 +180,20 @@ public async Task CreateReservationAsync(long customerId, Create reservation.ExpiresAt, reservation.CancelledAt, reservation.CancellationReason, - reservation.CreatedAt + reservation.CreatedAt, + reservation.PaymentMethod ); } public async Task CancelReservationAsync(long customerId, long reservationId, string reason, CancellationToken ct = default) { + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{reservationId}", ct); var reservation = await dbContext.Reservations .Where(r => r.ReservationId == reservationId && r.CustomerId == customerId) .FirstOrDefaultAsync(ct) ?? throw new InvalidOperationException("Không tìm thấy đơn đặt chỗ hợp lệ."); - if (reservation.Status != "PENDING_PAYMENT" && reservation.Status != "CONFIRMED") + if (reservation.Status != "PENDING_PAYMENT" && reservation.Status != "CONFIRMED" && reservation.Status != "PENDING_AT_FACILITY") { throw new InvalidOperationException($"Không thể hủy đơn đặt chỗ ở trạng thái '{reservation.Status}'."); } @@ -194,8 +201,15 @@ public async Task CancelReservationAsync(long customerId, long reservationId, st reservation.Status = "CANCELLED"; reservation.CancelledAt = DateTime.UtcNow; reservation.CancellationReason = reason; - + foreach (var a in await dbContext.UnitAssignments.Include(a => a.Unit).Where(a => a.ReservationId == reservationId && a.Status == "ACTIVE").ToListAsync(ct)) + { + a.Status = "CANCELLED"; + if (a.Unit.Status == "RESERVED") a.Unit.Status = "AVAILABLE"; + } + var draft = await dbContext.RentalContracts.SingleOrDefaultAsync(c => c.ReservationId == reservationId && c.Status == "DRAFT", ct); + if (draft != null) draft.Status = "CANCELLED"; await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); } /// @@ -256,6 +270,7 @@ public async Task ConfirmTransferAsync(long customerId, long res r.ExpiresAt, r.CancelledAt, r.CancellationReason, - r.CreatedAt + r.CreatedAt, + r.PaymentMethod ); } diff --git a/StorageProject.Infrastructure/Services/ReservationSettlement.cs b/StorageProject.Infrastructure/Services/ReservationSettlement.cs new file mode 100644 index 0000000..950e22e --- /dev/null +++ b/StorageProject.Infrastructure/Services/ReservationSettlement.cs @@ -0,0 +1,53 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +// Call inside the reservation transaction. Allocation attaches these rows; it never recreates them. +public static class ReservationSettlement +{ + public static decimal Amount(Reservation r) => r.EstimatedAmount + r.RequiredDeposit; + + public static async Task RecordAsync(AppDbContext db, Reservation r, string method, string reference, + long? actor, CancellationToken ct) + { + var rows = await db.Payments.Where(p => p.ReservationId == r.ReservationId && + (p.PaymentType == "RENT" || p.PaymentType == "DEPOSIT")).ToListAsync(ct); + var now = r.PaidAt ?? DateTime.UtcNow; + foreach (var (kind, amount) in new[] { ("RENT", r.EstimatedAmount), ("DEPOSIT", r.RequiredDeposit) }) + { + if (amount == 0) continue; + var row = rows.SingleOrDefault(p => p.PaymentType == kind); + if (row != null) + { + if (row.Amount != amount || row.Status != "PAID" || row.PaymentMethod != method) + throw new InvalidOperationException("Khoản thu đã tồn tại nhưng không khớp. Cần kiểm tra giao dịch."); + continue; + } + db.Payments.Add(new Payment { + ReservationId = r.ReservationId, ContractId = r.RentalContract?.ContractId, + PaymentType = kind, Amount = amount, PaymentMethod = method, + TransactionReference = $"{reference}:{kind}", Status = "PAID", PaidAt = now, + DueDate = r.StartDate, CreatedAt = now, UpdatedAt = now + }); + } + r.PaidAt = now; + r.Status = r.UnitAssignments.Any(a => a.Status == "ACTIVE") ? "UNIT_ASSIGNED" : "CONFIRMED"; + Audit(db, actor, "PAYMENT_CONFIRMED", r.ReservationId, new { method, reference, amount = Amount(r) }); + } + + public static async Task RequirePaidAsync(AppDbContext db, Reservation r, CancellationToken ct) + { + var rows = await db.Payments.Where(p => p.ReservationId == r.ReservationId && p.Status == "PAID" && + (p.PaymentType == "RENT" || p.PaymentType == "DEPOSIT")).ToListAsync(ct); + var paid = rows.Sum(p => p.Amount); + if (r.PaidAt == null || paid != Amount(r)) + throw new InvalidOperationException("Đơn chưa có đủ khoản thu đã xác nhận. Không được bàn giao kho."); + } + + public static void Audit(AppDbContext db, long? actor, string action, long id, object detail) => + db.ActivityLogs.Add(new ActivityLog { UserId = actor, Action = action, EntityType = "RESERVATION", + EntityId = id, NewValue = JsonSerializer.Serialize(detail), LoggedAt = DateTime.UtcNow }); +} diff --git a/StorageProject.Infrastructure/Services/StaffService.cs b/StorageProject.Infrastructure/Services/StaffService.cs index ace63bc..7389f4c 100644 --- a/StorageProject.Infrastructure/Services/StaffService.cs +++ b/StorageProject.Infrastructure/Services/StaffService.cs @@ -104,12 +104,9 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken }).ToList(); // 3. Payments (Đối soát thanh toán từ Reservations trong DB) - var reservations = await dbContext.Reservations - .AsNoTracking() - .Include(r => r.Customer) - .Include(r => r.UnitType) - .Where(r => r.FacilityId == fac.FacilityId && - (r.Status == "PENDING_VERIFICATION" || r.Status == "PENDING_PAYMENT" || r.Status == "CONFIRMED" || r.Status == "MISMATCH")) + var reservations = await dbContext.Reservations.AsNoTracking().Include(r => r.Customer).Include(r => r.UnitType) + .Where(r => r.FacilityId == fac.FacilityId && r.PaymentMethod == "AT_FACILITY" && + r.Status == "PENDING_AT_FACILITY" && r.ExpiresAt > DateTime.UtcNow) .OrderByDescending(r => r.CreatedAt) .ToListAsync(ct); @@ -128,7 +125,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken Id = $"SS-{r.CreatedAt:yyyyMMdd}-{r.ReservationId:D4}", Customer = r.Customer.FullName, Amount = totalAmount, - Method = "Chuyển khoản ngân hàng", + Method = "Thanh toán tại kho", ReportedAt = r.CreatedAt.ToString("yyyy-MM-ddTHH:mm:ss"), Memo = r.OrderCode.HasValue ? $"SSFRMS {r.OrderCode}" : $"SSFRMS {r.ReservationId}", Offer = $"Kho {r.UnitType.TypeName} · {(r.UnitType.ClimateControlled ? "Kiểm soát nhiệt độ" : "Thường")}", @@ -144,6 +141,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken .AsNoTracking() .Include(r => r.Customer) .Include(r => r.UnitAssignments).ThenInclude(ua => ua.Unit) + .Include(r => r.RentalContract).ThenInclude(c => c!.HandoverRecord) .Where(r => r.FacilityId == fac.FacilityId && r.UnitAssignments.Any(ua => ua.Status == "ACTIVE")) .OrderByDescending(r => r.CreatedAt) .ToListAsync(ct); @@ -158,7 +156,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken Customer = r.Customer.FullName, Unit = assign.Unit.UnitNumber, Appointment = $"{r.StartDate:yyyy-MM-dd}T09:00:00", - Status = r.Status == "CHECKED_IN" ? "DONE" : "TODO", + Status = r.RentalContract?.HandoverRecord?.Status is "VERIFIED" or "HANDED_OVER" ? "DONE" : "TODO", DocType = "Căn cước công dân", DocLast4 = null, VerifiedAt = r.Status == "CHECKED_IN" ? r.CreatedAt.ToString("yyyy-MM-ddTHH:mm:ss") : null @@ -169,7 +167,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken .AsNoTracking() .Include(h => h.Contract).ThenInclude(c => c.Customer) .Include(h => h.Contract).ThenInclude(c => c.Unit) - .Where(h => h.Contract.Unit.FacilityId == fac.FacilityId) + .Where(h => h.Contract.Unit.FacilityId == fac.FacilityId && h.Status != "CANCELLED") .OrderByDescending(h => h.ScheduledAt) .ToListAsync(ct); @@ -179,7 +177,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken VerificationId = $"XM-{(h.Contract.ReservationId > 0 ? h.Contract.ReservationId : h.HandoverId):D4}", Unit = h.Contract.Unit.UnitNumber, Customer = h.Contract.Customer.FullName, - Status = h.HandoverAt.HasValue ? "COMPLETED" : "WAITING", + Status = h.HandoverAt.HasValue ? "DONE" : "WAITING", Method = "PIN" }).ToList(); @@ -281,44 +279,19 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken public async Task ConfirmPaymentAsync(long userId, string id, CancellationToken ct = default) { var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct); - if (r == null) - { - throw new InvalidOperationException("Không tìm thấy thông tin đặt chỗ / thanh toán."); - } - if (r.Status == "CONFIRMED") - { - throw new InvalidOperationException("không xác nhận hai lần"); - } - - r.Status = "CONFIRMED"; - r.PaidAt = DateTime.UtcNow; - - // Auto assign available unit if none assigned yet - if (!r.UnitAssignments.Any(ua => ua.Status == "ACTIVE")) - { - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == fac.FacilityId && - u.UnitTypeId == r.UnitTypeId && - u.Status == "AVAILABLE", ct); - if (unit != null) - { - unit.Status = "RESERVED"; - unit.UpdatedAt = DateTime.UtcNow; - - dbContext.UnitAssignments.Add(new UnitAssignment - { - ReservationId = r.ReservationId, - UnitId = unit.UnitId, - AssignedBy = userId, - Status = "ACTIVE", - AssignedAt = DateTime.UtcNow, - Reason = "Nhân viên xác nhận đối soát thanh toán" - }); - } - } - + var found = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn tại cơ sở."); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{found.ReservationId}", ct); + await dbContext.Entry(found).ReloadAsync(ct); + await dbContext.Entry(found).Collection(r => r.UnitAssignments).LoadAsync(ct); + await dbContext.Entry(found).Reference(r => r.RentalContract).LoadAsync(ct); + if (found.PaymentMethod != "AT_FACILITY") throw new InvalidOperationException("Đơn PayOS phải được xác nhận qua webhook."); + if (found.PaidAt != null) { await tx.CommitAsync(ct); return; } + if (found.Status != "PENDING_AT_FACILITY" || found.ExpiresAt <= DateTime.UtcNow) + throw new InvalidOperationException("Đơn không còn chờ thu tại kho hoặc đã hết hạn."); + await ReservationSettlement.RecordAsync(dbContext, found, "CASH", $"CASH:{found.ReservationId}", userId, ct); await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); } public async Task MismatchPaymentAsync(long userId, string id, MismatchPaymentRequest request, CancellationToken ct = default) @@ -354,13 +327,19 @@ public async Task VerifyCustomerAsync(long userId, string id, VerifyCustomerRequ var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct); if (r != null) { - r.Status = "CHECKED_IN"; + await ReservationSettlement.RequirePaidAsync(dbContext, r, ct); + var record = await dbContext.HandoverRecords.SingleOrDefaultAsync(h => h.Contract.ReservationId == r.ReservationId, ct) + ?? throw new InvalidOperationException("Đơn chưa được quản lý phân bổ và lập lịch bàn giao."); + if (record.Status == "HANDED_OVER") return; + record.Status = "VERIFIED"; + record.Notes = $"Đã xác minh giấy tờ kết thúc {docNo[^4..]}"; await dbContext.SaveChangesAsync(ct); } } public async Task CompleteHandoverAsync(long userId, string id, CompleteHandoverRequest request, CancellationToken ct = default) { + var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); var num = FacilityOpsStateStore.ParseIdNumber(id); var now = DateTime.UtcNow; @@ -369,10 +348,15 @@ public async Task CompleteHandoverAsync(long userId, string id, CompleteHandover .Include(h => h.Contract).ThenInclude(c => c.Unit) .Include(h => h.Contract).ThenInclude(c => c.AccessCredentials) .Include(h => h.Contract).ThenInclude(c => c.Reservation) - .FirstOrDefaultAsync(h => h.HandoverId == num || h.ContractId == num, ct); + .FirstOrDefaultAsync(h => h.HandoverId == num && h.Contract.Unit.FacilityId == fac.FacilityId, ct); if (handover != null) { + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{handover.Contract.ReservationId}", ct); + await dbContext.Entry(handover.Contract.Reservation).ReloadAsync(ct); + await ReservationSettlement.RequirePaidAsync(dbContext, handover.Contract.Reservation, ct); + if (handover.Status == "HANDED_OVER") { await tx.CommitAsync(ct); return; } + if (handover.Status != "VERIFIED") throw new InvalidOperationException("Cần xác minh khách hàng trước khi bàn giao."); handover.Status = "HANDED_OVER"; handover.StaffConfirmed = true; handover.CustomerConfirmed = true; @@ -411,95 +395,11 @@ public async Task CompleteHandoverAsync(long userId, string id, CompleteHandover } } await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); return; } - // 2. Thử tìm theo Reservation - var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct); - if (r != null) - { - var assignment = r.UnitAssignments.FirstOrDefault(ua => ua.Status == "ACTIVE"); - if (assignment != null) - { - var unit = assignment.Unit; - unit.Status = "OCCUPIED"; - unit.UpdatedAt = now; - - var contract = await dbContext.RentalContracts - .Include(c => c.HandoverRecord) - .Include(c => c.AccessCredentials) - .FirstOrDefaultAsync(c => c.ReservationId == r.ReservationId, ct); - - if (contract == null) - { - contract = new RentalContract - { - ReservationId = r.ReservationId, - CustomerId = r.CustomerId, - UnitId = unit.UnitId, - StartDate = r.StartDate, - EndDate = r.ExpectedEndDate, - AgreedMonthlyRate = r.QuotedMonthlyRate, - DepositAmount = r.RequiredDeposit, - Status = "ACTIVE", - CreatedAt = now, - ActivatedAt = now - }; - dbContext.RentalContracts.Add(contract); - await dbContext.SaveChangesAsync(ct); - } - else - { - contract.Status = "ACTIVE"; - contract.ActivatedAt ??= now; - } - - var hRecord = contract.HandoverRecord ?? await dbContext.HandoverRecords.FirstOrDefaultAsync(h => h.ContractId == contract.ContractId, ct); - if (hRecord == null) - { - hRecord = new HandoverRecord - { - ContractId = contract.ContractId, - StaffId = userId, - ScheduledAt = now, - VerifiedAt = now, - HandoverAt = now, - InitialCondition = "Đã kiểm tra và bàn giao kho", - Notes = $"Phương thức mở khóa: {request.UnlockMethod}", - CustomerConfirmed = true, - StaffConfirmed = true, - Status = "HANDED_OVER" - }; - dbContext.HandoverRecords.Add(hRecord); - } - else - { - hRecord.StaffId = userId; - hRecord.StaffConfirmed = true; - hRecord.CustomerConfirmed = true; - hRecord.HandoverAt = now; - hRecord.Status = "HANDED_OVER"; - hRecord.Notes = $"Phương thức mở khóa: {request.UnlockMethod}"; - } - - if (!contract.AccessCredentials.Any(a => a.Status == "ACTIVE")) - { - var method = (request.UnlockMethod ?? "CARD").ToUpperInvariant(); - dbContext.AccessCredentials.Add(new AccessCredential - { - ContractId = contract.ContractId, - UnitId = unit.UnitId, - IssuedBy = userId, - CredentialType = method == "CARD" ? "ACCESS_CARD" : "ACCESS_CODE", - CredentialReference = $"{method}-{unit.UnitNumber}-{now.AddHours(7):yyMMdd}", - IssuedAt = now, - Status = "ACTIVE" - }); - } - } - await dbContext.SaveChangesAsync(ct); - } + throw new InvalidOperationException("Không tìm thấy lịch bàn giao. Quản lý cần phân bổ kho trước."); } public async Task SubmitReturnInspectionAsync(long userId, string id, ReturnInspectionRequest request, CancellationToken ct = default) @@ -543,31 +443,27 @@ public async Task AddTicketResponseAsync(long userId, string id, TicketResponseR public async Task UpdateUnitStatusAsync(long userId, string id, UpdateUnitStatusRequest request, CancellationToken ct = default) { - if (string.IsNullOrWhiteSpace(request.Status)) - { - throw new ArgumentException("Trạng thái kho không được để trống."); - } var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == fac.FacilityId && (u.UnitNumber == id || u.UnitId == FacilityOpsStateStore.ParseIdNumber(id)), ct); - if (unit == null) - { - throw new InvalidOperationException($"Không tìm thấy kho {id}."); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"inventory:{fac.FacilityId}", ct); + var number = FacilityOpsStateStore.ParseIdNumber(id); + var unit = await dbContext.StorageUnits.SingleOrDefaultAsync(u => u.FacilityId == fac.FacilityId && + (u.UnitNumber == id || u.UnitId == number), ct) ?? throw new InvalidOperationException("Không tìm thấy ô kho."); + var next = UnitStatusRules.Normalize(request.Status ?? ""); + UnitStatusRules.Validate(unit.Status, next, request.Reason); + var held = await dbContext.UnitAssignments.AnyAsync(a => a.UnitId == unit.UnitId && a.Status == "ACTIVE" && + a.Reservation.Status != "CANCELLED" && a.Reservation.Status != "EXPIRED" && a.Reservation.Status != "NO_SHOW" && + (a.Reservation.RentalContract == null || (a.Reservation.RentalContract.Status != "COMPLETED" && a.Reservation.RentalContract.Status != "TERMINATED" && a.Reservation.RentalContract.Status != "CANCELLED")), ct) + || await dbContext.RentalContracts.AnyAsync(c => c.UnitId == unit.UnitId && c.Status != "COMPLETED" && + c.Status != "CANCELLED" && c.Status != "TERMINATED", ct); + if (held) throw new InvalidOperationException("Ô đang được giữ hoặc có hợp đồng chưa đóng, không được đổi trạng thái bằng tay."); + if (unit.Status != next) { + dbContext.UnitStatusHistories.Add(new UnitStatusHistory { UnitId = unit.UnitId, ChangedBy = userId, + OldStatus = unit.Status, NewStatus = next, Reason = request.Reason!.Trim(), ChangedAt = DateTime.UtcNow }); + unit.Status = next; + unit.UpdatedAt = DateTime.UtcNow; + await dbContext.SaveChangesAsync(ct); } - - var dbStatus = request.Status.ToUpperInvariant() switch - { - "EMPTY" => "AVAILABLE", - "ACTIVE" => "OCCUPIED", - "WAITING_HANDOVER" => "RESERVED", - "MAINTENANCE" => "MAINTENANCE", - "LOCKED" => "LOCKED", - _ => request.Status.ToUpperInvariant() - }; - - unit.Status = dbStatus; - unit.UpdatedAt = DateTime.UtcNow; - await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); } public async Task RevokeCredentialAsync(long userId, string id, CancellationToken ct = default) diff --git a/StorageProject.Infrastructure/Services/UnitStatusRules.cs b/StorageProject.Infrastructure/Services/UnitStatusRules.cs new file mode 100644 index 0000000..6f3fefc --- /dev/null +++ b/StorageProject.Infrastructure/Services/UnitStatusRules.cs @@ -0,0 +1,24 @@ +namespace StorageProject.Infrastructure.Services; + +public static class UnitStatusRules +{ + // Lifecycle transitions RESERVED/OCCUPIED/INSPECTION are owned by allocation/handover/return services. + public static string Normalize(string status) => status.Trim().ToUpperInvariant() switch { + "EMPTY" => "AVAILABLE", "ACTIVE" => "OCCUPIED", "WAITING_HANDOVER" => "RESERVED", + "LOCKED" => "OUT_OF_SERVICE", var value => value + }; + + public static void Validate(string current, string next, string? reason) + { + if (string.IsNullOrWhiteSpace(reason) || reason.Trim().Length > 255) + throw new ArgumentException("Nhập lý do từ 1 đến 255 ký tự."); + if (current == next) return; + var allowed = current switch { + "AVAILABLE" => next is "MAINTENANCE" or "OUT_OF_SERVICE", + "MAINTENANCE" => next is "AVAILABLE" or "OUT_OF_SERVICE", + "OUT_OF_SERVICE" => next is "AVAILABLE" or "MAINTENANCE", + _ => false + }; + if (!allowed) throw new InvalidOperationException("Không được đổi trạng thái này bằng tay. Hãy dùng luồng phân bổ, bàn giao hoặc trả kho."); + } +} diff --git a/StorageProject.Tests/CheckoutTests.cs b/StorageProject.Tests/CheckoutTests.cs new file mode 100644 index 0000000..eedaeb8 --- /dev/null +++ b/StorageProject.Tests/CheckoutTests.cs @@ -0,0 +1,187 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using StorageProject.Core.DTOs.Ops; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; +using StorageProject.Infrastructure.Services; +using Xunit; + +namespace StorageProject.Tests; + +public sealed class CheckoutTests +{ + private sealed class TestDb(DbContextOptions options) : AppDbContext(options) + { + protected override void OnModelCreating(ModelBuilder b) + { + base.OnModelCreating(b); + foreach (var p in b.Model.GetEntityTypes().SelectMany(t => t.GetProperties())) + if (p.GetDefaultValueSql() != null) p.SetDefaultValueSql(null); + } + } + private sealed class Gateway : IPayOSGateway + { + public VerifiedReservationPayment? Payment = new(12345, 4000000); + public bool RejectSignature; + public bool FailCancel; + public int Cancellations; + public void EnsureConfigured() { } + public Task CancelAsync(long id) { if (FailCancel) throw new InvalidOperationException(); Cancellations++; return Task.CompletedTask; } + public Task CreateAsync(long code, int amount, long id, long expiry, string ret, string cancel) => Task.FromResult(new CheckoutLink("https://pay.payos.vn/test", "qr")); + public Task VerifyAsync(string body) { + if (RejectSignature) throw new InvalidOperationException("bad signature"); + return Task.FromResult(Payment); + } + } + private sealed class Fixture : IAsyncDisposable + { + public SqliteConnection Connection = new("Data Source=:memory:"); + public AppDbContext Db = null!; + public Gateway Gateway = new(); + public Reservation Order = null!; + public PayOSService PayOS => new(Db, Gateway, NullLogger.Instance); + public static async Task Create() + { + var f = new Fixture(); await f.Connection.OpenAsync(); + f.Db = new TestDb(new DbContextOptionsBuilder().UseSqlite(f.Connection).Options); + await f.Db.Database.EnsureCreatedAsync(); + var user = new User { Username = "test", Email = "test@example.com", FullName = "Test", PasswordHash = "x" }; + var customer = new User { Username = "customer", Email = "customer@example.com", FullName = "Customer", PasswordHash = "x" }; + var facility = new Facility { Name = "Test", Address = "Test", Status = "ACTIVE" }; + var type = new UnitType { TypeName = "Test", Area = 10, Status = "ACTIVE" }; + f.Db.AddRange(user, customer, facility, type); await f.Db.SaveChangesAsync(); + f.Db.UserFacilities.Add(new UserFacility { UserId = user.UserId, FacilityId = facility.FacilityId, + AssignedBy = user.UserId, AssignedFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-1)), Status = "ACTIVE" }); + f.Db.StorageUnits.Add(new StorageUnit { FacilityId = facility.FacilityId, UnitTypeId = type.UnitTypeId, + UnitNumber = "K01", Status = "AVAILABLE" }); + f.Order = new Reservation { CustomerId = customer.UserId, FacilityId = facility.FacilityId, UnitTypeId = type.UnitTypeId, + StartDate = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(2)), ExpectedEndDate = DateOnly.FromDateTime(DateTime.UtcNow.AddMonths(3)), + RentalPeriodMonths = 3, EstimatedAmount = 3000000, RequiredDeposit = 1000000, QuotedMonthlyRate = 1000000, + Status = "PENDING_PAYMENT", OrderCode = 12345, ExpiresAt = DateTime.UtcNow.AddMinutes(15), CreatedAt = DateTime.UtcNow }; + f.Db.Reservations.Add(f.Order); await f.Db.SaveChangesAsync(); return f; + } + public async ValueTask DisposeAsync() { await Db.DisposeAsync(); await Connection.DisposeAsync(); } + } + + [Fact] public async Task WrongAmountDoesNotConfirmOrWriteMoney() { + await using var f = await Fixture.Create(); f.Gateway.Payment = new(12345, 1); + Assert.False(await f.PayOS.ProcessWebhookAsync("{}", null)); + Assert.Empty(await f.Db.Payments.ToListAsync()); Assert.Equal("PENDING_PAYMENT", f.Order.Status); + } + [Fact] public async Task InvalidSignatureAndUnknownOrderDoNotWriteMoney() { + await using var f = await Fixture.Create(); f.Gateway.RejectSignature = true; + Assert.False(await f.PayOS.ProcessWebhookAsync("{}", null)); f.Gateway.RejectSignature = false; f.Gateway.Payment = new(999, 4000000); + Assert.False(await f.PayOS.ProcessWebhookAsync("{}", null)); Assert.Empty(await f.Db.Payments.ToListAsync()); + } + [Fact] public async Task DuplicateWebhookAndAllocationKeepTwoReceiptRows() { + await using var f = await Fixture.Create(); + Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); + var before = await f.Db.Payments.OrderBy(p => p.PaymentId).Select(p => p.PaymentId).ToListAsync(); Assert.Equal(2, before.Count); + Assert.Equal(4000000, (await f.Db.Payments.ToListAsync()).Sum(p => p.Amount)); + Assert.Empty(await f.Db.UnitAssignments.ToListAsync()); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + Assert.Equal(before, await f.Db.Payments.OrderBy(p => p.PaymentId).Select(p => p.PaymentId).ToListAsync()); + Assert.All(await f.Db.Payments.ToListAsync(), p => Assert.NotNull(p.ContractId)); + Assert.Single(await f.Db.RentalContracts.ToListAsync()); Assert.Single(await f.Db.UnitAssignments.ToListAsync()); + } + [Fact] public async Task CashCollectionIsIdempotentAndLatePayosNeedsReview() { + await using var f = await Fixture.Create(); f.Order.CheckoutUrl = "https://pay.payos.vn/test"; await f.Db.SaveChangesAsync(); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); Assert.Equal(1, f.Gateway.Cancellations); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + Assert.Empty(await f.Db.Payments.ToListAsync()); + await Assert.ThrowsAsync(() => new StaffService(f.Db).CompleteHandoverAsync(1, "BG-0001", new CompleteHandoverRequest { UnlockMethod = "CARD" })); + var staff = new StaffService(f.Db); await staff.ConfirmPaymentAsync(1, "SS-0001"); await staff.ConfirmPaymentAsync(1, "SS-0001"); + Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); + Assert.Equal(2, await f.Db.Payments.CountAsync()); Assert.All(await f.Db.Payments.ToListAsync(), p => Assert.Equal("CASH", p.PaymentMethod)); + Assert.Single(await f.Db.ActivityLogs.Where(l => l.Action == "PAYMENT_REVIEW_REQUIRED").ToListAsync()); + } + [Fact] public async Task FailedCancellationDoesNotSwitchMethod() { + await using var f = await Fixture.Create(); f.Order.CheckoutUrl = "https://pay.payos.vn/test"; await f.Db.SaveChangesAsync(); f.Gateway.FailCancel = true; + await Assert.ThrowsAsync(() => f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId)); + Assert.Equal("PAYOS", f.Order.PaymentMethod); Assert.Equal("PENDING_PAYMENT", f.Order.Status); + } + [Fact] public async Task OtherCustomerCannotSwitchAndExpiredHoldCannotBeCollected() { + await using var f = await Fixture.Create(); await Assert.ThrowsAsync(() => f.PayOS.PayAtFacilityAsync(1, f.Order.ReservationId)); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); f.Order.ExpiresAt = DateTime.UtcNow.AddMinutes(-1); await f.Db.SaveChangesAsync(); + await Assert.ThrowsAsync(() => new StaffService(f.Db).ConfirmPaymentAsync(1, "SS-0001")); + Assert.Empty(await f.Db.Payments.ToListAsync()); + } + [Fact] public async Task UnitMaintenanceWritesHistoryAndRefusesOccupiedUnit() { + await using var f = await Fixture.Create(); var staff = new StaffService(f.Db); + await Assert.ThrowsAsync(() => staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "MAINTENANCE" })); + await staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "MAINTENANCE", Reason = "Sửa cửa" }); + await staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "AVAILABLE", Reason = "Đã sửa xong" }); + Assert.Equal(2, await f.Db.UnitStatusHistories.CountAsync()); + var u = await f.Db.StorageUnits.SingleAsync(); u.Status = "OCCUPIED"; await f.Db.SaveChangesAsync(); + await Assert.ThrowsAsync(() => staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "AVAILABLE", Reason = "Sai luồng" })); + Assert.Equal("OCCUPIED", u.Status); + } + + [Fact] public async Task CashHoldExpiryReleasesUnitAndCancelsDraft() { + await using var f = await Fixture.Create(); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + f.Order.ExpiresAt = DateTime.UtcNow.AddMinutes(-1); await f.Db.SaveChangesAsync(); + await CashHoldExpiry.ExpireAsync(f.Db); + Assert.Equal("EXPIRED", f.Order.Status); + Assert.Equal("AVAILABLE", (await f.Db.StorageUnits.SingleAsync()).Status); + Assert.Equal("CANCELLED", (await f.Db.RentalContracts.SingleAsync()).Status); + Assert.Empty(await f.Db.Payments.ToListAsync()); + } + [Fact] public async Task PaidOrderCannotSwitchToCashAndPayosCannotBeConfirmedAtCounter() { + await using var f = await Fixture.Create(); + await Assert.ThrowsAsync(() => new StaffService(f.Db).ConfirmPaymentAsync(1, "SS-0001")); + Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); + await Assert.ThrowsAsync(() => f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId)); + Assert.Equal(2, await f.Db.Payments.CountAsync()); + } + [Fact] public async Task SecondAllocationCannotTakeAlreadyHeldUnit() { + await using var f = await Fixture.Create(); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + var other = new Reservation { CustomerId = f.Order.CustomerId, FacilityId = f.Order.FacilityId, UnitTypeId = f.Order.UnitTypeId, + StartDate = f.Order.StartDate, ExpectedEndDate = f.Order.ExpectedEndDate, RentalPeriodMonths = 3, + Status = "PENDING_AT_FACILITY", PaymentMethod = "AT_FACILITY", ExpiresAt = DateTime.UtcNow.AddDays(1) }; + f.Db.Reservations.Add(other); await f.Db.SaveChangesAsync(); + await Assert.ThrowsAsync(() => ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, other.ReservationId, "K01", default)); + Assert.Single(await f.Db.UnitAssignments.ToListAsync()); + } + [Fact] public async Task ClientAmountOverrideIsRejected() { + await using var f = await Fixture.Create(); + var request = new StorageProject.Core.DTOs.Payment.CreatePayOSQrRequest(null,null,null,f.Order.ReservationId,null,null,1,null,null); + await Assert.ThrowsAsync(() => f.PayOS.CreatePaymentQrAsync(f.Order.CustomerId, request)); + Assert.Empty(await f.Db.Payments.ToListAsync()); + } + [Fact] public async Task RealSdkRejectsInvalidSignature() { + var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder().AddInMemoryCollection(new Dictionary { + ["PayOS:ClientId"] = "test-client", ["PayOS:ApiKey"] = "test-key", ["PayOS:ChecksumKey"] = "test-checksum" + }).Build(); + var gateway = new SdkPayOSGateway(config); + await Assert.ThrowsAnyAsync(() => gateway.VerifyAsync("{\"code\":\"00\",\"success\":true,\"data\":{\"orderCode\":12345,\"amount\":4000000,\"code\":\"00\"},\"signature\":\"invalid\"}")); + } + + [Fact] public void SqlServerModelMatchesMigrationSnapshot() { + using var db = new AppDbContext(new DbContextOptionsBuilder() + .UseSqlServer("Server=unused;Database=unused;Integrated Security=true;TrustServerCertificate=true").Options); + Assert.False(db.Database.HasPendingModelChanges()); + } + + [Fact] public async Task CashPaymentVerificationAndHandoverUseTheSameReceipts() { + await using var f = await Fixture.Create(); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + var staff = new StaffService(f.Db); + await staff.ConfirmPaymentAsync(1, "SS-0001"); + await staff.VerifyCustomerAsync(1, "XM-0001", new VerifyCustomerRequest { DocType = "CCCD", DocNumber = "123456789012", PhotoMatched = true, InfoMatched = true }); + var board = await staff.GetStaffBoardAsync(1); + Assert.Equal("DONE", Assert.Single(board.Verifications).Status); + await staff.CompleteHandoverAsync(1, "BG-0001", new CompleteHandoverRequest { UnlockMethod = "CARD" }); + Assert.Equal("ACTIVE", (await f.Db.RentalContracts.SingleAsync()).Status); + Assert.Equal("CHECKED_IN", f.Order.Status); + Assert.Equal(2, await f.Db.Payments.CountAsync()); + Assert.Equal("DONE", Assert.Single((await staff.GetStaffBoardAsync(1)).Handovers).Status); + } +} diff --git a/StorageProject.Tests/RouteTests.cs b/StorageProject.Tests/RouteTests.cs new file mode 100644 index 0000000..2258c06 --- /dev/null +++ b/StorageProject.Tests/RouteTests.cs @@ -0,0 +1,32 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using StorageProject.Api.Endpoints; +using StorageProject.Core.Interfaces; +using StorageProject.Infrastructure.Services; +using Xunit; + +namespace StorageProject.Tests; + +public sealed class RouteTests +{ + [Fact] public void CheckoutAndOpsRoutesAreUnique() + { + var builder = WebApplication.CreateBuilder(); + builder.Services.AddAuthorization(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + var app = builder.Build(); + app.MapReservationEndpoints(); app.MapStaffEndpoints(); app.MapManagerEndpoints(); app.MapFacilityOpsEndpoints(); + var routes = ((IEndpointRouteBuilder)app).DataSources.SelectMany(s => s.Endpoints).OfType() + .SelectMany(e => (e.Metadata.GetMetadata()?.HttpMethods ?? ["ANY"]) + .Select(method => $"{method} {e.RoutePattern.RawText}")).ToList(); + Assert.DoesNotContain(routes.GroupBy(r => r), g => g.Count() > 1); + Assert.Contains("POST /api/reservations/{id:long}/pay-at-facility", routes); + Assert.Contains("PUT /api/staff/units/{id}/status", routes); + Assert.Single(routes, r => r == "GET /api/ops/board"); + } +} diff --git a/StorageProject.Tests/StorageProject.Tests.csproj b/StorageProject.Tests/StorageProject.Tests.csproj new file mode 100644 index 0000000..b4936e9 --- /dev/null +++ b/StorageProject.Tests/StorageProject.Tests.csproj @@ -0,0 +1,10 @@ + + net10.0enableenabletruefalse + + + + + all + + + diff --git a/StorageProject.slnx b/StorageProject.slnx index 09a4ca3..9c7358b 100644 --- a/StorageProject.slnx +++ b/StorageProject.slnx @@ -2,4 +2,5 @@ + diff --git a/docs/payment-integrity-2026-10-20.md b/docs/payment-integrity-2026-10-20.md new file mode 100644 index 0000000..dcfb773 --- /dev/null +++ b/docs/payment-integrity-2026-10-20.md @@ -0,0 +1,66 @@ +# Kiểm tra bản sửa thanh toán và trạng thái ô kho + +Nguồn main: 242f70158d4299da4c5206181ba52389461b0fa3. Xem D23–D24. Gói này không triển khai thanh toán gia hạn, phí trả kho, phản hồi ticket hay tự động hoàn tiền. + +## Thay đổi API + +- POST `/api/reservations/{id}/pay-at-facility`: JWT chủ đơn, đơn chưa thanh toán/còn hạn; trả 200 sau khi chuyển PENDING_AT_FACILITY. Nếu PayOS huỷ link thất bại thì trả 400 và giữ phương thức cũ. Gọi lại cùng lựa chọn trả 200. +- POST `/api/staff/payments/{id}/confirm`: JWT STAFF/MANAGER đúng cơ sở, xác nhận đã thu tiền mặt. Chỉ nhận đơn AT_FACILITY chưa hết hạn; gọi lại cùng khoản đã thu trả 200, không thêm tiền. `/api/ops/payments/{id}/confirm` dùng chung xử lý. +- POST `/api/manager/allocations/{id}`: đơn đã thu đủ hoặc chờ thu tại kho, ô đúng cơ sở/loại/còn trống. Tạo đúng một hợp đồng nháp; gắn khoản thu có sẵn. `/api/ops/allocations/{id}` dùng chung xử lý. +- PUT `/api/staff/units/{id}/status`: `{ "status": "MAINTENANCE", "reason": "Sửa cửa" }`. Lý do bắt buộc, chỉ chuyển trạng thái vận hành thủ công, ghi lịch sử. Khoá ô qua API manager cũng đi qua quy tắc này. +- ReservationDto và ReservationDetailDto thêm `paymentMethod`. PaymentDto.ContractId có thể null trước khi phân bổ; các endpoint trả thanh toán của hợp đồng vẫn gắn hợp đồng như trước. +- Chữ ký webhook được kiểm bằng SDK PayOS 2.1.0; không có API bỏ qua chữ ký. Fake gateway chỉ nằm trong project test, không đăng ký ở chương trình chạy thật. + +## Chạy kiểm chứng + +Từ thư mục có StorageProject.slnx: + +```powershell +dotnet restore +dotnet build StorageProject.slnx -m:1 +dotnet test StorageProject.slnx -m:1 +dotnet run --project StorageProject.Api --launch-profile http +``` + +BE tự chạy migration mới ReservationPaymentIntegrity khi khởi động. Không reset database. Cần .NET SDK 10, SQL Server, tài khoản có quyền cập nhật schema và connection string đúng trên máy bạn. Các cảnh báo NU1902/NU1903 về dependency đã tồn tại từ bản nguồn, không được coi là build error. + +Ở terminal khác: + +```powershell +cd SafeSpace-Customer-UI\SafeSpace-Customer-UI +npm ci +npm test +npm run test:render +npm run test:business +npm run build +npm run dev +``` + +## Kịch bản bắt buộc trên SQL Server và PayOS thật + +1. Tạo đơn, tạo QR PayOS. Kiểm số tiền bằng tiền thuê + cọc trong DB. Đổi amount trong request tạo QR phải bị từ chối. +2. Trả đúng tiền. Sau webhook: đơn CONFIRMED, bảng payments có RENT + DEPOSIT (bỏ qua dòng giá trị 0), chưa tự gán ô. Gửi lại chính thông báo có chữ ký đó: không thêm payments và không thêm phân bổ. +3. Gửi chữ ký sai, đúng chữ ký nhưng sai tiền hoặc orderCode không có: không xác nhận, không ghi payments. Muốn kiểm sai tiền có chữ ký hợp lệ phải dùng giao dịch test/fixture hợp lệ, không sửa payload đã ký rồi coi đó là kiểm số tiền. +4. Quản lý phân bổ đúng loại kho ở M05: có một assignment, một hợp đồng DRAFT. PaymentId trước và sau phân bổ giữ nguyên. Bấm lại không tạo hợp đồng/thu thêm; chọn ô khác khi đã phân bổ bị chặn. +5. Đơn khác chọn trả tại kho: link PayOS cũ phải được huỷ/không tồn tại; đăng nhập lại hoặc trình duyệt khác vẫn thấy chọn trả tại kho. S09 chỉ hiện đơn chờ thu tại kho. M05 phân bổ được, nhưng S03 không bàn giao khi chưa thu tiền. +6. Nhân viên thực thu và xác nhận S09; bấm hai lần: chỉ hai khoản RENT/DEPOSIT, tổng đúng. Xác minh khách rồi bàn giao được. +7. Kiểm PayOS thanh toán đến muộn sau khi chọn/trả tại kho: không thêm khoản thu thuê; activity_logs có PAYMENT_REVIEW_REQUIRED. Webhook gửi lại không thêm log trùng. Quản lý đối chiếu và hoàn thủ công, đây không phải lệnh tự hoàn của PayOS. +8. Chạy đồng thời hai request xác nhận tiền, hoặc hai quản lý phân bổ cùng một ô: SQL Server chỉ cho một kết quả; request còn lại trả kết quả cũ hoặc lỗi, không ghi trùng. Các test SQLite không thay thế kiểm khoá SQL Server này. +9. Với đơn trả tại kho chưa thu trên DB phát triển, đặt ExpiresAt về quá khứ, đợi worker tối đa một phút: EXPIRED, assignment/hợp đồng nháp CANCELLED, ô AVAILABLE. Không sửa ngày của dữ liệu thật để thử. +10. M02 đổi ô trống sang bảo trì rồi mở lại, nhập lý do: DB có lịch sử old/new/actor/reason/time. Bỏ lý do, đổi ô đang thuê thành trống, đổi ô đã giữ sang bảo trì đều bị chặn. +11. Token khác cơ sở không thu/phân bổ/sửa ô được; CUSTOMER không gọi được API staff. +12. Thử migration trên bản sao DB đang có dữ liệu và DB mới. So sánh số dòng/khoản thu trước sau; không có khoản tiền tự sinh cho đơn cũ thiếu payments. + +## SQL đối chiếu + +```sql +SELECT ReservationId, ContractId, PaymentType, Amount, PaymentMethod, TransactionReference, Status +FROM payments WHERE ReservationId = ORDER BY PaymentId; +SELECT ReservationId, PaymentType, COUNT(*) AS RowCount +FROM payments WHERE ReservationId IS NOT NULL AND PaymentType IN ('RENT','DEPOSIT') +GROUP BY ReservationId, PaymentType HAVING COUNT(*) > 1; +SELECT * FROM activity_logs WHERE Action = 'PAYMENT_REVIEW_REQUIRED' ORDER BY LoggedAt DESC; +SELECT * FROM unit_status_history ORDER BY ChangedAt DESC; +``` + +Các đơn PENDING_VERIFICATION đời cũ không được tự coi là tiền mặt đã thu. Đơn cũ có PaidAt nhưng thiếu payments cần thành viên nhóm đối chiếu, không tự tạo tiền chỉ để qua điều kiện bàn giao. Gói này cũng không sửa các lỗi riêng của quy trình trả kho/hoàn cọc đã được liệt kê ở lần rà soát trước. diff --git a/feature_list.json b/feature_list.json index c536776..2f2b56d 100644 --- a/feature_list.json +++ b/feature_list.json @@ -2,7 +2,7 @@ "_readme": "Danh sách tính năng = ranh giới phạm vi cho AI agent. Mỗi mục: behavior (hành vi), verification (lệnh/cách kiểm chứng), state. state: not_started -> active -> passing | blocked. Chỉ đổi sang passing khi verification pass và ghi evidence. Mỗi phiên chỉ một mục active.", "_fe": "cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm test && npm run test:render && npm run build", "_be": "dotnet build StorageProject.slnx", - "updated": "2026-10-16", + "updated": "2026-10-20", "features": [ { "id": "F01", "flow": 1, "uc": ["UC01"], "actor": "Khách hàng", @@ -253,6 +253,19 @@ "state": "passing", "depends_on": ["F32", "F33"], "evidence": "2026-10-16: Đã triển khai IAccessService, AccessService (HMAC-SHA256 sinh QR và backupCode), AccessEndpoints (GET /api/contracts/{id}/access-qr, POST /api/access/scan); kết nối useAccessQr.js và endpoints.js; test_full_flow.ps1 kiểm chứng thành công từ bàn giao kho đến quét mã mở cửa và ghi activity_logs; dotnet build và npm test pass." + }, + { + "id": "F35", + "flow": [ + 1, + 5, + 6 + ], + "actor": "Khách hàng / Nhân viên / Quản lý", + "behavior": "Bản sửa theo yêu cầu: kiểm số tiền PayOS, ghi khoản thu trước hợp đồng, chống lặp và phân bổ, dự phòng tại kho, D23–D24, F12 có lý do/lịch sử", + "state": "active", + "verification": "dotnet build StorageProject.slnx -m:1; dotnet test StorageProject.slnx -m:1; kiểm chứng SQL Server/PayOS thật theo docs/payment-integrity-2026-10-20.md", + "evidence": "2026-10-20: build BE PASS; xUnit 15/15; FE 67/67; business 9/9; render 92 route; build FE và init.sh PASS. SQLite + kiểm model SQL Server; chờ SQL Server/PayOS thật nên chưa passing." } ] } diff --git a/progress.md b/progress.md index 531fd5a..3a61772 100644 --- a/progress.md +++ b/progress.md @@ -319,3 +319,13 @@ - Kiểm chứng: 42 test gốc, 10 test QR, 9 test business pass; 76 route SSR pass; Vite build pass. - Browser Chromium: popup 480x598, QR, kết quả mở cửa, từ chối hết hạn, icon 96px, Escape, Đóng, khóa chưa bàn giao, mobile 390px, không pageerror. - Chưa có backend QR; hướng dẫn C07-QR-HUONG-DAN.md. + +## 2026-10-20 — F35 kiểm khoản thu và phân bổ, thanh toán tại kho, F12 + +- Theo yêu cầu người dùng sửa cùng gói: PayOS kiểm số tiền và orderCode, ghi RENT/DEPOSIT vào payments trước khi có hợp đồng; gắn lại PaymentId khi phân bổ, không thu thêm. Bỏ phân bổ tự động khỏi webhook. Chuyển trả tại kho huỷ link trước khi đổi, S09 thu tiền mặt, xử lý callback muộn bằng PAYMENT_REVIEW_REQUIRED. +- D23–D24 bổ sung, không sửa số/nội dung D19–D22. Trạng thái ô bằng tay có lý do, quy tắc và unit_status_history. Xoá các route /api/ops trùng trong Staff/Manager để giữ một bộ đăng ký; các thao tác thu tiền/phân bổ tương thích dùng chung xử lý. +- Migration mới 20261020154838_ReservationPaymentIntegrity: PaymentMethod, PENDING_AT_FACILITY, Payment.ReservationId, ContractId optional, unique index khoản thu. Nối các dòng cũ không mơ hồ; không xoá database/dữ liệu. Worker thu hồi giữ chỗ tại kho hết hạn. Không sửa migration cũ. +- Chặn xác minh/bàn giao chưa có đủ khoản thu, đồng bộ trạng thái xác minh từ HandoverRecord thay vì đánh dấu CHECKED_IN trước khi bàn giao. Test luồng chọn trả tại kho → phân bổ → thu → xác minh → bàn giao giữ nguyên hai khoản thu. +- Kiểm chứng: .NET SDK 10.0.100; dotnet build StorageProject.slnx -m:1 PASS; xUnit 15/15 PASS (SQLite, adapter SDK chữ ký sai, model SQL Server khớp snapshot, route không trùng); npm test 67/67 PASS; test:business 9/9 PASS; test:render 92 route PASS; npm run build PASS; bash init.sh PASS với dotnet build/test chạy m:1 do giới hạn tiến trình của môi trường; git diff --check PASS; sinh được SQL upgrade từ migration toạ độ tới migration mới. +- Giới hạn kiểm chứng: chưa chạy SQL Server thật, chưa thử PayOS/ngrok bằng key thật, chưa kiểm khoá/đồng thời trên SQL Server hay migration trên dữ liệu DB của nhóm. F35 giữ active, không tuyên bố 7 flow hoàn tất. Các cảnh báo dependency NU1902/NU1903 và nullable Board.cs:317 đã có từ nguồn. +- Chỉ bàn giao ZIP/bản vá để người dùng áp dụng và chạy thử trước khi tự push nhánh. Không push/PR/merge từ phiên này.