NTP_V2/tests/NTP.Tests/Refinery/WageClaimServiceTests.cs

239 lines
13 KiB
C#

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<T> ExecuteInTransactionAsync<T>(Func<CancellationToken, Task<T>> 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<string, string?> answer) : IJopetrolGateway
{
public readonly List<(string Pn, string ClaimNo)> Calls = [];
public Task<string?> 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<TransferTripRow> ToTransfer = [];
public int Candidates = 5;
public long? CommissionId;
public string? CommissionStatus = "NEW";
public readonly List<string> Writes = [];
public Task<PagedResult<WageClaimRowDto>> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException();
public Task<WageClaimRowDto?> GetAsync(long id, CancellationToken ct = default) =>
Task.FromResult<WageClaimRowDto?>(new WageClaimRowDto { Id = id, WageClaimNo = 20230100041, StatusCode = ClaimStatus, CommissionClaimId = CommissionId });
public Task<PagedResult<ClaimTripRowDto>> ClaimTripsAsync(long claimId, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException();
public Task<PagedResult<ClaimTripRowDto>> CandidateTripsAsync(IReadOnlyList<string> statuses, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException();
public Task<int> CountCandidateTripsAsync(IReadOnlyList<string> statuses, DateOnly from, DateOnly to, CancellationToken ct = default) => Task.FromResult(Candidates);
public Task<long> InsertClaimAsync(string createdBy, CancellationToken ct = default) { Writes.Add("insert:" + createdBy); return Task.FromResult(9L); }
public Task<int> AttachTripsAsync(long claimId, IReadOnlyList<string> statuses, DateOnly from, DateOnly to, CancellationToken ct = default) { Writes.Add("attach:" + claimId + ":" + string.Join('+', statuses)); return Task.FromResult(Candidates); }
public Task<string?> CommissionClaimStatusAsync(long commissionClaimId, CancellationToken ct = default) => Task.FromResult(CommissionStatus);
public Task SetClaimStatusAsync(long claimId, string status, string userLogin, CancellationToken ct = default) { Writes.Add("status:" + status); return Task.CompletedTask; }
public Task<IReadOnlyList<TransferTripRow>> TripsToTransferAsync(long claimId, CancellationToken ct = default) => Task.FromResult<IReadOnlyList<TransferTripRow>>(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<PagedResult<ClaimLogRowDto>> LogAsync(long claimId, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException();
public List<WageClaimReportRaw> Report = [];
public Task<IReadOnlyList<WageClaimReportRaw>> ReportRowsAsync(long claimId, CancellationToken ct = default) => Task.FromResult<IReadOnlyList<WageClaimReportRaw>>(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<BusinessException>(() =>
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_changes_only_the_claim_and_logs_it()
{
var repo = new FakeRepo();
await Service(repo).CloseAsync(5, null, default);
Assert.Equal(["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("<v>40000</v>", sheet);
Assert.Contains("<mergeCell ref=\"A3:E3\"/>", sheet);
}
[Fact]
public async Task Reopen_changes_only_the_claim_and_logs_it()
{
var repo = new FakeRepo { ClaimStatus = "CLOSE" };
await Service(repo).ReopenAsync(5, null, default);
Assert.Equal(["status:NEW", "log:CLAIM_REOPEN:{\"STATUS_CODE\":\"تم التسديد\"}:{\"STATUS_CODE\":\"جديد\"}"], repo.Writes);
}
[Fact]
public async Task Reopen_needs_a_closed_claim()
{
var notClosed = new FakeRepo { ClaimStatus = "NEW" };
await Assert.ThrowsAsync<BusinessException>(() => Service(notClosed).ReopenAsync(5, null, default));
Assert.Empty(notClosed.Writes);
}
[Fact]
public async Task Status_changes_are_allowed_while_the_commission_claim_is_new()
{
var repo = new FakeRepo { ClaimStatus = "CLOSE", CommissionId = 3, CommissionStatus = "NEW" };
await Service(repo).ReopenAsync(5, null, default);
Assert.Contains("status:NEW", repo.Writes);
}
[Theory]
[InlineData("CLOSE")]
[InlineData("COMPLETE")]
public async Task Status_changes_are_refused_once_the_commission_claim_is_not_new(string commissionStatus)
{
var reopen = new FakeRepo { ClaimStatus = "CLOSE", CommissionId = 3, CommissionStatus = commissionStatus };
var ex = await Assert.ThrowsAsync<BusinessException>(() => Service(reopen).ReopenAsync(5, null, default));
Assert.Equal("COMMISSION_NOT_NEW", ex.Code);
var close = new FakeRepo { ClaimStatus = "NEW", CommissionId = 3, CommissionStatus = commissionStatus };
await Assert.ThrowsAsync<BusinessException>(() => Service(close).CloseAsync(5, null, default));
Assert.Empty(reopen.Writes);
Assert.Empty(close.Writes);
}
[Fact]
public async Task Close_and_transfer_need_a_new_claim()
{
var repo = new FakeRepo { ClaimStatus = "CLOSE" };
await Assert.ThrowsAsync<BusinessException>(() => Service(repo).CloseAsync(5, null, default));
await Assert.ThrowsAsync<BusinessException>(() => 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<BusinessException>(() => 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<BusinessException>(() => Service(repo, gateway).TransferAsync(5, null, default));
Assert.Equal("JOPETROL_FAILED", ex.Code);
Assert.Empty(repo.Writes);
}
private sealed class ThrowingGateway : IJopetrolGateway
{
public Task<string?> SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default) =>
throw new HttpRequestException("down");
}
}