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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions StorageProject.Api/Endpoints/CounterRenewalEndpoints.cs
Original file line number Diff line number Diff line change
@@ -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;
}
}
14 changes: 14 additions & 0 deletions StorageProject.Api/Endpoints/PaymentEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
83 changes: 83 additions & 0 deletions StorageProject.Api/Endpoints/RentalPolicyEndpoints.cs
Original file line number Diff line number Diff line change
@@ -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;
}
}
4 changes: 4 additions & 0 deletions StorageProject.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,12 @@
builder.Services.AddScoped<IOperationsReportService, OperationsReportService>();
builder.Services.AddScoped<IFacilityOpsService, FacilityOpsService>();
builder.Services.AddScoped<IPayOSGateway, SdkPayOSGateway>();
builder.Services.AddScoped<IRentalPolicyService, RentalPolicyService>();
if (builder.Configuration.GetValue<bool>("Worker:EnableExpiredCashHold", true))
{
builder.Services.AddHostedService<ExpiredCashHoldWorker>();
}
builder.Services.AddHostedService<ExpiredRenewalWorker>();
builder.Services.AddScoped<IPayOSService, PayOSService>();
builder.Services.AddSingleton(new AccessQrOptions(
builder.Configuration["AccessQr:Secret"] ?? jwtSecret,
Expand Down Expand Up @@ -220,6 +222,8 @@
app.MapContractEndpoints();
app.MapPaymentEndpoints();
app.MapRenewalEndpoints();
app.MapCounterRenewalEndpoints();
app.MapRentalPolicyEndpoints();
app.MapSupportTicketEndpoints();
app.MapAdminEndpoints();
app.MapOperationsEndpoints();
Expand Down
37 changes: 37 additions & 0 deletions StorageProject.Api/Workers/ExpiredRenewalWorker.cs
Original file line number Diff line number Diff line change
@@ -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<ExpiredRenewalWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopeFactory.CreateScope();
var renewalService = scope.ServiceProvider.GetRequiredService<IRenewalService>();
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;
}
}
}
}
12 changes: 12 additions & 0 deletions StorageProject.Core/DTOs/Payment/PayOSDtos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
3 changes: 2 additions & 1 deletion StorageProject.Core/DTOs/Payment/PaymentDtos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ public record PaymentDto(
DateOnly? DueDate,
DateTime? PaidAt,
string Status,
DateTime CreatedAt
DateTime CreatedAt,
DateTime? PaymentDeadlineAt = null
);
30 changes: 30 additions & 0 deletions StorageProject.Core/DTOs/Policy/RentalPolicyDtos.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace StorageProject.Core.DTOs.Policy;

public record RentalPolicyDto(
decimal Rate,
Dictionary<string, string> Sections,
int Version,
string DisplayVersion,
DateTime UpdatedAt
);

public record SaveRentalPolicyRequest(
string Action,
decimal? Rate,
Dictionary<string, string>? 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
);
21 changes: 21 additions & 0 deletions StorageProject.Core/DTOs/Renewal/CounterRenewalDtos.cs
Original file line number Diff line number Diff line change
@@ -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
);
12 changes: 10 additions & 2 deletions StorageProject.Core/DTOs/Renewal/RenewalDtos.cs
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -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
);
8 changes: 7 additions & 1 deletion StorageProject.Core/Entities/ContractRenewal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Payment> Payments { get; set; } = [];
public ICollection<PolicyConsent> PolicyConsents { get; set; } = [];
}
1 change: 1 addition & 0 deletions StorageProject.Core/Entities/Payment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PaymentCheckout> Checkouts { get; set; } = [];
}
Loading
Loading