using System.Globalization; using NTP.Application.Abstractions; using NTP.Application.Common; using NTP.Application.Refinery.Integrations; using NTP.Application.Refinery.RemainingBalance; namespace NTP.Application.Refinery.Trips; public interface ITripActionService { Task FirstAdvanceAsync(long id, CancellationToken ct); Task SecondAdvanceAsync(long id, CancellationToken ct); Task FirstAdvanceReverseAsync(long id, CancellationToken ct); Task SecondAdvanceReverseAsync(long id, CancellationToken ct); Task ExchangeAsync(long id, CancellationToken ct); Task ExchangeAuditAsync(long id, CancellationToken ct); Task ReceiptAsync(long id, CancellationToken ct); Task PaymentAsync(long id, CancellationToken ct); Task ActivateWalletExchangeAsync(long id, CancellationToken ct); Task OrangePaymentAsync(long id, CancellationToken ct); Task CashPaymentAsync(long id, CancellationToken ct); Task ConfirmExchangeAsync(long id, CancellationToken ct); Task PrintAsync(long id, CancellationToken ct); } /// /// Port of the actions of refinerytripFactory.cfc (diesel card advances and their reversals, receipt / payment / exchange of the wage, /// audit, cash and Orange payments, confirm / activate wallet exchange, print of the cash voucher). /// Role-specific branches of the legacy code are gone: the permission key of each endpoint decides who may act. The status rules the /// legacy STATUS_ACTION_MATRIX enforced per action are kept (WrongStatus = legacy ERROR.NO_AUTHORITY). Mobile push notifications of the /// legacy actions are not sent. /// public sealed class TripActionService( ITripRepository trips, ITripAmountsService amountsService, IRemainingBalanceService balances, IDinarakGateway dinarak, IDinarakReferenceGateway dinarakReference, IVoucherSerialRepository voucherSerial, IUnitOfWork uow, ICurrentUser user, ITripSettingsService settings) : ITripActionService { private string UserId => user.Id.ToString(CultureInfo.InvariantCulture); private static TripsResult Ok(long id) => new(TripErrors.Ok, id); // ------------------------------------------------------------------ helpers private async Task LoadAsync(long id, CancellationToken ct) => await trips.GetAsync(id, ct) ?? throw new NotFoundException("RefineryTrip", id); /// Locks the trip row (inside the transaction) and reads it again, so two operators cannot act on the same trip together. private async Task LockAndLoadAsync(long id, CancellationToken ct) { if (await trips.LockAsync(id, ct) is null) throw new NotFoundException("RefineryTrip", id); return await LoadAsync(id, ct); } private static (bool Exists, object? Value) OldValue(TripRecord t, string key) => key switch { "STATUS_CODE" => (true, t.StatusCode), "REMARKS" => (true, t.Remarks ?? string.Empty), "CURRENT_BALANCE" => (true, t.CurrentBalance), "DINARAK_REFERENCE_ID" => (true, t.DinarakReferenceId), _ => (false, null) }; /// REFINERY_TRIPS_LOG row like legacy logs.saveLog (nothing when no argument changed). private async Task LogAsync(string method, TripRecord old, IReadOnlyDictionary args, CancellationToken ct) { var built = TripLogBuilder.Build(method, k => OldValue(old, k), args); if (built is { } b) await trips.InsertLogAsync(old.Id, method, UserId, b.OldJson, b.NewJson, ct); } private static void EnsureStatus(TripRecord t, params string[] allowed) { if (t.StatusCode is null || !allowed.Contains(t.StatusCode)) throw TripErrors.WrongStatus(); } private static string RequireTn(TripRecord t) => t.Tn ?? throw TripErrors.CardNotFound(); // ------------------------------------------------------------------ diesel card advances // refinerytripfactory.cfc:215-279 + dao FIRST_ADVANCED_PAYMENT public Task FirstAdvanceAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c => { var t = await LockAndLoadAsync(id, c); if (t.DieselCharge != 0) throw TripErrors.FirstAdvanceExists(); var card = await trips.GetActiveCardAsync(RequireTn(t), c) ?? throw TripErrors.CardNotFound(); var calc = await trips.CalculateDieselAsync(id, c) ?? throw TripErrors.PriceNotDeclared(); await trips.InsertCardLogAsync(card.Id, "FIRST_ADVANCED_PAYMENT", card.CurrentBalance, calc, calc - card.CurrentBalance, UserId, t.Pn ?? string.Empty, c); await trips.MarkFirstAdvanceAsync(id, UserId, c); await trips.UpdateCardBalanceAsync(card.Id, calc, UserId, id, c); await LogAsync("FIRST_ADVANCED_PAYMENT", t, new Dictionary { ["CURRENT_BALANCE"] = calc }, c); return Ok(id); }, ct); // refinerytripfactory.cfc:285-351 + dao SECOND_ADVANCED_PAYMENT public Task SecondAdvanceAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c => { var t = await LockAndLoadAsync(id, c); if (t.DieselCharge != 1) throw TripErrors.SecondAdvanceExists(); var calc = await trips.CalculateDieselAsync(id, c) ?? throw TripErrors.WrongLoadingDate(); var card = await trips.GetActiveCardAsync(RequireTn(t), c) ?? throw TripErrors.CardNotFound(); await trips.InsertCardLogAsync(card.Id, "SECOND_ADVANCED_PAYMENT", card.CurrentBalance, calc, calc - card.CurrentBalance, UserId, t.Pn ?? string.Empty, c); await trips.MarkSecondAdvanceAsync(id, UserId, calc, c); await trips.UpdateCardBalanceAsync(card.Id, calc, UserId, id, c); await LogAsync("SECOND_ADVANCED_PAYMENT", t, new Dictionary { ["CURRENT_BALANCE"] = calc }, c); return Ok(id); }, ct); // refinerytripfactory.cfc:358-412 + dao FIRST_ADVANCED_PAYMENT_REVERSE public Task FirstAdvanceReverseAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c => { var t = await LockAndLoadAsync(id, c); if (t.DieselCharge == 0) throw TripErrors.FirstAdvanceReverseExists(); if (t.DieselCharge != 1) throw TripErrors.CannotReverseAdvance(); await ReverseAsync(t, "FIRST_ADVANCED_PAYMENT", "FIRST_ADVANCED_PAYMENT_REVERSE", 0, c); return Ok(id); }, ct); // refinerytripfactory.cfc:418-477 + dao SECOND_ADVANCED_PAYMENT_REVERSE public Task SecondAdvanceReverseAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c => { var t = await LockAndLoadAsync(id, c); if (t.DieselCharge == 1) throw TripErrors.SecondAdvanceExists(); if (t.DieselCharge != 2) throw TripErrors.CannotReverseAdvance(); if (await trips.CalculateDieselAsync(id, c) is null) throw TripErrors.WrongLoadingDate(); await ReverseAsync(t, "SECOND_ADVANCED_PAYMENT", "SECOND_ADVANCED_PAYMENT_REVERSE", 1, c); return Ok(id); }, ct); /// Takes back the amount of the last card log row of the advance: card balance - amount, a negative log row, the trip goes back one step. private async Task ReverseAsync(TripRecord t, string advanceMethod, string reverseMethod, int newDieselCharge, CancellationToken c) { var card = await trips.GetActiveCardAsync(RequireTn(t), c) ?? throw TripErrors.CardNotFound(); var previous = await trips.GetLastCardLogAmountAsync(t.Pn ?? string.Empty, advanceMethod, c) ?? throw TripErrors.CannotReverseAdvance(); var balance = card.CurrentBalance - previous; await trips.MarkAdvanceReversedAsync(t.Id, UserId, newDieselCharge, c); await trips.InsertCardLogAsync(card.Id, reverseMethod, card.CurrentBalance, balance, -previous, UserId, t.Pn ?? string.Empty, c); await trips.UpdateCardBalanceAsync(card.Id, balance, UserId, t.Id, c); await LogAsync(reverseMethod, t, new Dictionary { ["CURRENT_BALANCE"] = balance }, c); } // ------------------------------------------------------------------ wage payment // refinerytripfactory.cfc:494-595 (e-wallet through Dinarak) public async Task ExchangeAsync(long id, CancellationToken ct) { var t = await LoadAsync(id, ct); EnsureStatus(t, TripStatus.Discharged, TripStatus.PendingExchange); var amounts = await amountsService.ComputeAsync(t, ct); TripPaymentRules.EnsurePayable(amounts.NetWage, settings.Value.MaxPaymentAmount); var wallet = await trips.GetActiveWalletByTruckAsync(RequireTn(t), ct); TripPaymentRules.EnsureWalletReady(wallet is not null, wallet?.Epayment, wallet?.WalletNumber, wallet?.OwnerNnpn?.ToString(CultureInfo.InvariantCulture), wallet?.OwnerName); // the legacy action stored the figures before it called Dinarak (and they stay when the call fails) await trips.SaveAmountsAsync(id, UserId, amounts, ct); // outside any transaction on purpose: the Dinarak log rows must survive a failed payment (legacy kept them too) var res = await dinarak.TransferAsync(id, wallet!.WalletNumber!, wallet.OwnerNnpn!.Value.ToString(CultureInfo.InvariantCulture), amounts.NetWage, wallet.OwnerName!, ct); if (!res.Success) { await LogAsync("EXCHANGE", t, new Dictionary { ["REMARKS"] = res.Message }, ct); if (res.Code == "106") throw new BusinessException("DINARAK_DISABLED", "خدمة دينارك غير مفعلة في الإعدادات"); throw TripErrors.DinarakRefused(res.Message); } return await uow.ExecuteInTransactionAsync(async c => { // the money is already sent: record it whatever the status became meanwhile await trips.MarkExchangedAsync(id, UserId, "SUCCESSFULL_EXCHANGE_OPERATION", null, true, wallet.Id, c); await balances.ResetAfterPaymentAsync(RequireTn(t), id, c); await LogAsync("EXCHANGE", t, new Dictionary { ["STATUS_CODE"] = TripStatus.Exchanged, ["REMARKS"] = "SUCCESSFULL_EXCHANGE_OPERATION" }, c); return Ok(id); }, ct); } // refinerytripfactory.cfc:598-648 public async Task ReceiptAsync(long id, CancellationToken ct) { var first = await LoadAsync(id, ct); var wallet = await trips.GetActiveWalletByTruckAsync(RequireTn(first), ct); if (wallet is null) throw TripErrors.NoPaymentMethod(); if (wallet.Epayment == 1) throw TripErrors.ReloadForm(); EnsureStatus(first, TripStatus.Discharged); return await uow.ExecuteInTransactionAsync(async c => { var t = await LockAndLoadAsync(id, c); EnsureStatus(t, TripStatus.Discharged); var amounts = await amountsService.ComputeAsync(t, c); if (amounts.NetWage == 0) throw TripErrors.PriceNotDeclared(); await trips.SetStatusReceivedAsync(id, UserId, TripStatus.ReadyToPay, c); await trips.SaveAmountsAsync(id, UserId, amounts, c); await LogAsync("RECEIPT", t, new Dictionary { ["STATUS_CODE"] = TripStatus.ReadyToPay }, c); return Ok(id); }, ct); } // refinerytripfactory.cfc:701-734 public Task ExchangeAuditAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c => { var t = await LockAndLoadAsync(id, c); EnsureStatus(t, TripStatus.Discharged); var amounts = await amountsService.ComputeAsync(t, c); if (amounts.NetWage == 0) throw TripErrors.PriceNotDeclared(); await trips.SetStatusReceivedAsync(id, UserId, TripStatus.PendingExchange, c); await trips.SaveAmountsAsync(id, UserId, amounts, c); await LogAsync("EXCHANGE_AUDIT", t, new Dictionary { ["STATUS_CODE"] = TripStatus.PendingExchange }, c); return Ok(id); }, ct); // refinerytripfactory.cfc:651-698 (bank transfer paid by the accountant) public Task PaymentAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c => { var t = await LockAndLoadAsync(id, c); EnsureStatus(t, TripStatus.ReadyToPay); var wallet = await trips.GetActiveWalletByTruckAsync(RequireTn(t), c) ?? throw TripErrors.NoPaymentMethod(); var amounts = await amountsService.ComputeAsync(t, c); TripPaymentRules.EnsurePayable(amounts.NetWage, settings.Value.MaxPaymentAmount); await trips.MarkExchangedAsync(id, UserId, null, null, false, wallet.Id, c); await trips.SaveAmountsAsync(id, UserId, amounts, c); await balances.ResetAfterPaymentAsync(RequireTn(t), id, c); await LogAsync("PAYMENT", t, new Dictionary { ["STATUS_CODE"] = TripStatus.Exchanged }, c); return Ok(id); }, ct); // refinerytripfactory.cfc:991-1085 public Task CashPaymentAsync(long id, CancellationToken ct) => WalletPaymentAsync(id, "CACH_PAYMENT", resetBalance: true, checkSign: true, ct); // refinerytripfactory.cfc:885-965 (no legacy screen can reach it: there is no STATUS_ACTION_MATRIX row; no sign / size check, no balance reset) public Task OrangePaymentAsync(long id, CancellationToken ct) => WalletPaymentAsync(id, "ORANGE_PAYMENT", resetBalance: false, checkSign: false, ct); private Task WalletPaymentAsync(long id, string method, bool resetBalance, bool checkSign, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c => { var t = await LockAndLoadAsync(id, c); var amounts = await amountsService.ComputeAsync(t, c); TripPaymentRules.EnsurePayable(amounts.NetWage, settings.Value.MaxPaymentAmount, checkSign); EnsureStatus(t, TripStatus.Discharged); var wallet = await trips.GetActiveWalletByTruckAsync(RequireTn(t), c); TripPaymentRules.EnsureWalletReady(wallet is not null, wallet?.Epayment, wallet?.WalletNumber, wallet?.OwnerNnpn?.ToString(CultureInfo.InvariantCulture), wallet?.OwnerName); await trips.SaveAmountsAsync(id, UserId, amounts, c); await trips.MarkExchangedAsync(id, UserId, "SUCCESSFULL_EXCHANGE_OPERATION", method, true, wallet!.Id, c); if (resetBalance) await balances.ResetAfterPaymentAsync(RequireTn(t), id, c); await LogAsync(method, t, new Dictionary { ["STATUS_CODE"] = TripStatus.Exchanged, ["REMARKS"] = "SUCCESSFULL_EXCHANGE_OPERATION" }, c); return Ok(id); }, ct); // refinerytripfactory.cfc:737-781: asks Dinarak first whether the transfer already went through, then moves the message id by 0.01 public async Task ActivateWalletExchangeAsync(long id, CancellationToken ct) { var t = await LoadAsync(id, ct); EnsureStatus(t, TripStatus.PendingExchange, TripStatus.Discharged); if (t.DinarakReferenceId is { } reference) { var status = await dinarakReference.GetTransferByReferenceAsync(reference, ct); if (status.StatusName == "ERROR") throw TripErrors.DinarakStatusUnknown(); if (status.Accepted) throw TripErrors.PaymentAlreadySent(); } return await uow.ExecuteInTransactionAsync(async c => { var locked = await LockAndLoadAsync(id, c); var next = await trips.BumpDinarakReferenceAsync(id, UserId, c); await LogAsync("ACTIVATE_WALLET_EXCHANGE", locked, new Dictionary { ["DINARAK_REFERENCE_ID"] = next }, c); return Ok(id); }, ct); } // refinerytripfactory.cfc:967-984 + dao CONFIRM_EXCHANGE public async Task ConfirmExchangeAsync(long id, CancellationToken ct) { var t = await LoadAsync(id, ct); EnsureStatus(t, TripStatus.Discharged, TripStatus.PendingExchange); if (!await trips.HasTransferLogAsync(id, ct)) throw TripErrors.NoFailedTransfer(); return await uow.ExecuteInTransactionAsync(async c => { await LockAndLoadAsync(id, c); await trips.ConfirmExchangeAsync(id, UserId, c); // not in the legacy action (it left the truck balance applied twice); the trip was paid, so the balance is consumed await balances.ResetAfterPaymentAsync(RequireTn(t), id, c); await LogAsync("CONFIRM_EXCHANGE", t, new Dictionary { ["STATUS_CODE"] = TripStatus.Exchanged }, c); return Ok(id); }, ct); } // refinerytripfactory.cfc:1112-1243: voucher serial stored on first print, amount from CalculateRefinaryAmount public Task PrintAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c => { var t = await LoadAsync(id, c); EnsureStatus(t, TripStatus.Discharged); long serial; if (t.VoucherSerialNumber is { } existing) serial = existing; else { serial = await voucherSerial.NextAsync(c); await trips.SetVoucherSerialAsync(id, serial, c); } var amount = await trips.CalculateAmountAsync(id, c) ?? throw TripErrors.PriceNotDeclared(); await LogAsync("PRINT", t, new Dictionary { ["NOTES"] = string.Empty }, c); return new TripVoucherDto(id, t.Pn ?? string.Empty, serial.ToString(CultureInfo.InvariantCulture), DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), amount, t.DischargeAuthNo, t.OwnerName); }, ct); }