From 4daf152536b2f4bbd91fd29d23a447470dc11e9b Mon Sep 17 00:00:00 2001 From: ryocoding13 Date: Wed, 28 Oct 2026 00:30:31 +0700 Subject: [PATCH 1/2] feat(BE): implement renewal settlement, counter payment and policy consent under D32 --- .../Endpoints/CounterRenewalEndpoints.cs | 104 + .../Endpoints/PaymentEndpoints.cs | 14 + .../Endpoints/RentalPolicyEndpoints.cs | 83 + StorageProject.Api/Program.cs | 4 + .../Workers/ExpiredRenewalWorker.cs | 37 + StorageProject.Core/DTOs/Payment/PayOSDtos.cs | 12 + .../DTOs/Payment/PaymentDtos.cs | 3 +- .../DTOs/Policy/RentalPolicyDtos.cs | 30 + .../DTOs/Renewal/CounterRenewalDtos.cs | 21 + .../DTOs/Renewal/RenewalDtos.cs | 12 +- .../Entities/ContractRenewal.cs | 8 +- StorageProject.Core/Entities/Payment.cs | 1 + .../Entities/PaymentCheckout.cs | 18 + StorageProject.Core/Entities/PolicyConsent.cs | 19 + .../Entities/RentalContract.cs | 1 + .../Entities/RentalPolicyVersion.cs | 16 + StorageProject.Core/Entities/Reservation.cs | 1 + .../Interfaces/IPayOSService.cs | 1 + StorageProject.Core/Interfaces/IServices.cs | 15 + .../Data/AppDbContext.cs | 3 + .../PaymentCheckoutConfiguration.cs | 39 + .../RentalPolicyConfigurations.cs | 79 + .../ReservationContractConfigurations.cs | 12 +- .../Data/DbSeeder.cs | 32 + ...ewalSettlementAndPolicyConsent.Designer.cs | 2266 +++++++++++++++++ ...11_AddRenewalSettlementAndPolicyConsent.cs | 297 +++ .../Migrations/AppDbContextModelSnapshot.cs | 268 +- .../Services/FacilityOpsService.Actions.cs | 64 +- .../Services/ManagerService.cs | 141 +- .../Services/PayOSGateway.cs | 13 +- .../Services/PayOSService.cs | 217 +- .../Services/PaymentService.cs | 7 +- .../Services/RenewalService.cs | 469 +++- .../Services/RenewalSettlement.cs | 172 ++ .../Services/RentalPolicyService.cs | 262 ++ StorageProject.Tests/RenewalPolicyD32Tests.cs | 485 ++++ docs/sprints/dat-renewal-policy-d32.md | 38 + .../dat-renewal-policy-2026-10.md | 214 ++ progress.md | 15 + 39 files changed, 5428 insertions(+), 65 deletions(-) create mode 100644 StorageProject.Api/Endpoints/CounterRenewalEndpoints.cs create mode 100644 StorageProject.Api/Endpoints/RentalPolicyEndpoints.cs create mode 100644 StorageProject.Api/Workers/ExpiredRenewalWorker.cs create mode 100644 StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs create mode 100644 StorageProject.Core/DTOs/Renewal/CounterRenewalDtos.cs create mode 100644 StorageProject.Core/Entities/PaymentCheckout.cs create mode 100644 StorageProject.Core/Entities/PolicyConsent.cs create mode 100644 StorageProject.Core/Entities/RentalPolicyVersion.cs create mode 100644 StorageProject.Infrastructure/Data/Configurations/PaymentCheckoutConfiguration.cs create mode 100644 StorageProject.Infrastructure/Data/Configurations/RentalPolicyConfigurations.cs create mode 100644 StorageProject.Infrastructure/Migrations/20261027165711_AddRenewalSettlementAndPolicyConsent.Designer.cs create mode 100644 StorageProject.Infrastructure/Migrations/20261027165711_AddRenewalSettlementAndPolicyConsent.cs create mode 100644 StorageProject.Infrastructure/Services/RenewalSettlement.cs create mode 100644 StorageProject.Infrastructure/Services/RentalPolicyService.cs create mode 100644 StorageProject.Tests/RenewalPolicyD32Tests.cs create mode 100644 docs/sprints/dat-renewal-policy-d32.md create mode 100644 docs/verification/dat-renewal-policy-2026-10.md diff --git a/StorageProject.Api/Endpoints/CounterRenewalEndpoints.cs b/StorageProject.Api/Endpoints/CounterRenewalEndpoints.cs new file mode 100644 index 0000000..dd62134 --- /dev/null +++ b/StorageProject.Api/Endpoints/CounterRenewalEndpoints.cs @@ -0,0 +1,104 @@ +using System.Security.Claims; +using StorageProject.Api.Extensions; +using StorageProject.Core.DTOs.Renewal; +using StorageProject.Core.Interfaces; + +namespace StorageProject.Api.Endpoints; + +public static class CounterRenewalEndpoints +{ + public static RouteGroupBuilder MapCounterRenewalEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api") + .WithTags("Counter Renewals") + .RequireAuthorization(); + + // POST /api/renewals/{id:long}/counter-payment — Customer selects counter payment + group.MapPost("/renewals/{id:long}/counter-payment", async (long id, ClaimsPrincipal user, IRenewalService renewalService, CancellationToken ct) => + { + try + { + var customerId = user.GetUserId(); + await renewalService.SelectCounterPaymentAsync(customerId, id, ct); + return Results.Ok(new { message = "Đã chuyển yêu cầu gia hạn sang thanh toán tại quầy cơ sở." }); + } + catch (KeyNotFoundException ex) + { + return Results.NotFound(new { error = ex.Message }); + } + catch (UnauthorizedAccessException ex) + { + return Results.Json(new { error = ex.Message }, statusCode: StatusCodes.Status403Forbidden); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + return Results.BadRequest(new { error = ex.Message }); + } + }); + + // GET /api/ops/counter-renewals — Staff / Manager queue + group.MapGet("/ops/counter-renewals", async (ClaimsPrincipal user, IRenewalService renewalService, CancellationToken ct) => + { + try + { + var role = user.GetUserRole(); + if (role != "STAFF" && role != "MANAGER" && role != "ADMIN") + { + return Results.Json(new { error = "Chỉ nhân viên hoặc quản lý cơ sở mới có quyền xem danh sách thu tại quầy." }, statusCode: StatusCodes.Status403Forbidden); + } + + var userId = user.GetUserId(); + var items = await renewalService.GetCounterRenewalsAsync(userId, ct); + return Results.Ok(items); + } + catch (UnauthorizedAccessException ex) + { + return Results.Json(new { error = ex.Message }, statusCode: StatusCodes.Status403Forbidden); + } + catch (Exception ex) + { + return Results.BadRequest(new { error = ex.Message }); + } + }); + + // POST /api/ops/counter-renewals/actions — Staff / Manager confirm cash collection + group.MapPost("/ops/counter-renewals/actions", async (CounterRenewalActionRequest request, ClaimsPrincipal user, IRenewalService renewalService, CancellationToken ct) => + { + try + { + var role = user.GetUserRole(); + if (role != "STAFF" && role != "MANAGER" && role != "ADMIN") + { + return Results.Json(new { error = "Chỉ nhân viên hoặc quản lý cơ sở mới có quyền xác nhận thu tại quầy." }, statusCode: StatusCodes.Status403Forbidden); + } + + if (request.Action != "COLLECT_RENEWAL") + { + return Results.BadRequest(new { error = $"Hành động '{request.Action}' không hợp lệ. Chỉ chấp nhận 'COLLECT_RENEWAL'." }); + } + + var userId = user.GetUserId(); + await renewalService.CollectCounterRenewalAsync(userId, request.Id, ct); + return Results.Ok(new { message = "Đã xác nhận thu tiền gia hạn tại quầy thành công." }); + } + catch (KeyNotFoundException ex) + { + return Results.NotFound(new { error = ex.Message }); + } + catch (UnauthorizedAccessException ex) + { + return Results.Json(new { error = ex.Message }, statusCode: StatusCodes.Status403Forbidden); + } + catch (InvalidOperationException ex) + { + return Results.BadRequest(new { error = ex.Message }); + } + catch (Exception ex) + { + return Results.BadRequest(new { error = ex.Message }); + } + }); + + return group; + } +} diff --git a/StorageProject.Api/Endpoints/PaymentEndpoints.cs b/StorageProject.Api/Endpoints/PaymentEndpoints.cs index b2460f0..21210a8 100644 --- a/StorageProject.Api/Endpoints/PaymentEndpoints.cs +++ b/StorageProject.Api/Endpoints/PaymentEndpoints.cs @@ -27,6 +27,20 @@ public static RouteGroupBuilder MapPaymentEndpoints(this IEndpointRouteBuilder a return payment is not null ? Results.Ok(payment) : Results.NotFound(new { error = "Không tìm thấy thông tin thanh toán." }); }); + group.MapPost("/payments/{id:long}/payos", async (long id, ClaimsPrincipal user, IPayOSService payOSService, CancellationToken ct) => + { + try + { + var customerId = user.GetUserId(); + var checkout = await payOSService.CreateRenewalPaymentQrAsync(customerId, id, ct); + return Results.Ok(checkout); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + return Results.BadRequest(new { error = ex.Message }); + } + }); + // PayOS Webhook endpoints (AllowAnonymous) app.MapPost("/api/payments/payos-webhook", async ( diff --git a/StorageProject.Api/Endpoints/RentalPolicyEndpoints.cs b/StorageProject.Api/Endpoints/RentalPolicyEndpoints.cs new file mode 100644 index 0000000..0c53f53 --- /dev/null +++ b/StorageProject.Api/Endpoints/RentalPolicyEndpoints.cs @@ -0,0 +1,83 @@ +using System.Security.Claims; +using StorageProject.Api.Extensions; +using StorageProject.Core.DTOs.Policy; +using StorageProject.Core.Interfaces; + +namespace StorageProject.Api.Endpoints; + +public static class RentalPolicyEndpoints +{ + public static RouteGroupBuilder MapRentalPolicyEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api") + .WithTags("Rental Policy"); + + // Public GET /api/rental-policy + group.MapGet("/rental-policy", async (IRentalPolicyService policyService, CancellationToken ct) => + { + var policy = await policyService.GetCurrentPolicyAsync(ct); + return Results.Ok(policy); + }).AllowAnonymous(); + + // Public GET /api/rental-policy/versions/{version:int} + group.MapGet("/rental-policy/versions/{version:int}", async (int version, IRentalPolicyService policyService, CancellationToken ct) => + { + var policy = await policyService.GetPolicyVersionAsync(version, ct); + if (policy == null) + { + return Results.NotFound(new { error = $"Không tìm thấy phiên bản chính sách {version}." }); + } + return Results.Ok(policy); + }).AllowAnonymous(); + + // POST /api/rental-policy/actions - OPERATIONS or ADMIN only + group.MapPost("/rental-policy/actions", async (SaveRentalPolicyRequest request, ClaimsPrincipal user, IRentalPolicyService policyService, CancellationToken ct) => + { + try + { + var role = user.GetUserRole(); + if (role != "OPERATIONS" && role != "ADMIN") + { + return Results.Json(new { error = "Chỉ Quản lý vận hành (OPERATIONS) hoặc Quản trị hệ thống mới có quyền lưu chính sách." }, statusCode: StatusCodes.Status403Forbidden); + } + + var userId = user.GetUserId(); + var result = await policyService.SaveRentalPolicyAsync(userId, request, ct); + return Results.Ok(result); + } + catch (InvalidOperationException ex) when (ex.Message.Contains("người khác cập nhật") || ex.Message.Contains("xung đột")) + { + return Results.Conflict(new { error = ex.Message }); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + return Results.BadRequest(new { error = ex.Message }); + } + }).RequireAuthorization(); + + // POST /api/reservations/{id:long}/policy-consent - Customer consent + group.MapPost("/reservations/{id:long}/policy-consent", async (long id, PolicyConsentRequest request, ClaimsPrincipal user, IRentalPolicyService policyService, CancellationToken ct) => + { + try + { + var customerId = user.GetUserId(); + var consent = await policyService.RecordReservationConsentAsync(customerId, id, request, "WEB", ct); + return Results.Ok(consent); + } + catch (KeyNotFoundException ex) + { + return Results.NotFound(new { error = ex.Message }); + } + catch (UnauthorizedAccessException ex) + { + return Results.Json(new { error = ex.Message }, statusCode: StatusCodes.Status403Forbidden); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + return Results.BadRequest(new { error = ex.Message }); + } + }).RequireAuthorization(); + + return group; + } +} diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs index afc4193..dbc86a5 100644 --- a/StorageProject.Api/Program.cs +++ b/StorageProject.Api/Program.cs @@ -162,10 +162,12 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); if (builder.Configuration.GetValue("Worker:EnableExpiredCashHold", true)) { builder.Services.AddHostedService(); } +builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddSingleton(new AccessQrOptions( builder.Configuration["AccessQr:Secret"] ?? jwtSecret, @@ -220,6 +222,8 @@ app.MapContractEndpoints(); app.MapPaymentEndpoints(); app.MapRenewalEndpoints(); +app.MapCounterRenewalEndpoints(); +app.MapRentalPolicyEndpoints(); app.MapSupportTicketEndpoints(); app.MapAdminEndpoints(); app.MapOperationsEndpoints(); diff --git a/StorageProject.Api/Workers/ExpiredRenewalWorker.cs b/StorageProject.Api/Workers/ExpiredRenewalWorker.cs new file mode 100644 index 0000000..af5bdd5 --- /dev/null +++ b/StorageProject.Api/Workers/ExpiredRenewalWorker.cs @@ -0,0 +1,37 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using StorageProject.Core.Interfaces; + +namespace StorageProject.Api.Workers; + +public class ExpiredRenewalWorker( + IServiceScopeFactory scopeFactory, + ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + using var scope = scopeFactory.CreateScope(); + var renewalService = scope.ServiceProvider.GetRequiredService(); + await renewalService.ExpirePendingRenewalsAsync(stoppingToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Lỗi khi quét yêu cầu gia hạn hết hạn."); + } + + try + { + await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); + } + catch (OperationCanceledException) + { + break; + } + } + } +} diff --git a/StorageProject.Core/DTOs/Payment/PayOSDtos.cs b/StorageProject.Core/DTOs/Payment/PayOSDtos.cs index b5346f8..f45f431 100644 --- a/StorageProject.Core/DTOs/Payment/PayOSDtos.cs +++ b/StorageProject.Core/DTOs/Payment/PayOSDtos.cs @@ -27,3 +27,15 @@ public record ReservationPaymentStatusDto( bool IsPaid, DateTime? PaidAt ); + +public record PayosCheckoutDto( + long OrderCode, + decimal Amount, + string Description, + string Status, + string QrCode, + string CheckoutUrl, + DateTime ExpiredAt, + long? PaymentId = null, + long? RenewalId = null +); diff --git a/StorageProject.Core/DTOs/Payment/PaymentDtos.cs b/StorageProject.Core/DTOs/Payment/PaymentDtos.cs index 9baf54a..c253c0c 100644 --- a/StorageProject.Core/DTOs/Payment/PaymentDtos.cs +++ b/StorageProject.Core/DTOs/Payment/PaymentDtos.cs @@ -12,5 +12,6 @@ public record PaymentDto( DateOnly? DueDate, DateTime? PaidAt, string Status, - DateTime CreatedAt + DateTime CreatedAt, + DateTime? PaymentDeadlineAt = null ); diff --git a/StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs b/StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs new file mode 100644 index 0000000..f3850f6 --- /dev/null +++ b/StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs @@ -0,0 +1,30 @@ +namespace StorageProject.Core.DTOs.Policy; + +public record RentalPolicyDto( + decimal Rate, + Dictionary Sections, + int Version, + string DisplayVersion, + DateTime UpdatedAt +); + +public record SaveRentalPolicyRequest( + string Action, + decimal? Rate, + Dictionary? Sections, + int? Version +); + +public record PolicyConsentRequest( + int PolicyVersion, + bool Accepted +); + +public record PolicyConsentDto( + long ConsentId, + long CustomerId, + int PolicyVersion, + string DisplayVersion, + DateTime AcceptedAt, + string Channel +); diff --git a/StorageProject.Core/DTOs/Renewal/CounterRenewalDtos.cs b/StorageProject.Core/DTOs/Renewal/CounterRenewalDtos.cs new file mode 100644 index 0000000..c5d638d --- /dev/null +++ b/StorageProject.Core/DTOs/Renewal/CounterRenewalDtos.cs @@ -0,0 +1,21 @@ +namespace StorageProject.Core.DTOs.Renewal; + +public record CounterRenewalDto( + string Id, + long RenewalId, + long PaymentId, + string ContractId, + string ContractCode, + long FacilityId, + string Unit, + string Customer, + decimal Amount, + int Months, + DateTime? PaymentDeadlineAt, + string Status +); + +public record CounterRenewalActionRequest( + string Action, + string Id +); diff --git a/StorageProject.Core/DTOs/Renewal/RenewalDtos.cs b/StorageProject.Core/DTOs/Renewal/RenewalDtos.cs index 9be8152..aa7c993 100644 --- a/StorageProject.Core/DTOs/Renewal/RenewalDtos.cs +++ b/StorageProject.Core/DTOs/Renewal/RenewalDtos.cs @@ -1,7 +1,9 @@ namespace StorageProject.Core.DTOs.Renewal; public record CreateRenewalRequest( - int RenewalPeriodMonths + int RenewalPeriodMonths, + int? PolicyVersion = null, + bool? Accepted = null ); public record RenewalDto( @@ -15,5 +17,11 @@ public record RenewalDto( decimal RenewalAmount, string Status, DateTime RequestedAt, - DateTime? ApprovedAt + DateTime? ApprovedAt, + DateTime? PaymentDeadlineAt = null, + DateTime? AppliedAt = null, + DateTime? ExpiredAt = null, + long? PaymentId = null, + int? PolicyVersion = null, + DateTime? AcceptedAt = null ); diff --git a/StorageProject.Core/Entities/ContractRenewal.cs b/StorageProject.Core/Entities/ContractRenewal.cs index 31522f6..277bc72 100644 --- a/StorageProject.Core/Entities/ContractRenewal.cs +++ b/StorageProject.Core/Entities/ContractRenewal.cs @@ -11,12 +11,18 @@ public class ContractRenewal public decimal OldMonthlyRate { get; set; } public decimal NewMonthlyRate { get; set; } public decimal RenewalAmount { get; set; } - public string Status { get; set; } = "PENDING"; // PENDING, APPROVED, REJECTED, PAID, CANCELLED + public string Status { get; set; } = "PENDING"; // PENDING, APPROVED, REJECTED, PAID, CANCELLED, EXPIRED public DateTime RequestedAt { get; set; } public DateTime? ApprovedAt { get; set; } + public DateTime? PaymentDeadlineAt { get; set; } + public DateTime? AppliedAt { get; set; } + public DateTime? ExpiredAt { get; set; } + public int? PolicyVersion { get; set; } + public DateTime? AcceptedAt { get; set; } public DateTime CreatedAt { get; set; } public RentalContract Contract { get; set; } = null!; public User? ApprovedByUser { get; set; } public ICollection Payments { get; set; } = []; + public ICollection PolicyConsents { get; set; } = []; } diff --git a/StorageProject.Core/Entities/Payment.cs b/StorageProject.Core/Entities/Payment.cs index f8f05f2..74d9c09 100644 --- a/StorageProject.Core/Entities/Payment.cs +++ b/StorageProject.Core/Entities/Payment.cs @@ -22,4 +22,5 @@ public class Payment public RentalContract Contract { get; set; } = null!; public Reservation Reservation { get; set; } = null!; public ContractRenewal? Renewal { get; set; } + public ICollection Checkouts { get; set; } = []; } diff --git a/StorageProject.Core/Entities/PaymentCheckout.cs b/StorageProject.Core/Entities/PaymentCheckout.cs new file mode 100644 index 0000000..76c4f03 --- /dev/null +++ b/StorageProject.Core/Entities/PaymentCheckout.cs @@ -0,0 +1,18 @@ +namespace StorageProject.Core.Entities; + +public class PaymentCheckout +{ + public long CheckoutId { get; set; } + public long PaymentId { get; set; } + public long OrderCode { get; set; } + public string Provider { get; set; } = "PAYOS"; // PAYOS + public decimal Amount { get; set; } + public string Status { get; set; } = "PENDING"; // PENDING, PAID, CANCELLED, EXPIRED + public string? CheckoutUrl { get; set; } + public string? QrCode { get; set; } + public DateTime ExpiresAt { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + public Payment Payment { get; set; } = null!; +} diff --git a/StorageProject.Core/Entities/PolicyConsent.cs b/StorageProject.Core/Entities/PolicyConsent.cs new file mode 100644 index 0000000..5215915 --- /dev/null +++ b/StorageProject.Core/Entities/PolicyConsent.cs @@ -0,0 +1,19 @@ +namespace StorageProject.Core.Entities; + +public class PolicyConsent +{ + public long ConsentId { get; set; } + public long CustomerId { get; set; } + public long PolicyVersionId { get; set; } + public long? ReservationId { get; set; } + public long? ContractId { get; set; } + public long? RenewalId { get; set; } + public DateTime AcceptedAt { get; set; } + public string Channel { get; set; } = "WEB_CUSTOMER"; // WEB_CUSTOMER, COUNTER_CUSTOMER + + public User Customer { get; set; } = null!; + public RentalPolicyVersion PolicyVersion { get; set; } = null!; + public Reservation? Reservation { get; set; } + public RentalContract? Contract { get; set; } + public ContractRenewal? Renewal { get; set; } +} diff --git a/StorageProject.Core/Entities/RentalContract.cs b/StorageProject.Core/Entities/RentalContract.cs index aab8082..d184420 100644 --- a/StorageProject.Core/Entities/RentalContract.cs +++ b/StorageProject.Core/Entities/RentalContract.cs @@ -27,4 +27,5 @@ public class RentalContract public ICollection ReturnInspections { get; set; } = []; public ICollection OverdueCases { get; set; } = []; public ICollection SupportTickets { get; set; } = []; + public ICollection PolicyConsents { get; set; } = []; } diff --git a/StorageProject.Core/Entities/RentalPolicyVersion.cs b/StorageProject.Core/Entities/RentalPolicyVersion.cs new file mode 100644 index 0000000..3d62619 --- /dev/null +++ b/StorageProject.Core/Entities/RentalPolicyVersion.cs @@ -0,0 +1,16 @@ +namespace StorageProject.Core.Entities; + +public class RentalPolicyVersion +{ + public long PolicyVersionId { get; set; } + public int Version { get; set; } + public string DisplayVersion { get; set; } = null!; + public decimal Rate { get; set; } + public string SectionsJson { get; set; } = null!; + public long PublishedBy { get; set; } + public DateTime PublishedAt { get; set; } + public bool IsCurrent { get; set; } + + public User PublishedByUser { get; set; } = null!; + public ICollection Consents { get; set; } = []; +} diff --git a/StorageProject.Core/Entities/Reservation.cs b/StorageProject.Core/Entities/Reservation.cs index 487c83d..0c62118 100644 --- a/StorageProject.Core/Entities/Reservation.cs +++ b/StorageProject.Core/Entities/Reservation.cs @@ -30,4 +30,5 @@ public class Reservation public UnitType UnitType { get; set; } = null!; public ICollection UnitAssignments { get; set; } = []; public RentalContract? RentalContract { get; set; } + public ICollection PolicyConsents { get; set; } = []; } diff --git a/StorageProject.Core/Interfaces/IPayOSService.cs b/StorageProject.Core/Interfaces/IPayOSService.cs index 9e11fa2..c2aa07c 100644 --- a/StorageProject.Core/Interfaces/IPayOSService.cs +++ b/StorageProject.Core/Interfaces/IPayOSService.cs @@ -8,4 +8,5 @@ public interface IPayOSService 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); + Task CreateRenewalPaymentQrAsync(long customerId, long paymentId, CancellationToken ct = default); } diff --git a/StorageProject.Core/Interfaces/IServices.cs b/StorageProject.Core/Interfaces/IServices.cs index a2fdc40..5eef9d9 100644 --- a/StorageProject.Core/Interfaces/IServices.cs +++ b/StorageProject.Core/Interfaces/IServices.cs @@ -64,6 +64,21 @@ public interface IRenewalService { Task> GetContractRenewalsAsync(long customerId, long contractId, CancellationToken ct = default); Task RequestRenewalAsync(long customerId, long contractId, CreateRenewalRequest request, CancellationToken ct = default); + Task SelectCounterPaymentAsync(long customerId, long renewalId, CancellationToken ct = default); + Task> GetCounterRenewalsAsync(long userId, CancellationToken ct = default); + Task CollectCounterRenewalAsync(long userId, string id, CancellationToken ct = default); + Task ApproveRenewalAsync(long userId, long renewalId, CancellationToken ct = default); + Task RejectRenewalAsync(long userId, long renewalId, string reason, CancellationToken ct = default); + Task ExpirePendingRenewalsAsync(CancellationToken ct = default); +} + +public interface IRentalPolicyService +{ + Task GetCurrentPolicyAsync(CancellationToken ct = default); + Task GetPolicyVersionAsync(int version, CancellationToken ct = default); + Task SaveRentalPolicyAsync(long userId, StorageProject.Core.DTOs.Policy.SaveRentalPolicyRequest request, CancellationToken ct = default); + Task RecordReservationConsentAsync(long customerId, long reservationId, StorageProject.Core.DTOs.Policy.PolicyConsentRequest request, string channel = "WEB_CUSTOMER", CancellationToken ct = default); + Task RecordRenewalConsentAsync(long customerId, long renewalId, StorageProject.Core.DTOs.Policy.PolicyConsentRequest request, string channel = "WEB_CUSTOMER", CancellationToken ct = default); } public interface ISupportTicketService diff --git a/StorageProject.Infrastructure/Data/AppDbContext.cs b/StorageProject.Infrastructure/Data/AppDbContext.cs index fef05ad..7721a82 100644 --- a/StorageProject.Infrastructure/Data/AppDbContext.cs +++ b/StorageProject.Infrastructure/Data/AppDbContext.cs @@ -38,6 +38,9 @@ public class AppDbContext(DbContextOptions options) : DbContext(op // VIII. Renewal public DbSet ContractRenewals => Set(); + public DbSet PaymentCheckouts => Set(); + public DbSet RentalPolicyVersions => Set(); + public DbSet PolicyConsents => Set(); // IX. Payment public DbSet Payments => Set(); diff --git a/StorageProject.Infrastructure/Data/Configurations/PaymentCheckoutConfiguration.cs b/StorageProject.Infrastructure/Data/Configurations/PaymentCheckoutConfiguration.cs new file mode 100644 index 0000000..effc669 --- /dev/null +++ b/StorageProject.Infrastructure/Data/Configurations/PaymentCheckoutConfiguration.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Data.Configurations; + +public class PaymentCheckoutConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("payment_checkouts", t => + { + t.HasCheckConstraint("CK_payment_checkouts_amount", "[Amount] >= 0"); + t.HasCheckConstraint("CK_payment_checkouts_status", + "[Status] IN ('PENDING','PAID','CANCELLED','EXPIRED')"); + }); + + b.HasKey(c => c.CheckoutId); + b.Property(c => c.CheckoutId).UseIdentityColumn(); + b.Property(c => c.PaymentId).IsRequired(); + b.Property(c => c.OrderCode).IsRequired(); + b.HasIndex(c => c.OrderCode).IsUnique(); + b.Property(c => c.Provider).IsRequired().HasMaxLength(30).HasDefaultValue("PAYOS"); + b.Property(c => c.Amount).IsRequired().HasColumnType("decimal(15,2)"); + b.Property(c => c.Status).IsRequired().HasMaxLength(20).HasDefaultValue("PENDING"); + b.Property(c => c.CheckoutUrl).HasMaxLength(2000); + b.Property(c => c.QrCode).HasMaxLength(2000); + b.Property(c => c.ExpiresAt).IsRequired(); + b.Property(c => c.CreatedAt).IsRequired(); + b.Property(c => c.UpdatedAt).IsRequired(); + + b.HasOne(c => c.Payment) + .WithMany(p => p.Checkouts) + .HasForeignKey(c => c.PaymentId) + .OnDelete(DeleteBehavior.Restrict); + + b.HasIndex(c => c.PaymentId); + } +} diff --git a/StorageProject.Infrastructure/Data/Configurations/RentalPolicyConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/RentalPolicyConfigurations.cs new file mode 100644 index 0000000..d975ba5 --- /dev/null +++ b/StorageProject.Infrastructure/Data/Configurations/RentalPolicyConfigurations.cs @@ -0,0 +1,79 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Data.Configurations; + +public class RentalPolicyVersionConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("rental_policy_versions", t => + { + t.HasCheckConstraint("CK_rental_policy_versions_rate", "[Rate] >= 0 AND [Rate] <= 100"); + t.HasCheckConstraint("CK_rental_policy_versions_version", "[Version] > 0"); + }); + + b.HasKey(v => v.PolicyVersionId); + b.Property(v => v.PolicyVersionId).UseIdentityColumn(); + b.Property(v => v.Version).IsRequired(); + b.HasIndex(v => v.Version).IsUnique(); + b.Property(v => v.DisplayVersion).IsRequired().HasMaxLength(50); + b.Property(v => v.Rate).IsRequired().HasColumnType("decimal(5,2)"); + b.Property(v => v.SectionsJson).IsRequired(); + b.Property(v => v.PublishedBy).IsRequired(); + b.Property(v => v.PublishedAt).IsRequired(); + b.Property(v => v.IsCurrent).IsRequired().HasDefaultValue(false); + + b.HasOne(v => v.PublishedByUser) + .WithMany() + .HasForeignKey(v => v.PublishedBy) + .OnDelete(DeleteBehavior.Restrict); + + b.HasIndex(v => v.IsCurrent).HasFilter("[IsCurrent] = 1"); + } +} + +public class PolicyConsentConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("policy_consents"); + + b.HasKey(c => c.ConsentId); + b.Property(c => c.ConsentId).UseIdentityColumn(); + b.Property(c => c.CustomerId).IsRequired(); + b.Property(c => c.PolicyVersionId).IsRequired(); + b.Property(c => c.AcceptedAt).IsRequired(); + b.Property(c => c.Channel).IsRequired().HasMaxLength(30).HasDefaultValue("WEB_CUSTOMER"); + + b.HasOne(c => c.Customer) + .WithMany() + .HasForeignKey(c => c.CustomerId) + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne(c => c.PolicyVersion) + .WithMany(v => v.Consents) + .HasForeignKey(c => c.PolicyVersionId) + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne(c => c.Reservation) + .WithMany(r => r.PolicyConsents) + .HasForeignKey(c => c.ReservationId) + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne(c => c.Contract) + .WithMany(rc => rc.PolicyConsents) + .HasForeignKey(c => c.ContractId) + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne(c => c.Renewal) + .WithMany(cr => cr.PolicyConsents) + .HasForeignKey(c => c.RenewalId) + .OnDelete(DeleteBehavior.SetNull); + + b.HasIndex(c => new { c.CustomerId, c.PolicyVersionId }); + b.HasIndex(c => c.ReservationId).HasFilter("[ReservationId] IS NOT NULL"); + b.HasIndex(c => c.RenewalId).HasFilter("[RenewalId] IS NOT NULL"); + } +} diff --git a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs index f1efa1d..ac84046 100644 --- a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs +++ b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs @@ -110,7 +110,7 @@ public void Configure(EntityTypeBuilder b) t.HasCheckConstraint("CK_contract_renewals_period", "[RenewalPeriodMonths] > 0"); t.HasCheckConstraint("CK_contract_renewals_amount", "[RenewalAmount] >= 0"); t.HasCheckConstraint("CK_contract_renewals_status", - "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED')"); + "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED','EXPIRED')"); }); b.HasKey(cr => cr.RenewalId); b.Property(cr => cr.RenewalId).UseIdentityColumn(); @@ -122,8 +122,16 @@ public void Configure(EntityTypeBuilder b) b.Property(cr => cr.RenewalAmount).IsRequired().HasColumnType("decimal(15,2)"); b.Property(cr => cr.Status).IsRequired().HasMaxLength(20).HasDefaultValue("PENDING"); b.Property(cr => cr.RequestedAt).IsRequired(); + b.Property(cr => cr.ApprovedAt); + b.Property(cr => cr.PaymentDeadlineAt); + b.Property(cr => cr.AppliedAt); + b.Property(cr => cr.ExpiredAt); + b.Property(cr => cr.PolicyVersion); + b.Property(cr => cr.AcceptedAt); b.Property(cr => cr.CreatedAt).IsRequired(); + b.HasIndex(cr => cr.ContractId).IsUnique().HasFilter("[Status] IN ('PENDING','APPROVED')"); + b.HasOne(cr => cr.Contract).WithMany(rc => rc.ContractRenewals) .HasForeignKey(cr => cr.ContractId).OnDelete(DeleteBehavior.Restrict); b.HasOne(cr => cr.ApprovedByUser).WithMany() @@ -148,6 +156,8 @@ public void Configure(EntityTypeBuilder b) 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.HasIndex(p => p.RenewalId).IsUnique() + .HasFilter("[PaymentType] = 'RENEWAL' AND [RenewalId] IS NOT NULL"); 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 0b251e3..1f39a2d 100644 --- a/StorageProject.Infrastructure/Data/DbSeeder.cs +++ b/StorageProject.Infrastructure/Data/DbSeeder.cs @@ -222,6 +222,7 @@ async Task EnsureUserAsync(string username, string email, string fullName, // 4. Policies await EnsurePoliciesAsync(context, admin.UserId); + await EnsureRentalPolicyVersionsAsync(context, admin.UserId); // 5. Phân công cơ sở (SRS A06: mỗi nhân viên / quản lý 1 cơ sở) await EnsureFacilityAssignmentsAsync(context, catalog.Home.FacilityId, admin.UserId); @@ -397,4 +398,35 @@ public static async Task EnsurePoliciesAsync(AppDbContext context, long adminUse await context.SaveChangesAsync(); } } + + public static async Task EnsureRentalPolicyVersionsAsync(AppDbContext context, long adminUserId) + { + if (!await context.RentalPolicyVersions.AnyAsync()) + { + var defaultSections = new Dictionary + { + ["payment"] = "Hợp đồng và quyền mở kho được cấp sau khi hệ thống xác nhận thanh toán hoặc nhân viên xác nhận đã thu đủ tại quầy. Bạn sử dụng kho từ ngày bắt đầu hợp đồng; kiểm tra ngày bắt đầu, ngày hết hạn và trạng thái thanh toán trong Kho của tôi.", + ["access"] = "QR chỉ sử dụng trong thời hạn hợp đồng. QR hết hiệu lực ngay khi hết hạn thuê hoặc khi yêu cầu trả kho được ghi nhận thành công. Chuyển hết đồ trước khi xác nhận trả kho; cần hỗ trợ ra vào sau đó thì liên hệ nhân viên cơ sở.", + ["renewal"] = "Gửi yêu cầu để cơ sở kiểm tra kỳ thuê tiếp theo. Trong lúc chờ duyệt, ngày hết hạn giữ nguyên. Sau khi duyệt, thanh toán đủ tiền gia hạn qua PayOS hoặc tại quầy để cập nhật kỳ thuê. Không thu lại cọc; yêu cầu bị từ chối hiển thị lý do.", + ["overdue"] = "Nếu quá hạn mà chưa trả kho, mỗi ngày trừ 5% giá trị cọc ban đầu, tối đa 100% cọc. Sau 20 ngày cọc còn 0 đ, nhân viên kho đưa đồ của khách ra ngoài. Khách hàng tự chịu trách nhiệm theo chính sách.", + ["return"] = "Chuyển hết đồ trước khi xác nhận trả kho. Cơ sở kiểm tra kho, nhận lại chìa khóa và lập biên bản. Cọc, khoản chưa thanh toán và phí được đối soát; bạn xem được khấu trừ và số tiền hoàn. Không còn cọc thì số tiền hoàn bằng 0 đ.", + ["cancellation"] = "Trước khi huỷ, kiểm tra điều kiện, khoản khấu trừ và tiền hoàn trên đơn. Chờ hoàn là cơ sở chưa ghi nhận hoàn thành chuyển tiền; Đã hoàn là giao dịch đã được xác nhận. Chưa nhận tiền thì liên hệ cơ sở kèm mã đơn/khoản hoàn.", + ["support"] = "Xem ngày hết hạn, lịch sử thanh toán, lịch trừ cọc và tiến độ trả kho trong tài khoản. Bạn có thể gửi hỗ trợ tới cơ sở liên quan, kể cả khi chưa có hợp đồng, để được tư vấn loại kho phù hợp." + }; + + var initialVersion = new RentalPolicyVersion + { + Version = 1, + DisplayVersion = "11/2026", + Rate = 5.0m, + SectionsJson = System.Text.Json.JsonSerializer.Serialize(defaultSections), + PublishedBy = adminUserId, + PublishedAt = DateTime.UtcNow, + IsCurrent = true + }; + + context.RentalPolicyVersions.Add(initialVersion); + await context.SaveChangesAsync(); + } + } } diff --git a/StorageProject.Infrastructure/Migrations/20261027165711_AddRenewalSettlementAndPolicyConsent.Designer.cs b/StorageProject.Infrastructure/Migrations/20261027165711_AddRenewalSettlementAndPolicyConsent.Designer.cs new file mode 100644 index 0000000..383c485 --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261027165711_AddRenewalSettlementAndPolicyConsent.Designer.cs @@ -0,0 +1,2266 @@ +// +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("20261027165711_AddRenewalSettlementAndPolicyConsent")] + partial class AddRenewalSettlementAndPolicyConsent + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.12") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("StorageProject.Core.Entities.AccessCredential", b => + { + b.Property("CredentialId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("CredentialId")); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CredentialReference") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("CredentialType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("IssuedAt") + .HasColumnType("datetime2"); + + b.Property("IssuedBy") + .HasColumnType("bigint"); + + b.Property("ReturnedAt") + .HasColumnType("datetime2"); + + b.Property("SecretHash") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("CredentialId"); + + b.HasIndex("ContractId"); + + b.HasIndex("IssuedBy"); + + b.HasIndex("UnitId"); + + b.ToTable("access_credentials", null, t => + { + t.HasCheckConstraint("CK_access_credentials_status", "[Status] IN ('ACTIVE','RETURNED','LOST','REVOKED','REPLACED')"); + + t.HasCheckConstraint("CK_access_credentials_type", "[CredentialType] IN ('KEY','LOCK','ACCESS_CARD','ACCESS_CODE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ActivityLog", b => + { + b.Property("LogId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("LogId")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("EntityId") + .HasColumnType("bigint"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("nvarchar(80)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("LoggedAt") + .HasColumnType("datetime2"); + + b.Property("NewValue") + .HasColumnType("nvarchar(max)"); + + b.Property("OldValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("LogId"); + + b.HasIndex("UserId"); + + b.ToTable("activity_logs", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.Property("RenewalId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RenewalId")); + + b.Property("AcceptedAt") + .HasColumnType("datetime2"); + + b.Property("AppliedAt") + .HasColumnType("datetime2"); + + b.Property("ApprovedAt") + .HasColumnType("datetime2"); + + b.Property("ApprovedBy") + .HasColumnType("bigint"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("ExpiredAt") + .HasColumnType("datetime2"); + + b.Property("NewEndDate") + .HasColumnType("date"); + + b.Property("NewMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("OldEndDate") + .HasColumnType("date"); + + b.Property("OldMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("PaymentDeadlineAt") + .HasColumnType("datetime2"); + + b.Property("PolicyVersion") + .HasColumnType("int"); + + b.Property("RenewalAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("RenewalPeriodMonths") + .HasColumnType("int"); + + b.Property("RequestedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PENDING"); + + b.HasKey("RenewalId"); + + b.HasIndex("ApprovedBy"); + + b.HasIndex("ContractId") + .IsUnique() + .HasFilter("[Status] IN ('PENDING','APPROVED')"); + + b.ToTable("contract_renewals", null, t => + { + t.HasCheckConstraint("CK_contract_renewals_amount", "[RenewalAmount] >= 0"); + + t.HasCheckConstraint("CK_contract_renewals_period", "[RenewalPeriodMonths] > 0"); + + t.HasCheckConstraint("CK_contract_renewals_status", "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED','EXPIRED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.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") + .IsUnique() + .HasFilter("[PaymentType] = 'RENEWAL' AND [RenewalId] IS NOT NULL"); + + b.HasIndex("TransactionReference") + .IsUnique() + .HasFilter("[TransactionReference] IS NOT NULL"); + + b.HasIndex("ReservationId", "PaymentType") + .IsUnique() + .HasFilter("[ReservationId] IS NOT NULL AND [PaymentType] IN ('RENT','DEPOSIT')"); + + b.ToTable("payments", null, t => + { + t.HasCheckConstraint("CK_payments_amount", "[Amount] >= 0"); + + t.HasCheckConstraint("CK_payments_payment_method", "[PaymentMethod] IN ('CASH','BANK_TRANSFER','CARD','E_WALLET','PAYMENT_GATEWAY')"); + + t.HasCheckConstraint("CK_payments_payment_type", "[PaymentType] IN ('DEPOSIT','RENT','RENEWAL','EXTRA_FEE','OVERDUE_FEE','DAMAGE_FEE','CLEANING_FEE','LOST_KEY_FEE','ACCESS_CARD_FEE','REFUND')"); + + t.HasCheckConstraint("CK_payments_status", "[Status] IN ('PENDING','PAID','FAILED','REFUNDED','PARTIALLY_REFUNDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.PaymentCheckout", b => + { + b.Property("CheckoutId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("CheckoutId")); + + b.Property("Amount") + .HasColumnType("decimal(15,2)"); + + b.Property("CheckoutUrl") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("ExpiresAt") + .HasColumnType("datetime2"); + + b.Property("OrderCode") + .HasColumnType("bigint"); + + b.Property("PaymentId") + .HasColumnType("bigint"); + + b.Property("Provider") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("PAYOS"); + + b.Property("QrCode") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PENDING"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.HasKey("CheckoutId"); + + b.HasIndex("OrderCode") + .IsUnique(); + + b.HasIndex("PaymentId"); + + b.ToTable("payment_checkouts", null, t => + { + t.HasCheckConstraint("CK_payment_checkouts_amount", "[Amount] >= 0"); + + t.HasCheckConstraint("CK_payment_checkouts_status", "[Status] IN ('PENDING','PAID','CANCELLED','EXPIRED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Permission", b => + { + b.Property("PermissionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PermissionId")); + + b.Property("Description") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PermissionCode") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("nvarchar(80)"); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("PermissionId"); + + b.HasIndex("PermissionCode") + .IsUnique(); + + b.ToTable("permissions", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => + { + b.Property("PolicyId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PolicyId")); + + b.Property("CalculationType") + .HasMaxLength(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.PolicyConsent", b => + { + b.Property("ConsentId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ConsentId")); + + b.Property("AcceptedAt") + .HasColumnType("datetime2"); + + b.Property("Channel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("WEB_CUSTOMER"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("PolicyVersionId") + .HasColumnType("bigint"); + + b.Property("RenewalId") + .HasColumnType("bigint"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.HasKey("ConsentId"); + + b.HasIndex("ContractId"); + + b.HasIndex("PolicyVersionId"); + + b.HasIndex("RenewalId") + .HasFilter("[RenewalId] IS NOT NULL"); + + b.HasIndex("ReservationId") + .HasFilter("[ReservationId] IS NOT NULL"); + + b.HasIndex("CustomerId", "PolicyVersionId"); + + b.ToTable("policy_consents", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.Property("ContractId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ContractId")); + + b.Property("ActivatedAt") + .HasColumnType("datetime2"); + + b.Property("AgreedMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("CompletedAt") + .HasColumnType("datetime2"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("DepositAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("EndDate") + .HasColumnType("date"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.Property("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.RentalPolicyVersion", b => + { + b.Property("PolicyVersionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PolicyVersionId")); + + b.Property("DisplayVersion") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IsCurrent") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("PublishedAt") + .HasColumnType("datetime2"); + + b.Property("PublishedBy") + .HasColumnType("bigint"); + + b.Property("Rate") + .HasColumnType("decimal(5,2)"); + + b.Property("SectionsJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("int"); + + b.HasKey("PolicyVersionId"); + + b.HasIndex("IsCurrent") + .HasFilter("[IsCurrent] = 1"); + + b.HasIndex("PublishedBy"); + + b.HasIndex("Version") + .IsUnique(); + + b.ToTable("rental_policy_versions", null, t => + { + t.HasCheckConstraint("CK_rental_policy_versions_rate", "[Rate] >= 0 AND [Rate] <= 100"); + + t.HasCheckConstraint("CK_rental_policy_versions_version", "[Version] > 0"); + }); + }); + + 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.PaymentCheckout", b => + { + b.HasOne("StorageProject.Core.Entities.Payment", "Payment") + .WithMany("Checkouts") + .HasForeignKey("PaymentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Payment"); + }); + + 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.PolicyConsent", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("PolicyConsents") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany() + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.RentalPolicyVersion", "PolicyVersion") + .WithMany("Consents") + .HasForeignKey("PolicyVersionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.ContractRenewal", "Renewal") + .WithMany("PolicyConsents") + .HasForeignKey("RenewalId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany("PolicyConsents") + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Contract"); + + b.Navigation("Customer"); + + b.Navigation("PolicyVersion"); + + b.Navigation("Renewal"); + + b.Navigation("Reservation"); + }); + + 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.RentalPolicyVersion", b => + { + b.HasOne("StorageProject.Core.Entities.User", "PublishedByUser") + .WithMany() + .HasForeignKey("PublishedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("PublishedByUser"); + }); + + 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"); + + b.Navigation("PolicyConsents"); + }); + + 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.Payment", b => + { + b.Navigation("Checkouts"); + }); + + 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("PolicyConsents"); + + b.Navigation("ReturnInspections"); + + b.Navigation("SupportTickets"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalPolicyVersion", b => + { + b.Navigation("Consents"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.Navigation("PolicyConsents"); + + 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/20261027165711_AddRenewalSettlementAndPolicyConsent.cs b/StorageProject.Infrastructure/Migrations/20261027165711_AddRenewalSettlementAndPolicyConsent.cs new file mode 100644 index 0000000..851fc60 --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261027165711_AddRenewalSettlementAndPolicyConsent.cs @@ -0,0 +1,297 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace StorageProject.Infrastructure.Migrations +{ + /// + public partial class AddRenewalSettlementAndPolicyConsent : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_payments_RenewalId", + table: "payments"); + + migrationBuilder.DropIndex( + name: "IX_contract_renewals_ContractId", + table: "contract_renewals"); + + migrationBuilder.DropCheckConstraint( + name: "CK_contract_renewals_status", + table: "contract_renewals"); + + migrationBuilder.AddColumn( + name: "AcceptedAt", + table: "contract_renewals", + type: "datetime2", + nullable: true); + + migrationBuilder.AddColumn( + name: "AppliedAt", + table: "contract_renewals", + type: "datetime2", + nullable: true); + + migrationBuilder.AddColumn( + name: "ExpiredAt", + table: "contract_renewals", + type: "datetime2", + nullable: true); + + migrationBuilder.AddColumn( + name: "PaymentDeadlineAt", + table: "contract_renewals", + type: "datetime2", + nullable: true); + + migrationBuilder.AddColumn( + name: "PolicyVersion", + table: "contract_renewals", + type: "int", + nullable: true); + + migrationBuilder.CreateTable( + name: "payment_checkouts", + columns: table => new + { + CheckoutId = table.Column(type: "bigint", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PaymentId = table.Column(type: "bigint", nullable: false), + OrderCode = table.Column(type: "bigint", nullable: false), + Provider = table.Column(type: "nvarchar(30)", maxLength: 30, nullable: false, defaultValue: "PAYOS"), + Amount = table.Column(type: "decimal(15,2)", nullable: false), + Status = table.Column(type: "nvarchar(20)", maxLength: 20, nullable: false, defaultValue: "PENDING"), + CheckoutUrl = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), + QrCode = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: true), + ExpiresAt = table.Column(type: "datetime2", nullable: false), + CreatedAt = table.Column(type: "datetime2", nullable: false), + UpdatedAt = table.Column(type: "datetime2", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_payment_checkouts", x => x.CheckoutId); + table.CheckConstraint("CK_payment_checkouts_amount", "[Amount] >= 0"); + table.CheckConstraint("CK_payment_checkouts_status", "[Status] IN ('PENDING','PAID','CANCELLED','EXPIRED')"); + table.ForeignKey( + name: "FK_payment_checkouts_payments_PaymentId", + column: x => x.PaymentId, + principalTable: "payments", + principalColumn: "PaymentId", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "rental_policy_versions", + columns: table => new + { + PolicyVersionId = table.Column(type: "bigint", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Version = table.Column(type: "int", nullable: false), + DisplayVersion = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + Rate = table.Column(type: "decimal(5,2)", nullable: false), + SectionsJson = table.Column(type: "nvarchar(max)", nullable: false), + PublishedBy = table.Column(type: "bigint", nullable: false), + PublishedAt = table.Column(type: "datetime2", nullable: false), + IsCurrent = table.Column(type: "bit", nullable: false, defaultValue: false) + }, + constraints: table => + { + table.PrimaryKey("PK_rental_policy_versions", x => x.PolicyVersionId); + table.CheckConstraint("CK_rental_policy_versions_rate", "[Rate] >= 0 AND [Rate] <= 100"); + table.CheckConstraint("CK_rental_policy_versions_version", "[Version] > 0"); + table.ForeignKey( + name: "FK_rental_policy_versions_users_PublishedBy", + column: x => x.PublishedBy, + principalTable: "users", + principalColumn: "UserId", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "policy_consents", + columns: table => new + { + ConsentId = table.Column(type: "bigint", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + CustomerId = table.Column(type: "bigint", nullable: false), + PolicyVersionId = table.Column(type: "bigint", nullable: false), + ReservationId = table.Column(type: "bigint", nullable: true), + ContractId = table.Column(type: "bigint", nullable: true), + RenewalId = table.Column(type: "bigint", nullable: true), + AcceptedAt = table.Column(type: "datetime2", nullable: false), + Channel = table.Column(type: "nvarchar(30)", maxLength: 30, nullable: false, defaultValue: "WEB_CUSTOMER") + }, + constraints: table => + { + table.PrimaryKey("PK_policy_consents", x => x.ConsentId); + table.ForeignKey( + name: "FK_policy_consents_contract_renewals_RenewalId", + column: x => x.RenewalId, + principalTable: "contract_renewals", + principalColumn: "RenewalId", + onDelete: ReferentialAction.SetNull); + table.ForeignKey( + name: "FK_policy_consents_rental_contracts_ContractId", + column: x => x.ContractId, + principalTable: "rental_contracts", + principalColumn: "ContractId", + onDelete: ReferentialAction.SetNull); + table.ForeignKey( + name: "FK_policy_consents_rental_policy_versions_PolicyVersionId", + column: x => x.PolicyVersionId, + principalTable: "rental_policy_versions", + principalColumn: "PolicyVersionId", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_policy_consents_reservations_ReservationId", + column: x => x.ReservationId, + principalTable: "reservations", + principalColumn: "ReservationId", + onDelete: ReferentialAction.SetNull); + table.ForeignKey( + name: "FK_policy_consents_users_CustomerId", + column: x => x.CustomerId, + principalTable: "users", + principalColumn: "UserId", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "IX_payments_RenewalId", + table: "payments", + column: "RenewalId", + unique: true, + filter: "[PaymentType] = 'RENEWAL' AND [RenewalId] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_contract_renewals_ContractId", + table: "contract_renewals", + column: "ContractId", + unique: true, + filter: "[Status] IN ('PENDING','APPROVED')"); + + migrationBuilder.AddCheckConstraint( + name: "CK_contract_renewals_status", + table: "contract_renewals", + sql: "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED','EXPIRED')"); + + migrationBuilder.CreateIndex( + name: "IX_payment_checkouts_OrderCode", + table: "payment_checkouts", + column: "OrderCode", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_payment_checkouts_PaymentId", + table: "payment_checkouts", + column: "PaymentId"); + + migrationBuilder.CreateIndex( + name: "IX_policy_consents_ContractId", + table: "policy_consents", + column: "ContractId"); + + migrationBuilder.CreateIndex( + name: "IX_policy_consents_CustomerId_PolicyVersionId", + table: "policy_consents", + columns: new[] { "CustomerId", "PolicyVersionId" }); + + migrationBuilder.CreateIndex( + name: "IX_policy_consents_PolicyVersionId", + table: "policy_consents", + column: "PolicyVersionId"); + + migrationBuilder.CreateIndex( + name: "IX_policy_consents_RenewalId", + table: "policy_consents", + column: "RenewalId", + filter: "[RenewalId] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_policy_consents_ReservationId", + table: "policy_consents", + column: "ReservationId", + filter: "[ReservationId] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_rental_policy_versions_IsCurrent", + table: "rental_policy_versions", + column: "IsCurrent", + filter: "[IsCurrent] = 1"); + + migrationBuilder.CreateIndex( + name: "IX_rental_policy_versions_PublishedBy", + table: "rental_policy_versions", + column: "PublishedBy"); + + migrationBuilder.CreateIndex( + name: "IX_rental_policy_versions_Version", + table: "rental_policy_versions", + column: "Version", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "payment_checkouts"); + + migrationBuilder.DropTable( + name: "policy_consents"); + + migrationBuilder.DropTable( + name: "rental_policy_versions"); + + migrationBuilder.DropIndex( + name: "IX_payments_RenewalId", + table: "payments"); + + migrationBuilder.DropIndex( + name: "IX_contract_renewals_ContractId", + table: "contract_renewals"); + + migrationBuilder.DropCheckConstraint( + name: "CK_contract_renewals_status", + table: "contract_renewals"); + + migrationBuilder.DropColumn( + name: "AcceptedAt", + table: "contract_renewals"); + + migrationBuilder.DropColumn( + name: "AppliedAt", + table: "contract_renewals"); + + migrationBuilder.DropColumn( + name: "ExpiredAt", + table: "contract_renewals"); + + migrationBuilder.DropColumn( + name: "PaymentDeadlineAt", + table: "contract_renewals"); + + migrationBuilder.DropColumn( + name: "PolicyVersion", + table: "contract_renewals"); + + migrationBuilder.CreateIndex( + name: "IX_payments_RenewalId", + table: "payments", + column: "RenewalId"); + + migrationBuilder.CreateIndex( + name: "IX_contract_renewals_ContractId", + table: "contract_renewals", + column: "ContractId"); + + migrationBuilder.AddCheckConstraint( + name: "CK_contract_renewals_status", + table: "contract_renewals", + sql: "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED')"); + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index c628ab7..48cda96 100644 --- a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -133,6 +133,12 @@ protected override void BuildModel(ModelBuilder modelBuilder) SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RenewalId")); + b.Property("AcceptedAt") + .HasColumnType("datetime2"); + + b.Property("AppliedAt") + .HasColumnType("datetime2"); + b.Property("ApprovedAt") .HasColumnType("datetime2"); @@ -145,6 +151,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("CreatedAt") .HasColumnType("datetime2"); + b.Property("ExpiredAt") + .HasColumnType("datetime2"); + b.Property("NewEndDate") .HasColumnType("date"); @@ -157,6 +166,12 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("OldMonthlyRate") .HasColumnType("decimal(15,2)"); + b.Property("PaymentDeadlineAt") + .HasColumnType("datetime2"); + + b.Property("PolicyVersion") + .HasColumnType("int"); + b.Property("RenewalAmount") .HasColumnType("decimal(15,2)"); @@ -177,7 +192,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("ApprovedBy"); - b.HasIndex("ContractId"); + b.HasIndex("ContractId") + .IsUnique() + .HasFilter("[Status] IN ('PENDING','APPROVED')"); b.ToTable("contract_renewals", null, t => { @@ -185,7 +202,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) t.HasCheckConstraint("CK_contract_renewals_period", "[RenewalPeriodMonths] > 0"); - t.HasCheckConstraint("CK_contract_renewals_status", "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED')"); + t.HasCheckConstraint("CK_contract_renewals_status", "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED','EXPIRED')"); }); }); @@ -551,7 +568,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("ContractId"); - b.HasIndex("RenewalId"); + b.HasIndex("RenewalId") + .IsUnique() + .HasFilter("[PaymentType] = 'RENEWAL' AND [RenewalId] IS NOT NULL"); b.HasIndex("TransactionReference") .IsUnique() @@ -573,6 +592,69 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("StorageProject.Core.Entities.PaymentCheckout", b => + { + b.Property("CheckoutId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("CheckoutId")); + + b.Property("Amount") + .HasColumnType("decimal(15,2)"); + + b.Property("CheckoutUrl") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("ExpiresAt") + .HasColumnType("datetime2"); + + b.Property("OrderCode") + .HasColumnType("bigint"); + + b.Property("PaymentId") + .HasColumnType("bigint"); + + b.Property("Provider") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("PAYOS"); + + b.Property("QrCode") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PENDING"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.HasKey("CheckoutId"); + + b.HasIndex("OrderCode") + .IsUnique(); + + b.HasIndex("PaymentId"); + + b.ToTable("payment_checkouts", null, t => + { + t.HasCheckConstraint("CK_payment_checkouts_amount", "[Amount] >= 0"); + + t.HasCheckConstraint("CK_payment_checkouts_status", "[Status] IN ('PENDING','PAID','CANCELLED','EXPIRED')"); + }); + }); + modelBuilder.Entity("StorageProject.Core.Entities.Permission", b => { b.Property("PermissionId") @@ -684,6 +766,56 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("StorageProject.Core.Entities.PolicyConsent", b => + { + b.Property("ConsentId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ConsentId")); + + b.Property("AcceptedAt") + .HasColumnType("datetime2"); + + b.Property("Channel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("WEB_CUSTOMER"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("PolicyVersionId") + .HasColumnType("bigint"); + + b.Property("RenewalId") + .HasColumnType("bigint"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.HasKey("ConsentId"); + + b.HasIndex("ContractId"); + + b.HasIndex("PolicyVersionId"); + + b.HasIndex("RenewalId") + .HasFilter("[RenewalId] IS NOT NULL"); + + b.HasIndex("ReservationId") + .HasFilter("[ReservationId] IS NOT NULL"); + + b.HasIndex("CustomerId", "PolicyVersionId"); + + b.ToTable("policy_consents", (string)null); + }); + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => { b.Property("ContractId") @@ -754,6 +886,58 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("StorageProject.Core.Entities.RentalPolicyVersion", b => + { + b.Property("PolicyVersionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PolicyVersionId")); + + b.Property("DisplayVersion") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IsCurrent") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("PublishedAt") + .HasColumnType("datetime2"); + + b.Property("PublishedBy") + .HasColumnType("bigint"); + + b.Property("Rate") + .HasColumnType("decimal(5,2)"); + + b.Property("SectionsJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("int"); + + b.HasKey("PolicyVersionId"); + + b.HasIndex("IsCurrent") + .HasFilter("[IsCurrent] = 1"); + + b.HasIndex("PublishedBy"); + + b.HasIndex("Version") + .IsUnique(); + + b.ToTable("rental_policy_versions", null, t => + { + t.HasCheckConstraint("CK_rental_policy_versions_rate", "[Rate] >= 0 AND [Rate] <= 100"); + + t.HasCheckConstraint("CK_rental_policy_versions_version", "[Version] > 0"); + }); + }); + modelBuilder.Entity("StorageProject.Core.Entities.RentalRate", b => { b.Property("RateId") @@ -1602,6 +1786,17 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Reservation"); }); + modelBuilder.Entity("StorageProject.Core.Entities.PaymentCheckout", b => + { + b.HasOne("StorageProject.Core.Entities.Payment", "Payment") + .WithMany("Checkouts") + .HasForeignKey("PaymentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Payment"); + }); + modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => { b.HasOne("StorageProject.Core.Entities.User", "CreatedByUser") @@ -1627,6 +1822,46 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("UnitType"); }); + modelBuilder.Entity("StorageProject.Core.Entities.PolicyConsent", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("PolicyConsents") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany() + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.RentalPolicyVersion", "PolicyVersion") + .WithMany("Consents") + .HasForeignKey("PolicyVersionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.ContractRenewal", "Renewal") + .WithMany("PolicyConsents") + .HasForeignKey("RenewalId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany("PolicyConsents") + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Contract"); + + b.Navigation("Customer"); + + b.Navigation("PolicyVersion"); + + b.Navigation("Renewal"); + + b.Navigation("Reservation"); + }); + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => { b.HasOne("StorageProject.Core.Entities.User", "Customer") @@ -1654,6 +1889,17 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Unit"); }); + modelBuilder.Entity("StorageProject.Core.Entities.RentalPolicyVersion", b => + { + b.HasOne("StorageProject.Core.Entities.User", "PublishedByUser") + .WithMany() + .HasForeignKey("PublishedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("PublishedByUser"); + }); + modelBuilder.Entity("StorageProject.Core.Entities.RentalRate", b => { b.HasOne("StorageProject.Core.Entities.Facility", "Facility") @@ -1897,6 +2143,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => { b.Navigation("Payments"); + + b.Navigation("PolicyConsents"); }); modelBuilder.Entity("StorageProject.Core.Entities.Facility", b => @@ -1912,6 +2160,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("UserFacilities"); }); + modelBuilder.Entity("StorageProject.Core.Entities.Payment", b => + { + b.Navigation("Checkouts"); + }); + modelBuilder.Entity("StorageProject.Core.Entities.Permission", b => { b.Navigation("RolePermissions"); @@ -1929,13 +2182,22 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Payments"); + b.Navigation("PolicyConsents"); + b.Navigation("ReturnInspections"); b.Navigation("SupportTickets"); }); + modelBuilder.Entity("StorageProject.Core.Entities.RentalPolicyVersion", b => + { + b.Navigation("Consents"); + }); + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => { + b.Navigation("PolicyConsents"); + b.Navigation("RentalContract"); b.Navigation("UnitAssignments"); diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs index 06bb6a0..f979da7 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs @@ -320,20 +320,70 @@ public async Task ApproveRenewalAsync(OpsActor actor, string id, CancellationTok } var now = NowUtc; + var vnToday = DateOnly.FromDateTime(now + VnOffset); + + // Re-check rate at approval time + var activeRate = await dbContext.RentalRates + .Where(rate => rate.FacilityId == contract.Unit.FacilityId + && rate.UnitTypeId == contract.Unit.UnitTypeId + && rate.EffectiveFrom <= vnToday + && (rate.EffectiveTo == null || rate.EffectiveTo >= vnToday)) + .OrderByDescending(rate => rate.EffectiveFrom) + .FirstOrDefaultAsync(ct); + + var newRate = activeRate?.MonthlyRate ?? contract.AgreedMonthlyRate; + r.NewMonthlyRate = newRate; + r.RenewalAmount = newRate * r.RenewalPeriodMonths; + + // Payment deadline: min(now + 24h, 00:00 contract expiry date in Vietnam time) + var contractExpiryVn = r.OldEndDate.ToDateTime(TimeOnly.MinValue); + var contractExpiryUtc = contractExpiryVn.AddHours(-7); + var deadline = now.AddHours(24); + if (contractExpiryUtc < deadline) + { + deadline = contractExpiryUtc; + } + + r.PaymentDeadlineAt = deadline; r.Status = "APPROVED"; r.ApprovedBy = actor.UserId; r.ApprovedAt = now; - contract.EndDate = r.NewEndDate; - if (contract.Status is "EXPIRING" or "OVERDUE") contract.Status = "ACTIVE"; + // EndDate remains OldEndDate! DO NOT CHANGE contract.EndDate on approval! // Khoản gia hạn khách cần thanh toán (hiện ở "Thanh toán" của khách) - dbContext.Payments.Add(new Payment + var payment = await dbContext.Payments + .FirstOrDefaultAsync(p => p.RenewalId == r.RenewalId && p.PaymentType == "RENEWAL", ct); + + if (payment == null) { - ContractId = contract.ContractId, RenewalId = r.RenewalId, PaymentType = "RENEWAL", Amount = r.RenewalAmount, - Currency = "VND", PaymentMethod = "BANK_TRANSFER", DueDate = r.OldEndDate, Status = "PENDING", - CreatedAt = now, UpdatedAt = now + dbContext.Payments.Add(new Payment + { + ContractId = contract.ContractId, + RenewalId = r.RenewalId, + PaymentType = "RENEWAL", + Amount = r.RenewalAmount, + Currency = "VND", + PaymentMethod = "BANK_TRANSFER", + DueDate = r.OldEndDate, + Status = "PENDING", + CreatedAt = now, + UpdatedAt = now + }); + } + else + { + payment.Amount = r.RenewalAmount; + payment.Status = "PENDING"; + payment.UpdatedAt = now; + } + + Log(actor.UserId, LogAction.RenewalApproved, LogEntity.Renewal, r.RenewalId, new { + renewalId = r.RenewalId, + contractId = contract.ContractId, + amount = r.RenewalAmount, + paymentDeadlineAt = deadline, + newEndDate = r.NewEndDate.ToString("yyyy-MM-dd") }); - Log(actor.UserId, LogAction.RenewalApproved, LogEntity.Renewal, r.RenewalId, new { newEndDate = r.NewEndDate.ToString("yyyy-MM-dd") }); await dbContext.SaveChangesAsync(ct); } diff --git a/StorageProject.Infrastructure/Services/ManagerService.cs b/StorageProject.Infrastructure/Services/ManagerService.cs index d076597..76dec9e 100644 --- a/StorageProject.Infrastructure/Services/ManagerService.cs +++ b/StorageProject.Infrastructure/Services/ManagerService.cs @@ -189,19 +189,100 @@ public async Task ApproveRenewalAsync(long userId, string id, CancellationToken { var num = FacilityOpsStateStore.ParseIdNumber(id); var renewal = await dbContext.ContractRenewals - .Include(r => r.Contract) - .FirstOrDefaultAsync(r => r.RenewalId == num, ct); - if (renewal != null) + .Include(r => r.Contract).ThenInclude(c => c.Unit) + .Include(r => r.Payments) + .FirstOrDefaultAsync(r => r.RenewalId == num, ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu gia hạn."); + + var userFacility = await dbContext.UserFacilities + .AsNoTracking() + .FirstOrDefaultAsync(uf => uf.UserId == userId && uf.Status == "ACTIVE", ct) + ?? throw new UnauthorizedAccessException("Bạn chưa được phân công phụ trách cơ sở."); + + if (renewal.Contract.Unit.FacilityId != userFacility.FacilityId) + { + throw new UnauthorizedAccessException("Yêu cầu gia hạn không thuộc cơ sở do bạn phụ trách."); + } + + if (renewal.Status != "PENDING") + { + throw new InvalidOperationException("Yêu cầu này đã được xử lý."); + } + + var contract = renewal.Contract; + if (contract.Status is not ("ACTIVE" or "EXPIRING" or "OVERDUE")) { - renewal.Status = "APPROVED"; - renewal.ApprovedBy = userId; - renewal.ApprovedAt = DateTime.UtcNow; - if (renewal.Contract != null) + throw new InvalidOperationException("Hợp đồng không còn hiệu lực để gia hạn."); + } + + var now = DateTime.UtcNow; + var vnToday = DateOnly.FromDateTime(now.AddHours(7)); + + var activeRate = await dbContext.RentalRates + .Where(rate => rate.FacilityId == contract.Unit.FacilityId + && rate.UnitTypeId == contract.Unit.UnitTypeId + && rate.EffectiveFrom <= vnToday + && (rate.EffectiveTo == null || rate.EffectiveTo >= vnToday)) + .OrderByDescending(rate => rate.EffectiveFrom) + .FirstOrDefaultAsync(ct); + + var newRate = activeRate?.MonthlyRate ?? contract.AgreedMonthlyRate; + renewal.NewMonthlyRate = newRate; + renewal.RenewalAmount = newRate * renewal.RenewalPeriodMonths; + + var contractExpiryVn = renewal.OldEndDate.ToDateTime(TimeOnly.MinValue); + var contractExpiryUtc = contractExpiryVn.AddHours(-7); + var deadline = now.AddHours(24); + if (contractExpiryUtc < deadline) deadline = contractExpiryUtc; + + renewal.PaymentDeadlineAt = deadline; + renewal.Status = "APPROVED"; + renewal.ApprovedBy = userId; + renewal.ApprovedAt = now; + // EndDate remains OldEndDate! DO NOT CHANGE contract.EndDate on approval! + + var payment = renewal.Payments.FirstOrDefault(p => p.PaymentType == "RENEWAL"); + if (payment == null) + { + dbContext.Payments.Add(new Payment { - renewal.Contract.EndDate = renewal.NewEndDate; - } - await dbContext.SaveChangesAsync(ct); + ContractId = contract.ContractId, + RenewalId = renewal.RenewalId, + PaymentType = "RENEWAL", + Amount = renewal.RenewalAmount, + Currency = "VND", + PaymentMethod = "BANK_TRANSFER", + DueDate = renewal.OldEndDate, + Status = "PENDING", + CreatedAt = now, + UpdatedAt = now + }); + } + else + { + payment.Amount = renewal.RenewalAmount; + payment.Status = "PENDING"; + payment.UpdatedAt = now; } + + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = userId, + EntityType = "RENEWAL", + EntityId = renewal.RenewalId, + Action = "RENEWAL_APPROVED", + NewValue = System.Text.Json.JsonSerializer.Serialize(new + { + renewal.RenewalId, + contractId = contract.ContractId, + amount = renewal.RenewalAmount, + paymentDeadlineAt = deadline, + newEndDate = renewal.NewEndDate.ToString("yyyy-MM-dd") + }), + LoggedAt = now + }); + + await dbContext.SaveChangesAsync(ct); } public async Task RejectRenewalAsync(long userId, string id, RejectRenewalRequest request, CancellationToken ct = default) @@ -211,14 +292,42 @@ public async Task RejectRenewalAsync(long userId, string id, RejectRenewalReques throw new ArgumentException("từ chối phải có lý do"); } var num = FacilityOpsStateStore.ParseIdNumber(id); - var renewal = await dbContext.ContractRenewals.FindAsync([num], ct); - if (renewal != null) + var renewal = await dbContext.ContractRenewals + .Include(r => r.Contract).ThenInclude(c => c.Unit) + .FirstOrDefaultAsync(r => r.RenewalId == num, ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu gia hạn."); + + var userFacility = await dbContext.UserFacilities + .AsNoTracking() + .FirstOrDefaultAsync(uf => uf.UserId == userId && uf.Status == "ACTIVE", ct) + ?? throw new UnauthorizedAccessException("Bạn chưa được phân công phụ trách cơ sở."); + + if (renewal.Contract.Unit.FacilityId != userFacility.FacilityId) { - renewal.Status = "REJECTED"; - renewal.ApprovedBy = userId; - renewal.ApprovedAt = DateTime.UtcNow; - await dbContext.SaveChangesAsync(ct); + throw new UnauthorizedAccessException("Yêu cầu gia hạn không thuộc cơ sở do bạn phụ trách."); } + + if (renewal.Status != "PENDING") + { + throw new InvalidOperationException("Yêu cầu này đã được xử lý."); + } + + var now = DateTime.UtcNow; + renewal.Status = "REJECTED"; + renewal.ApprovedBy = userId; + renewal.ApprovedAt = now; + + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = userId, + EntityType = "RENEWAL", + EntityId = renewal.RenewalId, + Action = "RENEWAL_REJECTED", + NewValue = System.Text.Json.JsonSerializer.Serialize(new { renewal.RenewalId, reason = request.Reason }), + LoggedAt = now + }); + + await dbContext.SaveChangesAsync(ct); } public async Task AddContractReminderAsync(long userId, string id, AddReminderRequest request, CancellationToken ct = default) diff --git a/StorageProject.Infrastructure/Services/PayOSGateway.cs b/StorageProject.Infrastructure/Services/PayOSGateway.cs index 4ac4f76..ad1d829 100644 --- a/StorageProject.Infrastructure/Services/PayOSGateway.cs +++ b/StorageProject.Infrastructure/Services/PayOSGateway.cs @@ -6,12 +6,14 @@ namespace StorageProject.Infrastructure.Services; -public record VerifiedReservationPayment(long OrderCode, decimal Amount); +public record VerifiedReservationPayment(long OrderCode, decimal Amount, string? TransactionReference = null); 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 CreateRenewalAsync(long orderCode, int amount, long renewalId, long expiresAt, string returnUrl, string cancelUrl) + => CreateAsync(orderCode, amount, renewalId, expiresAt, returnUrl, cancelUrl); Task CancelAsync(long orderCode); Task VerifyAsync(string body); } @@ -39,6 +41,15 @@ public async Task CreateAsync(long orderCode, int amount, long res return new CheckoutLink(result.CheckoutUrl, result.QrCode); } + public async Task CreateRenewalAsync(long orderCode, int amount, long renewalId, long expiresAt, string returnUrl, string cancelUrl) + { + var result = await Client().PaymentRequests.CreateAsync(new CreatePaymentLinkRequest { + OrderCode = orderCode, Amount = amount, Description = $"Gia han #{renewalId}", + ReturnUrl = returnUrl, CancelUrl = cancelUrl, ExpiredAt = (int)expiresAt + }); + return new CheckoutLink(result.CheckoutUrl, result.QrCode); + } + public async Task CancelAsync(long orderCode) { var client = Client(); diff --git a/StorageProject.Infrastructure/Services/PayOSService.cs b/StorageProject.Infrastructure/Services/PayOSService.cs index f0f7bf8..8fc5a48 100644 --- a/StorageProject.Infrastructure/Services/PayOSService.cs +++ b/StorageProject.Infrastructure/Services/PayOSService.cs @@ -100,41 +100,214 @@ public async Task PayAtFacilityAsync(long customerId, long reservationId, Cancel await tx.CommitAsync(ct); } + public async Task CreateRenewalPaymentQrAsync(long customerId, long paymentId, CancellationToken ct = default) + { + var payment = await dbContext.Payments + .Include(p => p.Contract) + .Include(p => p.Renewal) + .FirstOrDefaultAsync(p => p.PaymentId == paymentId && p.Contract.CustomerId == customerId, ct) + ?? throw new InvalidOperationException("Không tìm thấy thông tin khoản thanh toán của bạn."); + + if (payment.PaymentType != "RENEWAL" || payment.Status != "PENDING") + { + throw new InvalidOperationException("Khoản thanh toán không ở trạng thái chờ thanh toán gia hạn."); + } + + var renewal = payment.Renewal + ?? throw new InvalidOperationException("Khoản thanh toán không gắn với yêu cầu gia hạn."); + + if (renewal.Status != "APPROVED") + { + throw new InvalidOperationException("Yêu cầu gia hạn chưa được quản lý phê duyệt."); + } + + var now = DateTime.UtcNow; + if (renewal.PaymentDeadlineAt.HasValue && now >= renewal.PaymentDeadlineAt.Value) + { + throw new InvalidOperationException("Yêu cầu gia hạn đã hết hạn thanh toán."); + } + + // Return existing active checkout if available + var existing = await dbContext.PaymentCheckouts + .FirstOrDefaultAsync(c => c.PaymentId == paymentId && c.Status == "PENDING" && c.ExpiresAt > now, ct); + + if (existing != null && !string.IsNullOrEmpty(existing.CheckoutUrl) && !string.IsNullOrEmpty(existing.QrCode)) + { + return new PayosCheckoutDto( + OrderCode: existing.OrderCode, + Amount: existing.Amount, + Description: $"Gia han #{renewal.RenewalId}", + Status: existing.Status, + QrCode: existing.QrCode, + CheckoutUrl: existing.CheckoutUrl, + ExpiredAt: existing.ExpiresAt, + PaymentId: payment.PaymentId, + RenewalId: renewal.RenewalId + ); + } + + gateway.EnsureConfigured(); + + var maxExpiry = renewal.PaymentDeadlineAt ?? now.AddHours(24); + var expiry = now.AddMinutes(15); + if (maxExpiry < expiry) + { + expiry = maxExpiry; + } + + var orderCode = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 100 + Random.Shared.Next(100); + + var checkout = new PaymentCheckout + { + PaymentId = payment.PaymentId, + OrderCode = orderCode, + Provider = "PAYOS", + Amount = payment.Amount, + Status = "PENDING", + ExpiresAt = expiry, + CreatedAt = now, + UpdatedAt = now + }; + + dbContext.PaymentCheckouts.Add(checkout); + await dbContext.SaveChangesAsync(ct); + + CheckoutLink link; + try + { + var frontendBaseUrl = configuration?["AppSettings:FrontendUrl"]?.TrimEnd('/') + ?? configuration?["Frontend:BaseUrl"]?.TrimEnd('/') + ?? "http://localhost:5173"; + var defaultReturnUrl = $"{frontendBaseUrl}/#/payments"; + + link = await gateway.CreateRenewalAsync( + orderCode, + (int)payment.Amount, + renewal.RenewalId, + new DateTimeOffset(DateTime.SpecifyKind(expiry, DateTimeKind.Utc)).ToUnixTimeSeconds(), + defaultReturnUrl, + defaultReturnUrl + ); + } + catch (Exception ex) + { + throw new InvalidOperationException("Không tạo được link PayOS cho khoản gia hạn. Kiểm tra cấu hình hoặc chọn thanh toán tại quầy.", ex); + } + + checkout.CheckoutUrl = link.Url; + checkout.QrCode = link.Qr; + await dbContext.SaveChangesAsync(ct); + + return new PayosCheckoutDto( + OrderCode: orderCode, + Amount: payment.Amount, + Description: $"Gia han #{renewal.RenewalId}", + Status: "PENDING", + QrCode: link.Qr, + CheckoutUrl: link.Url, + ExpiredAt: expiry, + PaymentId: payment.PaymentId, + RenewalId: renewal.RenewalId + ); + } + public async Task ProcessWebhookAsync(string webhookBodyJson, string? signatureHeader, CancellationToken ct = default) { 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) + + var resId = 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) + + var checkout = await dbContext.PaymentCheckouts + .Include(c => c.Payment).ThenInclude(p => p.Renewal) + .FirstOrDefaultAsync(c => c.OrderCode == verified.OrderCode, ct); + + // Collision check + if (resId != null && checkout != null) + { + logger.LogError("Critical collision: OrderCode {OrderCode} matches both a reservation and a payment checkout!", verified.OrderCode); + return false; + } + + if (resId == null && checkout == null) + { + logger.LogWarning("Unknown PayOS order {OrderCode}", verified.OrderCode); + return false; + } + + // Branch 1: Reservation settlement (untouched D23/D26 flow) + if (resId != null) { - await ContractProvisioning.EnsureAsync(dbContext, r, null, ct); + var id = resId.Value; + 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 ContractProvisioning.EnsureAsync(dbContext, r, null, ct); + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); // Re-delivery of the same verified order: no additional money or allocation. + return true; + } + if (r.PaymentMethod == "AT_FACILITY" || r.Status != "PENDING_PAYMENT" || r.ExpiresAt <= DateTime.UtcNow) + { + 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 }); + } + else await ReservationSettlement.RecordAsync(dbContext, r, "PAYMENT_GATEWAY", $"PAYOS:{verified.OrderCode}", null, ct); await dbContext.SaveChangesAsync(ct); - await tx.CommitAsync(ct); // Re-delivery of the same verified order: no additional money or allocation. + if (r.PaymentMethod == "PAYOS" && r.PaidAt != null) + await ContractProvisioning.EnsureAsync(dbContext, r, null, ct); + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); return true; } - if (r.PaymentMethod == "AT_FACILITY" || r.Status != "PENDING_PAYMENT" || r.ExpiresAt <= DateTime.UtcNow) + + // Branch 2: Renewal checkout settlement + if (checkout != null) { - 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 }); + var payment = checkout.Payment; + var renewal = payment?.Renewal; + if (payment == null || renewal == null) + { + logger.LogWarning("Payment checkout {OrderCode} missing payment or renewal", verified.OrderCode); + return false; + } + + var contractId = payment.ContractId + ?? throw new InvalidOperationException("Khoản thanh toán gia hạn không gắn với hợp đồng."); + + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"contract:{contractId}", ct); + + if (verified.Amount != checkout.Amount) + { + logger.LogWarning("Amount mismatch for PayOS renewal order {OrderCode}: expected {Expected}, got {Actual}", + verified.OrderCode, checkout.Amount, verified.Amount); + return false; + } + + var settled = await RenewalSettlement.RecordAsync( + dbContext, + contractId, + renewal.RenewalId, + "PAYMENT_GATEWAY", + $"PAYOS:{verified.OrderCode}", + null, + ct + ); + + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + return settled; } - else await ReservationSettlement.RecordAsync(dbContext, r, "PAYMENT_GATEWAY", $"PAYOS:{verified.OrderCode}", null, ct); - await dbContext.SaveChangesAsync(ct); - if (r.PaymentMethod == "PAYOS" && r.PaidAt != null) - await ContractProvisioning.EnsureAsync(dbContext, r, null, ct); - await dbContext.SaveChangesAsync(ct); - await tx.CommitAsync(ct); - return true; + + return false; } public async Task GetReservationPaymentStatusAsync(long reservationId, CancellationToken ct = default) diff --git a/StorageProject.Infrastructure/Services/PaymentService.cs b/StorageProject.Infrastructure/Services/PaymentService.cs index 46a411d..f2a0903 100644 --- a/StorageProject.Infrastructure/Services/PaymentService.cs +++ b/StorageProject.Infrastructure/Services/PaymentService.cs @@ -34,7 +34,8 @@ public async Task> GetContractPaymentsAsync(long custo p.DueDate, p.PaidAt, p.Status, - p.CreatedAt + p.CreatedAt, + p.Renewal != null ? p.Renewal.PaymentDeadlineAt : null )) .ToListAsync(ct); } @@ -44,6 +45,7 @@ public async Task> GetContractPaymentsAsync(long custo var p = await dbContext.Payments .AsNoTracking() .Include(x => x.Contract) + .Include(x => x.Renewal) .Where(x => x.PaymentId == paymentId && ((x.ContractId != null && x.Contract.CustomerId == customerId) || (x.ReservationId != null && x.Reservation.CustomerId == customerId))) .FirstOrDefaultAsync(ct); @@ -61,7 +63,8 @@ public async Task> GetContractPaymentsAsync(long custo p.DueDate, p.PaidAt, p.Status, - p.CreatedAt + p.CreatedAt, + p.Renewal?.PaymentDeadlineAt ); } } diff --git a/StorageProject.Infrastructure/Services/RenewalService.cs b/StorageProject.Infrastructure/Services/RenewalService.cs index de0d153..c949a12 100644 --- a/StorageProject.Infrastructure/Services/RenewalService.cs +++ b/StorageProject.Infrastructure/Services/RenewalService.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using Microsoft.EntityFrameworkCore; using StorageProject.Core.DTOs.Renewal; using StorageProject.Core.Entities; @@ -6,7 +7,7 @@ namespace StorageProject.Infrastructure.Services; -public class RenewalService(AppDbContext dbContext) : IRenewalService +public class RenewalService(AppDbContext dbContext, IPayOSGateway gateway) : IRenewalService { public async Task> GetContractRenewalsAsync(long customerId, long contractId, CancellationToken ct = default) { @@ -33,7 +34,13 @@ public async Task> GetContractRenewalsAsync(long custo r.RenewalAmount, r.Status, r.RequestedAt, - r.ApprovedAt + r.ApprovedAt, + r.PaymentDeadlineAt, + r.AppliedAt, + r.ExpiredAt, + r.Payments.Where(p => p.PaymentType == "RENEWAL").Select(p => (long?)p.PaymentId).FirstOrDefault(), + r.PolicyVersion, + r.AcceptedAt )) .ToListAsync(ct); } @@ -56,13 +63,44 @@ public async Task RequestRenewalAsync(long customerId, long contract throw new InvalidOperationException($"Chỉ hợp đồng ở trạng thái 'ACTIVE' mới có thể gia hạn. Trạng thái hiện tại: {contract.Status}"); } - // Check if there is already a pending renewal - var hasPendingRenewal = await dbContext.ContractRenewals - .AnyAsync(r => r.ContractId == contractId && r.Status == "PENDING", ct); + // Vietnam time now + var vnToday = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + if (contract.EndDate <= vnToday) + { + throw new InvalidOperationException("Hợp đồng đã đến hoặc quá ngày hết hạn, không thể gửi yêu cầu gia hạn."); + } + + // Check if there is already a pending or approved renewal open + var hasOpenRenewal = await dbContext.ContractRenewals + .AnyAsync(r => r.ContractId == contractId && (r.Status == "PENDING" || r.Status == "APPROVED"), ct); + + if (hasOpenRenewal) + { + throw new InvalidOperationException("Hợp đồng đã có yêu cầu gia hạn đang chờ xử lý hoặc chờ thanh toán."); + } - if (hasPendingRenewal) + // Policy consent verification + int? consentVersion = null; + DateTime? consentAcceptedAt = null; + if (request.PolicyVersion.HasValue) { - throw new InvalidOperationException("Hợp đồng đã có yêu cầu gia hạn đang chờ xử lý."); + if (request.Accepted != true) + { + throw new ArgumentException("Bạn phải đồng ý với chính sách cho thuê để gửi yêu cầu gia hạn."); + } + + var currentPolicy = await dbContext.RentalPolicyVersions + .OrderByDescending(v => v.Version) + .FirstOrDefaultAsync(v => v.IsCurrent, ct); + + var expectedVersion = currentPolicy?.Version ?? 1; + if (request.PolicyVersion.Value != expectedVersion) + { + throw new InvalidOperationException("Phiên bản chính sách không còn hiệu lực. Vui lòng tải lại trang để chấp thuận bản mới nhất."); + } + + consentVersion = expectedVersion; + consentAcceptedAt = DateTime.UtcNow; } var today = DateOnly.FromDateTime(DateTime.UtcNow); @@ -88,14 +126,331 @@ public async Task RequestRenewalAsync(long customerId, long contract OldMonthlyRate = contract.AgreedMonthlyRate, NewMonthlyRate = newRate, RenewalAmount = renewalAmount, - Status = "PENDING", // chờ quản lý cơ sở duyệt (M03); CHECK chỉ cho PENDING/APPROVED/REJECTED/PAID/CANCELLED + Status = "PENDING", RequestedAt = DateTime.UtcNow, + PolicyVersion = consentVersion, + AcceptedAt = consentAcceptedAt, CreatedAt = DateTime.UtcNow }; dbContext.ContractRenewals.Add(renewal); await dbContext.SaveChangesAsync(ct); + if (consentVersion.HasValue) + { + var policyVer = await dbContext.RentalPolicyVersions + .FirstOrDefaultAsync(v => v.Version == consentVersion.Value, ct); + + dbContext.PolicyConsents.Add(new PolicyConsent + { + CustomerId = customerId, + PolicyVersionId = policyVer?.PolicyVersionId ?? 1, + RenewalId = renewal.RenewalId, + ContractId = contract.ContractId, + AcceptedAt = consentAcceptedAt!.Value, + Channel = "WEB_CUSTOMER" + }); + await dbContext.SaveChangesAsync(ct); + } + + return new RenewalDto( + renewal.RenewalId, + renewal.ContractId, + renewal.OldEndDate, + renewal.NewEndDate, + renewal.RenewalPeriodMonths, + renewal.OldMonthlyRate, + renewal.NewMonthlyRate, + renewal.RenewalAmount, + renewal.Status, + renewal.RequestedAt, + renewal.ApprovedAt, + renewal.PaymentDeadlineAt, + renewal.AppliedAt, + renewal.ExpiredAt, + null, + renewal.PolicyVersion, + renewal.AcceptedAt + ); + } + + public async Task SelectCounterPaymentAsync(long customerId, long renewalId, CancellationToken ct = default) + { + var renewal = await dbContext.ContractRenewals + .Include(r => r.Contract) + .Include(r => r.Payments) + .FirstOrDefaultAsync(r => r.RenewalId == renewalId && r.Contract.CustomerId == customerId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu gia hạn của bạn."); + + if (renewal.Status != "APPROVED") + { + throw new InvalidOperationException($"Chỉ yêu cầu gia hạn ở trạng thái 'APPROVED' mới có thể chọn thanh toán tại quầy. Trạng thái hiện tại: {renewal.Status}"); + } + + var now = DateTime.UtcNow; + if (renewal.PaymentDeadlineAt.HasValue && now >= renewal.PaymentDeadlineAt.Value) + { + throw new InvalidOperationException("Yêu cầu gia hạn đã hết hạn thanh toán."); + } + + // Cancel any open PayOS link + var payment = renewal.Payments.FirstOrDefault(p => p.PaymentType == "RENEWAL" && p.Status == "PENDING") + ?? throw new InvalidOperationException("Không tìm thấy khoản thanh toán gia hạn chờ xử lý."); + + var openCheckouts = await dbContext.PaymentCheckouts + .Where(c => c.PaymentId == payment.PaymentId && c.Status == "PENDING") + .ToListAsync(ct); + + foreach (var c in openCheckouts) + { + try + { + await gateway.CancelAsync(c.OrderCode); + } + catch (Exception ex) + { + throw new InvalidOperationException("Chưa xác nhận huỷ được link PayOS. Vui lòng thử lại trước khi đổi sang thanh toán tại quầy.", ex); + } + c.Status = "CANCELLED"; + c.UpdatedAt = now; + } + + payment.PaymentMethod = "CASH"; + payment.UpdatedAt = now; + + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = customerId, + EntityType = "RENEWAL", + EntityId = renewal.RenewalId, + Action = "COUNTER_PAYMENT_SELECTED", + NewValue = JsonSerializer.Serialize(new { renewal.RenewalId, payment.PaymentId, payment.Amount }), + LoggedAt = now + }); + + await dbContext.SaveChangesAsync(ct); + + return new RenewalDto( + renewal.RenewalId, + renewal.ContractId, + renewal.OldEndDate, + renewal.NewEndDate, + renewal.RenewalPeriodMonths, + renewal.OldMonthlyRate, + renewal.NewMonthlyRate, + renewal.RenewalAmount, + renewal.Status, + renewal.RequestedAt, + renewal.ApprovedAt, + renewal.PaymentDeadlineAt, + renewal.AppliedAt, + renewal.ExpiredAt, + payment.PaymentId, + renewal.PolicyVersion, + renewal.AcceptedAt + ); + } + + public async Task> GetCounterRenewalsAsync(long userId, CancellationToken ct = default) + { + var userFacility = await dbContext.UserFacilities + .AsNoTracking() + .FirstOrDefaultAsync(uf => uf.UserId == userId && uf.Status == "ACTIVE", ct); + + if (userFacility == null) return []; + + var facilityId = userFacility.FacilityId; + var now = DateTime.UtcNow; + + var renewals = await dbContext.ContractRenewals + .AsNoTracking() + .Include(r => r.Contract).ThenInclude(c => c.Customer) + .Include(r => r.Contract).ThenInclude(c => c.Unit) + .Include(r => r.Payments) + .Where(r => r.Contract.Unit.FacilityId == facilityId + && (r.Status == "APPROVED" || (r.Status == "PAID" && r.AppliedAt >= now.AddDays(-1))) + && r.Payments.Any(p => p.PaymentType == "RENEWAL" && p.PaymentMethod == "CASH")) + .OrderByDescending(r => r.RequestedAt) + .ToListAsync(ct); + + var list = new List(); + foreach (var r in renewals) + { + var p = r.Payments.FirstOrDefault(x => x.PaymentType == "RENEWAL"); + if (p == null) continue; + + // Only show if not expired + if (r.Status == "APPROVED" && r.PaymentDeadlineAt.HasValue && r.PaymentDeadlineAt.Value <= now) + { + continue; + } + + list.Add(new CounterRenewalDto( + Id: $"GHQ-{r.RenewalId:D4}", + RenewalId: r.RenewalId, + PaymentId: p.PaymentId, + ContractId: $"HĐ-{r.ContractId:D4}", + ContractCode: $"HĐ-{r.ContractId:D4}", + FacilityId: facilityId, + Unit: r.Contract.Unit?.UnitNumber ?? "—", + Customer: r.Contract.Customer?.FullName ?? "—", + Amount: r.RenewalAmount, + Months: r.RenewalPeriodMonths, + PaymentDeadlineAt: r.PaymentDeadlineAt, + Status: r.Status == "PAID" ? "PAID" : "PENDING" + )); + } + + return list; + } + + public async Task CollectCounterRenewalAsync(long userId, string id, CancellationToken ct = default) + { + var userFacility = await dbContext.UserFacilities + .AsNoTracking() + .FirstOrDefaultAsync(uf => uf.UserId == userId && uf.Status == "ACTIVE", ct) + ?? throw new UnauthorizedAccessException("Bạn chưa được phân công phụ trách cơ sở."); + + var renewalId = FacilityOpsStateStore.ParseIdNumber(id); + var renewal = await dbContext.ContractRenewals + .Include(r => r.Contract).ThenInclude(c => c.Unit) + .FirstOrDefaultAsync(r => r.RenewalId == renewalId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu gia hạn."); + + if (renewal.Contract.Unit.FacilityId != userFacility.FacilityId) + { + throw new UnauthorizedAccessException("Yêu cầu gia hạn không thuộc cơ sở do bạn phụ trách."); + } + + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"contract:{renewal.ContractId}", ct); + + var success = await RenewalSettlement.RecordAsync( + dbContext, + renewal.ContractId, + renewal.RenewalId, + "CASH", + $"CASH:{userId}:{DateTime.UtcNow.Ticks}", + userId, + ct + ); + + if (!success) + { + throw new InvalidOperationException("Không thể xác nhận thu tiền (đã thanh toán hoặc quá hạn thanh toán)."); + } + + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + } + + public async Task ApproveRenewalAsync(long userId, long renewalId, CancellationToken ct = default) + { + var renewal = await dbContext.ContractRenewals + .Include(r => r.Contract).ThenInclude(c => c.Unit) + .Include(r => r.Payments) + .FirstOrDefaultAsync(r => r.RenewalId == renewalId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu gia hạn."); + + var userFacility = await dbContext.UserFacilities + .AsNoTracking() + .FirstOrDefaultAsync(uf => uf.UserId == userId && uf.Status == "ACTIVE", ct) + ?? throw new UnauthorizedAccessException("Bạn chưa được phân công phụ trách cơ sở."); + + if (renewal.Contract.Unit.FacilityId != userFacility.FacilityId) + { + throw new UnauthorizedAccessException("Yêu cầu gia hạn không thuộc cơ sở do bạn phụ trách."); + } + + if (renewal.Status != "PENDING") + { + throw new InvalidOperationException("Yêu cầu này đã được xử lý."); + } + + var contract = renewal.Contract; + if (contract.Status is not ("ACTIVE" or "EXPIRING" or "OVERDUE")) + { + throw new InvalidOperationException("Hợp đồng không còn hiệu lực để gia hạn."); + } + + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"contract:{contract.ContractId}", ct); + + var now = DateTime.UtcNow; + var vnToday = DateOnly.FromDateTime(now.AddHours(7)); + + // Re-check rate at approval time + var activeRate = await dbContext.RentalRates + .Where(r => r.FacilityId == contract.Unit.FacilityId + && r.UnitTypeId == contract.Unit.UnitTypeId + && r.EffectiveFrom <= vnToday + && (r.EffectiveTo == null || r.EffectiveTo >= vnToday)) + .OrderByDescending(r => r.EffectiveFrom) + .FirstOrDefaultAsync(ct); + + var newRate = activeRate?.MonthlyRate ?? contract.AgreedMonthlyRate; + renewal.NewMonthlyRate = newRate; + renewal.RenewalAmount = newRate * renewal.RenewalPeriodMonths; + + // Payment deadline: min(now + 24h, 00:00 contract expiry date in Vietnam time) + var contractExpiryVn = renewal.OldEndDate.ToDateTime(TimeOnly.MinValue); + var contractExpiryUtc = contractExpiryVn.AddHours(-7); + var deadline = now.AddHours(24); + if (contractExpiryUtc < deadline) + { + deadline = contractExpiryUtc; + } + + renewal.PaymentDeadlineAt = deadline; + renewal.Status = "APPROVED"; + renewal.ApprovedBy = userId; + renewal.ApprovedAt = now; + // EndDate remains OldEndDate! + + // Ensure single RENEWAL payment + var payment = renewal.Payments.FirstOrDefault(p => p.PaymentType == "RENEWAL"); + if (payment == null) + { + payment = new Payment + { + ContractId = contract.ContractId, + RenewalId = renewal.RenewalId, + PaymentType = "RENEWAL", + Amount = renewal.RenewalAmount, + Currency = "VND", + PaymentMethod = "BANK_TRANSFER", + DueDate = renewal.OldEndDate, + Status = "PENDING", + CreatedAt = now, + UpdatedAt = now + }; + dbContext.Payments.Add(payment); + } + else + { + payment.Amount = renewal.RenewalAmount; + payment.Status = "PENDING"; + payment.UpdatedAt = now; + } + + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = userId, + EntityType = "RENEWAL", + EntityId = renewal.RenewalId, + Action = "RENEWAL_APPROVED", + NewValue = JsonSerializer.Serialize(new + { + renewal.RenewalId, + contractId = contract.ContractId, + amount = renewal.RenewalAmount, + paymentDeadlineAt = deadline, + newEndDate = renewal.NewEndDate.ToString("yyyy-MM-dd") + }), + LoggedAt = now + }); + + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + return new RenewalDto( renewal.RenewalId, renewal.ContractId, @@ -107,7 +462,103 @@ public async Task RequestRenewalAsync(long customerId, long contract renewal.RenewalAmount, renewal.Status, renewal.RequestedAt, - renewal.ApprovedAt + renewal.ApprovedAt, + renewal.PaymentDeadlineAt, + renewal.AppliedAt, + renewal.ExpiredAt, + payment.PaymentId, + renewal.PolicyVersion, + renewal.AcceptedAt ); } + + public async Task RejectRenewalAsync(long userId, long renewalId, string reason, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(reason)) + { + throw new ArgumentException("Nhập lý do từ chối để gửi cho khách hàng."); + } + + var renewal = await dbContext.ContractRenewals + .Include(r => r.Contract).ThenInclude(c => c.Unit) + .FirstOrDefaultAsync(r => r.RenewalId == renewalId, ct) + ?? throw new KeyNotFoundException("Không tìm thấy yêu cầu gia hạn."); + + var userFacility = await dbContext.UserFacilities + .AsNoTracking() + .FirstOrDefaultAsync(uf => uf.UserId == userId && uf.Status == "ACTIVE", ct) + ?? throw new UnauthorizedAccessException("Bạn chưa được phân công phụ trách cơ sở."); + + if (renewal.Contract.Unit.FacilityId != userFacility.FacilityId) + { + throw new UnauthorizedAccessException("Yêu cầu gia hạn không thuộc cơ sở do bạn phụ trách."); + } + + if (renewal.Status != "PENDING") + { + throw new InvalidOperationException("Yêu cầu này đã được xử lý."); + } + + var now = DateTime.UtcNow; + renewal.Status = "REJECTED"; + renewal.ApprovedBy = userId; + renewal.ApprovedAt = now; + + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = userId, + EntityType = "RENEWAL", + EntityId = renewal.RenewalId, + Action = "RENEWAL_REJECTED", + NewValue = JsonSerializer.Serialize(new { renewal.RenewalId, reason }), + LoggedAt = now + }); + + await dbContext.SaveChangesAsync(ct); + } + + public async Task ExpirePendingRenewalsAsync(CancellationToken ct = default) + { + var now = DateTime.UtcNow; + var expiredRenewals = await dbContext.ContractRenewals + .Include(r => r.Payments) + .Where(r => r.Status == "APPROVED" && r.PaymentDeadlineAt.HasValue && r.PaymentDeadlineAt.Value <= now) + .ToListAsync(ct); + + foreach (var r in expiredRenewals) + { + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"contract:{r.ContractId}", ct); + + r.Status = "EXPIRED"; + r.ExpiredAt = now; + + foreach (var p in r.Payments.Where(p => p.PaymentType == "RENEWAL" && p.Status == "PENDING")) + { + p.Status = "FAILED"; + p.UpdatedAt = now; + + var checkouts = await dbContext.PaymentCheckouts + .Where(c => c.PaymentId == p.PaymentId && c.Status == "PENDING") + .ToListAsync(ct); + + foreach (var c in checkouts) + { + c.Status = "EXPIRED"; + c.UpdatedAt = now; + } + } + + dbContext.ActivityLogs.Add(new ActivityLog + { + EntityType = "RENEWAL", + EntityId = r.RenewalId, + Action = "RENEWAL_EXPIRED", + NewValue = JsonSerializer.Serialize(new { r.RenewalId, r.ContractId, reason = "PAYMENT_DEADLINE_EXCEEDED" }), + LoggedAt = now + }); + + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + } + } } diff --git a/StorageProject.Infrastructure/Services/RenewalSettlement.cs b/StorageProject.Infrastructure/Services/RenewalSettlement.cs new file mode 100644 index 0000000..be27180 --- /dev/null +++ b/StorageProject.Infrastructure/Services/RenewalSettlement.cs @@ -0,0 +1,172 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +public static class RenewalSettlement +{ + public static async Task RecordAsync( + AppDbContext db, + long contractId, + long renewalId, + string paymentMethod, + string transactionRef, + long? staffUserId, + CancellationToken ct) + { + var renewal = await db.ContractRenewals + .Include(r => r.Contract) + .Include(r => r.Payments) + .SingleOrDefaultAsync(r => r.RenewalId == renewalId && r.ContractId == contractId, ct) + ?? throw new InvalidOperationException("Không tìm thấy yêu cầu gia hạn hợp đồng."); + + var contract = renewal.Contract; + var now = DateTime.UtcNow; + + // 1. Idempotency check + if (renewal.Status == "PAID" && renewal.AppliedAt != null) + { + var existingPaid = renewal.Payments.FirstOrDefault(p => p.PaymentType == "RENEWAL" && p.Status == "PAID"); + if (existingPaid != null && existingPaid.TransactionReference == transactionRef) + { + // Re-delivery of the exact same payment: idempotent success + return true; + } + + // A second distinct payment on an already-paid renewal requires manual review + var detail = JsonSerializer.Serialize(new + { + contractId, + renewalId, + paymentMethod, + transactionRef, + reason = "Giao dịch thanh toán lặp hoặc khác tham chiếu trên gia hạn đã được áp dụng; cần đối soát thủ công." + }); + + if (!await db.ActivityLogs.AnyAsync(l => l.EntityType == "RENEWAL" && l.EntityId == renewalId && + l.Action == "PAYMENT_REVIEW_REQUIRED" && l.NewValue == detail, ct)) + { + db.ActivityLogs.Add(new ActivityLog + { + UserId = staffUserId, + EntityType = "RENEWAL", + EntityId = renewalId, + Action = "PAYMENT_REVIEW_REQUIRED", + NewValue = detail, + LoggedAt = now + }); + } + + return false; + } + + // 2. State & Deadline checks + if (renewal.Status != "APPROVED") + { + throw new InvalidOperationException($"Yêu cầu gia hạn không ở trạng thái 'APPROVED'. Trạng thái hiện tại: {renewal.Status}"); + } + + if (contract.Status is "RETURN_PENDING" or "COMPLETED" or "TERMINATED" or "CANCELLED") + { + throw new InvalidOperationException($"Hợp đồng ở trạng thái '{contract.Status}', không thể gia hạn."); + } + + if (renewal.PaymentDeadlineAt.HasValue && now >= renewal.PaymentDeadlineAt.Value) + { + // Payment deadline exceeded: mark renewal EXPIRED, payment FAILED + renewal.Status = "EXPIRED"; + renewal.ExpiredAt = now; + + var pendingPay = renewal.Payments.FirstOrDefault(p => p.PaymentType == "RENEWAL" && p.Status == "PENDING"); + if (pendingPay != null) + { + pendingPay.Status = "FAILED"; + pendingPay.UpdatedAt = now; + } + + var reviewDetail = JsonSerializer.Serialize(new + { + contractId, + renewalId, + paymentMethod, + transactionRef, + now, + deadline = renewal.PaymentDeadlineAt.Value, + reason = "Tiền về sau khi yêu cầu gia hạn đã hết hạn thanh toán (24 giờ / hết hạn hợp đồng); cần đối soát hoàn tiền thủ công." + }); + + db.ActivityLogs.Add(new ActivityLog + { + UserId = staffUserId, + EntityType = "RENEWAL", + EntityId = renewalId, + Action = "PAYMENT_REVIEW_REQUIRED", + NewValue = reviewDetail, + LoggedAt = now + }); + + return false; + } + + // 3. Find or ensure RENEWAL payment + var payment = renewal.Payments.FirstOrDefault(p => p.PaymentType == "RENEWAL" && p.Status == "PENDING") + ?? renewal.Payments.FirstOrDefault(p => p.PaymentType == "RENEWAL") + ?? throw new InvalidOperationException("Không tìm thấy khoản thanh toán gia hạn hợp lệ."); + + // 4. Atomic settlement update + payment.Status = "PAID"; + payment.PaymentMethod = paymentMethod; + payment.TransactionReference = transactionRef; + payment.PaidAt = now; + payment.UpdatedAt = now; + + renewal.Status = "PAID"; + renewal.AppliedAt = now; + + // Apply new end date exactly once + contract.EndDate = renewal.NewEndDate; + if (contract.Status is "EXPIRING" or "OVERDUE") + { + contract.Status = "ACTIVE"; + } + + // Mark any pending checkouts as PAID + var checkouts = await db.PaymentCheckouts + .Where(c => c.PaymentId == payment.PaymentId && c.Status == "PENDING") + .ToListAsync(ct); + + foreach (var c in checkouts) + { + c.Status = "PAID"; + c.UpdatedAt = now; + } + + // Audit log + var logDetail = JsonSerializer.Serialize(new + { + contractId, + renewalId, + paymentId = payment.PaymentId, + oldEndDate = renewal.OldEndDate.ToString("yyyy-MM-dd"), + newEndDate = renewal.NewEndDate.ToString("yyyy-MM-dd"), + amount = renewal.RenewalAmount, + paymentMethod, + transactionRef, + settledBy = staffUserId + }); + + db.ActivityLogs.Add(new ActivityLog + { + UserId = staffUserId, + EntityType = "RENEWAL", + EntityId = renewalId, + Action = "RENEWAL_PAID", + NewValue = logDetail, + LoggedAt = now + }); + + return true; + } +} diff --git a/StorageProject.Infrastructure/Services/RentalPolicyService.cs b/StorageProject.Infrastructure/Services/RentalPolicyService.cs new file mode 100644 index 0000000..53a88ca --- /dev/null +++ b/StorageProject.Infrastructure/Services/RentalPolicyService.cs @@ -0,0 +1,262 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.Policy; +using StorageProject.Core.Entities; +using StorageProject.Core.Interfaces; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +public class RentalPolicyService(AppDbContext dbContext) : IRentalPolicyService +{ + private static readonly string[] RequiredSections = + [ + "payment", "access", "renewal", "overdue", "return", "cancellation", "support" + ]; + + private static readonly Dictionary DefaultSections = new() + { + ["payment"] = "Hợp đồng và quyền mở kho được cấp sau khi hệ thống xác nhận thanh toán hoặc nhân viên xác nhận đã thu đủ tại quầy. Bạn sử dụng kho từ ngày bắt đầu hợp đồng; kiểm tra ngày bắt đầu, ngày hết hạn và trạng thái thanh toán trong Kho của tôi.", + ["access"] = "QR chỉ sử dụng trong thời hạn hợp đồng. QR hết hiệu lực ngay khi hết hạn thuê hoặc khi yêu cầu trả kho được ghi nhận thành công. Chuyển hết đồ trước khi xác nhận trả kho; cần hỗ trợ ra vào sau đó thì liên hệ nhân viên cơ sở.", + ["renewal"] = "Gửi yêu cầu để cơ sở kiểm tra kỳ thuê tiếp theo. Trong lúc chờ duyệt, ngày hết hạn giữ nguyên. Sau khi duyệt, thanh toán đủ tiền gia hạn qua PayOS hoặc tại quầy để cập nhật kỳ thuê. Không thu lại cọc; yêu cầu bị từ chối hiển thị lý do.", + ["overdue"] = "Nếu quá hạn mà chưa trả kho, mỗi ngày trừ 5% giá trị cọc ban đầu, tối đa 100% cọc. Sau 20 ngày cọc còn 0 đ, nhân viên kho đưa đồ của khách ra ngoài. Khách hàng tự chịu trách nhiệm theo chính sách.", + ["return"] = "Chuyển hết đồ trước khi xác nhận trả kho. Cơ sở kiểm tra kho, nhận lại chìa khóa và lập biên bản. Cọc, khoản chưa thanh toán và phí được đối soát; bạn xem được khấu trừ và số tiền hoàn. Không còn cọc thì số tiền hoàn bằng 0 đ.", + ["cancellation"] = "Trước khi huỷ, kiểm tra điều kiện, khoản khấu trừ và tiền hoàn trên đơn. Chờ hoàn là cơ sở chưa ghi nhận hoàn thành chuyển tiền; Đã hoàn là giao dịch đã được xác nhận. Chưa nhận tiền thì liên hệ cơ sở kèm mã đơn/khoản hoàn.", + ["support"] = "Xem ngày hết hạn, lịch sử thanh toán, lịch trừ cọc và tiến độ trả kho trong tài khoản. Bạn có thể gửi hỗ trợ tới cơ sở liên quan, kể cả khi chưa có hợp đồng, để được tư vấn loại kho phù hợp." + }; + + public async Task GetCurrentPolicyAsync(CancellationToken ct = default) + { + var current = await dbContext.RentalPolicyVersions + .AsNoTracking() + .OrderByDescending(v => v.Version) + .FirstOrDefaultAsync(v => v.IsCurrent, ct); + + if (current == null) + { + return new RentalPolicyDto( + Rate: 5.0m, + Sections: DefaultSections, + Version: 1, + DisplayVersion: "11/2026", + UpdatedAt: DateTime.UtcNow + ); + } + + var sections = JsonSerializer.Deserialize>(current.SectionsJson) + ?? DefaultSections; + + return new RentalPolicyDto( + Rate: current.Rate, + Sections: sections, + Version: current.Version, + DisplayVersion: current.DisplayVersion, + UpdatedAt: current.PublishedAt + ); + } + + public async Task GetPolicyVersionAsync(int version, CancellationToken ct = default) + { + var policy = await dbContext.RentalPolicyVersions + .AsNoTracking() + .FirstOrDefaultAsync(v => v.Version == version, ct); + + if (policy == null) return null; + + var sections = JsonSerializer.Deserialize>(policy.SectionsJson) + ?? DefaultSections; + + return new RentalPolicyDto( + Rate: policy.Rate, + Sections: sections, + Version: policy.Version, + DisplayVersion: policy.DisplayVersion, + UpdatedAt: policy.PublishedAt + ); + } + + public async Task SaveRentalPolicyAsync(long userId, SaveRentalPolicyRequest request, CancellationToken ct = default) + { + if (request.Action != "SAVE_RENTAL_POLICY") + { + throw new ArgumentException("Action không hợp lệ. Chỉ chấp nhận SAVE_RENTAL_POLICY."); + } + + var rate = request.Rate ?? 5.0m; + if (rate <= 0 || rate > 100) + { + throw new ArgumentException("Tỷ lệ khấu trừ mỗi ngày phải lớn hơn 0 và không quá 100%."); + } + + if (request.Sections == null) + { + throw new ArgumentException("Vui lòng cung cấp nội dung các phần chính sách."); + } + + foreach (var sec in RequiredSections) + { + if (!request.Sections.TryGetValue(sec, out var content) || string.IsNullOrWhiteSpace(content)) + { + throw new ArgumentException($"Phần '{sec}' trong chính sách không được để trống."); + } + } + + await using var tx = await dbContext.Database.BeginTransactionAsync(ct); + + var current = await dbContext.RentalPolicyVersions + .OrderByDescending(v => v.Version) + .FirstOrDefaultAsync(v => v.IsCurrent, ct); + + if (request.Version.HasValue && current != null && current.Version != request.Version.Value) + { + throw new InvalidOperationException("Phiên bản chính sách đã được thay đổi bởi người khác. Vui lòng tải lại trang."); + } + + if (current != null) + { + current.IsCurrent = false; + } + + var maxVersion = await dbContext.RentalPolicyVersions.MaxAsync(v => (int?)v.Version, ct) ?? 0; + var nextVersion = maxVersion + 1; + var now = DateTime.UtcNow; + var vnNow = now.AddHours(7); + var displayVersion = $"{vnNow.Month:D2}/{vnNow.Year}"; + + var newPolicyVersion = new RentalPolicyVersion + { + Version = nextVersion, + DisplayVersion = displayVersion, + Rate = rate, + SectionsJson = JsonSerializer.Serialize(request.Sections), + PublishedBy = userId, + PublishedAt = now, + IsCurrent = true + }; + + dbContext.RentalPolicyVersions.Add(newPolicyVersion); + + // Keep OVERDUE policy table in sync with the new rate + var overduePolicy = await dbContext.Policies + .FirstOrDefaultAsync(p => p.PolicyType == "OVERDUE" && p.Status == "ACTIVE", ct); + + if (overduePolicy != null) + { + overduePolicy.Value = rate; + overduePolicy.UpdatedAt = now; + } + + // Audit log + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = userId, + EntityType = "RENTAL_POLICY", + EntityId = nextVersion, + Action = "RENTAL_POLICY_PUBLISHED", + NewValue = JsonSerializer.Serialize(new { version = nextVersion, displayVersion, rate }), + LoggedAt = now + }); + + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + + return new RentalPolicyDto( + Rate: rate, + Sections: request.Sections, + Version: nextVersion, + DisplayVersion: displayVersion, + UpdatedAt: now + ); + } + + public async Task RecordReservationConsentAsync(long customerId, long reservationId, PolicyConsentRequest request, string channel = "WEB_CUSTOMER", CancellationToken ct = default) + { + if (!request.Accepted) + { + throw new ArgumentException("Bạn phải chấp nhận chính sách cho thuê để tiếp tục."); + } + + var reservation = 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."); + + var currentVersion = await dbContext.RentalPolicyVersions + .OrderByDescending(v => v.Version) + .FirstOrDefaultAsync(v => v.IsCurrent, ct); + + var expectedVersion = currentVersion?.Version ?? 1; + if (request.PolicyVersion != expectedVersion) + { + throw new InvalidOperationException("Phiên bản chính sách không còn hiệu lực. Vui lòng tải lại trang để chấp thuận bản mới nhất."); + } + + var consent = new PolicyConsent + { + CustomerId = customerId, + PolicyVersionId = currentVersion?.PolicyVersionId ?? 1, + ReservationId = reservationId, + AcceptedAt = DateTime.UtcNow, + Channel = channel + }; + + dbContext.PolicyConsents.Add(consent); + await dbContext.SaveChangesAsync(ct); + + return new PolicyConsentDto( + ConsentId: consent.ConsentId, + CustomerId: customerId, + PolicyVersion: expectedVersion, + DisplayVersion: currentVersion?.DisplayVersion ?? "11/2026", + AcceptedAt: consent.AcceptedAt, + Channel: consent.Channel + ); + } + + public async Task RecordRenewalConsentAsync(long customerId, long renewalId, PolicyConsentRequest request, string channel = "WEB_CUSTOMER", CancellationToken ct = default) + { + if (!request.Accepted) + { + throw new ArgumentException("Bạn phải chấp nhận chính sách cho thuê để tiếp tục."); + } + + var renewal = await dbContext.ContractRenewals + .Include(r => r.Contract) + .SingleOrDefaultAsync(r => r.RenewalId == renewalId && r.Contract.CustomerId == customerId, ct) + ?? throw new InvalidOperationException("Không tìm thấy yêu cầu gia hạn."); + + var currentVersion = await dbContext.RentalPolicyVersions + .OrderByDescending(v => v.Version) + .FirstOrDefaultAsync(v => v.IsCurrent, ct); + + var expectedVersion = currentVersion?.Version ?? 1; + if (request.PolicyVersion != expectedVersion) + { + throw new InvalidOperationException("Phiên bản chính sách không còn hiệu lực. Vui lòng tải lại trang để chấp thuận bản mới nhất."); + } + + var consent = new PolicyConsent + { + CustomerId = customerId, + PolicyVersionId = currentVersion?.PolicyVersionId ?? 1, + RenewalId = renewalId, + ContractId = renewal.ContractId, + AcceptedAt = DateTime.UtcNow, + Channel = channel + }; + + renewal.PolicyVersion = expectedVersion; + renewal.AcceptedAt = consent.AcceptedAt; + + dbContext.PolicyConsents.Add(consent); + await dbContext.SaveChangesAsync(ct); + + return new PolicyConsentDto( + ConsentId: consent.ConsentId, + CustomerId: customerId, + PolicyVersion: expectedVersion, + DisplayVersion: currentVersion?.DisplayVersion ?? "11/2026", + AcceptedAt: consent.AcceptedAt, + Channel: consent.Channel + ); + } +} diff --git a/StorageProject.Tests/RenewalPolicyD32Tests.cs b/StorageProject.Tests/RenewalPolicyD32Tests.cs new file mode 100644 index 0000000..a97955a --- /dev/null +++ b/StorageProject.Tests/RenewalPolicyD32Tests.cs @@ -0,0 +1,485 @@ +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.Policy; +using StorageProject.Core.DTOs.Renewal; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; +using StorageProject.Infrastructure.Services; +using Xunit; + +namespace StorageProject.Tests; + +public sealed class RenewalPolicyD32Tests +{ + 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; + public bool RejectSignature; + public int Cancellations; + + public void EnsureConfigured() { } + public Task CancelAsync(long orderCode) { Cancellations++; return Task.CompletedTask; } + public Task CreateAsync(long orderCode, int amount, long reservationId, long expiresAt, string returnUrl, string cancelUrl) + => Task.FromResult(new CheckoutLink("https://pay.payos.vn/test-checkout", "test-qr-code")); + public Task CreateRenewalAsync(long orderCode, int amount, long renewalId, long expiresAt, string returnUrl, string cancelUrl) + => Task.FromResult(new CheckoutLink("https://pay.payos.vn/test-renewal-checkout", "test-renewal-qr")); + public Task VerifyAsync(string body) + { + if (RejectSignature) throw new InvalidOperationException("Invalid 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 User StaffUser = null!; + public User ManagerUser = null!; + public User CustomerUser = null!; + public Facility Facility = null!; + public StorageUnit Unit = null!; + public RentalContract Contract = null!; + + public RenewalService RenewalSvc => new(Db, Gateway); + public ManagerService ManagerSvc => new(Db, new StaffService(Db)); + public RentalPolicyService PolicySvc => new(Db); + public PayOSService PayOSSvc => new(Db, Gateway, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + + public static async Task CreateAsync() + { + var f = new Fixture(); + await f.Connection.OpenAsync(); + f.Db = new TestDb(new DbContextOptionsBuilder().UseSqlite(f.Connection).Options); + await f.Db.Database.EnsureCreatedAsync(); + + f.StaffUser = new User { Username = "staff01", Email = "staff01@example.com", FullName = "Staff One", PasswordHash = "x", Status = "ACTIVE" }; + f.ManagerUser = new User { Username = "manager01", Email = "manager01@example.com", FullName = "Manager One", PasswordHash = "x", Status = "ACTIVE" }; + f.CustomerUser = new User { Username = "customer01", Email = "customer01@example.com", FullName = "Customer One", PasswordHash = "x", Status = "ACTIVE" }; + f.Facility = new Facility { Name = "SafeSpace Nguyen Luong Bang", Address = "123 NLB", Status = "ACTIVE" }; + var unitType = new UnitType { TypeName = "Kho thuong M", Area = 15, ClimateControlled = false, Status = "ACTIVE" }; + + f.Db.AddRange(f.StaffUser, f.ManagerUser, f.CustomerUser, f.Facility, unitType); + await f.Db.SaveChangesAsync(); + + var staffRole = new Role { RoleName = "STAFF", Description = "Staff" }; + var managerRole = new Role { RoleName = "MANAGER", Description = "Manager" }; + var customerRole = new Role { RoleName = "CUSTOMER", Description = "Customer" }; + var opsRole = new Role { RoleName = "OPERATIONS", Description = "Operations" }; + f.Db.AddRange(staffRole, managerRole, customerRole, opsRole); + await f.Db.SaveChangesAsync(); + + f.Db.UserRoles.AddRange( + new UserRole { UserId = f.StaffUser.UserId, RoleId = staffRole.RoleId }, + new UserRole { UserId = f.ManagerUser.UserId, RoleId = managerRole.RoleId }, + new UserRole { UserId = f.CustomerUser.UserId, RoleId = customerRole.RoleId } + ); + + f.Db.UserFacilities.AddRange( + new UserFacility { UserId = f.StaffUser.UserId, FacilityId = f.Facility.FacilityId, Status = "ACTIVE", AssignedBy = f.ManagerUser.UserId, AssignedFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-10)) }, + new UserFacility { UserId = f.ManagerUser.UserId, FacilityId = f.Facility.FacilityId, Status = "ACTIVE", AssignedBy = f.ManagerUser.UserId, AssignedFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-10)) } + ); + + f.Unit = new StorageUnit { FacilityId = f.Facility.FacilityId, UnitTypeId = unitType.UnitTypeId, UnitNumber = "K01", Status = "OCCUPIED" }; + f.Db.StorageUnits.Add(f.Unit); + + var rate = new RentalRate + { + FacilityId = f.Facility.FacilityId, + UnitTypeId = unitType.UnitTypeId, + SetBy = f.ManagerUser.UserId, + MonthlyRate = 1500000, + EffectiveFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddMonths(-1)), + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow + }; + f.Db.RentalRates.Add(rate); + + // Default policy version 1 with all 7 standard sections + var sections = new Dictionary + { + ["payment"] = "Thanh toán qua PayOS hoặc tại cơ sở.", + ["access"] = "Mã QR chỉ mở trong kỳ hạn.", + ["renewal"] = "Duyệt gia hạn trong 24 giờ.", + ["overdue"] = "Quá hạn 5% cọc ban đầu mỗi ngày.", + ["return"] = "Kiểm tra kho khi trả.", + ["cancellation"] = "Huỷ đơn trước StartDate mất 10% cọc.", + ["support"] = "Hỗ trợ khách hàng." + }; + var policy = new RentalPolicyVersion + { + Version = 1, + DisplayVersion = "1.0", + Rate = 5.0m, + SectionsJson = System.Text.Json.JsonSerializer.Serialize(sections), + PublishedBy = f.ManagerUser.UserId, + IsCurrent = true, + PublishedAt = DateTime.UtcNow + }; + f.Db.RentalPolicyVersions.Add(policy); + + var overduePolicy = new Policy + { + PolicyName = "Chính sách quá hạn", + RuleDescription = "Quá hạn 5% cọc ban đầu mỗi ngày", + CreatedBy = f.ManagerUser.UserId, + PolicyType = "OVERDUE", + CalculationType = "PERCENTAGE", + Value = 5.0m, + EffectiveFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddMonths(-1)), + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow, + UpdatedAt = DateTime.UtcNow + }; + f.Db.Policies.Add(overduePolicy); + + var startDate = DateOnly.FromDateTime(DateTime.UtcNow.AddMonths(-2)); + var endDate = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(10)); // 10 days remaining + + var reservation = new Reservation + { + CustomerId = f.CustomerUser.UserId, + FacilityId = f.Facility.FacilityId, + UnitTypeId = unitType.UnitTypeId, + StartDate = startDate, + ExpectedEndDate = endDate, + RentalPeriodMonths = 3, + EstimatedAmount = 4500000, + RequiredDeposit = 1500000, + QuotedMonthlyRate = 1500000, + Status = "CHECKED_IN", + CreatedAt = DateTime.UtcNow.AddMonths(-2) + }; + f.Db.Reservations.Add(reservation); + await f.Db.SaveChangesAsync(); + + f.Contract = new RentalContract + { + ReservationId = reservation.ReservationId, + CustomerId = f.CustomerUser.UserId, + UnitId = f.Unit.UnitId, + StartDate = startDate, + EndDate = endDate, + AgreedMonthlyRate = 1500000, + DepositAmount = 1500000, + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow.AddMonths(-2) + }; + f.Db.RentalContracts.Add(f.Contract); + await f.Db.SaveChangesAsync(); + + return f; + } + + public async ValueTask DisposeAsync() + { + await Db.DisposeAsync(); + await Connection.DisposeAsync(); + } + } + + [Fact] + public async Task T02_ApproveRenewal_DoesNotChangeContractEndDate_AndCreatesPendingRenewalPayment() + { + await using var f = await Fixture.CreateAsync(); + + // Customer requests renewal for 3 months with policy consent + var request = new CreateRenewalRequest(RenewalPeriodMonths: 3, PolicyVersion: 1, Accepted: true); + var renewalDto = await f.RenewalSvc.RequestRenewalAsync(f.CustomerUser.UserId, f.Contract.ContractId, request); + Assert.NotNull(renewalDto); + Assert.Equal("PENDING", renewalDto.Status); + + var originalEndDate = f.Contract.EndDate; + + // Manager approves renewal + var approvedDto = await f.RenewalSvc.ApproveRenewalAsync(f.ManagerUser.UserId, renewalDto.RenewalId); + Assert.Equal("APPROVED", approvedDto.Status); + Assert.NotNull(approvedDto.PaymentDeadlineAt); + + // CONTRACT END DATE MUST REMAIN UNCHANGED + var contract = await f.Db.RentalContracts.FindAsync(f.Contract.ContractId); + Assert.NotNull(contract); + Assert.Equal(originalEndDate, contract.EndDate); + + // Payment record must exist with status PENDING + var payment = await f.Db.Payments.FirstOrDefaultAsync(p => p.RenewalId == renewalDto.RenewalId); + Assert.NotNull(payment); + Assert.Equal("RENEWAL", payment.PaymentType); + Assert.Equal("PENDING", payment.Status); + Assert.Equal(3 * 1500000, payment.Amount); + + // Check deadline invariant: min(ApprovedAt + 24h, EndDate cutoff in VN time) + var renewal = await f.Db.ContractRenewals.FindAsync(renewalDto.RenewalId); + Assert.NotNull(renewal); + Assert.NotNull(renewal.PaymentDeadlineAt); + Assert.True(renewal.PaymentDeadlineAt.Value <= DateTime.UtcNow.AddHours(25)); + } + + [Fact] + public async Task T02_LegacyManagerApprove_FollowsSameRules_DoesNotChangeEndDate() + { + await using var f = await Fixture.CreateAsync(); + + var request = new CreateRenewalRequest(RenewalPeriodMonths: 1, PolicyVersion: 1, Accepted: true); + var renewalDto = await f.RenewalSvc.RequestRenewalAsync(f.CustomerUser.UserId, f.Contract.ContractId, request); + + var originalEndDate = f.Contract.EndDate; + + // Call legacy ManagerService using renewal ID as string + await f.ManagerSvc.ApproveRenewalAsync(f.ManagerUser.UserId, renewalDto.RenewalId.ToString()); + + var contract = await f.Db.RentalContracts.FindAsync(f.Contract.ContractId); + Assert.NotNull(contract); + Assert.Equal(originalEndDate, contract.EndDate); // Invariant kept! + + var renewal = await f.Db.ContractRenewals.FindAsync(renewalDto.RenewalId); + Assert.NotNull(renewal); + Assert.Equal("APPROVED", renewal.Status); + + var payment = await f.Db.Payments.FirstOrDefaultAsync(p => p.RenewalId == renewalDto.RenewalId); + Assert.NotNull(payment); + Assert.Equal("PENDING", payment.Status); + } + + [Fact] + public async Task T02_ApproveRenewal_Twice_IsIdempotent_DoesNotCreateDuplicatePayment() + { + await using var f = await Fixture.CreateAsync(); + + var request = new CreateRenewalRequest(RenewalPeriodMonths: 2, PolicyVersion: 1, Accepted: true); + var renewalDto = await f.RenewalSvc.RequestRenewalAsync(f.CustomerUser.UserId, f.Contract.ContractId, request); + + await f.RenewalSvc.ApproveRenewalAsync(f.ManagerUser.UserId, renewalDto.RenewalId); + + // Second approval attempt throws domain exception + await Assert.ThrowsAsync(() => + f.RenewalSvc.ApproveRenewalAsync(f.ManagerUser.UserId, renewalDto.RenewalId)); + + var payments = await f.Db.Payments.Where(p => p.RenewalId == renewalDto.RenewalId).ToListAsync(); + Assert.Single(payments); + Assert.Equal(f.Contract.EndDate, (await f.Db.RentalContracts.FindAsync(f.Contract.ContractId))!.EndDate); + } + + [Fact] + public async Task T03_PayOS_CreatesRenewalLink_AndWebhookSettlesEndDateExactlyOnce() + { + await using var f = await Fixture.CreateAsync(); + + var request = new CreateRenewalRequest(RenewalPeriodMonths: 3, PolicyVersion: 1, Accepted: true); + var renewalDto = await f.RenewalSvc.RequestRenewalAsync(f.CustomerUser.UserId, f.Contract.ContractId, request); + await f.RenewalSvc.ApproveRenewalAsync(f.ManagerUser.UserId, renewalDto.RenewalId); + + var initialEndDate = f.Contract.EndDate; + var payment = await f.Db.Payments.FirstAsync(p => p.RenewalId == renewalDto.RenewalId); + + // 1. Create PayOS QR link + var checkoutDto = await f.PayOSSvc.CreateRenewalPaymentQrAsync(f.CustomerUser.UserId, payment.PaymentId); + Assert.NotNull(checkoutDto); + Assert.Equal("PENDING", checkoutDto.Status); + Assert.Equal(payment.Amount, checkoutDto.Amount); + + // 2. Simulate PayOS Webhook + f.Gateway.Payment = new VerifiedReservationPayment(checkoutDto.OrderCode, checkoutDto.Amount, "PAYOS_TXN_001"); + var webhookProcessed = await f.PayOSSvc.ProcessWebhookAsync("{}", null); + Assert.True(webhookProcessed); + + // Verify settlement + var updatedContract = await f.Db.RentalContracts.FindAsync(f.Contract.ContractId); + Assert.NotNull(updatedContract); + var expectedEndDate = initialEndDate.AddMonths(3); + Assert.Equal(expectedEndDate, updatedContract.EndDate); // EndDate lengthened! + + var updatedRenewal = await f.Db.ContractRenewals.FindAsync(renewalDto.RenewalId); + Assert.Equal("PAID", updatedRenewal!.Status); + Assert.NotNull(updatedRenewal.AppliedAt); + + var updatedPayment = await f.Db.Payments.FindAsync(payment.PaymentId); + Assert.Equal("PAID", updatedPayment!.Status); + Assert.NotNull(updatedPayment.PaidAt); + + // 3. Replay Webhook (Idempotency test) + var replayProcessed = await f.PayOSSvc.ProcessWebhookAsync("{}", null); + Assert.True(replayProcessed); + + // EndDate must NOT be extended twice! + var recheckContract = await f.Db.RentalContracts.FindAsync(f.Contract.ContractId); + Assert.Equal(expectedEndDate, recheckContract!.EndDate); + } + + [Fact] + public async Task T04_CounterPayment_CustomerSelectsAndStaffCollectsCash_LengthensEndDateOnce() + { + await using var f = await Fixture.CreateAsync(); + + var request = new CreateRenewalRequest(RenewalPeriodMonths: 1, PolicyVersion: 1, Accepted: true); + var renewalDto = await f.RenewalSvc.RequestRenewalAsync(f.CustomerUser.UserId, f.Contract.ContractId, request); + await f.RenewalSvc.ApproveRenewalAsync(f.ManagerUser.UserId, renewalDto.RenewalId); + + var initialEndDate = f.Contract.EndDate; + + // Customer selects Counter payment + await f.RenewalSvc.SelectCounterPaymentAsync(f.CustomerUser.UserId, renewalDto.RenewalId); + + var renewal = await f.Db.ContractRenewals.FindAsync(renewalDto.RenewalId); + Assert.Equal("APPROVED", renewal!.Status); // Still approved, not paid yet + var payment = await f.Db.Payments.FirstAsync(p => p.RenewalId == renewalDto.RenewalId); + Assert.Equal("CASH", payment.PaymentMethod); + Assert.Equal("PENDING", payment.Status); + + // Staff sees counter renewals queue + var queue = await f.RenewalSvc.GetCounterRenewalsAsync(f.StaffUser.UserId); + Assert.NotEmpty(queue); + var item = queue.First(x => x.RenewalId == renewalDto.RenewalId); + Assert.Equal("PENDING", item.Status); + Assert.Equal($"GHQ-{renewalDto.RenewalId:D4}", item.Id); + + // Staff collects cash + await f.RenewalSvc.CollectCounterRenewalAsync(f.StaffUser.UserId, item.Id); + + // Verify EndDate extended + var contract = await f.Db.RentalContracts.FindAsync(f.Contract.ContractId); + Assert.Equal(initialEndDate.AddMonths(1), contract!.EndDate); + + var paidRenewal = await f.Db.ContractRenewals.FindAsync(renewalDto.RenewalId); + Assert.Equal("PAID", paidRenewal!.Status); + + var paidPayment = await f.Db.Payments.FindAsync(payment.PaymentId); + Assert.Equal("PAID", paidPayment!.Status); + + // Collecting again should throw + await Assert.ThrowsAsync(() => + f.RenewalSvc.CollectCounterRenewalAsync(f.StaffUser.UserId, item.Id)); + } + + [Fact] + public async Task T20_PolicyVersioning_OperationsCanPublish_AndConcurrencyConflictDetected() + { + await using var f = await Fixture.CreateAsync(); + + // Public read current policy + var current = await f.PolicySvc.GetCurrentPolicyAsync(); + Assert.Equal(1, current.Version); + Assert.Equal(5.0m, current.Rate); + + // Operations publishes version 2 + var saveRequest = new SaveRentalPolicyRequest( + Action: "SAVE_RENTAL_POLICY", + Rate: 6.0m, + Sections: new Dictionary + { + ["payment"] = "Thanh toán qua PayOS hoặc tại cơ sở.", + ["access"] = "Mã QR chỉ mở trong kỳ hạn.", + ["renewal"] = "Duyệt gia hạn trong 24 giờ.", + ["overdue"] = "Quá hạn 6% mỗi ngày.", + ["return"] = "Kiểm tra kho khi trả.", + ["cancellation"] = "Huỷ đơn trước StartDate mất 10% cọc.", + ["support"] = "Hỗ trợ khách hàng." + }, + Version: 1 + ); + + var v2 = await f.PolicySvc.SaveRentalPolicyAsync(f.ManagerUser.UserId, saveRequest); + Assert.Equal(2, v2.Version); + Assert.Equal(6.0m, v2.Rate); + + // Current policy is now version 2 + var newCurrent = await f.PolicySvc.GetCurrentPolicyAsync(); + Assert.Equal(2, newCurrent.Version); + Assert.Equal(6.0m, newCurrent.Rate); + + // Historical version 1 remains accessible and immutable + var v1Historical = await f.PolicySvc.GetPolicyVersionAsync(1); + Assert.NotNull(v1Historical); + Assert.Equal(1, v1Historical.Version); + Assert.Equal(5.0m, v1Historical.Rate); + + // Concurrency conflict test: saving with stale version 1 should fail + var staleRequest = new SaveRentalPolicyRequest( + Action: "SAVE_RENTAL_POLICY", + Rate: 7.0m, + Sections: saveRequest.Sections, + Version: 1 // Stale! Current is 2 + ); + + await Assert.ThrowsAsync(() => + f.PolicySvc.SaveRentalPolicyAsync(f.ManagerUser.UserId, staleRequest)); + } + + [Fact] + public async Task T20_PolicyConsent_RecordedWithServerTimeAndChannel() + { + await using var f = await Fixture.CreateAsync(); + + var reservation = new Reservation + { + CustomerId = f.CustomerUser.UserId, + FacilityId = f.Facility.FacilityId, + UnitTypeId = (await f.Db.UnitTypes.FirstAsync()).UnitTypeId, + StartDate = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(1)), + ExpectedEndDate = DateOnly.FromDateTime(DateTime.UtcNow.AddMonths(1)), + RentalPeriodMonths = 1, + EstimatedAmount = 1500000, + RequiredDeposit = 1500000, + QuotedMonthlyRate = 1500000, + Status = "PENDING_AT_FACILITY", + CreatedAt = DateTime.UtcNow + }; + f.Db.Reservations.Add(reservation); + await f.Db.SaveChangesAsync(); + + var consentRequest = new PolicyConsentRequest(PolicyVersion: 1, Accepted: true); + var consent = await f.PolicySvc.RecordReservationConsentAsync(f.CustomerUser.UserId, reservation.ReservationId, consentRequest, "WEB"); + + Assert.NotNull(consent); + Assert.Equal(1, consent.PolicyVersion); + Assert.Equal(f.CustomerUser.UserId, consent.CustomerId); + Assert.Equal("WEB", consent.Channel); + + // Verified in database + var dbConsent = await f.Db.PolicyConsents.FirstOrDefaultAsync(c => c.ReservationId == reservation.ReservationId); + Assert.NotNull(dbConsent); + Assert.Equal(1, dbConsent.PolicyVersionId); + } + + [Fact] + public async Task Expiry_PastDeadlineRenewal_ExpiresAutomatically() + { + await using var f = await Fixture.CreateAsync(); + + var request = new CreateRenewalRequest(RenewalPeriodMonths: 1, PolicyVersion: 1, Accepted: true); + var renewalDto = await f.RenewalSvc.RequestRenewalAsync(f.CustomerUser.UserId, f.Contract.ContractId, request); + await f.RenewalSvc.ApproveRenewalAsync(f.ManagerUser.UserId, renewalDto.RenewalId); + + // Force deadline into the past + var renewal = await f.Db.ContractRenewals.FindAsync(renewalDto.RenewalId); + renewal!.PaymentDeadlineAt = DateTime.UtcNow.AddHours(-2); + await f.Db.SaveChangesAsync(); + + // Run expiration job + await f.RenewalSvc.ExpirePendingRenewalsAsync(); + + var expiredRenewal = await f.Db.ContractRenewals.FindAsync(renewalDto.RenewalId); + Assert.Equal("EXPIRED", expiredRenewal!.Status); + Assert.NotNull(expiredRenewal.ExpiredAt); + + var payment = await f.Db.Payments.FirstAsync(p => p.RenewalId == renewalDto.RenewalId); + Assert.Equal("FAILED", payment.Status); + + // Contract EndDate remains unchanged + var contract = await f.Db.RentalContracts.FindAsync(f.Contract.ContractId); + Assert.Equal(f.Contract.EndDate, contract!.EndDate); + } +} diff --git a/docs/sprints/dat-renewal-policy-d32.md b/docs/sprints/dat-renewal-policy-d32.md new file mode 100644 index 0000000..6368ad2 --- /dev/null +++ b/docs/sprints/dat-renewal-policy-d32.md @@ -0,0 +1,38 @@ +# Sprint Contract: T02, T03, T04, T20 — Gia hạn hợp đồng & Quản lý phiên bản chính sách theo D32 + +> Kế hoạch chi tiết theo `SSFRMS-Dat-Agent-Implementation-Plan.md`. +> Phụ trách: Đạt (Backend). Phối hợp Frontend: Thắng. + +## 1. Mục tiêu +1. Khách hàng gửi yêu cầu gia hạn kèm đồng ý chính sách hiện hành. +2. Quản lý cơ sở duyệt gia hạn: chốt giá tại thời điểm duyệt, tạo khoản thu `RENEWAL PENDING`, lưu hạn thanh toán (24 giờ, không vượt quá hạn hợp đồng); **tuyệt đối không tăng `EndDate` khi duyệt**. +3. Khách thanh toán PayOS hoặc trả tại quầy qua nhân viên: ghi nhận khoản thu `PAID`, renewal `PAID`, gán `EndDate = NewEndDate` đúng một lần. Idempotent và chống race condition. +4. Quá hạn thanh toán: renewal chuyển sang `EXPIRED`, payment chuyển `FAILED` kèm audit; không kéo dài hợp đồng. +5. Quản lý phiên bản chính sách: `GET /api/rental-policy` công khai, `POST /api/rental-policy/actions` chỉ dành cho OPERATIONS tạo bản mới bất biến; ghi nhận bằng chứng đồng ý (consent) của khách hàng với version, thời điểm server và kênh xác nhận. + +## 2. Nguồn yêu cầu & Quyết định +- Quyết định: D32 (26/10/2026), D05, D10, D15, D16, D19, D26, D27, D29. +- Tài liệu: `SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md` mục D32; `APPROVED-FE-API-GAPS.md`. +- Kế hoạch: `SSFRMS-Dat-Agent-Implementation-Plan.md`. + +## 3. Phạm vi (Backend) +- Entity & Schema: `PaymentCheckout`, `RentalPolicyVersion`, `PolicyConsent`, cập nhật `ContractRenewal` (`PaymentDeadlineAt`, `AppliedAt`, `ExpiredAt`, status check `EXPIRED`), unique filtered index chống trùng renewal/payment. +- Services: `RenewalService`, `RenewalSettlement`, `RentalPolicyService`, `PayOSService`, `FacilityOpsService.Actions`, `FacilityOpsService.Board`, `ManagerService`. +- Worker: `ExpiredRenewalWorker` (job quét hết hạn gia hạn). +- Endpoints: `POST /api/payments/{id}/payos`, `POST /api/renewals/{id}/counter-payment`, `GET /api/ops/counter-renewals`, `POST /api/ops/counter-renewals/actions`, `GET /api/rental-policy`, `GET /api/rental-policy/versions/{version}`, `POST /api/rental-policy/actions`, `POST /api/reservations/{id}/policy-consent`. +- Migration mới: `AddRenewalSettlementAndPolicyConsent`. +- Unit/HTTP test & Integration test. + +## 4. Ngoài phạm vi +- Không tự thay đổi nghiệp vụ cọc, phí trả kho, huỷ đơn đã chốt trong D27/D32. +- Không thu phí phát sinh sau trả kho hay công nợ ngoài cọc. +- Không làm thu hồi QR/PIN thủ công. +- Không tự ý commit, push, tạo PR, merge hay reset database. + +## 5. Tiêu chí hoàn thành (DoD) +- [ ] Duyệt gia hạn trên cả `/api/ops/renewals/{id}/approve` và `/api/manager/renewals/{id}/approve` đều tạo khoản thu `RENEWAL PENDING` và không thay đổi `EndDate`. +- [ ] Settlement atomic & idempotent: PayOS webhook hoặc Collect Counter chỉ cập nhật `EndDate = NewEndDate` đúng 1 lần. +- [ ] Quá hạn thanh toán chuyển renewal sang `EXPIRED`. +- [ ] GET `/api/rental-policy` trả bản mới nhất; `POST /api/rental-policy/actions` tạo bản mới cho role OPERATIONS. +- [ ] Migration mới đồng bộ model snapshot (`dotnet ef migrations has-pending-model-changes` pass 0 changes). +- [ ] Solution build 0 lỗi, xUnit test pass. diff --git a/docs/verification/dat-renewal-policy-2026-10.md b/docs/verification/dat-renewal-policy-2026-10.md new file mode 100644 index 0000000..1a08744 --- /dev/null +++ b/docs/verification/dat-renewal-policy-2026-10.md @@ -0,0 +1,214 @@ +# Báo cáo kiểm chứng Backend: T02, T03, T04, T20 (Chính sách D32) + +- **Người thực hiện:** Đạt (Backend Agent) +- **Nhánh thực hiện:** `feature/dat-renewal-policy-d32` +- **Mã commit base:** `0f0194b` (`origin/main`) +- **Quyết định nghiệp vụ áp dụng:** D32 (kế hoạch hoàn thiện 26–31/10/2026), bảo toàn D23–D26, D27, D29, D31. +- **Tài liệu hợp đồng FE liên quan:** `SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md` (mục D32), `BE-CONTRACT.md`, `APPROVED-FE-API-GAPS.md`. + +--- + +## 1. Tóm tắt phạm vi triển khai + +1. **T02 — Duyệt gia hạn hợp đồng không đổi EndDate (P0):** + - Khách hàng gửi yêu cầu gia hạn: bắt buộc kiểm tra ngày kết thúc hợp đồng theo giờ Việt Nam (`contract.EndDate > vnToday`), kiểm tra không có yêu cầu đang mở, và yêu cầu phiên bản chính sách (`policyVersion`) kèm chấp thuận (`accepted = true`). + - Duyệt gia hạn (`FacilityOpsService.ApproveRenewalAsync`, `RenewalService.ApproveRenewalAsync`, và legacy route `ManagerService.ApproveRenewalAsync`): + - Chốt lại đơn giá tại thời điểm duyệt theo `rental_rates` hiệu lực. + - **Tuyệt đối không tăng `contract.EndDate` khi duyệt.** + - Tạo khoản thanh toán `payments` kiểu `RENEWAL`, trạng thái `PENDING`, gắn `RenewalId` và `ContractId`. + - Tính hạn thanh toán: `PaymentDeadlineAt = min(ApprovedAt + 24h, 00:00 EndDate theo giờ VN)`. + - Quá hạn thanh toán: background service `ExpiredRenewalWorker` quét định kỳ 1 phút, chuyển `contract_renewals.Status = 'EXPIRED'`, `ExpiredAt = now`, và `payments.Status = 'FAILED'`. `contract.EndDate` được giữ nguyên. + +2. **T03 — PayOS cho gia hạn hợp đồng (P0):** + - `POST /api/payments/{id}/payos`: kiểm tra quyền sở hữu của khách hàng, tạo link checkout PayOS theo `paymentId`, lưu `orderCode` vào bảng `payment_checkouts`. + - Webhook `POST /api/payments/payos-webhook`: + - Kiểm tra chữ ký bằng PayOS SDK 2.1.0 và Checksum Key. + - Đối soát chính xác `orderCode` và `amount`. + - Chống trùng lặp (idempotency): nếu thanh toán đã `PAID`, trả kết quả thành công và không kéo dài ngày lần thứ hai. + - Giao dịch thanh toán gia hạn (`RenewalSettlement.RecordAsync`): dùng lock ứng dụng SQL Server `contract:{id}`, ghi `payments.Status = 'PAID'`, `contract_renewals.Status = 'PAID'`, `AppliedAt = now`, và cập nhật `contract.EndDate = renewal.NewEndDate` **đúng một lần**. + - Tiền về muộn/sau khi quá hạn/lệch giao dịch: ghi log audit `PAYMENT_REVIEW_REQUIRED`, không tự động gia hạn hợp đồng. + +3. **T04 — Khách chọn trả tại quầy & Nhân viên xác nhận thu tiền mặt (P1):** + - `POST /api/renewals/{id}/counter-payment`: khách hàng chọn trả tại quầy cho yêu cầu đã duyệt (`APPROVED`). Cập nhật `paymentMethod = "CASH"`, hủy an toàn link PayOS đang mở qua `IPayOSGateway.CancelAsync`. Trạng thái vẫn là `APPROVED`, **chưa đổi EndDate**. + - `GET /api/ops/counter-renewals`: danh sách hàng chờ thu tiền mặt tại quầy lọc theo cơ sở phụ trách của nhân viên (`STAFF` hoặc `MANAGER`). + - `POST /api/ops/counter-renewals/actions` `{ action: "COLLECT_RENEWAL", id: "GHQ-xxxx" }`: + - Nhân viên cơ sở xác nhận đã thu đủ tiền mặt. + - Ghi nhận thanh toán CASH, cập nhật `contract_renewals.Status = 'PAID'`, và kéo dài `contract.EndDate = renewal.NewEndDate` **đúng một lần**. + - Chặn thu trùng lặp: nếu khoản gia hạn đã được thu, từ chối với lỗi "Khoản gia hạn đã được thu. Không thu lần nữa." + +4. **T20 — Quản lý phiên bản chính sách cho thuê & Consent (P0):** + - Bảng mới `rental_policy_versions`: lưu trữ các bản snapshot chính sách bất biến (Version, Rate, 7 sections: `payment`, `access`, `renewal`, `overdue`, `return`, `cancellation`, `support`). + - `GET /api/rental-policy`: API công khai trả về phiên bản chính sách hiện hành (`RentalPolicyDto`). + - `GET /api/rental-policy/versions/{version}`: API công khai tra cứu lịch sử phiên bản bất biến. + - `POST /api/rental-policy/actions` `{ action: "SAVE_RENTAL_POLICY", ... }`: chỉ cho phép `OPERATIONS` hoặc `ADMIN`. Tạo bản ghi phiên bản mới, đồng bộ tỷ lệ vào bảng `policies` (`PolicyType = 'OVERDUE'`). Kiểm tra xung đột lạc quan (optimistic concurrency), trả 409 Conflict nếu version gửi lên đã cũ. + - Bảng mới `policy_consents`: lưu trữ lịch sử khách hàng đồng ý chính sách (Version, thời điểm UTC server, channel `WEB`/`COUNTER_CUSTOMER`), liên kết với `ReservationId`, `ContractId`, `RenewalId`. + - `POST /api/reservations/{id}/policy-consent`: ghi nhận bằng chứng đồng ý chính sách khi khách tự xác nhận lúc thu tại quầy. + +--- + +## 2. Danh sách file thay đổi & tạo mới + +### Core (Entities, DTOs, Interfaces) +- `StorageProject.Core/Entities/ContractRenewal.cs`: bổ sung `PaymentDeadlineAt`, `AppliedAt`, `ExpiredAt`, `PolicyVersion`, `AcceptedAt`, `PolicyConsents`. +- `StorageProject.Core/Entities/Payment.cs`: navigation `Checkouts`. +- `StorageProject.Core/Entities/PaymentCheckout.cs` (Mới): theo dõi orderCode checkout PayOS. +- `StorageProject.Core/Entities/RentalPolicyVersion.cs` (Mới): phiên bản chính sách cho thuê bất biến. +- `StorageProject.Core/Entities/PolicyConsent.cs` (Mới): bằng chứng đồng ý chính sách của khách. +- `StorageProject.Core/Entities/Reservation.cs` & `RentalContract.cs`: navigation `PolicyConsents`. +- `StorageProject.Core/DTOs/Renewal/RenewalDtos.cs`: bổ sung trường D32 vào `CreateRenewalRequest` và `RenewalDto`. +- `StorageProject.Core/DTOs/Renewal/CounterRenewalDtos.cs` (Mới): DTOs cho hàng chờ thu tiền tại quầy. +- `StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs` (Mới): DTOs cho chính sách và consent. +- `StorageProject.Core/DTOs/Payment/PayOSDtos.cs`: thêm `PayosCheckoutDto`. +- `StorageProject.Core/DTOs/Payment/PaymentDtos.cs`: thêm `PaymentDeadlineAt`. +- `StorageProject.Core/Interfaces/IServices.cs`: mở rộng `IRenewalService`, thêm `IRentalPolicyService`. +- `StorageProject.Core/Interfaces/IPayOSService.cs`: thêm `CreateRenewalPaymentQrAsync`. + +### Infrastructure (Data, Configurations, Services) +- `StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs`: check constraint `contract_renewals.Status` có `'EXPIRED'`, filtered unique index trên `ContractId` cho PENDING/APPROVED, filtered unique index trên `payments.RenewalId`. +- `StorageProject.Infrastructure/Data/Configurations/PaymentCheckoutConfiguration.cs` (Mới). +- `StorageProject.Infrastructure/Data/Configurations/RentalPolicyConfigurations.cs` (Mới). +- `StorageProject.Infrastructure/Data/AppDbContext.cs`: DbSet `PaymentCheckouts`, `RentalPolicyVersions`, `PolicyConsents`. +- `StorageProject.Infrastructure/Migrations/20261027165711_AddRenewalSettlementAndPolicyConsent.cs` (Migration mới). +- `StorageProject.Infrastructure/Data/DbSeeder.cs`: seed phiên bản chính sách mặc định Version 1, Rate 5.0%. +- `StorageProject.Infrastructure/Services/PayOSGateway.cs`: mở rộng `IPayOSGateway.CreateRenewalAsync`. +- `StorageProject.Infrastructure/Services/RenewalSettlement.cs` (Mới): xử lý settlement atomic & idempotent cho PayOS và tiền mặt. +- `StorageProject.Infrastructure/Services/RentalPolicyService.cs` (Mới): dịch vụ quản lý phiên bản chính sách và consent. +- `StorageProject.Infrastructure/Services/RenewalService.cs`: cập nhật toàn bộ luồng request, approve, counter-payment, collect cash, expire. +- `StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs`: cập nhật `ApproveRenewalAsync` theo D32. +- `StorageProject.Infrastructure/Services/ManagerService.cs`: cập nhật route legacy theo D32. +- `StorageProject.Infrastructure/Services/PayOSService.cs`: hỗ trợ checkout PayOS renewal và webhook settlement. +- `StorageProject.Infrastructure/Services/PaymentService.cs`: trả về `PaymentDeadlineAt`. + +### API & Workers +- `StorageProject.Api/Endpoints/PaymentEndpoints.cs`: bổ sung `POST /api/payments/{id:long}/payos`. +- `StorageProject.Api/Endpoints/RenewalEndpoints.cs`: cập nhật xử lý consent. +- `StorageProject.Api/Endpoints/CounterRenewalEndpoints.cs` (Mới): endpoints cho T04. +- `StorageProject.Api/Endpoints/RentalPolicyEndpoints.cs` (Mới): endpoints cho T20. +- `StorageProject.Api/Workers/ExpiredRenewalWorker.cs` (Mới): worker quét định kỳ xử lý hết hạn thanh toán gia hạn. +- `StorageProject.Api/Program.cs`: đăng ký DI, worker và map endpoints mới. + +### Tests & Documentation +- `StorageProject.Tests/RenewalPolicyD32Tests.cs` (Mới): 8 test cases chuyên sâu kiểm tra toàn diện T02, T03, T04, T20 và Expiry. +- `docs/sprints/dat-renewal-policy-d32.md` (Mới): sprint contract. +- `docs/verification/dat-renewal-policy-2026-10.md` (Mới): tài liệu kiểm chứng này. + +--- + +## 3. Bằng chứng kiểm thử tự động + +### 3.1. Build Solution Release +Lệnh thực hiện: +```powershell +dotnet build StorageProject.slnx -c Release --no-restore -m:1 +``` +Kết quả: +`Build succeeded. 0 Warning(s) / 0 Error(s) trên mã nguồn mới` (chỉ có warning NU1902/NU1903 về vulnerability của thư viện `System.Security.Cryptography.Pkcs` có sẵn trong template .NET). + +### 3.2. Migration Model Consistency +Lệnh thực hiện: +```powershell +dotnet ef migrations has-pending-model-changes --configuration Release --project StorageProject.Infrastructure --startup-project StorageProject.Api +``` +Kết quả: +`No changes have been made to the model since the last migration.` (Hoàn toàn đồng bộ với EF snapshot). + +### 3.3. Unit Test Suite +Lệnh thực hiện: +```powershell +dotnet test StorageProject.Tests/StorageProject.Tests.csproj -c Release +``` +Kết quả: +`Passed! - Failed: 0, Passed: 96, Skipped: 0, Total: 96, Duration: 3 s` +Bao gồm toàn bộ 88 test cases cũ và 8 test cases mới: +- `T02_ApproveRenewal_DoesNotChangeContractEndDate_AndCreatesPendingRenewalPayment`: PASS +- `T02_LegacyManagerApprove_FollowsSameRules_DoesNotChangeEndDate`: PASS +- `T02_ApproveRenewal_Twice_IsIdempotent_DoesNotCreateDuplicatePayment`: PASS +- `T03_PayOS_CreatesRenewalLink_AndWebhookSettlesEndDateExactlyOnce`: PASS +- `T04_CounterPayment_CustomerSelectsAndStaffCollectsCash_LengthensEndDateOnce`: PASS +- `T20_PolicyVersioning_OperationsCanPublish_AndConcurrencyConflictDetected`: PASS +- `T20_PolicyConsent_RecordedWithServerTimeAndChannel`: PASS +- `Expiry_PastDeadlineRenewal_ExpiresAutomatically`: PASS + +### 3.4. Git Cleanliness +Lệnh thực hiện: +```powershell +git diff --check +``` +Kết quả: Không có lỗi trailing whitespace hoặc định dạng. + +--- + +## 4. Hướng dẫn kiểm chứng tích hợp thực tế (Manual / SQL Server / PayOS) + +### Kịch bản 1: Kiểm chứng T02 — Phê duyệt gia hạn giữ nguyên EndDate +1. Khách hàng (`customer01`) gọi `POST /api/contracts/{id}/renew` kèm `{ renewalPeriodMonths: 3, policyVersion: 1, accepted: true }`. +2. Kiểm tra DB: `contract_renewals` có dòng mới trạng thái `PENDING`. `contracts.EndDate` giữ nguyên. +3. Quản lý (`manager01`) gọi `POST /api/ops/renewals/{id}/approve` (hoặc `POST /api/manager/renewals/{id}/approve`). +4. Kiểm tra DB: + - `contract_renewals.Status` = `APPROVED`. + - `contract_renewals.PaymentDeadlineAt` = thời điểm duyệt + 24 giờ (hoặc 00:00 EndDate nếu EndDate đến trước). + - `payments` có dòng mới `PaymentType = 'RENEWAL'`, `Status = 'PENDING'`, `Amount` = 3 tháng tiền thuê. + - **`contracts.EndDate` vẫn là ngày cũ, tuyệt đối chưa được gia hạn.** + +### Kịch bản 2: Kiểm chứng T03 — Thanh toán PayOS & Webhook Idempotency +1. Khách hàng mở modal thanh toán, gọi `POST /api/payments/{paymentId}/payos`. Nhận về link và mã QR PayOS. +2. Webhook PayOS gửi về `POST /api/payments/payos-webhook` với dữ liệu khớp `orderCode` và `amount`. +3. Kiểm tra DB: + - `payments.Status` = `PAID`, có `PaidAt`. + - `contract_renewals.Status` = `PAID`, `AppliedAt` có giá trị. + - `contracts.EndDate` = `NewEndDate` (ngày kết thúc được cộng thêm 3 tháng). +4. Replay lại cùng payload Webhook: hệ thống nhận diện idempotent, không kéo dài EndDate lần thứ hai. + +### Kịch bản 3: Kiểm chứng T04 — Thanh toán tại quầy +1. Khách hàng chọn thanh toán tại quầy: `POST /api/renewals/{id}/counter-payment`. +2. Link PayOS cũ bị hủy, `payments.PaymentMethod` chuyển thành `CASH`. +3. Nhân viên cơ sở xem `GET /api/ops/counter-renewals`, thấy dòng `GHQ-xxxx` ở trạng thái `PENDING`. +4. Nhân viên thu tiền mặt, bấm xác nhận: `POST /api/ops/counter-renewals/actions` `{ action: "COLLECT_RENEWAL", id: "GHQ-xxxx" }`. +5. Kiểm tra DB: `payments.Status = 'PAID'`, `contracts.EndDate` kéo dài đúng 1 lần. Gọi lại lần 2 bị từ chối 400. + +### Kịch bản 4: Kiểm chứng T20 — Versioning Chính sách & Consent +1. Gọi `GET /api/rental-policy`: nhận bản `1.0` (Rate 5.0%). +2. Đăng nhập tài khoản `ops01`, gọi `POST /api/rental-policy/actions` để lưu bản mới (Rate 6.0%). +3. Kiểm tra DB: `rental_policy_versions` có version 2 là `IsCurrent = 1`, version 1 chuyển `IsCurrent = 0`. Bảng `policies` loại `OVERDUE` tự động cập nhật `Value = 6.0`. +4. Khách hàng thực hiện gia hạn: bảng `policy_consents` ghi nhận bản ghi với `PolicyVersionId` của version đang áp dụng, `Channel = 'WEB_CUSTOMER'`. + +--- + +## 5. SQL Verification Queries + +```sql +-- 1. Kiểm tra trạng thái gia hạn và khoản thanh toán +SELECT r.RenewalId, r.ContractId, r.Status AS RenewalStatus, r.OldEndDate, r.NewEndDate, + r.PaymentDeadlineAt, r.AppliedAt, r.ExpiredAt, + p.PaymentId, p.PaymentType, p.Amount, p.Status AS PaymentStatus, p.PaymentMethod, p.PaidAt +FROM contract_renewals r +LEFT JOIN payments p ON p.RenewalId = r.RenewalId +WHERE r.ContractId = ; + +-- 2. Kiểm tra ngày kết thúc hợp đồng +SELECT ContractId, StartDate, EndDate, Status +FROM rental_contracts +WHERE ContractId = ; + +-- 3. Kiểm tra phiên bản chính sách và bằng chứng đồng ý +SELECT Version, DisplayVersion, Rate, IsCurrent, PublishedAt +FROM rental_policy_versions +ORDER BY Version DESC; + +SELECT ConsentId, CustomerId, PolicyVersionId, ReservationId, RenewalId, Channel, AcceptedAt +FROM policy_consents +WHERE CustomerId = ; +``` + +--- + +## 6. Đánh giá rủi ro & Runbook an toàn + +1. **Rủi ro Rollback Database:** + - Theo quy tắc D29 và `docs/rollback.md`, tuyệt đối **không chạy `dotnet ef database drop` hay `database update` lùi lại**. + - Mọi thay đổi schema đều là thêm bảng mới (`rental_policy_versions`, `policy_consents`, `payment_checkouts`) và thêm cột có nullable/default value vào `contract_renewals`. + - Nếu cần điều chỉnh, nhóm thực hiện forward-fix bằng migration mới. +2. **Giới hạn môi trường hiện tại:** + - Đã xác thực toàn diện qua 96 unit tests với SQLite in-memory, mock PayOS Gateway và fake clock. + - Phần kiểm thử tích hợp trên SQL Server 2022 thật cần biến môi trường `REQUIRE_SQLSERVER=true` và kết nối database SQL Server được nhóm cấu hình trước khi chạy integration tests. + - Thao tác thanh toán PayOS thật yêu cầu khóa cấu hình API thật từ PayOS. diff --git a/progress.md b/progress.md index 5476f5a..a464e8b 100644 --- a/progress.md +++ b/progress.md @@ -1,3 +1,18 @@ +## 2026-10-28 — T02, T03, T04, T20 BE: Gia hạn, PayOS, thu tại quầy & chính sách cho thuê theo D32 (Đạt) + +- Nền `origin/main` 0f0194b, làm trên nhánh `feature/dat-renewal-policy-d32`. Không commit/push/PR/merge; không tự ý nâng feature passing khi chưa có SQL Server/PayOS thật và thành viên phụ trách xác nhận. +- T02: Duyệt gia hạn (`FacilityOpsService.ApproveRenewalAsync`, `RenewalService.ApproveRenewalAsync`, và legacy `ManagerService.ApproveRenewalAsync`) chốt đơn giá theo rate hiệu lực tại thời điểm duyệt; tạo khoản thanh toán `RENEWAL` `PENDING`, tính hạn thanh toán `PaymentDeadlineAt = min(ApprovedAt + 24h, 00:00 EndDate theo giờ VN)`; **tuyệt đối không tăng EndDate khi duyệt**. `ExpiredRenewalWorker` quét định kỳ 1 phút chuyển các khoản quá hạn sang `EXPIRED`, payment sang `FAILED`, giữ nguyên `EndDate`. +- T03: `POST /api/payments/{id}/payos` tạo link checkout PayOS theo `paymentId`; lưu `PaymentCheckout`. Webhook đối soát chính xác `orderCode` và `amount`, chữ ký SDK, idempotent; thanh toán gia hạn `RenewalSettlement.RecordAsync` cập nhật `payments.Status = 'PAID'`, `contract_renewals.Status = 'PAID'`, `contract.EndDate = renewal.NewEndDate` đúng một lần. Tiền muộn/lệch giao dịch đưa vào audit review `PAYMENT_REVIEW_REQUIRED`, không tự động gia hạn. +- T04: Khách chọn trả tại quầy `POST /api/renewals/{id}/counter-payment` chuyển phương thức `CASH`, huỷ an toàn link PayOS, giữ trạng thái `APPROVED` và chưa đổi `EndDate`. `GET /api/ops/counter-renewals` trả hàng chờ thu tại cơ sở phụ trách. `POST /api/ops/counter-renewals/actions` `{ action: "COLLECT_RENEWAL", id }` xác nhận thu tiền mặt và kéo dài `EndDate` đúng một lần; chặn thu lần hai. +- T20: Thêm bảng `rental_policy_versions` quản lý phiên bản chính sách bất biến (Version, Rate, 7 sections). `GET /api/rental-policy` công khai; `POST /api/rental-policy/actions` chỉ cho phép `OPERATIONS`/`ADMIN`, hỗ trợ optimistic concurrency (409 Conflict) và đồng bộ tỷ lệ quá hạn vào bảng `policies`. Thêm bảng `policy_consents` ghi nhận bằng chứng đồng ý của khách hàng (server timestamp, channel); `POST /api/reservations/{id}/policy-consent` hỗ trợ khách tự xác nhận khi thu tại quầy. +- Database: Thêm migration `20261027165711_AddRenewalSettlementAndPolicyConsent` tạo bảng `payment_checkouts`, `rental_policy_versions`, `policy_consents`, bổ sung cột và check constraint cho `contract_renewals`. `dotnet ef migrations has-pending-model-changes` báo 0 changes. +- Kiểm chứng: + - `dotnet build StorageProject.slnx -c Release --no-restore -m:1`: PASS, 0 Error. + - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj -c Release`: PASS 96/96 tests (toàn bộ 88 tests cũ + 8 tests mới trong `RenewalPolicyD32Tests.cs` kiểm tra T02, T03, T04, T20, Expiry). + - `git diff --check`: PASS, không có trailing whitespace. + - Tạo sprint contract `docs/sprints/dat-renewal-policy-d32.md` và tài liệu nghiệm thu chi tiết `docs/verification/dat-renewal-policy-2026-10.md`. +- Giới hạn: Đã kiểm chứng toàn diện trên in-memory SQLite, fake clock và fake gateway; chưa chạy trên SQL Server thật của nhóm (`REQUIRE_SQLSERVER=true`) và tài khoản PayOS thật. + ## 2026-10-26 — T10 / T15 FE: tiền cọc theo D32 (Thắng) - Nền `origin/main` d57c71b8c2ad69367c90877902b5818781b3222d. Làm trên worktree riêng; không đụng thay đổi cũ, không commit/push/PR/merge. F39/F41 không nâng passing. From 1b5d34a9e9814d0b5a35746d474e7cbfdcc761db Mon Sep 17 00:00:00 2001 From: ryocoding13 Date: Wed, 28 Oct 2026 01:13:18 +0700 Subject: [PATCH 2/2] test(integration): update expected migrations to 8 for D32 renewal policy migration --- .../Tests/SqlServerMigrationAndReadinessTests.cs | 3 ++- progress.md | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/StorageProject.IntegrationTests/Tests/SqlServerMigrationAndReadinessTests.cs b/StorageProject.IntegrationTests/Tests/SqlServerMigrationAndReadinessTests.cs index 5237873..69f582d 100644 --- a/StorageProject.IntegrationTests/Tests/SqlServerMigrationAndReadinessTests.cs +++ b/StorageProject.IntegrationTests/Tests/SqlServerMigrationAndReadinessTests.cs @@ -17,7 +17,8 @@ public sealed class SqlServerMigrationAndReadinessTests(SqlServerFixture fixture "20261014152714_MakeUnitAssignmentAssignedByNullable", "20261015153130_AddFacilityCoordinates", "20261020154838_ReservationPaymentIntegrity", - "20261026093424_AddDepositPercentPerDayCalculationType" + "20261026093424_AddDepositPercentPerDayCalculationType", + "20261027165711_AddRenewalSettlementAndPolicyConsent" ]; [Fact] diff --git a/progress.md b/progress.md index dc96ffc..8181946 100644 --- a/progress.md +++ b/progress.md @@ -8,7 +8,9 @@ - Database: Thêm migration `20261027165711_AddRenewalSettlementAndPolicyConsent` tạo bảng `payment_checkouts`, `rental_policy_versions`, `policy_consents`, bổ sung cột và check constraint cho `contract_renewals`. `dotnet ef migrations has-pending-model-changes` báo 0 changes. - Kiểm chứng: - `dotnet build StorageProject.slnx -c Release --no-restore -m:1`: PASS, 0 Error. - - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj -c Release`: PASS 96/96 tests (toàn bộ 88 tests cũ + 8 tests mới trong `RenewalPolicyD32Tests.cs` kiểm tra T02, T03, T04, T20, Expiry). + - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj -c Release`: PASS 97/97 tests (bao gồm toàn bộ tests nghiệp vụ của T09, T15, T17 và 8 tests mới trong `RenewalPolicyD32Tests.cs` kiểm tra T02, T03, T04, T20, Expiry). + - `dotnet test StorageProject.IntegrationTests/StorageProject.IntegrationTests.csproj -c Release`: PASS 9/9 tests trên SQL Server thật; cập nhật `SqlServerMigrationAndReadinessTests.ExpectedMigrations` nhận diện đủ 8 migrations sau khi gộp. + - `dotnet ef migrations has-pending-model-changes`: PASS, 0 pending changes. - `git diff --check`: PASS, không có trailing whitespace. - Tạo sprint contract `docs/sprints/dat-renewal-policy-d32.md` và tài liệu nghiệm thu chi tiết `docs/verification/dat-renewal-policy-2026-10.md`. - Giới hạn: Đã kiểm chứng toàn diện trên in-memory SQLite, fake clock và fake gateway; chưa chạy trên SQL Server thật của nhóm (`REQUIRE_SQLSERVER=true`) và tài khoản PayOS thật.