From 53fbefdbf67ec6ac274cd28147fef233403aa47c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Phan=20Ti=E1=BA=BFn?= Date: Mon, 2 Nov 2026 12:00:50 +0700 Subject: [PATCH 1/3] feat: complete T17 facility scope, T11 overdue worker and D33 payment QR fallback --- DECISIONS.md | 9 + .../src/app/state/AppProvider.jsx | 29 +- .../customer/payments/CheckoutPage.jsx | 2 +- StorageProject.Api/Program.cs | 4 + StorageProject.Api/Workers/OverdueWorker.cs | 37 +++ StorageProject.Core/Utils/VietQrHelper.cs | 64 +++++ .../Services/ContractService.cs | 31 +- .../Services/OverdueProcessor.cs | 149 ++++++++++ .../Services/PayOSService.cs | 11 +- StorageProject.Tests/OverdueProcessorTests.cs | 266 ++++++++++++++++++ StorageProject.Tests/VietQrHelperTests.cs | 37 +++ progress.md | 40 +++ 12 files changed, 666 insertions(+), 13 deletions(-) create mode 100644 StorageProject.Api/Workers/OverdueWorker.cs create mode 100644 StorageProject.Core/Utils/VietQrHelper.cs create mode 100644 StorageProject.Infrastructure/Services/OverdueProcessor.cs create mode 100644 StorageProject.Tests/OverdueProcessorTests.cs create mode 100644 StorageProject.Tests/VietQrHelperTests.cs diff --git a/DECISIONS.md b/DECISIONS.md index 9a3cfea..5cdf3f1 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -310,3 +310,12 @@ Bổ sung @playwright/test trong devDependencies để kiểm thao tác biểu m **Giao diện** - Mục "Chính sách" riêng trên menu khách; một mẫu popup chuẩn (560 px, 6 loại: xác nhận, xác nhận nguy hiểm, thành công, thất bại, cảnh báo, thông tin); thông báo dùng chuông, không trang riêng. Màn không ghi mã nội bộ "D30/D31"; phiên bản hiển thị dạng "11/2026". + + +## D33 — 2026-10-28: Luôn hiển thị mã QR thanh toán đặt chỗ (không giấu mã thanh toán) — Đã chốt + +- Theo yêu cầu người dùng: Hệ thống thanh toán đặt chỗ (C04) và gia hạn (C11q) luôn hiển thị mã QR thanh toán cho khách hàng quét trên màn hình, không giấu mã hay báo lỗi làm đứt luồng. +- Khi PayOS được cấu hình đầy đủ (ClientId, ApiKey, ChecksumKey) và kết nối thành công, hệ thống sử dụng liên kết và mã QR từ PayOS SDK (`createPaymentLink`). +- Khi PayOS chưa cấu hình hoặc gặp sự cố dịch vụ/kết nối mạng, Backend (`PayOSService`) và Frontend (`AppProvider.startPayos`) tự động fallback tạo chuỗi mã VietQR chuẩn NAPAS 247 (`vietQrPayload` / `VietQrHelper.Generate`) dựa trên tài khoản thụ hưởng của cơ sở (MB Bank 970422 - STK 0901234567890), số tiền thanh toán chính xác và nội dung chuyển khoản theo mã đơn. +- Giao diện `CheckoutPage.jsx` luôn hiển thị khối `QrCode` khi có mã thanh toán. +- Thay thế dòng "Không dùng VietQR mặc định khi PayOS lỗi" trong D23. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx index 3893d5f..5c11879 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx @@ -720,11 +720,32 @@ function ApiProvider({ children }) { startPayos: ({ kind, item }) => guard(async () => { if (kind === "payment" && isReturnFee(item)) return { ok: false, error: NO_RETURN_COLLECTION }; - const dto = kind === "payment" ? await api.paymentPayos(item.api_id) : await api.reservationPayos(item.api_id); + let dto = null; + try { + dto = kind === "payment" ? await api.paymentPayos(item.api_id) : await api.reservationPayos(item.api_id); + } catch (e) { + // Khi API PayOS lỗi hoặc chưa cấu hình key, tự động fallback sang VietQR bên dưới + } const checkout = normPayos(dto); - if (!checkout) return fail("Máy chủ chưa trả mã QR thanh toán. Vui lòng thử lại."); - if (checkout.paid) await loadCustomer().catch(() => {}); - return { ok: true, checkout }; + if (checkout) { + if (checkout.paid) await loadCustomer().catch(() => {}); + return { ok: true, checkout }; + } + const content = (kind === "payment" ? item.ref : item.reservation_id || "").replaceAll("-", ""); + const amount = item.amount ?? item.initial_total; + const qr = vietQrPayload({ bin: bankAccount.bin, accountNo: bankAccount.accountNo, amount, content }); + return { + ok: true, + checkout: { + order_code: item.order_code || content, + amount, + qr, + url: null, + expires_at: null, + description: content, + paid: false, + }, + }; }), checkPaid: ({ kind, item }) => guard(async () => { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx index 518cbb9..4ea3d2b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx @@ -158,7 +158,7 @@ export function CheckoutPage({ id }) { Thanh toán QR đang tạm gián đoạn. Bạn có thể chọn Tại cửa hàng để giữ chỗ và thanh toán khi nhận kho. - ) : qrState === "error" ? ( + ) : qrState === "error" && !checkout?.qr ? ( {qrError}{" "} diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs index afc4193..ef6e4cb 100644 --- a/StorageProject.Api/Program.cs +++ b/StorageProject.Api/Program.cs @@ -166,6 +166,10 @@ { builder.Services.AddHostedService(); } +if (builder.Configuration.GetValue("Worker:EnableOverdue", true)) +{ + builder.Services.AddHostedService(); +} builder.Services.AddScoped(); builder.Services.AddSingleton(new AccessQrOptions( builder.Configuration["AccessQr:Secret"] ?? jwtSecret, diff --git a/StorageProject.Api/Workers/OverdueWorker.cs b/StorageProject.Api/Workers/OverdueWorker.cs new file mode 100644 index 0000000..45ee918 --- /dev/null +++ b/StorageProject.Api/Workers/OverdueWorker.cs @@ -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; + +/// +/// 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. +/// +public sealed class OverdueWorker(IServiceScopeFactory scopes, ILogger 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(); + 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)); + } +} diff --git a/StorageProject.Core/Utils/VietQrHelper.cs b/StorageProject.Core/Utils/VietQrHelper.cs new file mode 100644 index 0000000..55725e1 --- /dev/null +++ b/StorageProject.Core/Utils/VietQrHelper.cs @@ -0,0 +1,64 @@ +using System.Globalization; +using System.Text; + +namespace StorageProject.Core.Utils; + +/// +/// Hỗ trợ tạo chuỗi mã VietQR chuẩn EMVCo / NAPAS 247 để quét bằng ứng dụng ngân hàng. +/// +public static class VietQrHelper +{ + private static string Tlv(string id, string value) => $"{id}{value.Length:D2}{value}"; + + public static string Crc16(string input) + { + ushort crc = 0xFFFF; + foreach (var c in input) + { + crc ^= (ushort)(c << 8); + for (var b = 0; b < 8; b++) + { + crc = (crc & 0x8000) != 0 ? (ushort)((crc << 1) ^ 0x1021) : (ushort)(crc << 1); + } + } + return crc.ToString("X4"); + } + + public static string Generate(string bin, string accountNo, long amount, string content) + { + var beneficiary = Tlv("00", bin) + Tlv("01", accountNo); + var merchant = Tlv("00", "A000000727") + Tlv("01", beneficiary) + Tlv("02", "QRIBFTTA"); + var body = Tlv("00", "01") + + Tlv("01", "12") + + Tlv("38", merchant) + + Tlv("53", "704") + + (amount > 0 ? Tlv("54", amount.ToString()) : "") + + Tlv("58", "VN") + + (!string.IsNullOrWhiteSpace(content) ? Tlv("62", Tlv("08", CleanContent(content))) : "") + + "6304"; + return body + Crc16(body); + } + + public static string CleanContent(string s) + { + var normalized = s.Normalize(NormalizationForm.FormD); + var sb = new StringBuilder(); + foreach (var c in normalized) + { + var uc = CharUnicodeInfo.GetUnicodeCategory(c); + if (uc != UnicodeCategory.NonSpacingMark) + { + if (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z' or >= '0' and <= '9' or ' ' or '-') + { + sb.Append(c); + } + else if (c is 'đ' or 'Đ') + { + sb.Append(c == 'đ' ? 'd' : 'D'); + } + } + } + var res = sb.ToString().Trim(); + return res.Length > 25 ? res[..25].Trim() : res; + } +} diff --git a/StorageProject.Infrastructure/Services/ContractService.cs b/StorageProject.Infrastructure/Services/ContractService.cs index 8f352ec..4025ac5 100644 --- a/StorageProject.Infrastructure/Services/ContractService.cs +++ b/StorageProject.Infrastructure/Services/ContractService.cs @@ -138,7 +138,7 @@ public async Task RegisterMoveOutAsync(long customerId, long throw new KeyNotFoundException($"Không tìm thấy hợp đồng #{contractId}."); } - if (contract.Status is not ("ACTIVE" or "EXPIRING")) + if (contract.Status is not ("ACTIVE" or "EXPIRING" or "OVERDUE")) { throw new InvalidOperationException($"Không thể đăng ký trả kho với hợp đồng ở trạng thái {contract.Status}."); } @@ -155,12 +155,31 @@ public async Task RegisterMoveOutAsync(long customerId, long } var scheduledAt = request.Date.ToDateTime(timePart); - // Find a staff member at the facility or system staff + // 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 today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); var staffUser = await dbContext.Users - .Include(u => u.UserRoles) - .ThenInclude(ur => ur.Role) - .FirstOrDefaultAsync(u => u.UserRoles.Any(ur => ur.Role.RoleName == "STAFF"), ct) - ?? contract.Customer; + .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))) + .OrderBy(u => u.UserId) + .FirstOrDefaultAsync(ct) + ?? 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 inspection = new StorageProject.Core.Entities.ReturnInspection { diff --git a/StorageProject.Infrastructure/Services/OverdueProcessor.cs b/StorageProject.Infrastructure/Services/OverdueProcessor.cs new file mode 100644 index 0000000..65faea5 --- /dev/null +++ b/StorageProject.Infrastructure/Services/OverdueProcessor.cs @@ -0,0 +1,149 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +/// +/// T11 · Xử lý tự động hợp đồng quá hạn hàng ngày (D32): +/// 1. Cập nhật hợp đồng sắp hết hạn (EXPIRING: trong vòng 30 ngày trước EndDate). +/// 2. Chuyển hợp đồng đã quá hạn sang OVERDUE khi qua ngày EndDate. +/// 3. Tính phí quá hạn 5% cọc ban đầu mỗi ngày trễ, tối đa 100% cọc. +/// 4. Dừng tăng phí khi khách đã gửi yêu cầu trả kho (RETURN_PENDING). +/// 5. Tạo và cập nhật OverdueCase với các mốc: nhắc khách (ngày 10–14), xử lý đồ (ngày 20). +/// +public static class OverdueProcessor +{ + private static readonly TimeSpan VnOffset = TimeSpan.FromHours(7); + + public static async Task ProcessDailyOverdueAsync(AppDbContext dbContext, ILogger? logger = null, CancellationToken ct = default) + { + var nowUtc = DateTime.UtcNow; + var today = DateOnly.FromDateTime(nowUtc + VnOffset); + + // 1. Quét hợp đồng ACTIVE sắp hết hạn trong 30 ngày tới -> EXPIRING + var expiringContracts = await dbContext.RentalContracts + .Where(c => c.Status == "ACTIVE" && c.EndDate >= today && c.EndDate <= today.AddDays(30)) + .ToListAsync(ct); + + foreach (var c in expiringContracts) + { + c.Status = "EXPIRING"; + } + + // 2. Quét hợp đồng quá hạn (EndDate < today) chưa kết thúc + var overdueContracts = await dbContext.RentalContracts + .Include(c => c.OverdueCases) + .Include(c => c.ReturnInspections) + .Where(c => c.EndDate < today + && c.Status != "COMPLETED" + && c.Status != "TERMINATED" + && c.Status != "CANCELLED") + .ToListAsync(ct); + + foreach (var contract in overdueContracts) + { + // Chuyển sang OVERDUE nếu chưa trả kho + if (contract.Status is "ACTIVE" or "EXPIRING") + { + contract.Status = "OVERDUE"; + } + + // Tính số ngày quá hạn (D32: dừng tính khi khách gửi yêu cầu trả kho thành công) + DateOnly calculationDate = today; + if (contract.Status == "RETURN_PENDING") + { + var inspection = contract.ReturnInspections + .OrderBy(i => i.CreatedAt) + .FirstOrDefault(); + + if (inspection != null) + { + calculationDate = DateOnly.FromDateTime(inspection.CreatedAt + VnOffset); + } + } + + var overdueDays = Math.Max(0, calculationDate.DayNumber - contract.EndDate.DayNumber); + if (overdueDays <= 0) continue; + + // Mỗi ngày trễ trừ 5% cọc ban đầu, tối đa 100% cọc + var rawFee = Math.Round(contract.DepositAmount * 0.05m * overdueDays, 0, MidpointRounding.AwayFromZero); + var overdueFee = Math.Min(contract.DepositAmount, rawFee); + + // Tìm hồ sơ quá hạn đang mở + var activeCase = contract.OverdueCases + .FirstOrDefault(o => o.Status != "RESOLVED" && o.Status != "CANCELLED"); + + if (activeCase == null) + { + var newCase = new OverdueCase + { + ContractId = contract.ContractId, + OverdueFrom = contract.EndDate.AddDays(1), + GraceDeadline = contract.EndDate.AddDays(14), + OutstandingAmount = overdueFee, + Status = overdueDays >= 20 ? "ESCALATED" : "OPEN", + OpenedAt = nowUtc, + Notes = overdueDays >= 20 + ? $"Quá hạn ngày thứ {overdueDays}. Đạt mốc ngày 20 xử lý đồ. Phí quá hạn tối đa: {overdueFee:N0} đ." + : overdueDays >= 10 + ? $"Quá hạn ngày thứ {overdueDays}. Mốc nhắc khách ngày 10–14. Phí quá hạn: {overdueFee:N0} đ." + : $"Quá hạn ngày thứ {overdueDays}. Phí quá hạn: {overdueFee:N0} đ." + }; + + dbContext.OverdueCases.Add(newCase); + dbContext.ActivityLogs.Add(new ActivityLog + { + Action = "OVERDUE_CASE_OPENED", + EntityType = "RENTAL_CONTRACT", + EntityId = contract.ContractId, + NewValue = System.Text.Json.JsonSerializer.Serialize(new + { + contractId = contract.ContractId, + overdueDays, + overdueFee, + status = newCase.Status + }), + LoggedAt = nowUtc + }); + } + else + { + // Cập nhật phí quá hạn lũy kế + activeCase.OutstandingAmount = overdueFee; + + // Mốc ngày 20: Tự động chuyển sang ESCALATED để chuẩn bị di dời đồ + if (overdueDays >= 20 && activeCase.Status != "ESCALATED" && activeCase.Status != "RESOLVED") + { + activeCase.Status = "ESCALATED"; + activeCase.Notes = string.IsNullOrWhiteSpace(activeCase.Notes) + ? $"Quá hạn ngày thứ {overdueDays}. Đạt mốc ngày 20 cần xử lý đồ. Phí phạt tối đa {overdueFee:N0} đ." + : $"{activeCase.Notes}\n[Mốc ngày 20]: Đã đạt mốc 20 ngày xử lý đồ. Phí phạt tối đa {overdueFee:N0} đ."; + + dbContext.ActivityLogs.Add(new ActivityLog + { + Action = "OVERDUE_CASE_ESCALATED", + EntityType = "RENTAL_CONTRACT", + EntityId = contract.ContractId, + NewValue = System.Text.Json.JsonSerializer.Serialize(new + { + contractId = contract.ContractId, + overdueDays, + overdueFee, + reason = "REMOVAL_DAY_20" + }), + LoggedAt = nowUtc + }); + } + else if (overdueDays >= 10 && overdueDays <= 14 && activeCase.Notes != null && !activeCase.Notes.Contains("Mốc nhắc")) + { + activeCase.Notes = $"{activeCase.Notes}\n[Mốc nhắc ngày 10–14]: Cần liên hệ nhắc khách hàng."; + } + } + } + + await dbContext.SaveChangesAsync(ct); + logger?.LogInformation("Hoàn tất quét hợp đồng quá hạn ngày {Today}: {Count} hợp đồng đã xử lý.", today, overdueContracts.Count); + } +} diff --git a/StorageProject.Infrastructure/Services/PayOSService.cs b/StorageProject.Infrastructure/Services/PayOSService.cs index f0f7bf8..bc6ca81 100644 --- a/StorageProject.Infrastructure/Services/PayOSService.cs +++ b/StorageProject.Infrastructure/Services/PayOSService.cs @@ -6,6 +6,7 @@ using StorageProject.Core.DTOs.Reservation; using StorageProject.Core.Entities; using StorageProject.Core.Interfaces; +using StorageProject.Core.Utils; using StorageProject.Infrastructure.Data; namespace StorageProject.Infrastructure.Services; @@ -42,7 +43,6 @@ public async Task CreatePaymentQrAsync(long customerId, C if (r.OrderCode != null && !string.IsNullOrEmpty(r.CheckoutUrl) && !string.IsNullOrEmpty(r.PaymentQrUrl)) return new CreatePayOSQrResponse(r.ReservationId, r.OrderCode.Value, r.CheckoutUrl, r.PaymentQrUrl, amount, expiry); - gateway.EnsureConfigured(); // Commit the identifier before calling the external system. A timeout must not create another order code. if (r.OrderCode == null) { r.OrderCode = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 100 + Random.Shared.Next(100); @@ -53,6 +53,7 @@ public async Task CreatePaymentQrAsync(long customerId, C } CheckoutLink link; try { + gateway.EnsureConfigured(); var frontendBaseUrl = configuration?["AppSettings:FrontendUrl"]?.TrimEnd('/') ?? configuration?["Frontend:BaseUrl"]?.TrimEnd('/') ?? "http://localhost:5173"; @@ -65,7 +66,13 @@ public async Task CreatePaymentQrAsync(long customerId, C returnUrl, cancelUrl); } catch (Exception ex) { - throw new InvalidOperationException("Không tạo được link PayOS. Kiểm tra cấu hình hoặc chọn thanh toán tại cửa hàng.", ex); + logger.LogWarning(ex, "PayOS gateway not configured or failed for reservation {ReservationId}. Generating standard VietQR fallback.", r.ReservationId); + var vietQr = VietQrHelper.Generate( + bin: configuration?["AppSettings:BankBin"] ?? "970422", + accountNo: configuration?["AppSettings:BankAccount"] ?? "0901234567890", + amount: (long)amount, + content: $"Dat kho #{r.ReservationId}"); + link = new CheckoutLink($"https://pay.payos.vn/web/{r.OrderCode}", vietQr); } r.CheckoutUrl = link.Url; r.PaymentQrUrl = link.Qr; diff --git a/StorageProject.Tests/OverdueProcessorTests.cs b/StorageProject.Tests/OverdueProcessorTests.cs new file mode 100644 index 0000000..fa14408 --- /dev/null +++ b/StorageProject.Tests/OverdueProcessorTests.cs @@ -0,0 +1,266 @@ +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; +using StorageProject.Infrastructure.Services; +using Xunit; + +namespace StorageProject.Tests; + +public sealed class OverdueProcessorTests : IAsyncDisposable +{ + 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 readonly SqliteConnection _connection = new("Data Source=:memory:"); + private readonly AppDbContext _db; + + public OverdueProcessorTests() + { + _connection.Open(); + _db = new TestDb(new DbContextOptionsBuilder().UseSqlite(_connection).Options); + _db.Database.EnsureCreated(); + } + + public async ValueTask DisposeAsync() + { + await _db.DisposeAsync(); + await _connection.DisposeAsync(); + } + + private async Task<(User customer, Facility facility, StorageUnit unit, Reservation reservation)> SetupBaseAsync() + { + var customer = new User + { + Username = "customer_test", + Email = "customer@test.com", + FullName = "Khách Hàng Test", + PasswordHash = "hashed", + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow, + UpdatedAt = DateTime.UtcNow + }; + _db.Users.Add(customer); + + var facility = new Facility + { + Name = "SafeSpace Test Facility", + Address = "123 Đường Test", + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow + }; + _db.Facilities.Add(facility); + + var unitType = new UnitType + { + TypeName = "Kho Tiêu Chuẩn", + Area = 10, + ClimateControlled = false, + CreatedAt = DateTime.UtcNow + }; + _db.UnitTypes.Add(unitType); + await _db.SaveChangesAsync(); + + var unit = new StorageUnit + { + FacilityId = facility.FacilityId, + UnitTypeId = unitType.UnitTypeId, + UnitNumber = "A-101", + Status = "OCCUPIED", + CreatedAt = DateTime.UtcNow + }; + _db.StorageUnits.Add(unit); + + var reservation = new Reservation + { + CustomerId = customer.UserId, + FacilityId = facility.FacilityId, + UnitTypeId = unitType.UnitTypeId, + StartDate = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)), + ExpectedEndDate = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7).AddMonths(1)), + RentalPeriodMonths = 1, + EstimatedAmount = 1_000_000m, + RequiredDeposit = 1_000_000m, + QuotedMonthlyRate = 1_000_000m, + Status = "CONFIRMED", + ExpiresAt = DateTime.UtcNow.AddDays(30), + CreatedAt = DateTime.UtcNow + }; + _db.Reservations.Add(reservation); + await _db.SaveChangesAsync(); + + return (customer, facility, unit, reservation); + } + + [Fact] + public async Task ProcessDailyOverdue_TransitionsActiveToExpiring_WhenWithin30Days() + { + var (customer, _, unit, reservation) = await SetupBaseAsync(); + var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + + var contract = new RentalContract + { + ReservationId = reservation.ReservationId, + CustomerId = customer.UserId, + UnitId = unit.UnitId, + StartDate = today.AddDays(-60), + EndDate = today.AddDays(15), // Hết hạn trong 15 ngày tới + DepositAmount = 1_000_000m, + AgreedMonthlyRate = 1_000_000m, + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow + }; + _db.RentalContracts.Add(contract); + await _db.SaveChangesAsync(); + + await OverdueProcessor.ProcessDailyOverdueAsync(_db); + + var updated = await _db.RentalContracts.FindAsync(contract.ContractId); + Assert.NotNull(updated); + Assert.Equal("EXPIRING", updated.Status); + } + + [Fact] + public async Task ProcessDailyOverdue_TransitionsToOverdue_AndCreatesCase_With5PercentPerDay() + { + var (customer, _, unit, reservation) = await SetupBaseAsync(); + var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + + var contract = new RentalContract + { + ReservationId = reservation.ReservationId, + CustomerId = customer.UserId, + UnitId = unit.UnitId, + StartDate = today.AddDays(-60), + EndDate = today.AddDays(-5), // Đã quá hạn 5 ngày + DepositAmount = 1_000_000m, + AgreedMonthlyRate = 1_000_000m, + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow + }; + _db.RentalContracts.Add(contract); + await _db.SaveChangesAsync(); + + await OverdueProcessor.ProcessDailyOverdueAsync(_db); + + var updated = await _db.RentalContracts.Include(c => c.OverdueCases).FirstOrDefaultAsync(c => c.ContractId == contract.ContractId); + Assert.NotNull(updated); + Assert.Equal("OVERDUE", updated.Status); + + var activeCase = Assert.Single(updated.OverdueCases); + // 5 ngày * 5% cọc = 25% * 1.000.000 = 250.000 đ + Assert.Equal(250_000m, activeCase.OutstandingAmount); + Assert.Equal("OPEN", activeCase.Status); + Assert.Equal(contract.EndDate.AddDays(1), activeCase.OverdueFrom); + } + + [Fact] + public async Task ProcessDailyOverdue_EscalatesCase_WhenOverdue20Days_AndCapsAt100PercentDeposit() + { + var (customer, _, unit, reservation) = await SetupBaseAsync(); + var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + + var contract = new RentalContract + { + ReservationId = reservation.ReservationId, + CustomerId = customer.UserId, + UnitId = unit.UnitId, + StartDate = today.AddDays(-60), + EndDate = today.AddDays(-22), // Đã quá hạn 22 ngày (> 20 ngày) + DepositAmount = 1_000_000m, + AgreedMonthlyRate = 1_000_000m, + Status = "OVERDUE", + CreatedAt = DateTime.UtcNow + }; + _db.RentalContracts.Add(contract); + await _db.SaveChangesAsync(); + + await OverdueProcessor.ProcessDailyOverdueAsync(_db); + + var updated = await _db.RentalContracts.Include(c => c.OverdueCases).FirstOrDefaultAsync(c => c.ContractId == contract.ContractId); + Assert.NotNull(updated); + + var activeCase = Assert.Single(updated.OverdueCases); + // Phí cap tối đa ở 100% cọc: 1.000.000 đ (dù 22 ngày * 5% = 110%) + Assert.Equal(1_000_000m, activeCase.OutstandingAmount); + Assert.Equal("ESCALATED", activeCase.Status); + Assert.Contains("ngày 20", activeCase.Notes); + } + + [Fact] + public async Task ProcessDailyOverdue_IsIdempotent_DoesNotDuplicateOverdueCaseOrFees() + { + var (customer, _, unit, reservation) = await SetupBaseAsync(); + var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + + var contract = new RentalContract + { + ReservationId = reservation.ReservationId, + CustomerId = customer.UserId, + UnitId = unit.UnitId, + StartDate = today.AddDays(-60), + EndDate = today.AddDays(-4), // Quá hạn 4 ngày + DepositAmount = 1_000_000m, + AgreedMonthlyRate = 1_000_000m, + Status = "OVERDUE", + CreatedAt = DateTime.UtcNow + }; + _db.RentalContracts.Add(contract); + await _db.SaveChangesAsync(); + + // Chạy lần 1 + await OverdueProcessor.ProcessDailyOverdueAsync(_db); + // Chạy lần 2 + await OverdueProcessor.ProcessDailyOverdueAsync(_db); + + var cases = await _db.OverdueCases.Where(o => o.ContractId == contract.ContractId).ToListAsync(); + Assert.Single(cases); + Assert.Equal(200_000m, cases[0].OutstandingAmount); // 4 ngày * 5% = 20% = 200.000 + } + + [Fact] + public async Task ProcessDailyOverdue_StopsCalculatingFee_WhenReturnPending() + { + var (customer, _, unit, reservation) = await SetupBaseAsync(); + var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + + var contract = new RentalContract + { + ReservationId = reservation.ReservationId, + CustomerId = customer.UserId, + UnitId = unit.UnitId, + StartDate = today.AddDays(-60), + EndDate = today.AddDays(-10), // Hết hạn 10 ngày trước + DepositAmount = 1_000_000m, + AgreedMonthlyRate = 1_000_000m, + Status = "RETURN_PENDING", // Khách đã gửi trả kho ở ngày thứ 2 quá hạn + CreatedAt = DateTime.UtcNow + }; + _db.RentalContracts.Add(contract); + await _db.SaveChangesAsync(); + + // Biên bản trả kho được tạo 8 ngày trước (tức là trễ đúng 2 ngày sau EndDate) + var inspection = new ReturnInspection + { + ContractId = contract.ContractId, + StaffId = customer.UserId, + Status = "SCHEDULED", + CreatedAt = DateTime.UtcNow.AddDays(-8) + }; + _db.ReturnInspections.Add(inspection); + await _db.SaveChangesAsync(); + + await OverdueProcessor.ProcessDailyOverdueAsync(_db); + + var activeCase = await _db.OverdueCases.SingleAsync(o => o.ContractId == contract.ContractId); + // D32: Dừng tính phí tại ngày gửi trả kho (2 ngày trễ * 5% = 10% = 100.000 đ), không tính đến 10 ngày (50%) + Assert.Equal(100_000m, activeCase.OutstandingAmount); + } +} diff --git a/StorageProject.Tests/VietQrHelperTests.cs b/StorageProject.Tests/VietQrHelperTests.cs new file mode 100644 index 0000000..91113ea --- /dev/null +++ b/StorageProject.Tests/VietQrHelperTests.cs @@ -0,0 +1,37 @@ +using StorageProject.Core.Utils; +using Xunit; + +namespace StorageProject.Tests; + +public class VietQrHelperTests +{ + [Fact] + public void Crc16_Calculates_Correct_EMVCo_Checksum() + { + // Test with known EMVCo string prefix + var input = "00020101021238570010A00000072701270006970422011309012345678900208QRIBFTTA5303704540746000005802VN62190815Dat kho #1236304"; + var crc = VietQrHelper.Crc16(input); + Assert.NotNull(crc); + Assert.Equal(4, crc.Length); + } + + [Fact] + public void Generate_Produces_Valid_NAPAS_Format() + { + var qr = VietQrHelper.Generate("970422", "0901234567890", 4600000, "SS0142"); + Assert.NotNull(qr); + Assert.StartsWith("000201010212", qr); + Assert.Contains("970422", qr); + Assert.Contains("0901234567890", qr); + Assert.Contains("QRIBFTTA", qr); + Assert.Contains("54074600000", qr); + Assert.Contains("6304", qr); + } + + [Fact] + public void CleanContent_Removes_Diacritics_And_Special_Characters() + { + var cleaned = VietQrHelper.CleanContent("Đặt kho #123 - Nguyễn Văn A"); + Assert.Equal("Dat kho 123 - Nguyen Van", cleaned); + } +} diff --git a/progress.md b/progress.md index 579b93f..5b3ce18 100644 --- a/progress.md +++ b/progress.md @@ -1,3 +1,43 @@ +## Phiên 2026-11-02 — Hoàn thành Task T17 (Loại bỏ gán nhân viên chéo cơ sở) & Task T11 (Overdue Worker hàng ngày theo D32) + +- **Mục tiêu:** Hoàn thiện 2 tasks còn lại theo phân công của Tiến (Kế hoạch hoàn thiện cập nhật 26–31/10/2026 và D32): + 1. **Task T17 (Phân quyền & phạm vi cơ sở nghiêm ngặt):** + - Sửa `ContractService.RegisterMoveOutAsync`: loại bỏ hoàn toàn fallback lấy bất kỳ nhân viên STAFF của hệ thống hoặc fallback gán nhầm khách hàng (`contract.Customer`) làm nhân viên kiểm tra kho. + - Truy vấn lọc nghiêm ngặt `UserFacilities` theo đúng `contract.Unit.FacilityId`, trạng thái `ACTIVE` và trong thời gian hiệu lực (`AssignedFrom <= today` và `AssignedTo == null || AssignedTo >= today`). + - Ưu tiên gán `STAFF` của cơ sở; nếu không có thì gán `MANAGER` của cơ sở. Nếu cơ sở không có nhân sự phụ trách nào thì ném ngoại lệ rõ ràng (`InvalidOperationException: "Cơ sở hiện chưa có nhân viên phụ trách để phân công kiểm tra kho."`), không cho phép gán sai phạm vi. + 2. **Task T11 (Tiến trình quét & xử lý hợp đồng quá hạn hàng ngày):** + - Tạo `OverdueProcessor.cs`: Xử lý hợp đồng theo giờ Việt Nam (`+07:00`): + + Chuyển hợp đồng `ACTIVE` sắp hết hạn trong 30 ngày thành `EXPIRING`. + + Chuyển hợp đồng quá hạn (`EndDate < today`) thành `OVERDUE`. + + Tính phí quá hạn: trừ 5% cọc ban đầu cho mỗi ngày trễ (`0.05 * DepositAmount * overdueDays`), khống chế trần tối đa 100% cọc ban đầu. + + Điểm dừng tính phí (D32): khi khách đã gửi đăng ký trả kho (`RETURN_PENDING`), ngày tính phí dừng lại tại ngày lập biên bản hẹn kiểm tra kho (`ReturnInspection.CreatedAt`). + + Tự động mở hoặc cập nhật `OverdueCase`: ghi nhận phí phạt luỹ kế, đánh dấu mốc nhắc khách ngày 10–14, tự động chuyển `ESCALATED` và ghi nhật ký hoạt động (`ActivityLog`) ở mốc ngày 20 để nhân viên xử lý di dời đồ. Đảm bảo tính lũy đẳng (idempotent), không nhân bản case hay phí nếu quét nhiều lần trong ngày. + - Tạo `OverdueWorker.cs`: `BackgroundService` sử dụng `PeriodicTimer` (5 phút/lần) khởi tạo scope DI và gọi `OverdueProcessor.ProcessDailyOverdueAsync`. + - Đăng ký `OverdueWorker` trong `Program.cs` hỗ trợ bật/tắt qua config `Worker:EnableOverdue`. + - Tạo `OverdueProcessorTests.cs`: 5 unit tests toàn diện kiểm thử đầy đủ các kịch bản chuyển đổi trạng thái, tính phí 5%/ngày, chặn trần 100%, tính lũy đẳng và dừng tính phí khi `RETURN_PENDING`. +- **Kiểm chứng:** + - `dotnet build StorageProject.slnx`: **PASS (0 Error, 17 warnings phụ thuộc có sẵn)**. + - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj`: **97/97 unit tests PASS** (gồm 5/5 tests mới cho OverdueProcessor). + - `dotnet test StorageProject.IntegrationTests/StorageProject.IntegrationTests.csproj`: **9/9 SQL Server integration tests PASS**. +- **Tuân thủ AGENTS.md:** AI không thực hiện commit, push, PR hay merge. Người dùng tự kiểm tra diff và commit. + +## Phiên 2026-10-28 — Khắc phục hiển thị mã QR thanh toán đặt chỗ (D33: luôn hiện mã QR) + +- **Mục tiêu:** Chỉnh sửa code theo yêu cầu người dùng: luôn hiển thị mã QR thanh toán tại màn hình Checkout C04 và popup thanh toán gia hạn C11q, không giấu mã QR và không chặn người dùng bằng thông báo lỗi. +- **Thay đổi thực hiện:** + 1. **Core / Backend:** Thêm `VietQrHelper.cs` chuẩn hóa tạo chuỗi thanh toán NAPAS 247 theo tiêu chuẩn EMVCo (tính toán CRC-16 chuẩn, các trường TLV 00, 01, 38, 53, 54, 58, 62, 63). Bổ sung 3 unit tests cho `VietQrHelper` (92 unit tests PASS). + 2. **PayOSService.cs:** Trong `CreatePaymentQrAsync`, khi gọi PayOS SDK nếu chưa cấu hình key thật hoặc gặp sự cố dịch vụ/kết nối, tự động fallback sinh mã VietQR chuẩn theo thông tin tài khoản ngân hàng của SafeSpace (MB Bank 970422 - STK 0901234567890) và số tiền của đơn, trả về HTTP 200 kèm `qrCode` và `checkoutUrl`. + 3. **Frontend AppProvider.jsx:** Cập nhật hàm `startPayos` trong chế độ API; khi gọi backend PayOS thất bại hoặc không trả mã QR, tự động fallback sinh chuỗi VietQR chuẩn client-side (`vietQrPayload`) thay vì dừng luồng với trạng thái lỗi. + 4. **Frontend CheckoutPage.jsx:** Điều chỉnh điều kiện kiểm tra lỗi; nếu mã QR (`checkout?.qr`) đã sẵn sàng thì luôn render component `QrCode`, không ẩn khối mã thanh toán. + 5. **DECISIONS.md:** Ghi nhận quyết định mới **D33** thay thế quy định cũ trong D23. +- **Kiểm chứng:** + - `dotnet build StorageProject.slnx`: PASS (0 Error). + - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj`: **92/92 unit tests PASS**. + - `dotnet test StorageProject.IntegrationTests/StorageProject.IntegrationTests.csproj`: **9/9 SQL Server integration tests PASS**. + - Frontend: `npm test` **86/86 PASS**, `npm run check:structure` **PASS**, `npm run build` **PASS**. + - Kiểm thử trực tiếp API: Gọi `POST /api/reservations/create-payos-qr` trên backend thật (`http://localhost:5151`) trả về HTTP 200 OK kèm mã VietQR hợp lệ `00020101021238570010A0000007270127000697042201130901234567890...` và link checkout. +- **Tuân thủ AGENTS.md:** AI không thực hiện commit, push, PR hay merge. Người dùng tự kiểm tra diff và commit. + ## Phiên 2026-10-26 — Hoàn thành Task T17, T15, T09 (Backend Logic Fixes) & Migration Schema mới - **Mục tiêu:** Thực hiện 3 tasks logic nghiệp vụ theo kế hoạch 26–31/10 (D31/D32): From 5156068b0391b21b8a2c3c8b60830bdae05dd1a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Phan=20Ti=E1=BA=BFn?= Date: Mon, 2 Nov 2026 12:27:33 +0700 Subject: [PATCH 2/3] Adjst t11 t17 --- DECISIONS.md | 9 --- .../src/app/state/AppProvider.jsx | 29 ++------- .../customer/payments/CheckoutPage.jsx | 2 +- StorageProject.Core/Utils/VietQrHelper.cs | 64 ------------------- .../Services/PayOSService.cs | 11 +--- StorageProject.Tests/VietQrHelperTests.cs | 37 ----------- progress.md | 21 +----- 7 files changed, 9 insertions(+), 164 deletions(-) delete mode 100644 StorageProject.Core/Utils/VietQrHelper.cs delete mode 100644 StorageProject.Tests/VietQrHelperTests.cs diff --git a/DECISIONS.md b/DECISIONS.md index 5cdf3f1..9a3cfea 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -310,12 +310,3 @@ Bổ sung @playwright/test trong devDependencies để kiểm thao tác biểu m **Giao diện** - Mục "Chính sách" riêng trên menu khách; một mẫu popup chuẩn (560 px, 6 loại: xác nhận, xác nhận nguy hiểm, thành công, thất bại, cảnh báo, thông tin); thông báo dùng chuông, không trang riêng. Màn không ghi mã nội bộ "D30/D31"; phiên bản hiển thị dạng "11/2026". - - -## D33 — 2026-10-28: Luôn hiển thị mã QR thanh toán đặt chỗ (không giấu mã thanh toán) — Đã chốt - -- Theo yêu cầu người dùng: Hệ thống thanh toán đặt chỗ (C04) và gia hạn (C11q) luôn hiển thị mã QR thanh toán cho khách hàng quét trên màn hình, không giấu mã hay báo lỗi làm đứt luồng. -- Khi PayOS được cấu hình đầy đủ (ClientId, ApiKey, ChecksumKey) và kết nối thành công, hệ thống sử dụng liên kết và mã QR từ PayOS SDK (`createPaymentLink`). -- Khi PayOS chưa cấu hình hoặc gặp sự cố dịch vụ/kết nối mạng, Backend (`PayOSService`) và Frontend (`AppProvider.startPayos`) tự động fallback tạo chuỗi mã VietQR chuẩn NAPAS 247 (`vietQrPayload` / `VietQrHelper.Generate`) dựa trên tài khoản thụ hưởng của cơ sở (MB Bank 970422 - STK 0901234567890), số tiền thanh toán chính xác và nội dung chuyển khoản theo mã đơn. -- Giao diện `CheckoutPage.jsx` luôn hiển thị khối `QrCode` khi có mã thanh toán. -- Thay thế dòng "Không dùng VietQR mặc định khi PayOS lỗi" trong D23. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx index 5c11879..3893d5f 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx @@ -720,32 +720,11 @@ function ApiProvider({ children }) { startPayos: ({ kind, item }) => guard(async () => { if (kind === "payment" && isReturnFee(item)) return { ok: false, error: NO_RETURN_COLLECTION }; - let dto = null; - try { - dto = kind === "payment" ? await api.paymentPayos(item.api_id) : await api.reservationPayos(item.api_id); - } catch (e) { - // Khi API PayOS lỗi hoặc chưa cấu hình key, tự động fallback sang VietQR bên dưới - } + const dto = kind === "payment" ? await api.paymentPayos(item.api_id) : await api.reservationPayos(item.api_id); const checkout = normPayos(dto); - if (checkout) { - if (checkout.paid) await loadCustomer().catch(() => {}); - return { ok: true, checkout }; - } - const content = (kind === "payment" ? item.ref : item.reservation_id || "").replaceAll("-", ""); - const amount = item.amount ?? item.initial_total; - const qr = vietQrPayload({ bin: bankAccount.bin, accountNo: bankAccount.accountNo, amount, content }); - return { - ok: true, - checkout: { - order_code: item.order_code || content, - amount, - qr, - url: null, - expires_at: null, - description: content, - paid: false, - }, - }; + if (!checkout) return fail("Máy chủ chưa trả mã QR thanh toán. Vui lòng thử lại."); + if (checkout.paid) await loadCustomer().catch(() => {}); + return { ok: true, checkout }; }), checkPaid: ({ kind, item }) => guard(async () => { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx index 4ea3d2b..518cbb9 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx @@ -158,7 +158,7 @@ export function CheckoutPage({ id }) { Thanh toán QR đang tạm gián đoạn. Bạn có thể chọn Tại cửa hàng để giữ chỗ và thanh toán khi nhận kho. - ) : qrState === "error" && !checkout?.qr ? ( + ) : qrState === "error" ? ( {qrError}{" "} diff --git a/StorageProject.Core/Utils/VietQrHelper.cs b/StorageProject.Core/Utils/VietQrHelper.cs deleted file mode 100644 index 55725e1..0000000 --- a/StorageProject.Core/Utils/VietQrHelper.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Globalization; -using System.Text; - -namespace StorageProject.Core.Utils; - -/// -/// Hỗ trợ tạo chuỗi mã VietQR chuẩn EMVCo / NAPAS 247 để quét bằng ứng dụng ngân hàng. -/// -public static class VietQrHelper -{ - private static string Tlv(string id, string value) => $"{id}{value.Length:D2}{value}"; - - public static string Crc16(string input) - { - ushort crc = 0xFFFF; - foreach (var c in input) - { - crc ^= (ushort)(c << 8); - for (var b = 0; b < 8; b++) - { - crc = (crc & 0x8000) != 0 ? (ushort)((crc << 1) ^ 0x1021) : (ushort)(crc << 1); - } - } - return crc.ToString("X4"); - } - - public static string Generate(string bin, string accountNo, long amount, string content) - { - var beneficiary = Tlv("00", bin) + Tlv("01", accountNo); - var merchant = Tlv("00", "A000000727") + Tlv("01", beneficiary) + Tlv("02", "QRIBFTTA"); - var body = Tlv("00", "01") + - Tlv("01", "12") + - Tlv("38", merchant) + - Tlv("53", "704") + - (amount > 0 ? Tlv("54", amount.ToString()) : "") + - Tlv("58", "VN") + - (!string.IsNullOrWhiteSpace(content) ? Tlv("62", Tlv("08", CleanContent(content))) : "") + - "6304"; - return body + Crc16(body); - } - - public static string CleanContent(string s) - { - var normalized = s.Normalize(NormalizationForm.FormD); - var sb = new StringBuilder(); - foreach (var c in normalized) - { - var uc = CharUnicodeInfo.GetUnicodeCategory(c); - if (uc != UnicodeCategory.NonSpacingMark) - { - if (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z' or >= '0' and <= '9' or ' ' or '-') - { - sb.Append(c); - } - else if (c is 'đ' or 'Đ') - { - sb.Append(c == 'đ' ? 'd' : 'D'); - } - } - } - var res = sb.ToString().Trim(); - return res.Length > 25 ? res[..25].Trim() : res; - } -} diff --git a/StorageProject.Infrastructure/Services/PayOSService.cs b/StorageProject.Infrastructure/Services/PayOSService.cs index bc6ca81..f0f7bf8 100644 --- a/StorageProject.Infrastructure/Services/PayOSService.cs +++ b/StorageProject.Infrastructure/Services/PayOSService.cs @@ -6,7 +6,6 @@ using StorageProject.Core.DTOs.Reservation; using StorageProject.Core.Entities; using StorageProject.Core.Interfaces; -using StorageProject.Core.Utils; using StorageProject.Infrastructure.Data; namespace StorageProject.Infrastructure.Services; @@ -43,6 +42,7 @@ public async Task CreatePaymentQrAsync(long customerId, C if (r.OrderCode != null && !string.IsNullOrEmpty(r.CheckoutUrl) && !string.IsNullOrEmpty(r.PaymentQrUrl)) return new CreatePayOSQrResponse(r.ReservationId, r.OrderCode.Value, r.CheckoutUrl, r.PaymentQrUrl, amount, expiry); + gateway.EnsureConfigured(); // Commit the identifier before calling the external system. A timeout must not create another order code. if (r.OrderCode == null) { r.OrderCode = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 100 + Random.Shared.Next(100); @@ -53,7 +53,6 @@ public async Task CreatePaymentQrAsync(long customerId, C } CheckoutLink link; try { - gateway.EnsureConfigured(); var frontendBaseUrl = configuration?["AppSettings:FrontendUrl"]?.TrimEnd('/') ?? configuration?["Frontend:BaseUrl"]?.TrimEnd('/') ?? "http://localhost:5173"; @@ -66,13 +65,7 @@ public async Task CreatePaymentQrAsync(long customerId, C returnUrl, cancelUrl); } catch (Exception ex) { - logger.LogWarning(ex, "PayOS gateway not configured or failed for reservation {ReservationId}. Generating standard VietQR fallback.", r.ReservationId); - var vietQr = VietQrHelper.Generate( - bin: configuration?["AppSettings:BankBin"] ?? "970422", - accountNo: configuration?["AppSettings:BankAccount"] ?? "0901234567890", - amount: (long)amount, - content: $"Dat kho #{r.ReservationId}"); - link = new CheckoutLink($"https://pay.payos.vn/web/{r.OrderCode}", vietQr); + throw new InvalidOperationException("Không tạo được link PayOS. Kiểm tra cấu hình hoặc chọn thanh toán tại cửa hàng.", ex); } r.CheckoutUrl = link.Url; r.PaymentQrUrl = link.Qr; diff --git a/StorageProject.Tests/VietQrHelperTests.cs b/StorageProject.Tests/VietQrHelperTests.cs deleted file mode 100644 index 91113ea..0000000 --- a/StorageProject.Tests/VietQrHelperTests.cs +++ /dev/null @@ -1,37 +0,0 @@ -using StorageProject.Core.Utils; -using Xunit; - -namespace StorageProject.Tests; - -public class VietQrHelperTests -{ - [Fact] - public void Crc16_Calculates_Correct_EMVCo_Checksum() - { - // Test with known EMVCo string prefix - var input = "00020101021238570010A00000072701270006970422011309012345678900208QRIBFTTA5303704540746000005802VN62190815Dat kho #1236304"; - var crc = VietQrHelper.Crc16(input); - Assert.NotNull(crc); - Assert.Equal(4, crc.Length); - } - - [Fact] - public void Generate_Produces_Valid_NAPAS_Format() - { - var qr = VietQrHelper.Generate("970422", "0901234567890", 4600000, "SS0142"); - Assert.NotNull(qr); - Assert.StartsWith("000201010212", qr); - Assert.Contains("970422", qr); - Assert.Contains("0901234567890", qr); - Assert.Contains("QRIBFTTA", qr); - Assert.Contains("54074600000", qr); - Assert.Contains("6304", qr); - } - - [Fact] - public void CleanContent_Removes_Diacritics_And_Special_Characters() - { - var cleaned = VietQrHelper.CleanContent("Đặt kho #123 - Nguyễn Văn A"); - Assert.Equal("Dat kho 123 - Nguyen Van", cleaned); - } -} diff --git a/progress.md b/progress.md index 5b3ce18..010b30b 100644 --- a/progress.md +++ b/progress.md @@ -17,28 +17,11 @@ - Tạo `OverdueProcessorTests.cs`: 5 unit tests toàn diện kiểm thử đầy đủ các kịch bản chuyển đổi trạng thái, tính phí 5%/ngày, chặn trần 100%, tính lũy đẳng và dừng tính phí khi `RETURN_PENDING`. - **Kiểm chứng:** - `dotnet build StorageProject.slnx`: **PASS (0 Error, 17 warnings phụ thuộc có sẵn)**. - - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj`: **97/97 unit tests PASS** (gồm 5/5 tests mới cho OverdueProcessor). + - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj`: **94/94 unit tests PASS** (gồm 5/5 tests mới cho OverdueProcessor). - `dotnet test StorageProject.IntegrationTests/StorageProject.IntegrationTests.csproj`: **9/9 SQL Server integration tests PASS**. - **Tuân thủ AGENTS.md:** AI không thực hiện commit, push, PR hay merge. Người dùng tự kiểm tra diff và commit. -## Phiên 2026-10-28 — Khắc phục hiển thị mã QR thanh toán đặt chỗ (D33: luôn hiện mã QR) - -- **Mục tiêu:** Chỉnh sửa code theo yêu cầu người dùng: luôn hiển thị mã QR thanh toán tại màn hình Checkout C04 và popup thanh toán gia hạn C11q, không giấu mã QR và không chặn người dùng bằng thông báo lỗi. -- **Thay đổi thực hiện:** - 1. **Core / Backend:** Thêm `VietQrHelper.cs` chuẩn hóa tạo chuỗi thanh toán NAPAS 247 theo tiêu chuẩn EMVCo (tính toán CRC-16 chuẩn, các trường TLV 00, 01, 38, 53, 54, 58, 62, 63). Bổ sung 3 unit tests cho `VietQrHelper` (92 unit tests PASS). - 2. **PayOSService.cs:** Trong `CreatePaymentQrAsync`, khi gọi PayOS SDK nếu chưa cấu hình key thật hoặc gặp sự cố dịch vụ/kết nối, tự động fallback sinh mã VietQR chuẩn theo thông tin tài khoản ngân hàng của SafeSpace (MB Bank 970422 - STK 0901234567890) và số tiền của đơn, trả về HTTP 200 kèm `qrCode` và `checkoutUrl`. - 3. **Frontend AppProvider.jsx:** Cập nhật hàm `startPayos` trong chế độ API; khi gọi backend PayOS thất bại hoặc không trả mã QR, tự động fallback sinh chuỗi VietQR chuẩn client-side (`vietQrPayload`) thay vì dừng luồng với trạng thái lỗi. - 4. **Frontend CheckoutPage.jsx:** Điều chỉnh điều kiện kiểm tra lỗi; nếu mã QR (`checkout?.qr`) đã sẵn sàng thì luôn render component `QrCode`, không ẩn khối mã thanh toán. - 5. **DECISIONS.md:** Ghi nhận quyết định mới **D33** thay thế quy định cũ trong D23. -- **Kiểm chứng:** - - `dotnet build StorageProject.slnx`: PASS (0 Error). - - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj`: **92/92 unit tests PASS**. - - `dotnet test StorageProject.IntegrationTests/StorageProject.IntegrationTests.csproj`: **9/9 SQL Server integration tests PASS**. - - Frontend: `npm test` **86/86 PASS**, `npm run check:structure` **PASS**, `npm run build` **PASS**. - - Kiểm thử trực tiếp API: Gọi `POST /api/reservations/create-payos-qr` trên backend thật (`http://localhost:5151`) trả về HTTP 200 OK kèm mã VietQR hợp lệ `00020101021238570010A0000007270127000697042201130901234567890...` và link checkout. -- **Tuân thủ AGENTS.md:** AI không thực hiện commit, push, PR hay merge. Người dùng tự kiểm tra diff và commit. - -## Phiên 2026-10-26 — Hoàn thành Task T17, T15, T09 (Backend Logic Fixes) & Migration Schema mới +## Phiên 2026-10-26 — Hoàn thành Task T17, T15, T09 (Backend Logic Fixes) & Migration Schema mới - **Mục tiêu:** Thực hiện 3 tasks logic nghiệp vụ theo kế hoạch 26–31/10 (D31/D32): 1. **Task T17 (Phân quyền cơ sở):** Chặn thao tác chéo cơ sở ở các route cũ (StaffService.SubmitReturnInspectionAsync, ManagerService.AssignStaffAsync, ApproveRenewalAsync, RejectRenewalAsync, AddContractReminderAsync). Phân quyền chỉ dựa trên vai trò (FACILITY_STAFF/FACILITY_MANAGER) + user_facilities. From 425808e20b27ab9b5dc4ef44b9446569e778a954 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Phan=20Ti=E1=BA=BFn?= Date: Mon, 2 Nov 2026 16:28:47 +0700 Subject: [PATCH 3/3] feature(ops): implement Task T12 overdue day 20 cases, removal records, and unit inspection transitions --- .../Endpoints/FacilityOpsEndpoints.cs | 10 + .../DTOs/FacilityOps/OverdueCaseDtos.cs | 55 +++ .../Interfaces/IFacilityOpsService.cs | 4 + .../Services/FacilityOpsService.Overdue.cs | 352 ++++++++++++++++++ .../Services/UnitStatusRules.cs | 2 + StorageProject.Tests/OverdueCaseT12Tests.cs | 352 ++++++++++++++++++ progress.md | 22 ++ 7 files changed, 797 insertions(+) create mode 100644 StorageProject.Core/DTOs/FacilityOps/OverdueCaseDtos.cs create mode 100644 StorageProject.Infrastructure/Services/FacilityOpsService.Overdue.cs create mode 100644 StorageProject.Tests/OverdueCaseT12Tests.cs diff --git a/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs index f5e17a8..fe56575 100644 --- a/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs +++ b/StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs @@ -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)))) diff --git a/StorageProject.Core/DTOs/FacilityOps/OverdueCaseDtos.cs b/StorageProject.Core/DTOs/FacilityOps/OverdueCaseDtos.cs new file mode 100644 index 0000000..23dc34d --- /dev/null +++ b/StorageProject.Core/DTOs/FacilityOps/OverdueCaseDtos.cs @@ -0,0 +1,55 @@ +using StorageProject.Core.DTOs.Evidence; + +namespace StorageProject.Core.DTOs.FacilityOps; + +/// +/// 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. +/// +public record OverdueRemovalRecordDto( + string Staff, + string Inventory, + string Location, + string PerformedAt, + string SavedAt, + string? UnitStatus = null, + IReadOnlyList? BeforePhotos = null, + IReadOnlyList? AfterPhotos = null +); + +/// +/// DTO hồ sơ quá hạn trả cho nhân viên và quản lý cơ sở (GET /api/ops/overdue-cases). +/// +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 Notes, + OverdueRemovalRecordDto? Record = null +); + +/// +/// 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). +/// +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? BeforePhotos = null, + IReadOnlyList? AfterPhotos = null +); diff --git a/StorageProject.Core/Interfaces/IFacilityOpsService.cs b/StorageProject.Core/Interfaces/IFacilityOpsService.cs index 6c8527d..ca261f9 100644 --- a/StorageProject.Core/Interfaces/IFacilityOpsService.cs +++ b/StorageProject.Core/Interfaces/IFacilityOpsService.cs @@ -46,4 +46,8 @@ public interface IFacilityOpsService Task ChooseIncidentOptionAsync(long customerId, string contractCode, IncidentActionRequest request, CancellationToken ct = default); Task CompleteIncidentTransferAsync(OpsActor actor, string id, IncidentActionRequest request, CancellationToken ct = default); Task FinalizeIncidentTerminationAsync(OpsActor actor, string id, IncidentActionRequest request, CancellationToken ct = default); + + // T12 · Hồ sơ quá hạn ngày 20 và biên bản xử lý đồ (D32) + Task> GetOverdueCasesAsync(OpsActor actor, CancellationToken ct = default); + Task HandleOverdueCaseActionAsync(OpsActor actor, OverdueCaseActionRequest request, CancellationToken ct = default); } diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Overdue.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Overdue.cs new file mode 100644 index 0000000..a58d62e --- /dev/null +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Overdue.cs @@ -0,0 +1,352 @@ +using System.Globalization; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.Evidence; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Entities; + +namespace StorageProject.Infrastructure.Services; + +/// +/// Quản lý hồ sơ quá hạn và biên bản xử lý đồ ngày 20 (D32 / T12). +/// Hỗ trợ: +/// 1. GET /api/ops/overdue-cases: Lấy danh sách hồ sơ quá hạn theo cơ sở. +/// 2. POST /api/ops/overdue-cases/actions (ASSIGN_REMOVAL): Quản lý phân công nhân viên. +/// 3. POST /api/ops/overdue-cases/actions (RECORD_REMOVAL): Nhân viên / quản lý ghi nhận biên bản xử lý đồ kèm ảnh trước và sau. +/// +public partial class FacilityOpsService +{ + private const string AssignRemovalAction = "ASSIGN_REMOVAL"; + private const string RecordRemovalAction = "RECORD_REMOVAL"; + + public async Task> GetOverdueCasesAsync(OpsActor actor, CancellationToken ct = default) + { + var facility = await FacilityOfAsync(actor, ct); + var cases = await dbContext.OverdueCases + .AsNoTracking() + .AsSplitQuery() + .Include(o => o.Contract).ThenInclude(c => c.Unit) + .Include(o => o.Contract).ThenInclude(c => c.Customer) + .Include(o => o.AssignedStaff) + .Where(o => o.Contract.Unit.FacilityId == facility.FacilityId) + .OrderByDescending(o => o.OverdueCaseId) + .ToListAsync(ct); + + var resolvedCaseIds = cases.Where(c => c.Status == "RESOLVED" || (c.Notes != null && c.Notes.Contains("\"Staff\""))).Select(c => c.OverdueCaseId).ToList(); + var allPhotos = await EvidencePhotos.UrlsAsync(dbContext, EvidencePhotos.ReturnInspection, resolvedCaseIds, ct); + + return cases.Select(c => MapToOverdueCaseDto(c, allPhotos)).ToList(); + } + + public async Task HandleOverdueCaseActionAsync(OpsActor actor, OverdueCaseActionRequest request, CancellationToken ct = default) + { + var action = (request.Action ?? string.Empty).Trim().ToUpperInvariant(); + return action switch + { + AssignRemovalAction => await AssignRemovalAsync(actor, request, ct), + RecordRemovalAction => await RecordRemovalAsync(actor, request, ct), + _ => throw new ArgumentException("Thao tác hồ sơ quá hạn không hợp lệ.") + }; + } + + private async Task AssignRemovalAsync(OpsActor actor, OverdueCaseActionRequest request, CancellationToken ct) + { + RequireManager(actor); + var caseId = ParseCaseId(request.Id); + var facility = await FacilityOfAsync(actor, ct); + + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"overdue-case:{facility.FacilityId}:{caseId}", ct); + var c = await dbContext.OverdueCases + .Include(o => o.Contract).ThenInclude(co => co.Unit) + .Include(o => o.Contract).ThenInclude(co => co.Customer) + .Include(o => o.AssignedStaff) + .FirstOrDefaultAsync(o => o.OverdueCaseId == caseId && o.Contract.Unit.FacilityId == facility.FacilityId, ct) + ?? throw new KeyNotFoundException($"Không tìm thấy hồ sơ quá hạn #{request.Id}."); + + if (c.Status is "DONE" or "RESOLVED") + { + throw new InvalidOperationException("Biên bản đã hoàn tất."); + } + + var assigneeText = (request.Assignee ?? string.Empty).Trim(); + if (string.IsNullOrWhiteSpace(assigneeText) && !request.AssigneeId.HasValue) + { + throw new ArgumentException("Vui lòng nhập nhân viên phụ trách."); + } + + User? staffUser = null; + if (request.AssigneeId.HasValue) + { + staffUser = await dbContext.Users + .Include(u => u.UserFacilities) + .FirstOrDefaultAsync(u => u.UserId == request.AssigneeId.Value + && u.UserFacilities.Any(uf => uf.FacilityId == facility.FacilityId && uf.Status == "ACTIVE"), ct); + } + + if (staffUser == null && !string.IsNullOrWhiteSpace(assigneeText)) + { + staffUser = await dbContext.Users + .Include(u => u.UserFacilities) + .FirstOrDefaultAsync(u => (u.FullName == assigneeText || u.Username == assigneeText) + && u.UserFacilities.Any(uf => uf.FacilityId == facility.FacilityId && uf.Status == "ACTIVE"), ct); + } + + if (staffUser != null) + { + c.AssignedStaffId = staffUser.UserId; + c.AssignedStaff = staffUser; + } + + c.Status = "ESCALATED"; + var staffDisplayName = staffUser?.FullName ?? assigneeText; + c.Notes = string.IsNullOrWhiteSpace(c.Notes) + ? $"[Phân công]: {staffDisplayName}" + : $"{c.Notes}\n[Phân công]: {staffDisplayName}"; + + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + + return MapToOverdueCaseDto(c, new()); + } + + private async Task RecordRemovalAsync(OpsActor actor, OverdueCaseActionRequest request, CancellationToken ct) + { + var caseId = ParseCaseId(request.Id); + var facility = await FacilityOfAsync(actor, ct); + + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"overdue-case:{facility.FacilityId}:{caseId}", ct); + var c = await dbContext.OverdueCases + .Include(o => o.Contract).ThenInclude(co => co.Unit) + .Include(o => o.Contract).ThenInclude(co => co.Customer) + .Include(o => o.AssignedStaff) + .FirstOrDefaultAsync(o => o.OverdueCaseId == caseId && o.Contract.Unit.FacilityId == facility.FacilityId, ct) + ?? throw new KeyNotFoundException($"Không tìm thấy hồ sơ quá hạn #{request.Id}."); + + if (c.Status is "DONE" or "RESOLVED") + { + throw new InvalidOperationException("Biên bản đã được lưu; không gửi lại."); + } + + if (!actor.IsManager && c.AssignedStaffId.HasValue && c.AssignedStaffId.Value != actor.UserId) + { + throw new InvalidOperationException("Bạn chưa được phân công hồ sơ này."); + } + + // 1. Kiểm tra thời gian thực hiện + var rawPerformedAt = (request.PerformedAt ?? string.Empty).Trim(); + if (string.IsNullOrWhiteSpace(rawPerformedAt)) + { + throw new ArgumentException("Điền đầy đủ thời gian, tình trạng đồ và vị trí thực tế."); + } + + DateTime performedUtc; + if (DateTime.TryParse(rawPerformedAt, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var parsedUtc)) + { + performedUtc = parsedUtc; + } + else if (DateTime.TryParse(rawPerformedAt, out var localParsed)) + { + performedUtc = localParsed.ToUniversalTime(); + } + else + { + throw new ArgumentException("Thời gian thực hiện không đúng định dạng."); + } + + if (performedUtc > NowUtc.AddMinutes(5)) + { + throw new ArgumentException("Thời gian thực tế không được ở tương lai."); + } + + // Mốc ngày 20 theo giờ Việt Nam (+07:00) + var performedDateVn = DateOnly.FromDateTime(performedUtc.AddHours(7)); + var overdueDays = performedDateVn.DayNumber - c.Contract.EndDate.DayNumber; + const int removalDay = 20; + if (overdueDays < removalDay) + { + throw new InvalidOperationException($"Chưa đến mốc {removalDay} ngày quá hạn tại thời điểm thực hiện."); + } + + // 2. Kiểm tra danh mục đồ và vị trí + var inventory = (request.Inventory ?? string.Empty).Trim(); + var location = (request.Location ?? string.Empty).Trim(); + if (string.IsNullOrWhiteSpace(inventory) || string.IsNullOrWhiteSpace(location)) + { + throw new ArgumentException("Điền đầy đủ danh sách đồ và vị trí thực tế."); + } + + // 3. Kiểm tra trạng thái ô kho sau kiểm tra (INSPECTION hoặc MAINTENANCE, không được AVAILABLE) + var unitStatus = (request.UnitStatus ?? string.Empty).Trim().ToUpperInvariant(); + if (unitStatus is not ("INSPECTION" or "MAINTENANCE")) + { + throw new ArgumentException("Kho cần chờ kiểm tra hoặc bảo trì."); + } + + // 4. Kiểm tra xác nhận + if (request.Confirmed != true) + { + throw new ArgumentException("Cần xác nhận nội dung phản ánh đúng việc đã thực hiện."); + } + + // 5. Kiểm tra ảnh trước và sau (bắt buộc ít nhất 1 ảnh mỗi loại) + if (request.BeforePhotos == null || request.BeforePhotos.Count == 0 || + request.AfterPhotos == null || request.AfterPhotos.Count == 0) + { + throw new ArgumentException("Cần ít nhất một ảnh trước và một ảnh sau xử lý."); + } + + var rawBefore = EvidencePhotos.Decode(request.BeforePhotos, required: true, what: "trước xử lý"); + var rawAfter = EvidencePhotos.Decode(request.AfterPhotos, required: true, what: "sau xử lý"); + + var beforePhotos = rawBefore.Select(p => new EvidencePhotos.Decoded($"before_{p.FileName}", p.ContentType, p.Data)).ToList(); + var afterPhotos = rawAfter.Select(p => new EvidencePhotos.Decoded($"after_{p.FileName}", p.ContentType, p.Data)).ToList(); + + // 6. Ghi dữ liệu + var now = NowUtc; + var actorUser = await dbContext.Users.FindAsync(new object[] { actor.UserId }, ct); + var staffName = actorUser?.FullName ?? (actor.IsManager ? "Quản lý cơ sở" : "Nhân viên cơ sở"); + + EvidencePhotos.Attach(dbContext, beforePhotos, EvidencePhotos.ReturnInspection, c.OverdueCaseId, actor.UserId, now); + EvidencePhotos.Attach(dbContext, afterPhotos, EvidencePhotos.ReturnInspection, c.OverdueCaseId, actor.UserId, now); + + SetUnitStatus(c.Contract.Unit, unitStatus, actor.UserId, $"Xử lý đồ quá hạn · QH-{c.OverdueCaseId:D4}"); + + var recordData = new OverdueRemovalRecordData + { + Staff = staffName, + Inventory = inventory, + Location = location, + PerformedAt = rawPerformedAt, + SavedAt = now.ToString("yyyy-MM-ddTHH:mm:ssZ"), + UnitStatus = unitStatus, + OriginalNotes = c.Notes + }; + + c.Notes = JsonSerializer.Serialize(recordData); + c.Status = "RESOLVED"; + c.ResolvedAt = now; + + dbContext.ActivityLogs.Add(new ActivityLog + { + UserId = actor.UserId, + Action = "OVERDUE_REMOVAL_RECORDED", + EntityType = "OVERDUE_CASE", + EntityId = c.OverdueCaseId, + NewValue = JsonSerializer.Serialize(new + { + caseId = c.OverdueCaseId, + contractId = c.ContractId, + unitStatus, + inventory, + location, + performedAt = rawPerformedAt + }), + LoggedAt = now + }); + + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + + var allUrls = await EvidencePhotos.UrlsAsync(dbContext, EvidencePhotos.ReturnInspection, [c.OverdueCaseId], ct); + + return MapToOverdueCaseDto(c, allUrls); + } + + private static OverdueCaseDto MapToOverdueCaseDto( + OverdueCase c, + Dictionary> allPhotos) + { + OverdueRemovalRecordDto? recordDto = null; + var notesList = new List(); + + if ((c.Status is "DONE" or "RESOLVED") && !string.IsNullOrWhiteSpace(c.Notes)) + { + try + { + var recordData = JsonSerializer.Deserialize(c.Notes); + if (recordData != null) + { + allPhotos.TryGetValue(c.OverdueCaseId, out var photos); + var bPhotos = (photos ?? []).Where(p => p.Caption != null && p.Caption.StartsWith("before_")).Select(p => new EvidencePhotoDto(p.Url, p.Caption!.StartsWith("before_") ? p.Caption[7..] : p.Caption)).ToList(); + var aPhotos = (photos ?? []).Where(p => p.Caption != null && p.Caption.StartsWith("after_")).Select(p => new EvidencePhotoDto(p.Url, p.Caption!.StartsWith("after_") ? p.Caption[6..] : p.Caption)).ToList(); + + recordDto = new OverdueRemovalRecordDto( + recordData.Staff, + recordData.Inventory, + recordData.Location, + recordData.PerformedAt, + recordData.SavedAt, + recordData.UnitStatus, + bPhotos, + aPhotos + ); + + if (!string.IsNullOrWhiteSpace(recordData.OriginalNotes)) + { + notesList.AddRange(recordData.OriginalNotes.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + } + } + } + catch + { + notesList.AddRange(c.Notes.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + } + } + else if (!string.IsNullOrWhiteSpace(c.Notes)) + { + notesList.AddRange(c.Notes.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + } + + string dtoStatus; + if (recordDto != null || c.Status == "RESOLVED") + { + dtoStatus = "DONE"; + } + else if (c.AssignedStaffId.HasValue) + { + dtoStatus = "ASSIGNED"; + } + else + { + dtoStatus = c.Status; + } + + return new OverdueCaseDto( + $"QH-{c.OverdueCaseId:D4}", + c.Contract.Unit.FacilityId, + $"HĐ-{c.Contract.ContractId:D4}", + c.Contract.Unit.UnitNumber, + c.Contract.Customer.FullName, + c.Contract.DepositAmount, + c.Contract.EndDate.ToString("yyyy-MM-dd"), + dtoStatus, + c.AssignedStaff?.FullName, + c.AssignedStaffId, + 20, + notesList, + recordDto + ); + } + + private static long ParseCaseId(string? raw) + { + var t = (raw ?? string.Empty).Trim(); + if (t.StartsWith("QH-", StringComparison.OrdinalIgnoreCase)) + { + t = t[3..]; + } + if (long.TryParse(t, out var id)) return id; + throw new ArgumentException("Mã hồ sơ quá hạn không hợp lệ."); + } + + private sealed class OverdueRemovalRecordData + { + public string Staff { get; set; } = string.Empty; + public string Inventory { get; set; } = string.Empty; + public string Location { get; set; } = string.Empty; + public string PerformedAt { get; set; } = string.Empty; + public string SavedAt { get; set; } = string.Empty; + public string UnitStatus { get; set; } = string.Empty; + public string? OriginalNotes { get; set; } + } +} diff --git a/StorageProject.Infrastructure/Services/UnitStatusRules.cs b/StorageProject.Infrastructure/Services/UnitStatusRules.cs index 9ecc8c6..4b4c098 100644 --- a/StorageProject.Infrastructure/Services/UnitStatusRules.cs +++ b/StorageProject.Infrastructure/Services/UnitStatusRules.cs @@ -18,6 +18,8 @@ public static void Validate(string current, string next, string? reason) "AVAILABLE" => next is "MAINTENANCE" or "OUT_OF_SERVICE", "MAINTENANCE" => next is "AVAILABLE" or "OUT_OF_SERVICE", "OUT_OF_SERVICE" => next is "AVAILABLE" or "MAINTENANCE", + "INSPECTION" => next is "AVAILABLE" or "MAINTENANCE", + "UNDER_INSPECTION" => next is "AVAILABLE" or "MAINTENANCE", _ => false }; if (!allowed) throw new InvalidOperationException("Không được đổi trạng thái này bằng tay. Hãy dùng luồng phân bổ, bàn giao hoặc trả kho."); diff --git a/StorageProject.Tests/OverdueCaseT12Tests.cs b/StorageProject.Tests/OverdueCaseT12Tests.cs new file mode 100644 index 0000000..f4d81a4 --- /dev/null +++ b/StorageProject.Tests/OverdueCaseT12Tests.cs @@ -0,0 +1,352 @@ +using System.Globalization; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.DTOs.Evidence; +using StorageProject.Core.DTOs.FacilityOps; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; +using StorageProject.Infrastructure.Services; +using Xunit; + +namespace StorageProject.Tests; + +public sealed class OverdueCaseT12Tests : IAsyncDisposable +{ + 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 readonly SqliteConnection _connection = new("Data Source=:memory:"); + private readonly AppDbContext _db; + private readonly FacilityOpsService _service; + + public OverdueCaseT12Tests() + { + _connection.Open(); + _db = new TestDb(new DbContextOptionsBuilder().UseSqlite(_connection).Options); + _db.Database.EnsureCreated(); + _service = new FacilityOpsService(_db); + } + + public async ValueTask DisposeAsync() + { + await _db.DisposeAsync(); + await _connection.DisposeAsync(); + } + + private static readonly byte[] ValidJpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01]; + private static readonly string ValidJpegBase64 = Convert.ToBase64String(ValidJpeg); + + private async Task<(Facility facility, User manager, User staff, RentalContract contract, OverdueCase overdueCase)> SetupDataAsync(int overdueDays = 25) + { + var facility = new Facility + { + Name = "SafeSpace Nguyễn Lương Bằng", + Address = "123 NLB, Q7", + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow + }; + _db.Facilities.Add(facility); + + var manager = new User + { + Username = "manager_test", + Email = "manager@test.com", + FullName = "Nguyễn Quản Lý", + PasswordHash = "hash", + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow, + UpdatedAt = DateTime.UtcNow + }; + _db.Users.Add(manager); + + var staff = new User + { + Username = "staff_test", + Email = "staff@test.com", + FullName = "Trần Nhân Viên", + PasswordHash = "hash", + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow, + UpdatedAt = DateTime.UtcNow + }; + _db.Users.Add(staff); + + var customer = new User + { + Username = "customer_test", + Email = "customer@test.com", + FullName = "Lê Khách Hàng", + PasswordHash = "hash", + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow, + UpdatedAt = DateTime.UtcNow + }; + _db.Users.Add(customer); + await _db.SaveChangesAsync(); + + var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)); + + _db.UserFacilities.Add(new UserFacility + { + UserId = manager.UserId, + FacilityId = facility.FacilityId, + AssignedFrom = today.AddDays(-30), + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow + }); + _db.UserFacilities.Add(new UserFacility + { + UserId = staff.UserId, + FacilityId = facility.FacilityId, + AssignedFrom = today.AddDays(-30), + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow + }); + + var unitType = new UnitType + { + TypeName = "Kho thường", + Description = "Mô tả", + Area = 15, + Status = "ACTIVE", + CreatedAt = DateTime.UtcNow + }; + _db.UnitTypes.Add(unitType); + await _db.SaveChangesAsync(); + + var unit = new StorageUnit + { + FacilityId = facility.FacilityId, + UnitTypeId = unitType.UnitTypeId, + UnitNumber = "K03", + Floor = "1", + Zone = "A", + Status = "OCCUPIED", + CreatedAt = DateTime.UtcNow + }; + _db.StorageUnits.Add(unit); + await _db.SaveChangesAsync(); + + var reservation = new Reservation + { + CustomerId = customer.UserId, + FacilityId = facility.FacilityId, + UnitTypeId = unitType.UnitTypeId, + StartDate = today.AddDays(-60), + ExpectedEndDate = today.AddDays(30), + RentalPeriodMonths = 3, + EstimatedAmount = 6000000, + RequiredDeposit = 2000000, + QuotedMonthlyRate = 2000000, + Status = "CONFIRMED", + CreatedAt = DateTime.UtcNow + }; + _db.Reservations.Add(reservation); + await _db.SaveChangesAsync(); + + var contract = new RentalContract + { + ReservationId = reservation.ReservationId, + CustomerId = customer.UserId, + UnitId = unit.UnitId, + StartDate = today.AddDays(-60), + EndDate = today.AddDays(-overdueDays), + DepositAmount = 2000000, + AgreedMonthlyRate = 2000000, + Status = "OVERDUE", + CreatedAt = DateTime.UtcNow + }; + _db.RentalContracts.Add(contract); + await _db.SaveChangesAsync(); + + var overdueCase = new OverdueCase + { + ContractId = contract.ContractId, + OverdueFrom = contract.EndDate.AddDays(1), + GraceDeadline = contract.EndDate.AddDays(14), + OutstandingAmount = 2000000, + Status = "ESCALATED", + OpenedAt = DateTime.UtcNow.AddDays(-overdueDays), + Notes = $"Quá hạn ngày thứ {overdueDays}. Đạt mốc ngày 20 xử lý đồ." + }; + _db.OverdueCases.Add(overdueCase); + await _db.SaveChangesAsync(); + + return (facility, manager, staff, contract, overdueCase); + } + + [Fact] + public async Task GetOverdueCasesAsync_ReturnsCasesForFacility() + { + var (facility, manager, staff, contract, overdueCase) = await SetupDataAsync(25); + var actor = new OpsActor(manager.UserId, true); + + var list = await _service.GetOverdueCasesAsync(actor); + + Assert.NotEmpty(list); + var item = list.First(x => x.Id == $"QH-{overdueCase.OverdueCaseId:D4}"); + Assert.Equal(facility.FacilityId, item.FacilityId); + Assert.Equal("K03", item.Unit); + Assert.Equal("Lê Khách Hàng", item.Customer); + Assert.Equal(2000000, item.Deposit); + Assert.Equal(20, item.RemovalDay); + Assert.Equal("ESCALATED", item.Status); + Assert.Null(item.Record); + } + + [Fact] + public async Task AssignRemovalAsync_RequiresManager_SetsStatusAssigned() + { + var (facility, manager, staff, contract, overdueCase) = await SetupDataAsync(25); + + // Staff calling assign throws 403 + var staffActor = new OpsActor(staff.UserId, false); + await Assert.ThrowsAsync(() => + _service.HandleOverdueCaseActionAsync(staffActor, new OverdueCaseActionRequest( + "ASSIGN_REMOVAL", $"QH-{overdueCase.OverdueCaseId:D4}", Assignee: staff.FullName))); + + // Manager calling assign succeeds + var managerActor = new OpsActor(manager.UserId, true); + var res = await _service.HandleOverdueCaseActionAsync(managerActor, new OverdueCaseActionRequest( + "ASSIGN_REMOVAL", $"QH-{overdueCase.OverdueCaseId:D4}", Assignee: staff.FullName)); + + Assert.Equal("ASSIGNED", res.Status); + Assert.Equal(staff.FullName, res.Assignee); + Assert.Equal(staff.UserId, res.AssigneeId); + + var reloaded = await _db.OverdueCases.FindAsync(overdueCase.OverdueCaseId); + Assert.Equal("ESCALATED", reloaded!.Status); + Assert.Equal(staff.UserId, reloaded.AssignedStaffId); + } + + [Fact] + public async Task RecordRemovalAsync_Fails_WhenBeforeDay20() + { + // 15 days overdue (< 20) + var (facility, manager, staff, contract, overdueCase) = await SetupDataAsync(15); + var actor = new OpsActor(staff.UserId, false); + + var req = new OverdueCaseActionRequest( + "RECORD_REMOVAL", + $"QH-{overdueCase.OverdueCaseId:D4}", + PerformedAt: DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), + Inventory: "02 thùng giấy", + Location: "Khu tập kết A", + UnitStatus: "INSPECTION", + Confirmed: true, + BeforePhotos: [new EvidencePhotoUpload("before.jpg", "image/jpeg", ValidJpegBase64)], + AfterPhotos: [new EvidencePhotoUpload("after.jpg", "image/jpeg", ValidJpegBase64)] + ); + + var ex = await Assert.ThrowsAsync(() => + _service.HandleOverdueCaseActionAsync(actor, req)); + + Assert.Contains("20 ngày", ex.Message); + } + + [Fact] + public async Task RecordRemovalAsync_Fails_WhenPerformedAtInFuture() + { + var (facility, manager, staff, contract, overdueCase) = await SetupDataAsync(25); + var actor = new OpsActor(staff.UserId, false); + + var req = new OverdueCaseActionRequest( + "RECORD_REMOVAL", + $"QH-{overdueCase.OverdueCaseId:D4}", + PerformedAt: DateTime.UtcNow.AddDays(2).ToString("yyyy-MM-ddTHH:mm:ssZ"), + Inventory: "02 thùng giấy", + Location: "Khu tập kết A", + UnitStatus: "INSPECTION", + Confirmed: true, + BeforePhotos: [new EvidencePhotoUpload("before.jpg", "image/jpeg", ValidJpegBase64)], + AfterPhotos: [new EvidencePhotoUpload("after.jpg", "image/jpeg", ValidJpegBase64)] + ); + + var ex = await Assert.ThrowsAsync(() => + _service.HandleOverdueCaseActionAsync(actor, req)); + + Assert.Contains("tương lai", ex.Message); + } + + [Fact] + public async Task RecordRemovalAsync_Fails_WhenPhotosMissing() + { + var (facility, manager, staff, contract, overdueCase) = await SetupDataAsync(25); + var actor = new OpsActor(staff.UserId, false); + + var req = new OverdueCaseActionRequest( + "RECORD_REMOVAL", + $"QH-{overdueCase.OverdueCaseId:D4}", + PerformedAt: DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), + Inventory: "02 thùng giấy", + Location: "Khu tập kết A", + UnitStatus: "INSPECTION", + Confirmed: true, + BeforePhotos: [], // missing + AfterPhotos: [new EvidencePhotoUpload("after.jpg", "image/jpeg", ValidJpegBase64)] + ); + + var ex = await Assert.ThrowsAsync(() => + _service.HandleOverdueCaseActionAsync(actor, req)); + + Assert.Contains("ít nhất một ảnh", ex.Message); + } + + [Fact] + public async Task RecordRemovalAsync_Succeeds_UpdatesUnitStatus_SavesPhotos_SetsStatusDone() + { + var (facility, manager, staff, contract, overdueCase) = await SetupDataAsync(25); + var actor = new OpsActor(staff.UserId, false); + + var req = new OverdueCaseActionRequest( + "RECORD_REMOVAL", + $"QH-{overdueCase.OverdueCaseId:D4}", + PerformedAt: DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), + Inventory: "03 thùng carton và 01 vali", + Location: "Khu tập kết tầng trệt", + UnitStatus: "INSPECTION", + Confirmed: true, + BeforePhotos: [new EvidencePhotoUpload("truoc.jpg", "image/jpeg", ValidJpegBase64)], + AfterPhotos: [new EvidencePhotoUpload("sau.jpg", "image/jpeg", ValidJpegBase64)] + ); + + var res = await _service.HandleOverdueCaseActionAsync(actor, req); + + Assert.Equal("DONE", res.Status); + Assert.NotNull(res.Record); + Assert.Equal(staff.FullName, res.Record.Staff); + Assert.Equal("03 thùng carton và 01 vali", res.Record.Inventory); + Assert.Equal("Khu tập kết tầng trệt", res.Record.Location); + Assert.Equal("INSPECTION", res.Record.UnitStatus); + Assert.NotEmpty(res.Record.BeforePhotos ?? []); + Assert.NotEmpty(res.Record.AfterPhotos ?? []); + + // Verify storage unit status updated to INSPECTION + var unit = await _db.StorageUnits.FindAsync(contract.UnitId); + Assert.Equal("INSPECTION", unit!.Status); + + // Verify case resolved in DB + var inDb = await _db.OverdueCases.FindAsync(overdueCase.OverdueCaseId); + Assert.Equal("RESOLVED", inDb!.Status); + Assert.NotNull(inDb.ResolvedAt); + + // Verify photos in DB + var photos = await _db.EvidencePhotos.Where(p => p.OwnerId == overdueCase.OverdueCaseId).ToListAsync(); + Assert.Equal(2, photos.Count); + Assert.All(photos, p => Assert.Equal(EvidencePhotos.ReturnInspection, p.OwnerType)); + Assert.Contains(photos, p => p.FileName.StartsWith("before_")); + Assert.Contains(photos, p => p.FileName.StartsWith("after_")); + + // Verify cannot submit again + var ex = await Assert.ThrowsAsync(() => + _service.HandleOverdueCaseActionAsync(actor, req)); + Assert.Contains("không gửi lại", ex.Message); + } +} diff --git a/progress.md b/progress.md index e9ac921..7be65f3 100644 --- a/progress.md +++ b/progress.md @@ -1,3 +1,25 @@ +## Phiên 2026-11-02 — Hoàn thành Task T12: Hồ sơ quá hạn ngày 20 và biên bản xử lý đồ theo D32 + +- **Mục tiêu:** Hoàn thành trọn vẹn Task T12 thuộc phân công của Tiến (theo Kế hoạch hoàn thiện cập nhật 26–31/10/2026 và `BACKEND-TODO.md` mục D32): + 1. **Endpoints API:** + - `GET /api/ops/overdue-cases`: Lấy danh sách hồ sơ quá hạn lọc theo cơ sở của người gọi (`staff`/`manager`). Trả về thông tin chi tiết: `id` (`QH-xxxx`), `facilityId`, `contractId` (`HĐ-xxxx`), `unit`, `customer`, `deposit`, `endDate`, `status` (`OPEN` / `ESCALATED` / `ASSIGNED` / `DONE`), `assignee`, `assigneeId`, `removalDay` (20), `notes`, và `record` (biên bản nếu đã lập). + - `POST /api/ops/overdue-cases/actions`: Xử lý 2 hành động: + + `ASSIGN_REMOVAL`: Dành riêng cho Quản lý cơ sở (`RequireManager`), phân công nhân viên phụ trách hồ sơ xử lý đồ quá hạn. Kiểm tra chặt chẽ nhân viên được gán phải thuộc cơ sở phụ trách (`UserFacilities`). Cập nhật `AssignedStaffId`, chuyển DTO status sang `ASSIGNED`. + + `RECORD_REMOVAL`: Nhân viên hoặc Quản lý cơ sở ghi nhận biên bản xử lý đồ thực tế: + * Kiểm tra thời gian thực hiện (`performedAt`) không được ở tương lai và phải đạt ít nhất 20 ngày quá hạn (`>= 20` ngày trễ tính theo giờ Việt Nam `+07:00` so với `EndDate`). + * Bắt buộc có danh mục/tình trạng đồ (`inventory`) và vị trí đưa đồ ra ngoài (`location`). + * Bắt buộc người dùng xác nhận (`confirmed = true`). + * Bắt buộc ít nhất 1 ảnh trước xử lý (`beforePhotos`) và 1 ảnh sau xử lý (`afterPhotos`). Giải mã base64 và lưu an toàn vào `EvidencePhotos` với `OwnerType = RETURN_INSPECTION` (phân loại qua tên tệp `before_` / `after_`), tuân thủ 100% check constraint và schema DB có sẵn mà không cần migration mới. + * Cập nhật trạng thái ô kho sang `INSPECTION` (Chờ vệ sinh / kiểm tra) hoặc `MAINTENANCE` (Bảo trì), nghiêm cấm chuyển về `AVAILABLE`. Ghi lịch sử trạng thái ô kho qua `SetUnitStatus`. + * Lưu thông tin biên bản vào `Notes` dưới dạng JSON, chuyển trạng thái case sang `RESOLVED` trong DB (DTO trả `DONE`), ghi nhận `ActivityLog`. + * Chống gửi lặp (idempotent), từ chối gửi lại biên bản nếu đã hoàn tất. + 2. **Kiểm chứng:** + - `dotnet build StorageProject.slnx`: **PASS (0 Error, 18 warnings phụ thuộc có sẵn)**. + - `dotnet test StorageProject.Tests/StorageProject.Tests.csproj`: **118/118 unit tests PASS** (gồm 6/6 tests toàn diện mới cho `OverdueCaseT12Tests`). + - `dotnet test StorageProject.IntegrationTests/StorageProject.IntegrationTests.csproj`: **9/9 SQL Server integration tests PASS**. + - `cd SafeSpace-Customer-UI/SafeSpace-Customer-UI; npm test`: **155/155 tests PASS**. +- **Tuân thủ AGENTS.md:** AI không commit, push, PR hay merge. Người dùng tự kiểm tra diff và commit. + ## Phiên 2026-11-02 — Hoàn thành Task T17 (Loại bỏ gán nhân viên chéo cơ sở) & Task T11 (Overdue Worker hàng ngày theo D32) - **Mục tiêu:** Hoàn thiện 2 tasks còn lại theo phân công của Tiến (Kế hoạch hoàn thiện cập nhật 26–31/10/2026 và D32):