using System.Text.Encodings.Web; using System.Text.Json; using NTP.Application.Abstractions; using NTP.Application.Common; using NTP.Application.Grains.Orders; using NTP.Application.Refinery.Integrations; namespace NTP.Application.Refinery.WageClaims; /// JSON of the OLD_DATA / NEW_DATA columns of the *_LOG tables: {"STATUS_CODE":"..."} with real (unescaped) Arabic, as legacy logs.saveLog. public static class ClaimLogJson { private static readonly JsonSerializerOptions Opts = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; public static string Status(string caption) => JsonSerializer.Serialize(new Dictionary { ["STATUS_CODE"] = caption }, Opts); } public interface IWageClaimService { Task> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct); Task GetAsync(long id, CancellationToken ct); Task> TripsAsync(long id, PageRequest page, CancellationToken ct); Task> CandidateTripsAsync(IReadOnlyList? statusCodes, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct); Task> LogAsync(long id, PageRequest page, CancellationToken ct); Task CreateAsync(CreateWageClaimRequest request, string? ip, CancellationToken ct); Task CloseAsync(long id, string? ip, CancellationToken ct); Task ReopenAsync(long id, string? ip, CancellationToken ct); Task TransferAsync(long id, string? ip, CancellationToken ct); Task ExportAsync(long id, CancellationToken ct); } /// /// Port of refinery_wage_claimfactory.cfc. Who may do what is decided by the permission keys on the controller /// (PermissionKeys.RefineryWageClaims*), not by the legacy role branches. /// public sealed class WageClaimService(IWageClaimRepository repo, IUnitOfWork unit, IJopetrolGateway jopetrol, ICurrentUser user) : IWageClaimService { public Task> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct) => repo.SearchAsync(query, page, ct); public async Task GetAsync(long id, CancellationToken ct) => await repo.GetAsync(id, ct) ?? throw new NotFoundException("REFINERY_WAGE_CLAIM", id); public async Task> TripsAsync(long id, PageRequest page, CancellationToken ct) { await GetAsync(id, ct); return await repo.ClaimTripsAsync(id, page, ct); } public Task> CandidateTripsAsync(IReadOnlyList? statusCodes, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct) { // legacy searchClaimTrips: no status = the three statuses of the dialog; from after to is refused var statuses = WageClaimRules.NormalizeTripStatuses(statusCodes); if (statuses.Count == 0) statuses = WageClaimRules.ClaimableTripStatuses; if (from is not null && to is not null && from.Value > to.Value) throw new BusinessException("FROM_GREATER_THAN_TO", ClaimMessages.FromGreaterThanTo); return repo.CandidateTripsAsync(statuses, from, to, page, ct); } public async Task> LogAsync(long id, PageRequest page, CancellationToken ct) { await GetAsync(id, ct); return await repo.LogAsync(id, page, ct); } /// factory.create: attaches the trips of the chosen statuses and loading dates that have no wage claim to a new NEW claim. public async Task CreateAsync(CreateWageClaimRequest request, string? ip, CancellationToken ct) { var statuses = WageClaimRules.NormalizeTripStatuses(request.StatusCodes); WageClaimRules.ValidateCreate(statuses, request.LoadingDateFrom, request.LoadingDateTo); var from = request.LoadingDateFrom!.Value; var to = request.LoadingDateTo!.Value; var id = await unit.ExecuteInTransactionAsync(async c => { if (await repo.CountCandidateTripsAsync(statuses, from, to, c) == 0) throw new BusinessException("NO_TRIPS_NEED_WAGE", ClaimMessages.NoTripsNeedWage); var claimId = await repo.InsertClaimAsync(user.UserId, c); await repo.AttachTripsAsync(claimId, statuses, from, to, c); await repo.AddLogAsync(claimId, "CREATE", "{}", ClaimLogJson.Status(WageClaimRules.New), user.Id, ip, c); return claimId; }, ct); return new ClaimResult(ClaimMessages.Success, id); } /// factory.CLAIM_CLOSE (تسديد): NEW claim whose trips are all EXCHANGED -> trips COMPLETE (+ trip log), claim CLOSE (+ log). public async Task CloseAsync(long id, string? ip, CancellationToken ct) { var claim = await GetAsync(id, ct); if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority); if (!WageClaimRules.CanCloseClaim(await repo.ClaimTripStatusesAsync(id, ct))) throw new BusinessException("CLOSE_CLAIM", ClaimMessages.CloseClaim); await unit.ExecuteInTransactionAsync(async c => { await repo.CompleteClaimTripsAsync(id, user.UserId, user.Id, ip, c); await repo.SetClaimStatusAsync(id, WageClaimRules.Close, user.UserId, c); await repo.AddLogAsync(id, "CLAIM_CLOSE", ClaimLogJson.Status(ClaimMessages.StatusNew), ClaimLogJson.Status(ClaimMessages.StatusClose), user.Id, ip, c); return 0; }, ct); return new ClaimResult(ClaimMessages.Success, id); } /// Reopen: CLOSE claim -> NEW, its COMPLETE trips back to EXCHANGED. Refused once a commission claim took the wage claim. public async Task ReopenAsync(long id, string? ip, CancellationToken ct) { var claim = await GetAsync(id, ct); if (claim.StatusCode != WageClaimRules.Close) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority); if (claim.CommissionClaimId is not null) throw new BusinessException("REOPEN_HAS_COMMISSION", ClaimMessages.ReopenHasCommission); await unit.ExecuteInTransactionAsync(async c => { await repo.ReopenClaimTripsAsync(id, user.UserId, user.Id, ip, c); await repo.SetClaimStatusAsync(id, WageClaimRules.New, user.UserId, c); await repo.AddLogAsync(id, "CLAIM_REOPEN", ClaimLogJson.Status(ClaimMessages.StatusClose), ClaimLogJson.Status(ClaimMessages.StatusNew), user.Id, ip, c); return 0; }, ct); return new ClaimResult(ClaimMessages.Success, id); } /// /// factory.TRANSFER (ترحيل): each trip of the claim with TRIP_STATUS 6 is sent to Jopetrol; when the service answers "Status Updated successfully To 7" /// the trip gets TRIP_STATUS 7 and a TRANSFER_TO_REFINERY log row. When the integration is disabled nothing is called and nothing is changed. /// public async Task TransferAsync(long id, string? ip, CancellationToken ct) { var claim = await GetAsync(id, ct); if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority); var trips = await repo.TripsToTransferAsync(id, ct); var sent = 0; foreach (var trip in trips) { string? answer; try { answer = await jopetrol.SendClaimAndUpdateStatusTo7Async(trip.Pn ?? "", claim.WageClaimNo?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "", ct); } catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException or System.Xml.XmlException) { // the service is down: stop here, what was already moved stays moved throw new BusinessException("JOPETROL_FAILED", $"تعذر الاتصال بخدمة المصفاة، تم ترحيل {sent} من {trips.Count} ارسالية"); } if (answer is null) throw new BusinessException("JOPETROL_DISABLED", ClaimMessages.JopetrolDisabled); if (!WageClaimRules.IsStatus7Success(answer)) continue; await unit.ExecuteInTransactionAsync(async c => { await repo.MarkTripTransferredAsync(trip, user.Id, ip, c); return 0; }, ct); sent++; } return new ClaimResult(sent == trips.Count ? ClaimMessages.Success : $"تم ترحيل {sent} من {trips.Count} ارسالية", id); } /// factoryweb.report: the trips of the claim with the amounts, deductions shown negative (column list of the legacy report). public async Task ExportAsync(long id, CancellationToken ct) { var claim = await GetAsync(id, ct); var lines = (await repo.ReportRowsAsync(id, ct)).Select(WageClaimRules.ToReportLine).ToList(); string[] headers = [ "متسلسل", "اسم السائق", "رقم الشاحنة", "رقم النموذج", "السنة", "تاريخ النموذج", "رقم الناقل الفرعي", "اسم الناقل الفرعي", "رقم البوليصة", "تاريخ البوليصة", "كمية البوليصة", "كمية الماء (كغم)", "كمية المصفاة (كغم)", "الفروقات", "الكمية المحسوبة طن", "كمية السماح", "الماء المصاحب", "كمية التغريم (كغم)", "سعر الطن", "خصم قيمة فرق كمية مغرمة", "اكرامية السائق", "خصم تسريب الصهريج", "خصم اصدار وثيقة", "سعر لتر دينار/لتر", "خصم قيمة 350 لتر ديزل", "خصم عمولة الصرف التنافسي", "صافي قيمة الصرف الفعلي", ]; var i = 0; var rows = lines.Select(l => new object?[] { ++i, l.Drvr, l.Tn, l.DischargeAuthoriztionNo, l.DischargeAuthoriztionYear, ClaimExcel.D(l.DischargeEntryDate), l.ClientNo, "", l.LoadingNo, ClaimExcel.D(l.ActualLoadingDate), ClaimExcel.N(l.NetLoadingWeight), ClaimExcel.N(l.WaterAmount), ClaimExcel.N(l.NetDischargeWeight), ClaimExcel.N(l.WeightDifference), ClaimExcel.N(l.CalculatedQuantityTon), ClaimExcel.N(l.ToleranceQuantity), l.WaterExist ? "نعم" : "لا", ClaimExcel.N(l.PenaltyQuantity), ClaimExcel.N(l.TonPrice), ClaimExcel.N(l.PenaltyAmount), ClaimExcel.N(l.DriverTip), ClaimExcel.N(l.PermitDispatch), ClaimExcel.N(l.WaybillFee), ClaimExcel.N(l.DieselLiterPrice), ClaimExcel.N(l.AdvancePaymentForDiesel), ClaimExcel.N(l.Commission), ClaimExcel.N(l.NetWage), }); return ClaimExcel.Build("شاشة مطالبات صرف أجور النقل", [$"رقم مطالبة اجور النقل : {claim.WageClaimNo}"], headers, rows, user.UserId, $"wage_claim_{claim.WageClaimNo}"); } }