using NTP.Application.Abstractions; using NTP.Application.Common; using NTP.Application.Refinery.Integrations; using NTP.Application.Refinery.WageClaims; namespace NTP.Tests.Refinery; public class WageClaimServiceTests { private sealed class FakeUnit : IUnitOfWork { public Task BeginAsync(CancellationToken ct = default) => Task.CompletedTask; public Task CommitAsync(CancellationToken ct = default) => Task.CompletedTask; public Task RollbackAsync(CancellationToken ct = default) => Task.CompletedTask; public Task ExecuteInTransactionAsync(Func> work, CancellationToken ct = default) => work(ct); } private sealed class FakeUser : ICurrentUser { public bool IsAuthenticated => true; public long Id => 77; public string UserId => "TESTER"; public string Name => "t"; public string RoleCode => "REFINERY_MGR"; public string RoleName => "REFINERY_MGR"; public string Domain => "ASEZA"; public long? LocationId => null; public string LocationName => ""; public long? StkId => null; public long? CompId => null; public long? CompanyId => null; public string CompanyName => ""; public string CompanyCode => ""; public string EmpNo => ""; public string Lang => "AR"; public bool IsStaff => false; public bool IsInRole(string roleCode) => true; public bool IsInAnyRole(params string[] roleCodes) => true; } private sealed class FakeGateway(Func answer) : IJopetrolGateway { public readonly List<(string Pn, string ClaimNo)> Calls = []; public Task SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default) { Calls.Add((pn, claimNo)); return Task.FromResult(answer(pn)); } } private sealed class FakeRepo : IWageClaimRepository { public string ClaimStatus = "NEW"; public List TripStatuses = ["EXCHANGED"]; public List ToTransfer = []; public int Candidates = 5; public long? CommissionId; public readonly List Writes = []; public Task> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException(); public Task GetAsync(long id, CancellationToken ct = default) => Task.FromResult(new WageClaimRowDto { Id = id, WageClaimNo = 20230100041, StatusCode = ClaimStatus, CommissionClaimId = CommissionId }); public Task> ClaimTripsAsync(long claimId, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException(); public Task> CandidateTripsAsync(IReadOnlyList statuses, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException(); public Task CountCandidateTripsAsync(IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default) => Task.FromResult(Candidates); public Task InsertClaimAsync(string createdBy, CancellationToken ct = default) { Writes.Add("insert:" + createdBy); return Task.FromResult(9L); } public Task AttachTripsAsync(long claimId, IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default) { Writes.Add("attach:" + claimId + ":" + string.Join('+', statuses)); return Task.FromResult(Candidates); } public Task> ClaimTripStatusesAsync(long claimId, CancellationToken ct = default) => Task.FromResult>(TripStatuses); public Task CompleteClaimTripsAsync(long claimId, string userLogin, long userId, string? ip, CancellationToken ct = default) { Writes.Add("tripsComplete:" + userLogin + ":" + userId); return Task.FromResult(1); } public Task ReopenClaimTripsAsync(long claimId, string userLogin, long userId, string? ip, CancellationToken ct = default) { Writes.Add("tripsReopen:" + userLogin + ":" + userId); return Task.FromResult(1); } public Task SetClaimStatusAsync(long claimId, string status, string userLogin, CancellationToken ct = default) { Writes.Add("status:" + status); return Task.CompletedTask; } public Task> TripsToTransferAsync(long claimId, CancellationToken ct = default) => Task.FromResult>(ToTransfer); public Task MarkTripTransferredAsync(TransferTripRow trip, long userId, string? ip, CancellationToken ct = default) { Writes.Add("transferred:" + trip.Id); return Task.CompletedTask; } public Task AddLogAsync(long claimId, string method, string? oldData, string? newData, long userId, string? ip, CancellationToken ct = default) { Writes.Add($"log:{method}:{oldData}:{newData}"); return Task.CompletedTask; } public Task> LogAsync(long claimId, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException(); public List Report = []; public Task> ReportRowsAsync(long claimId, CancellationToken ct = default) => Task.FromResult>(Report); } private static WageClaimService Service(FakeRepo repo, IJopetrolGateway? gateway = null) => new(repo, new FakeUnit(), gateway ?? new FakeGateway(_ => null), new FakeUser()); [Fact] public async Task Create_takes_the_trips_logs_it_and_returns_the_id() { var repo = new FakeRepo(); var r = await Service(repo).CreateAsync(new CreateWageClaimRequest(["ALL", "EXCHANGED"], new DateOnly(2024, 3, 1), new DateOnly(2024, 3, 31)), "10.0.0.1", default); Assert.Equal(9, r.Id); Assert.Equal(["insert:TESTER", "attach:9:EXCHANGED", "log:CREATE:{}:{\"STATUS_CODE\":\"NEW\"}"], repo.Writes); } [Fact] public async Task Create_without_trips_ready_is_refused_with_the_legacy_text_and_writes_nothing() { var repo = new FakeRepo { Candidates = 0 }; var ex = await Assert.ThrowsAsync(() => Service(repo).CreateAsync(new CreateWageClaimRequest(["EXCHANGED"], new DateOnly(2024, 3, 1), new DateOnly(2024, 3, 31)), null, default)); Assert.Equal("لا يوجد ارساليات جاهزة لانشاء مطالبة مالية", ex.Message); Assert.Empty(repo.Writes); } [Fact] public async Task Close_completes_the_trips_and_the_claim() { var repo = new FakeRepo(); await Service(repo).CloseAsync(5, null, default); Assert.Equal(["tripsComplete:TESTER:77", "status:CLOSE", "log:CLAIM_CLOSE:{\"STATUS_CODE\":\"جديد\"}:{\"STATUS_CODE\":\"تم التسديد\"}"], repo.Writes); } private static WageClaimReportRaw Trip(string no, decimal load, decimal discharge, decimal tolerance, decimal penaltyQty) => new() { DischargeAuthoriztionNo = no, DischargeAuthoriztionYear = 2021, NetLoadingWeight = load, NetDischargeWeight = discharge, WaterAmount = 0, CalculatedQuantityTon = discharge / 1000, TonWage = 16.747m, ToleranceQuantity = tolerance, PenaltyQuantity = penaltyQty, PenaltyAmount = 0.45m, DriverTip = 20, PermitDispatch = 2.5m, WaybillFee = 0.75m, AdvancePaymentForDiesel = 100, Commission = 0.45m, NetWage = 400, }; [Fact] public void Summary_adds_up_the_trips_deductions_positive_and_names_the_tender_of_the_highest_form() { var s = WageClaimRules.ToSummary([Trip("26596", 40000, 39980, 50, 100), Trip("27132", 40000, 39990, 50, 100)]); Assert.Equal(2, s.TripCount); Assert.Equal(80000, s.LoadingWeight); Assert.Equal(30, s.Difference); // 20 + 10 Assert.Equal(0, s.PenaltyQuantity); // both differences are under the tolerance Assert.Equal(79.97m, s.CalculatedTon); Assert.Equal(Math.Round(79.97m * 16.747m, 3), Math.Round(s.QuantityWage, 3)); Assert.Equal(200, s.DieselAdvance); Assert.Equal(800, s.NetWage); Assert.Equal("27/2021", s.Tender); } [Fact] public async Task Summary_export_is_a_workbook_with_the_claim_number_tender_and_totals() { var repo = new FakeRepo { Report = [Trip("26596", 40000, 39980, 50, 100)] }; var f = await Service(repo).ExportSummaryAsync(5, default); Assert.EndsWith(".xlsx", f.FileName); using var zip = new System.IO.Compression.ZipArchive(new MemoryStream(f.Content)); var sheet = new StreamReader(zip.GetEntry("xl/worksheets/sheet1.xml")!.Open()).ReadToEnd(); Assert.Contains("رقم المطالبة :20230100041", sheet); Assert.Contains("رقم العطاء:26/2021", sheet); Assert.Contains("40000", sheet); Assert.Contains("", sheet); } [Fact] public async Task Reopen_puts_the_trips_and_the_claim_back_and_logs_it() { var repo = new FakeRepo { ClaimStatus = "CLOSE" }; await Service(repo).ReopenAsync(5, null, default); Assert.Equal(["tripsReopen:TESTER:77", "status:NEW", "log:CLAIM_REOPEN:{\"STATUS_CODE\":\"تم التسديد\"}:{\"STATUS_CODE\":\"جديد\"}"], repo.Writes); } [Fact] public async Task Reopen_needs_a_closed_claim_without_a_commission_claim() { var notClosed = new FakeRepo { ClaimStatus = "NEW" }; await Assert.ThrowsAsync(() => Service(notClosed).ReopenAsync(5, null, default)); var taken = new FakeRepo { ClaimStatus = "CLOSE", CommissionId = 3 }; var ex = await Assert.ThrowsAsync(() => Service(taken).ReopenAsync(5, null, default)); Assert.Equal("REOPEN_HAS_COMMISSION", ex.Code); Assert.Empty(notClosed.Writes); Assert.Empty(taken.Writes); } [Fact] public async Task Close_is_refused_while_a_trip_is_not_exchanged() { var repo = new FakeRepo { TripStatuses = ["EXCHANGED", "DISCHARGED"] }; var ex = await Assert.ThrowsAsync(() => Service(repo).CloseAsync(5, null, default)); Assert.Contains("جاهز للدفع او تم التفريغ", ex.Message); Assert.Empty(repo.Writes); } [Fact] public async Task Close_and_transfer_need_a_new_claim() { var repo = new FakeRepo { ClaimStatus = "CLOSE" }; await Assert.ThrowsAsync(() => Service(repo).CloseAsync(5, null, default)); await Assert.ThrowsAsync(() => Service(repo).TransferAsync(5, null, default)); Assert.Empty(repo.Writes); } [Fact] public async Task Transfer_with_the_integration_disabled_tells_the_user_and_changes_nothing() { var repo = new FakeRepo { ToTransfer = [new() { Id = 1, Pn = "111" }, new() { Id = 2, Pn = "222" }] }; var gateway = new FakeGateway(_ => null); // disabled: the gateway answers null var ex = await Assert.ThrowsAsync(() => Service(repo, gateway).TransferAsync(5, null, default)); Assert.Equal("JOPETROL_DISABLED", ex.Code); Assert.Contains("غير مفعلة", ex.Message); Assert.Empty(repo.Writes); Assert.Single(gateway.Calls); // stopped at the first trip } [Fact] public async Task Transfer_moves_only_the_trips_the_service_confirms() { var repo = new FakeRepo { ToTransfer = [new() { Id = 1, Pn = "111" }, new() { Id = 2, Pn = "222" }, new() { Id = 3, Pn = "333" }] }; var gateway = new FakeGateway(pn => pn == "222" ? "Error" : "Status Updated successfully To 7"); var r = await Service(repo, gateway).TransferAsync(5, null, default); Assert.Equal(["transferred:1", "transferred:3"], repo.Writes); Assert.Equal("تم ترحيل 2 من 3 ارسالية", r.Message); Assert.All(gateway.Calls, c => Assert.Equal("20230100041", c.ClaimNo)); } [Fact] public async Task Transfer_of_everything_answers_with_the_standard_success_text() { var repo = new FakeRepo { ToTransfer = [new() { Id = 1, Pn = "111" }] }; var r = await Service(repo, new FakeGateway(_ => "Status Updated successfully To 7")).TransferAsync(5, null, default); Assert.Equal("تمت العملية بنجاح", r.Message); } [Fact] public async Task Transfer_stops_when_the_service_is_unreachable() { var repo = new FakeRepo { ToTransfer = [new() { Id = 1, Pn = "111" }, new() { Id = 2, Pn = "222" }] }; var gateway = new ThrowingGateway(); var ex = await Assert.ThrowsAsync(() => Service(repo, gateway).TransferAsync(5, null, default)); Assert.Equal("JOPETROL_FAILED", ex.Code); Assert.Empty(repo.Writes); } private sealed class ThrowingGateway : IJopetrolGateway { public Task SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default) => throw new HttpRequestException("down"); } }