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
10 changes: 10 additions & 0 deletions StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ public static void MapFacilityOpsEndpoints(this IEndpointRouteBuilder routes)
Run(async () => Results.Ok(new { item = await ops.ConfirmDepositRefundAsync(Actor(user), request, ct) })))
.WithSummary("CONFIRM_DEPOSIT_REFUND: quản lý ghi mã giao dịch → PAID; expectedVersion cũ trả 409");

// ---- T12 · Hồ sơ quá hạn ngày 20 và biên bản xử lý đồ (D32)
group.MapGet("/overdue-cases", (ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
Run(async () => Results.Ok(await ops.GetOverdueCasesAsync(Actor(user), ct))))
.WithSummary("Danh sách hồ sơ quá hạn của cơ sở phụ trách (mốc ngày 20 xử lý đồ)");

group.MapPost("/overdue-cases/actions", (OverdueCaseActionRequest request, ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
Run(async () => Results.Ok(new { item = await ops.HandleOverdueCaseActionAsync(Actor(user), request, ct) })))
.WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(EvidencePhotos.RequestBodyLimit))
.WithSummary("ASSIGN_REMOVAL (quản lý phân công) / RECORD_REMOVAL (nhân viên/quản lý lưu biên bản xử lý đồ ngày 20 kèm ảnh)");

// ---- T13 · Sự cố do cơ sở (quản lý)
group.MapGet("/incidents", (ClaimsPrincipal user, IFacilityOpsService ops, CancellationToken ct) =>
Run(async () => Results.Ok(await ops.GetIncidentsAsync(Actor(user), ct))))
Expand Down
4 changes: 4 additions & 0 deletions StorageProject.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@
{
builder.Services.AddHostedService<ExpiredCashHoldWorker>();
}
if (builder.Configuration.GetValue<bool>("Worker:EnableOverdue", true))
{
builder.Services.AddHostedService<OverdueWorker>();
}
builder.Services.AddHostedService<ExpiredRenewalWorker>();
builder.Services.AddScoped<IPayOSService, PayOSService>();
builder.Services.AddSingleton(new AccessQrOptions(
Expand Down
37 changes: 37 additions & 0 deletions StorageProject.Api/Workers/OverdueWorker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using StorageProject.Infrastructure.Data;
using StorageProject.Infrastructure.Services;

namespace StorageProject.Api.Workers;

/// <summary>
/// T11 · Tiến trình chạy ngầm quét hợp đồng quá hạn hàng ngày (D32).
/// Định kỳ kiểm tra hợp đồng đến hạn, chuyển EXPIRING/OVERDUE,
/// tính phí 5%/ngày (cap 100% cọc) và tạo/cập nhật OverdueCase.
/// </summary>
public sealed class OverdueWorker(IServiceScopeFactory scopes, ILogger<OverdueWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
do
{
try
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await OverdueProcessor.ProcessDailyOverdueAsync(db, logger, stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
logger.LogError(ex, "Lỗi trong tiến trình quét hợp đồng quá hạn hàng ngày (OverdueWorker).");
}
} while (await timer.WaitForNextTickAsync(stoppingToken));
}
}
55 changes: 55 additions & 0 deletions StorageProject.Core/DTOs/FacilityOps/OverdueCaseDtos.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using StorageProject.Core.DTOs.Evidence;

namespace StorageProject.Core.DTOs.FacilityOps;

/// <summary>
/// Biên bản xử lý đồ quá hạn sau mốc ngày 20 (D32 / T12).
/// Gồm nhân viên thực hiện, kiểm kê tài sản, vị trí đưa ra ngoài và ảnh đối chứng trước/sau.
/// </summary>
public record OverdueRemovalRecordDto(
string Staff,
string Inventory,
string Location,
string PerformedAt,
string SavedAt,
string? UnitStatus = null,
IReadOnlyList<EvidencePhotoDto>? BeforePhotos = null,
IReadOnlyList<EvidencePhotoDto>? AfterPhotos = null
);

/// <summary>
/// DTO hồ sơ quá hạn trả cho nhân viên và quản lý cơ sở (GET /api/ops/overdue-cases).
/// </summary>
public record OverdueCaseDto(
string Id,
long FacilityId,
string ContractId,
string Unit,
string Customer,
decimal Deposit,
string EndDate,
string Status,
string? Assignee,
long? AssigneeId,
int RemovalDay,
IReadOnlyList<string> Notes,
OverdueRemovalRecordDto? Record = null
);

/// <summary>
/// Yêu cầu thao tác trên hồ sơ quá hạn (POST /api/ops/overdue-cases/actions).
/// Hỗ trợ ASSIGN_REMOVAL (quản lý phân công) và RECORD_REMOVAL (nhân viên/quản lý lưu biên bản).
/// </summary>
public record OverdueCaseActionRequest(
string? Action,
string? Id,
string? Assignee = null,
long? AssigneeId = null,
string? PerformedAt = null,
string? Inventory = null,
string? Location = null,
string? UnitStatus = null,
bool? Confirmed = null,
IReadOnlyList<EvidencePhotoUpload>? BeforePhotos = null,
IReadOnlyList<EvidencePhotoUpload>? AfterPhotos = null
);
4 changes: 4 additions & 0 deletions StorageProject.Core/Interfaces/IFacilityOpsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,8 @@ public interface IFacilityOpsService
Task<IncidentReceiptDto> ChooseIncidentOptionAsync(long customerId, string contractCode, IncidentActionRequest request, CancellationToken ct = default);
Task<IncidentReceiptDto> CompleteIncidentTransferAsync(OpsActor actor, string id, IncidentActionRequest request, CancellationToken ct = default);
Task<IncidentReceiptDto> FinalizeIncidentTerminationAsync(OpsActor actor, string id, IncidentActionRequest request, CancellationToken ct = default);

// T12 · Hồ sơ quá hạn ngày 20 và biên bản xử lý đồ (D32)
Task<IReadOnlyList<OverdueCaseDto>> GetOverdueCasesAsync(OpsActor actor, CancellationToken ct = default);
Task<OverdueCaseDto> HandleOverdueCaseActionAsync(OpsActor actor, OverdueCaseActionRequest request, CancellationToken ct = default);
}
24 changes: 19 additions & 5 deletions StorageProject.Infrastructure/Services/ContractService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,16 +180,30 @@ public async Task<MoveOutResponseDto> RegisterMoveOutAsync(long customerId, long
}
var scheduledAt = DateTime.SpecifyKind(request.Date.ToDateTime(timePart).AddHours(-7), DateTimeKind.Utc);

// Nhân viên đang được phân công tại cơ sở của ô kho (quản lý có thể giao lại ở M06).
// Tìm nhân viên (STAFF hoặc MANAGER) đang được phân công tại cơ sở của kho (T17: chặn gán chéo cơ sở)
var staffUser = await dbContext.Users
.Where(u => u.Status == "ACTIVE"
&& u.UserRoles.Any(ur => ur.Role.RoleName == "STAFF")
&& u.UserFacilities.Any(uf => uf.FacilityId == contract.Unit.FacilityId && uf.Status == "ACTIVE"
&& uf.AssignedFrom <= today && (uf.AssignedTo == null || uf.AssignedTo >= today)))
&& u.UserFacilities.Any(uf => uf.FacilityId == contract.Unit.FacilityId
&& uf.Status == "ACTIVE"
&& uf.AssignedFrom <= today
&& (uf.AssignedTo == null || uf.AssignedTo >= today)))
.OrderBy(u => u.UserId)
.FirstOrDefaultAsync(ct)
?? await dbContext.Users.Where(u => u.UserRoles.Any(ur => ur.Role.RoleName == "STAFF")).OrderBy(u => u.UserId).FirstOrDefaultAsync(ct)
?? contract.Customer;
?? await dbContext.Users
.Where(u => u.Status == "ACTIVE"
&& u.UserRoles.Any(ur => ur.Role.RoleName == "MANAGER")
&& u.UserFacilities.Any(uf => uf.FacilityId == contract.Unit.FacilityId
&& uf.Status == "ACTIVE"
&& uf.AssignedFrom <= today
&& (uf.AssignedTo == null || uf.AssignedTo >= today)))
.OrderBy(u => u.UserId)
.FirstOrDefaultAsync(ct);

if (staffUser == null)
{
throw new InvalidOperationException("Cơ sở hiện chưa có nhân viên phụ trách để phân công kiểm tra kho.");
}

var now = DateTime.UtcNow;
var inspection = new StorageProject.Core.Entities.ReturnInspection
Expand Down
Loading
Loading