diff --git a/src/NTP.Api/Controllers/V1/Refinery/CardsController.cs b/src/NTP.Api/Controllers/V1/Refinery/CardsController.cs new file mode 100644 index 0000000..3fb485a --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Refinery/CardsController.cs @@ -0,0 +1,56 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Api.Authorization; +using NTP.Application.Access; +using NTP.Application.Common; +using NTP.Application.Refinery.Cards; + +namespace NTP.Api.Controllers.V1.Refinery; + +/// Refinery diesel cards (بطاقات الديزل): port of refinery_cards*.cfc. Access by permission keys only (SU / PTADM). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/refinery/cards")] +[Produces("application/json")] +public sealed class CardsController(ICardsService cards) : ControllerBase +{ + private static IReadOnlyList Split(string? statusCode) => + (statusCode ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + /// search: filters tn and cardNumber (exact), statusCode (one or several, comma separated). + [HttpGet] + [RequirePermission(PermissionKeys.RefineryCards)] + public Task> Search([FromQuery] string? tn, [FromQuery] string? cardNumber, [FromQuery] string? statusCode, + [FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) => + cards.SearchAsync(new CardsQuery(tn, cardNumber, Split(statusCode)), new PageRequest(page, pageSize), ct); + + [HttpGet("export")] + [RequirePermission(PermissionKeys.RefineryCardsReport)] + public async Task Export([FromQuery] string? tn, [FromQuery] string? cardNumber, [FromQuery] string? statusCode, CancellationToken ct) + { + var f = await cards.ExportAsync(new CardsQuery(tn, cardNumber, Split(statusCode)), ct); + return File(f.Content, f.ContentType, f.FileName); + } + + [HttpGet("{id:long}")] + [RequirePermission(PermissionKeys.RefineryCards)] + public Task Get(long id, CancellationToken ct) => cards.GetAsync(id, ct); + + /// log: movements of the card (create, activate, deactivate, diesel top-ups of the trips). + [HttpGet("{id:long}/log")] + [RequirePermission(PermissionKeys.RefineryCards)] + public Task> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) => + cards.GetLogAsync(id, new PageRequest(page, pageSize), ct); + + [HttpPost] + [RequirePermission(PermissionKeys.RefineryCardsCreate)] + public Task Create([FromBody] CreateCardRequest request, CancellationToken ct) => cards.CreateAsync(request, ct); + + [HttpPost("{id:long}/activate")] + [RequirePermission(PermissionKeys.RefineryCardsActivate)] + public Task Activate(long id, CancellationToken ct) => cards.ActivateAsync(id, ct); + + [HttpPost("{id:long}/deactivate")] + [RequirePermission(PermissionKeys.RefineryCardsDeactivate)] + public Task Deactivate(long id, CancellationToken ct) => cards.DeactivateAsync(id, ct); +} diff --git a/src/NTP.Api/Controllers/V1/Refinery/CommissionClaimsController.cs b/src/NTP.Api/Controllers/V1/Refinery/CommissionClaimsController.cs new file mode 100644 index 0000000..4ae42a4 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Refinery/CommissionClaimsController.cs @@ -0,0 +1,71 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Api.Authorization; +using NTP.Application.Access; +using NTP.Application.Common; +using NTP.Application.Refinery.CommissionClaims; +using NTP.Application.Refinery.WageClaims; + +namespace NTP.Api.Controllers.V1.Refinery; + +/// +/// Refinery commission claims (مطالبة العمولة): port of backend\entities\refinery_commission_claim. Thin controller; the rules are in +/// . Search / view / log need the screen key, every action its own key. +/// +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/refinery/commission-claims")] +[Produces("application/json")] +public sealed class CommissionClaimsController(ICommissionClaimService claims) : ControllerBase +{ + private string? Ip => HttpContext.Connection.RemoteIpAddress?.ToString(); + + /// The grid: COMMISSION_CLAIM_NO, COMMISSION_CLAIM_DATE, STATUS_CODE (comma list). + [HttpGet] + [RequirePermission(PermissionKeys.RefineryCommissionClaims)] + public Task> Search( + [FromQuery] string? commissionClaimNo, [FromQuery] DateOnly? commissionClaimDate, [FromQuery] string? statusCode, + [FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) => + claims.SearchAsync(new CommissionClaimQuery(commissionClaimNo, commissionClaimDate, Split(statusCode)), new PageRequest(page, pageSize), ct); + + [HttpGet("{id:long}")] + [RequirePermission(PermissionKeys.RefineryCommissionClaims)] + public Task Get(long id, CancellationToken ct) => claims.GetAsync(id, ct); + + /// The wage claims grouped by the commission claim. + [HttpGet("{id:long}/wage-claims")] + [RequirePermission(PermissionKeys.RefineryCommissionClaims)] + public Task> WageClaims(long id, CancellationToken ct) => claims.WageClaimsAsync(id, ct); + + /// Create dialog: wage claims without a commission claim (statusCode NEW and / or CLOSE, default both). + [HttpGet("wage-claim-candidates")] + [RequirePermission(PermissionKeys.RefineryCommissionClaimsCreate)] + public Task> Candidates([FromQuery] string? statusCode, CancellationToken ct) => + claims.CandidateWageClaimsAsync(Split(statusCode), ct); + + [HttpGet("{id:long}/log")] + [RequirePermission(PermissionKeys.RefineryCommissionClaims)] + public Task> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) => + claims.LogAsync(id, new PageRequest(page, pageSize), ct); + + [HttpPost] + [RequirePermission(PermissionKeys.RefineryCommissionClaimsCreate)] + public Task Create(CreateCommissionClaimRequest request, CancellationToken ct) => claims.CreateAsync(request, Ip, ct); + + /// CLAIM_COMPLETE. + [HttpPost("{id:long}/complete")] + [RequirePermission(PermissionKeys.RefineryCommissionClaimsComplete)] + public Task Complete(long id, CancellationToken ct) => claims.CompleteAsync(id, Ip, ct); + + /// REPORT: the monthly commission invoice as an Excel file. + [HttpGet("{id:long}/report")] + [RequirePermission(PermissionKeys.RefineryCommissionClaimsReport)] + public async Task Report(long id, CancellationToken ct) + { + var f = await claims.ReportAsync(id, ct); + return File(f.Content, f.ContentType, f.FileName); + } + + private static IReadOnlyList Split(string? s) => + (s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); +} diff --git a/src/NTP.Api/Controllers/V1/Refinery/TripsController.cs b/src/NTP.Api/Controllers/V1/Refinery/TripsController.cs new file mode 100644 index 0000000..fe5e8de --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Refinery/TripsController.cs @@ -0,0 +1,164 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Api.Authorization; +using NTP.Application.Access; +using NTP.Application.Common; +using NTP.Application.Refinery.RemainingBalance; +using NTP.Application.Refinery.Trips; + +namespace NTP.Api.Controllers.V1.Refinery; + +/// +/// Refinery trips (legacy REFINERYTRIP: refinerytripfactoryweb.cfc, REFINERYTRIPGRID / REFINERYTRIP / REFINERYTRIPLOG screens). +/// Each action has its own permission key (PermissionKeys.Refinery.Trips.cs); the list, the form and the history use the screen key. +/// +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/refinery/trips")] +[Produces("application/json")] +public sealed class TripsController( + ITripQueryService queries, + ITripActionService actions, + ITripReportService reports, + IRemainingBalanceService balances) : ControllerBase +{ + // ---- list, form, history + [HttpGet] + [RequirePermission(PermissionKeys.RefineryTrips)] + public Task> Search([FromQuery] TripQuery query, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + queries.SearchAsync(query, new PageRequest(page, pageSize), ct); + + [HttpGet("{id:long}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [RequirePermission(PermissionKeys.RefineryTrips)] + public Task Get(long id, CancellationToken ct) => queries.GetAsync(id, ct); + + [HttpGet("{id:long}/log")] + [RequirePermission(PermissionKeys.RefineryTrips)] + public Task> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) => + queries.LogAsync(id, new PageRequest(page, pageSize), ct); + + // ---- diesel card advances + [HttpPost("{id:long}/first-advance")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsFirstAdvance)] + public Task FirstAdvance(long id, CancellationToken ct) => actions.FirstAdvanceAsync(id, ct); + + [HttpPost("{id:long}/second-advance")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsSecondAdvance)] + public Task SecondAdvance(long id, CancellationToken ct) => actions.SecondAdvanceAsync(id, ct); + + [HttpPost("{id:long}/first-advance-reverse")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsFirstAdvanceReverse)] + public Task FirstAdvanceReverse(long id, CancellationToken ct) => actions.FirstAdvanceReverseAsync(id, ct); + + [HttpPost("{id:long}/second-advance-reverse")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsSecondAdvanceReverse)] + public Task SecondAdvanceReverse(long id, CancellationToken ct) => actions.SecondAdvanceReverseAsync(id, ct); + + // ---- wage payment + /// صرف: e-wallet payment through Dinarak. + [HttpPost("{id:long}/exchange")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsExchange)] + public Task Exchange(long id, CancellationToken ct) => actions.ExchangeAsync(id, ct); + + [HttpPost("{id:long}/exchange-audit")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsExchangeAudit)] + public Task ExchangeAudit(long id, CancellationToken ct) => actions.ExchangeAuditAsync(id, ct); + + [HttpPost("{id:long}/receipt")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsReceipt)] + public Task Receipt(long id, CancellationToken ct) => actions.ReceiptAsync(id, ct); + + [HttpPost("{id:long}/payment")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsPayment)] + public Task Payment(long id, CancellationToken ct) => actions.PaymentAsync(id, ct); + + [HttpPost("{id:long}/activate-wallet-exchange")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsActivateWalletExchange)] + public Task ActivateWalletExchange(long id, CancellationToken ct) => actions.ActivateWalletExchangeAsync(id, ct); + + [HttpPost("{id:long}/orange-payment")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsOrangePayment)] + public Task OrangePayment(long id, CancellationToken ct) => actions.OrangePaymentAsync(id, ct); + + [HttpPost("{id:long}/cash-payment")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsCashPayment)] + public Task CashPayment(long id, CancellationToken ct) => actions.CashPaymentAsync(id, ct); + + [HttpPost("{id:long}/confirm-exchange")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsConfirmExchange)] + public Task ConfirmExchange(long id, CancellationToken ct) => actions.ConfirmExchangeAsync(id, ct); + + /// Cash voucher (سند صرف نقدي): stores the serial on the first call, logs PRINT; the page prints the returned data. + [HttpPost("{id:long}/print")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsPrint)] + public Task Print(long id, CancellationToken ct) => actions.PrintAsync(id, ct); + + // ---- remaining balance of the trucks (used by the variables screen after a ton-price correction) + [HttpPost("remaining-balance/recalculate")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.RefineryTripsRecalculateBalance)] + public Task RecalculateBalance(RecalculateBalanceRequest request, CancellationToken ct) => + balances.RecalculateForPeriodAsync(request.StartDate, request.EndDate, request.VariableGroupId, ct); + + // ---- reports (xlsx) + [HttpGet("reports/trips")] + [RequirePermission(PermissionKeys.RefineryTripsReport)] + public async Task TripsReport([FromQuery] TripQuery query, CancellationToken ct) + { + var f = await reports.TripsAsync(query, ct); + return File(f.Content, f.ContentType, f.FileName); + } + + [HttpGet("reports/diesel")] + [RequirePermission(PermissionKeys.RefineryTripsDieselReport)] + public async Task DieselReport([FromQuery] DieselReportQuery query, CancellationToken ct) + { + var f = await reports.DieselAsync(query, ct); + return File(f.Content, f.ContentType, f.FileName); + } + + [HttpGet("reports/cards")] + [RequirePermission(PermissionKeys.RefineryTripsCardsReport)] + public async Task CardsReport([FromQuery] string? tn, CancellationToken ct) + { + var f = await reports.CardsAsync(tn, ct); + return File(f.Content, f.ContentType, f.FileName); + } + + [HttpGet("reports/bank")] + [RequirePermission(PermissionKeys.RefineryTripsBankReport)] + public async Task BankReport([FromQuery] BankReportQuery query, CancellationToken ct) + { + var f = await reports.BankAsync(query, ct); + return File(f.Content, f.ContentType, f.FileName); + } +} diff --git a/src/NTP.Api/Controllers/V1/Refinery/VariablesController.cs b/src/NTP.Api/Controllers/V1/Refinery/VariablesController.cs new file mode 100644 index 0000000..96cb6c9 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Refinery/VariablesController.cs @@ -0,0 +1,64 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Api.Authorization; +using NTP.Application.Access; +using NTP.Application.Common; +using NTP.Application.Refinery.Variables; + +namespace NTP.Api.Controllers.V1.Refinery; + +/// +/// Refinery pricing periods (تسعير عطاء النفط الخام): port of refinery_variables*.cfc. Thin controller; access is by permission keys only +/// (SU / PTADM through GRAINS_SCREEN_PERMISSIONS), the legacy REFINERY_MGR / REFINERY_AC role branches are not ported. +/// +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/refinery/variables")] +[Produces("application/json")] +public sealed class VariablesController(IVariablesService variables) : ControllerBase +{ + /// search: periods newest first. Filters: startDate (+ endDate = range of start dates) or endDate alone. + [HttpGet] + [RequirePermission(PermissionKeys.RefineryVariables)] + public Task> Search([FromQuery] DateOnly? startDate, [FromQuery] DateOnly? endDate, + [FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) => + variables.SearchAsync(new VariablesQuery(startDate, endDate), new PageRequest(page, pageSize), ct); + + /// Excel of the periods grid (legacy REFINERY_VARIABLES_report). + [HttpGet("export")] + [RequirePermission(PermissionKeys.RefineryVariablesReport)] + public async Task Export([FromQuery] DateOnly? startDate, [FromQuery] DateOnly? endDate, CancellationToken ct) + { + var f = await variables.ExportAsync(new VariablesQuery(startDate, endDate), ct); + return File(f.Content, f.ContentType, f.FileName); + } + + /// refineryRemainingBalanceReport: previous balances per truck. + [HttpGet("remaining-balance/export")] + [RequirePermission(PermissionKeys.RefineryVariablesRemainingBalanceReport)] + public async Task ExportRemainingBalance(CancellationToken ct) + { + var f = await variables.ExportRemainingBalanceAsync(ct); + return File(f.Content, f.ContentType, f.FileName); + } + + /// getrefinery_variables: one period (by group id) and what may still be done with it. + [HttpGet("{groupId:long}")] + [RequirePermission(PermissionKeys.RefineryVariables)] + public Task Get(long groupId, CancellationToken ct) => variables.GetAsync(groupId, ct); + + [HttpPost] + [RequirePermission(PermissionKeys.RefineryVariablesCreate)] + public Task Create([FromBody] SaveVariablesRequest request, CancellationToken ct) => variables.CreateAsync(request, ct); + + [HttpPut("{groupId:long}")] + [RequirePermission(PermissionKeys.RefineryVariablesUpdate)] + public Task Update(long groupId, [FromBody] SaveVariablesRequest request, CancellationToken ct) => + variables.UpdateAsync(groupId, request, ct); + + /// UPDATE_TON_PRICE_CORRECTION (once per period). + [HttpPost("{groupId:long}/ton-price-correction")] + [RequirePermission(PermissionKeys.RefineryVariablesTonPriceCorrection)] + public Task TonPriceCorrection(long groupId, [FromBody] TonPriceCorrectionRequest request, CancellationToken ct) => + variables.SetTonPriceCorrectionAsync(groupId, request, ct); +} diff --git a/src/NTP.Api/Controllers/V1/Refinery/WageClaimsController.cs b/src/NTP.Api/Controllers/V1/Refinery/WageClaimsController.cs new file mode 100644 index 0000000..7c8d003 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Refinery/WageClaimsController.cs @@ -0,0 +1,82 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Api.Authorization; +using NTP.Application.Access; +using NTP.Application.Common; +using NTP.Application.Refinery.WageClaims; + +namespace NTP.Api.Controllers.V1.Refinery; + +/// +/// Refinery wage claims (مطالبة الأجور): port of backend\entities\refinery_wage_claim (factory / factoryweb). Thin controller; the rules are in +/// . Search / view / log need the screen key, every action its own key (see PermissionKeys.Refinery.WageClaims.cs). +/// +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/refinery/wage-claims")] +[Produces("application/json")] +public sealed class WageClaimsController(IWageClaimService claims) : ControllerBase +{ + private string? Ip => HttpContext.Connection.RemoteIpAddress?.ToString(); + + /// The grid: WAGE_CLAIM_NO, WAGE_CLAIM_DATE, STATUS_CODE (comma list), COMMISSION_CLAIM_NO, HAS_COMMISSION_CLAIM (0 / 1). + [HttpGet] + [RequirePermission(PermissionKeys.RefineryWageClaims)] + public Task> Search( + [FromQuery] string? wageClaimNo, [FromQuery] DateOnly? wageClaimDate, [FromQuery] string? statusCode, [FromQuery] string? commissionClaimNo, + [FromQuery] string? hasCommissionClaim, [FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) => + claims.SearchAsync(new WageClaimQuery( + wageClaimNo, wageClaimDate, Split(statusCode), commissionClaimNo, + string.IsNullOrWhiteSpace(hasCommissionClaim) ? null : hasCommissionClaim.Trim() is "1" or "true"), + new PageRequest(page, pageSize), ct); + + [HttpGet("{id:long}")] + [RequirePermission(PermissionKeys.RefineryWageClaims)] + public Task Get(long id, CancellationToken ct) => claims.GetAsync(id, ct); + + /// The trips attached to the claim (legacy REFINERYTRIP.searchClaimTrips with WAGE_CLAIM_ID). + [HttpGet("{id:long}/trips")] + [RequirePermission(PermissionKeys.RefineryWageClaims)] + public Task> Trips(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) => + claims.TripsAsync(id, new PageRequest(page, pageSize), ct); + + /// Preview of the create dialog: trips of the statuses (default: all three) without a wage claim, optionally in a loading date range. + [HttpGet("candidate-trips")] + [RequirePermission(PermissionKeys.RefineryWageClaimsCreate)] + public Task> CandidateTrips( + [FromQuery] string? statusCode, [FromQuery] DateOnly? loadingDateFrom, [FromQuery] DateOnly? loadingDateTo, + [FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) => + claims.CandidateTripsAsync(Split(statusCode), loadingDateFrom, loadingDateTo, new PageRequest(page, pageSize), ct); + + [HttpGet("{id:long}/log")] + [RequirePermission(PermissionKeys.RefineryWageClaims)] + public Task> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) => + claims.LogAsync(id, new PageRequest(page, pageSize), ct); + + /// create: attaches the trips of the statuses and loading dates that have no wage claim to a new claim. + [HttpPost] + [RequirePermission(PermissionKeys.RefineryWageClaimsCreate)] + public Task Create(CreateWageClaimRequest request, CancellationToken ct) => claims.CreateAsync(request, Ip, ct); + + /// CLAIM_CLOSE (تسديد). + [HttpPost("{id:long}/close")] + [RequirePermission(PermissionKeys.RefineryWageClaimsClose)] + public Task Close(long id, CancellationToken ct) => claims.CloseAsync(id, Ip, ct); + + /// TRANSFER (ترحيل): sends the claim to Jopetrol; refused with a message when the integration is disabled. + [HttpPost("{id:long}/transfer")] + [RequirePermission(PermissionKeys.RefineryWageClaimsTransfer)] + public Task Transfer(long id, CancellationToken ct) => claims.TransferAsync(id, Ip, ct); + + /// REPORT: Excel of the trips of the claim. + [HttpGet("{id:long}/export")] + [RequirePermission(PermissionKeys.RefineryWageClaimsReport)] + public async Task Export(long id, CancellationToken ct) + { + var f = await claims.ExportAsync(id, ct); + return File(f.Content, f.ContentType, f.FileName); + } + + private static IReadOnlyList Split(string? s) => + (s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); +} diff --git a/src/NTP.Api/Controllers/V1/Refinery/WalletsController.cs b/src/NTP.Api/Controllers/V1/Refinery/WalletsController.cs new file mode 100644 index 0000000..e6b3c2a --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Refinery/WalletsController.cs @@ -0,0 +1,64 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Api.Authorization; +using NTP.Application.Access; +using NTP.Application.Common; +using NTP.Application.Refinery.Wallets; + +namespace NTP.Api.Controllers.V1.Refinery; + +/// Refinery payment methods (شاشة طرق الدفع): port of refinery_wallet*.cfc. Access by permission keys only (SU / PTADM). The Dinarak API is not called. +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/refinery/wallets")] +[Produces("application/json")] +public sealed class WalletsController(IWalletsService wallets) : ControllerBase +{ + private string? Ip => HttpContext.Connection.RemoteIpAddress?.ToString(); + + private static WalletsQuery Q(string? tn, string? walletNumber, string? ownerName, string? bankAccount, string? paymentMethod, string? statusCode, string? nnpn) => + new(tn, walletNumber, ownerName, bankAccount, paymentMethod, statusCode, nnpn); + + /// search. paymentMethod: BANK, EWALLET or DRAIVER_WALLET; ownerName is a contains match. + [HttpGet] + [RequirePermission(PermissionKeys.RefineryWallets)] + public Task> Search([FromQuery] string? tn, [FromQuery] string? walletNumber, [FromQuery] string? ownerName, + [FromQuery] string? bankAccount, [FromQuery] string? paymentMethod, [FromQuery] string? statusCode, [FromQuery] string? nnpn, + [FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) => + wallets.SearchAsync(Q(tn, walletNumber, ownerName, bankAccount, paymentMethod, statusCode, nnpn), new PageRequest(page, pageSize), ct); + + [HttpGet("export")] + [RequirePermission(PermissionKeys.RefineryWalletsReport)] + public async Task Export([FromQuery] string? tn, [FromQuery] string? walletNumber, [FromQuery] string? ownerName, + [FromQuery] string? bankAccount, [FromQuery] string? paymentMethod, [FromQuery] string? statusCode, [FromQuery] string? nnpn, CancellationToken ct) + { + var f = await wallets.ExportAsync(Q(tn, walletNumber, ownerName, bankAccount, paymentMethod, statusCode, nnpn), ct); + return File(f.Content, f.ContentType, f.FileName); + } + + [HttpGet("{id:long}")] + [RequirePermission(PermissionKeys.RefineryWallets)] + public Task Get(long id, CancellationToken ct) => wallets.GetAsync(id, ct); + + [HttpGet("{id:long}/log")] + [RequirePermission(PermissionKeys.RefineryWallets)] + public Task> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) => + wallets.GetLogAsync(id, new PageRequest(page, pageSize), ct); + + [HttpPost] + [RequirePermission(PermissionKeys.RefineryWalletsCreate)] + public Task Create([FromBody] SaveWalletRequest request, CancellationToken ct) => wallets.CreateAsync(request, Ip, ct); + + /// Deactivates the record and creates a new ACTIVE one with the new data; the answer carries the NEW id. + [HttpPut("{id:long}")] + [RequirePermission(PermissionKeys.RefineryWalletsUpdate)] + public Task Update(long id, [FromBody] SaveWalletRequest request, CancellationToken ct) => wallets.UpdateAsync(id, request, Ip, ct); + + [HttpPost("{id:long}/activate")] + [RequirePermission(PermissionKeys.RefineryWalletsActivate)] + public Task Activate(long id, CancellationToken ct) => wallets.ActivateAsync(id, Ip, ct); + + [HttpPost("{id:long}/deactivate")] + [RequirePermission(PermissionKeys.RefineryWalletsDeactivate)] + public Task Deactivate(long id, CancellationToken ct) => wallets.DeactivateAsync(id, Ip, ct); +} diff --git a/src/NTP.Application/Access/PermissionDefaults.cs b/src/NTP.Application/Access/PermissionDefaults.cs index faf5d14..897562f 100644 --- a/src/NTP.Application/Access/PermissionDefaults.cs +++ b/src/NTP.Application/Access/PermissionDefaults.cs @@ -4,7 +4,7 @@ namespace NTP.Application.Access; /// Stable resource keys the front end and the API agree on. A key is a menu entry (module/screen) or an action /// inside a screen. The front end uses the menu key of each entry (see web/src/features/*/routes.tsx). /// -public static class PermissionKeys +public static partial class PermissionKeys { // Screens (menu keys) public const string OrdersList = "grains.orders.list"; diff --git a/src/NTP.Application/Access/PermissionKeys.Refinery.Cards.cs b/src/NTP.Application/Access/PermissionKeys.Refinery.Cards.cs new file mode 100644 index 0000000..ba179b9 --- /dev/null +++ b/src/NTP.Application/Access/PermissionKeys.Refinery.Cards.cs @@ -0,0 +1,14 @@ +namespace NTP.Application.Access; + +/// Refinery diesel cards (بطاقات الديزل) action keys. The screen itself (search / view / log) is . +public static partial class PermissionKeys +{ + /// Legacy CREATE (REFINERY_CARDS_CREATE): define a card. + public const string RefineryCardsCreate = "refinery.cards.create"; + /// Legacy CHSTAT INACTIVE -> ACTIVE (REFINERY_CARDS_ACTIVE). + public const string RefineryCardsActivate = "refinery.cards.activate"; + /// Legacy CHSTAT ACTIVE -> INACTIVE (REFINERY_CARDS_DEACTIVE). + public const string RefineryCardsDeactivate = "refinery.cards.deactivate"; + /// Excel of the cards grid (legacy REFINERY_CARDS_report). + public const string RefineryCardsReport = "refinery.cards.report"; +} diff --git a/src/NTP.Application/Access/PermissionKeys.Refinery.CommissionClaims.cs b/src/NTP.Application/Access/PermissionKeys.Refinery.CommissionClaims.cs new file mode 100644 index 0000000..d8d6840 --- /dev/null +++ b/src/NTP.Application/Access/PermissionKeys.Refinery.CommissionClaims.cs @@ -0,0 +1,12 @@ +namespace NTP.Application.Access; + +/// +/// Action keys of the refinery commission claims screen (مطالبة العمولة), object REFINERY_COMMISSION_CLAIM of STATUS_ACTION_MATRIX; +/// search / view / log use the screen key . +/// +public static partial class PermissionKeys +{ + public const string RefineryCommissionClaimsCreate = "refinery.commissionClaims.create"; // CREATE + public const string RefineryCommissionClaimsComplete = "refinery.commissionClaims.complete"; // CLAIM_CLOSE / CLAIM_COMPLETE + public const string RefineryCommissionClaimsReport = "refinery.commissionClaims.report"; // REPORT (invoice) +} diff --git a/src/NTP.Application/Access/PermissionKeys.Refinery.Trips.cs b/src/NTP.Application/Access/PermissionKeys.Refinery.Trips.cs new file mode 100644 index 0000000..bacf7d4 --- /dev/null +++ b/src/NTP.Application/Access/PermissionKeys.Refinery.Trips.cs @@ -0,0 +1,27 @@ +namespace NTP.Application.Access; + +/// +/// Action keys of the refinery trips screen (legacy REFINERYTRIP actions). The screen key itself is +/// (list, view, log). Granted only by GRAINS_SCREEN_PERMISSIONS rows (SU always, PTADM by script). +/// +public static partial class PermissionKeys +{ + public const string RefineryTripsFirstAdvance = "refinery.trips.firstAdvance"; // FIRST_ADVANCED_PAYMENT + public const string RefineryTripsSecondAdvance = "refinery.trips.secondAdvance"; // SECOND_ADVANCED_PAYMENT + public const string RefineryTripsFirstAdvanceReverse = "refinery.trips.firstAdvanceReverse"; // FIRST_ADVANCED_PAYMENT_REVERSE + public const string RefineryTripsSecondAdvanceReverse = "refinery.trips.secondAdvanceReverse"; // SECOND_ADVANCED_PAYMENT_REVERSE + public const string RefineryTripsExchange = "refinery.trips.exchange"; // EXCHANGE (e-wallet through Dinarak) + public const string RefineryTripsExchangeAudit = "refinery.trips.exchangeAudit"; // EXCHANGE_AUDIT + public const string RefineryTripsReceipt = "refinery.trips.receipt"; // RECEIPT + public const string RefineryTripsPayment = "refinery.trips.payment"; // PAYMENT (bank transfer) + public const string RefineryTripsActivateWalletExchange = "refinery.trips.activateWalletExchange"; // ACTIVATE_WALLET_EXCHANGE + public const string RefineryTripsOrangePayment = "refinery.trips.orangePayment"; // ORANGE_PAYMENT + public const string RefineryTripsCashPayment = "refinery.trips.cashPayment"; // CACH_PAYMENT + public const string RefineryTripsConfirmExchange = "refinery.trips.confirmExchange"; // CONFIRM_EXCHANGE + public const string RefineryTripsPrint = "refinery.trips.print"; // print (cash voucher) + public const string RefineryTripsReport = "refinery.trips.report"; // report (trips excel) + public const string RefineryTripsDieselReport = "refinery.trips.dieselReport"; // REFINERY_DIESEL_REPORT_VIEW report + public const string RefineryTripsCardsReport = "refinery.trips.cardsReport"; // refineryCardsReport + public const string RefineryTripsBankReport = "refinery.trips.bankReport"; // refineryBankReport + public const string RefineryTripsRecalculateBalance = "refinery.trips.recalculateBalance"; // calculateRemainigBalance +} diff --git a/src/NTP.Application/Access/PermissionKeys.Refinery.Variables.cs b/src/NTP.Application/Access/PermissionKeys.Refinery.Variables.cs new file mode 100644 index 0000000..65a8932 --- /dev/null +++ b/src/NTP.Application/Access/PermissionKeys.Refinery.Variables.cs @@ -0,0 +1,16 @@ +namespace NTP.Application.Access; + +/// Refinery variables (تسعير عطاء النفط الخام) action keys. The screen itself (search / view) is . +public static partial class PermissionKeys +{ + /// Legacy STATUS_ACTION_MATRIX CREATE (REFINERY_VARIABLES_CREATE): new pricing period. + public const string RefineryVariablesCreate = "refinery.variables.create"; + /// Legacy UPDATE: edit a pricing period (only while no trip was loaded inside it). + public const string RefineryVariablesUpdate = "refinery.variables.update"; + /// Legacy UPDATE_TON_PRICE_CORRECTION: set the actual ton price once. + public const string RefineryVariablesTonPriceCorrection = "refinery.variables.tonPriceCorrection"; + /// Excel of the pricing periods grid (legacy REFINERY_VARIABLES_report). + public const string RefineryVariablesReport = "refinery.variables.report"; + /// Excel of the previous balances per truck (legacy refineryRemainingBalanceReport). + public const string RefineryVariablesRemainingBalanceReport = "refinery.variables.remainingBalanceReport"; +} diff --git a/src/NTP.Application/Access/PermissionKeys.Refinery.WageClaims.cs b/src/NTP.Application/Access/PermissionKeys.Refinery.WageClaims.cs new file mode 100644 index 0000000..cd0f2f7 --- /dev/null +++ b/src/NTP.Application/Access/PermissionKeys.Refinery.WageClaims.cs @@ -0,0 +1,13 @@ +namespace NTP.Application.Access; + +/// +/// Action keys of the refinery wage claims screen (مطالبة الأجور). One key per legacy action of STATUS_ACTION_MATRIX +/// (object REFINERY_WAGE_CLAIM); search / view / log use the screen key . +/// +public static partial class PermissionKeys +{ + public const string RefineryWageClaimsCreate = "refinery.wageClaims.create"; // CREATE + public const string RefineryWageClaimsClose = "refinery.wageClaims.close"; // CLAIM_CLOSE (تسديد) + public const string RefineryWageClaimsTransfer = "refinery.wageClaims.transfer"; // TRANSFER (ترحيل) + public const string RefineryWageClaimsReport = "refinery.wageClaims.report"; // REPORT (excel of the trips of a claim) +} diff --git a/src/NTP.Application/Access/PermissionKeys.Refinery.Wallets.cs b/src/NTP.Application/Access/PermissionKeys.Refinery.Wallets.cs new file mode 100644 index 0000000..48928e2 --- /dev/null +++ b/src/NTP.Application/Access/PermissionKeys.Refinery.Wallets.cs @@ -0,0 +1,16 @@ +namespace NTP.Application.Access; + +/// Refinery payment methods (شاشة طرق الدفع: e-wallet, bank transfer, driver tip wallet) action keys. The screen itself is . +public static partial class PermissionKeys +{ + /// Legacy CREATE (REFINERY_WALLET_CREATE). + public const string RefineryWalletsCreate = "refinery.wallets.create"; + /// Legacy UPDATE (REFINERY_WALLET_update): ACTIVE records only; the old record is deactivated and a new one created. + public const string RefineryWalletsUpdate = "refinery.wallets.update"; + /// Legacy CHSTAT INACTIVE -> ACTIVE (REFINERY_WALLET_ACTIVATE). + public const string RefineryWalletsActivate = "refinery.wallets.activate"; + /// Legacy DEACTIVATE (REFINERY_WALLET_DEACTIVATE). + public const string RefineryWalletsDeactivate = "refinery.wallets.deactivate"; + /// Legacy REPORT (REFINERY_WALLET_report): Excel of the filtered grid. + public const string RefineryWalletsReport = "refinery.wallets.report"; +} diff --git a/src/NTP.Application/Access/PermissionKeys.Refinery.cs b/src/NTP.Application/Access/PermissionKeys.Refinery.cs new file mode 100644 index 0000000..f4d2217 --- /dev/null +++ b/src/NTP.Application/Access/PermissionKeys.Refinery.cs @@ -0,0 +1,17 @@ +namespace NTP.Application.Access; + +/// +/// Refinery (المصفاة) module keys, ported from the AqabaTCS app. Granted ONLY by rows in GRAINS_SCREEN_PERMISSIONS (see +/// db/refinery-permissions.sql: SU is always allowed, PTADM gets every key); none of them is in . +/// Action keys of one module live in that module's own partial file (PermissionKeys.Refinery.<Module>.cs). +/// +public static partial class PermissionKeys +{ + // Screens (menu keys), one per legacy menu entry (customtags/Menu.cfm) + public const string RefineryTrips = "refinery.trips"; // REFINERYTRIPGRID + public const string RefineryWageClaims = "refinery.wageClaims"; // REFINERY_WAGE_CLAIMGRID + public const string RefineryCommissionClaims = "refinery.commissionClaims"; // REFINERY_COMMISSION_CLAIMGRID + public const string RefineryWallets = "refinery.wallets"; // REFINERY_WALLETGRID + public const string RefineryVariables = "refinery.variables"; // REFINERY_VARIABLESGRID + public const string RefineryCards = "refinery.cards"; // REFINERY_CARDSGRID +} diff --git a/src/NTP.Application/Refinery/Cards/CardsContracts.cs b/src/NTP.Application/Refinery/Cards/CardsContracts.cs new file mode 100644 index 0000000..8402abf --- /dev/null +++ b/src/NTP.Application/Refinery/Cards/CardsContracts.cs @@ -0,0 +1,52 @@ +namespace NTP.Application.Refinery.Cards; + +/// Row of REFINERY_CARDS (a Jopetrol diesel card of a truck). Class with settable properties (Dapper + Oracle NUMBER). +public class CardRow +{ + public long Id { get; set; } + public long Tn { get; set; } + public string? CardNumber { get; set; } + public long? BoxNo { get; set; } + public decimal CurrentBalance { get; set; } + public DateTime? CreationDate { get; set; } + public string? CreatedBy { get; set; } + public DateTime? UpdateDate { get; set; } + public string? UpdatedBy { get; set; } + public string? StatusCode { get; set; } + public long? LastTripId { get; set; } +} + +/// Row of REFINERY_CARDS_LOG (legacy REFINERY_CARDS_LOG_VIEW). METHOD_NAME is the raw code, the screen translates it. +public class CardLogRow +{ + public long Id { get; set; } + public long EntityId { get; set; } + public string? MethodName { get; set; } + public decimal BalanceBefore { get; set; } + public decimal BalanceAfter { get; set; } + public decimal Amount { get; set; } + public string? Pn { get; set; } + public string? UpdatedBy { get; set; } + public DateTime? LastUpdateDate { get; set; } +} + +/// Grid filters (legacy TN, CARD_NUMBER exact match, STATUS_CODE multi select). +public sealed record CardsQuery(string? Tn, string? CardNumber, IReadOnlyList StatusCodes); + +public sealed class CreateCardRequest +{ + public long Tn { get; set; } + public string? CardNumber { get; set; } + public decimal CurrentBalance { get; set; } +} + +public sealed record CardsResult(string Message, long? Id = null); + +public static class CardValues +{ + public const string Active = "ACTIVE"; + public const string Inactive = "INACTIVE"; + public const string MethodCreate = "CREATE"; + public const string MethodActive = "ACTIVE"; + public const string MethodDeactive = "DEACTIVE"; +} diff --git a/src/NTP.Application/Refinery/Cards/CardsRules.cs b/src/NTP.Application/Refinery/Cards/CardsRules.cs new file mode 100644 index 0000000..77e1798 --- /dev/null +++ b/src/NTP.Application/Refinery/Cards/CardsRules.cs @@ -0,0 +1,44 @@ +namespace NTP.Application.Refinery.Cards; + +/// User-facing texts (legacy captions verbatim; * = no row in LT_CAPTION, new wording). +public static class CardsMessages +{ + public const string CardExists = "هذه البطاقة معرفة سابقاً"; // ERROR.REINERY_CARDS_IS_EXIST + public const string TruckHasActiveCard = "الشاحنة له بطاقة ديزل فعالة معرفة مسبقاً"; // ERROR.REINERY_CARDS_TN_HAS_ACTIVE_CARD + public const string BalanceNotEqualPrevious = "رصيد البطاقة الجديدة غير مطابق للبطاقة السابقة"; // ERROR.CURRENT_BALANCE_IS_NOT_EQ_PERVIOS_CARD + public const string CardNotFound = "بطاقة تعبئة الديزل غير معرفة"; // ERROR.THE_REFINERY_CARD_IS_NOT_EXIST + public const string StatusNotAllowed = "لا يمكن تنفيذ هذا الإجراء على البطاقة في حالتها الحالية"; // * (legacy: STATUS_ACTION_MATRIX refusal) + public const string Required = "الرجاء ادخال جميع الحقول"; // REPORT.VALIDATION + public const string Done = ""; +} + +public static class CardsErrors +{ + public const string CardExists = "REINERY_CARDS_IS_EXIST"; + public const string TruckHasActiveCard = "REINERY_CARDS_TN_HAS_ACTIVE_CARD"; + public const string BalanceNotEqualPrevious = "CURRENT_BALANCE_IS_NOT_EQ_PERVIOS_CARD"; + public const string CardNotFound = "THE_REFINERY_CARD_IS_NOT_EXIST"; + public const string StatusNotAllowed = "REFINERY_CARD_STATUS_NOT_ALLOWED"; +} + +/// Pure rules of refinery_cardsfactory.cfc. +public static class CardsRules +{ + /// REFINERY_CARDS.CARD_NUMBER is VARCHAR2(10). + public const int CardNumberMaxLength = 10; + /// The balance is also copied into REFINERY_CARDS_LOG (NUMBER(10,3)). + public const decimal BalanceLimit = 10_000_000m; + + /// Legacy matrix: only INACTIVE -> ACTIVE (CHSTAT, REFINERY_CARDS_ACTIVE) ... + public static bool CanActivate(string? status) => string.Equals(status, CardValues.Inactive, StringComparison.OrdinalIgnoreCase); + + /// ... and ACTIVE -> INACTIVE (REFINERY_CARDS_DEACTIVE). There is no other transition and no card update. + public static bool CanDeactivate(string? status) => string.Equals(status, CardValues.Active, StringComparison.OrdinalIgnoreCase); + + /// + /// refinery_cardsfactory.cfc:154-165: a truck that already had (inactive) cards may only get a new card with the balance of the + /// previous one (the balance travels with the truck). = balance of its latest inactive card. + /// + public static bool BalanceMatchesPrevious(decimal? previousInactiveBalance, decimal newBalance) => + previousInactiveBalance is null || previousInactiveBalance.Value == newBalance; +} diff --git a/src/NTP.Application/Refinery/Cards/CardsService.cs b/src/NTP.Application/Refinery/Cards/CardsService.cs new file mode 100644 index 0000000..57d7853 --- /dev/null +++ b/src/NTP.Application/Refinery/Cards/CardsService.cs @@ -0,0 +1,115 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; +using NTP.Application.Grains.Reports; + +namespace NTP.Application.Refinery.Cards; + +/// +/// Port of refinery_cardsfactory.cfc / refinery_cardsfactoryweb.cfc (screen REFINERY_CARDS, بطاقات الديزل). Access is by permission keys only +/// (legacy REFINERY_MGR / REFINERY_AC branches not ported). There is no card update: the legacy update is broken (it reads a variable that does +/// not exist and updates variable columns) and STATUS_ACTION_MATRIX has no usable UPDATE row for cards. +/// +public sealed class CardsService( + ICardsRepository repository, + IUnitOfWork unitOfWork, + ICurrentUser user, + IReportExcelService excel, + IValidator createValidator) : ICardsService +{ + public Task> SearchAsync(CardsQuery query, PageRequest page, CancellationToken ct) => + repository.SearchAsync(query, page, ct); + + public async Task GetAsync(long id, CancellationToken ct) => + await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery card", id); + + public async Task> GetLogAsync(long id, PageRequest page, CancellationToken ct) + { + _ = await GetAsync(id, ct); + return await repository.GetLogAsync(id, page, ct); + } + + public async Task CreateAsync(CreateCardRequest request, CancellationToken ct) + { + await createValidator.ValidateAndThrowAsync(request, ct); + var number = request.CardNumber!.Trim(); + + if (await repository.CardNumberExistsAsync(number, ct)) + throw new BusinessException(CardsErrors.CardExists, CardsMessages.CardExists); + + var cards = await repository.GetByTruckAsync(request.Tn, ct); + if (cards.Any(c => string.Equals(c.StatusCode, CardValues.Active, StringComparison.OrdinalIgnoreCase))) + throw new BusinessException(CardsErrors.TruckHasActiveCard, CardsMessages.TruckHasActiveCard); + var previous = cards.Where(c => string.Equals(c.StatusCode, CardValues.Inactive, StringComparison.OrdinalIgnoreCase)) + .OrderByDescending(c => c.Id).FirstOrDefault(); + if (!CardsRules.BalanceMatchesPrevious(previous?.CurrentBalance, request.CurrentBalance)) + throw new BusinessException(CardsErrors.BalanceNotEqualPrevious, CardsMessages.BalanceNotEqualPrevious); + + var id = await unitOfWork.ExecuteInTransactionAsync(async token => + { + var newId = await repository.InsertAsync(request.Tn, number, request.CurrentBalance, user.UserId, token); + // refinery_cardsfactory.cfc:176: CREATE log row, balance 0 -> opening balance + await repository.InsertLogAsync(newId, CardValues.MethodCreate, 0, request.CurrentBalance, request.CurrentBalance, user.UserId, token); + return newId; + }, ct); + return new CardsResult(CardsMessages.Done, id); + } + + public async Task ActivateAsync(long id, CancellationToken ct) + { + var card = await repository.GetAsync(id, ct) ?? throw new BusinessException(CardsErrors.CardNotFound, CardsMessages.CardNotFound); + if (!CardsRules.CanActivate(card.StatusCode)) + throw new BusinessException(CardsErrors.StatusNotAllowed, CardsMessages.StatusNotAllowed); + // a truck keeps one active card (refinery_cardsfactory.cfc:250) + var cards = await repository.GetByTruckAsync(card.Tn, ct); + if (cards.Any(c => string.Equals(c.StatusCode, CardValues.Active, StringComparison.OrdinalIgnoreCase))) + throw new BusinessException(CardsErrors.TruckHasActiveCard, CardsMessages.TruckHasActiveCard); + + await ChangeStatusAsync(card, CardValues.Active, CardValues.MethodActive, ct); + return new CardsResult(CardsMessages.Done, id); + } + + public async Task DeactivateAsync(long id, CancellationToken ct) + { + var card = await repository.GetAsync(id, ct) ?? throw new BusinessException(CardsErrors.CardNotFound, CardsMessages.CardNotFound); + if (!CardsRules.CanDeactivate(card.StatusCode)) + throw new BusinessException(CardsErrors.StatusNotAllowed, CardsMessages.StatusNotAllowed); + + await ChangeStatusAsync(card, CardValues.Inactive, CardValues.MethodDeactive, ct); + return new CardsResult(CardsMessages.Done, id); + } + + /// Status change + log row (balance before = after = the card balance, amount 0, PN '0'), like the legacy ACTIVE / DEACTIVE. + private Task ChangeStatusAsync(CardRow card, string status, string method, CancellationToken ct) => + unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.ChangeStatusAsync(card.Id, status, user.UserId, token); + await repository.InsertLogAsync(card.Id, method, card.CurrentBalance, card.CurrentBalance, 0, user.UserId, token); + return true; + }, ct); + + public async Task ExportAsync(CardsQuery query, CancellationToken ct) + { + var rows = new List(); + for (var p = 1; rows.Count < 20000; p++) + { + var r = await repository.SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct); + rows.AddRange(r.Items); + if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break; + } + var cols = new List + { + new("tn", "رقم الشاحنة", "Truck"), new("cardNumber", "رقم بطاقة جوبترول", "Card number"), + new("currentBalance", "الرصيد الحالي", "Current balance"), new("status", "الحالة", "Status"), + }; + var data = rows.Select(r => (IReadOnlyDictionary)new Dictionary + { + ["tn"] = r.Tn, ["cardNumber"] = r.CardNumber, ["currentBalance"] = r.CurrentBalance, + ["status"] = string.Equals(r.StatusCode, CardValues.Active, StringComparison.OrdinalIgnoreCase) ? "فعال" : "غير فعال", + }).ToList(); + var table = new ReportTable { Key = "REFINERY_CARDS", TitleAr = "بطاقات الديزل", TitleEn = "Diesel cards", Columns = cols, Rows = data }; + return new ExportFile(excel.Build(table, user.UserId, DateTime.Now, true), + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "REFINERY_CARDS.xlsx"); + } +} diff --git a/src/NTP.Application/Refinery/Cards/ICards.cs b/src/NTP.Application/Refinery/Cards/ICards.cs new file mode 100644 index 0000000..9f68889 --- /dev/null +++ b/src/NTP.Application/Refinery/Cards/ICards.cs @@ -0,0 +1,41 @@ +using FluentValidation; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; + +namespace NTP.Application.Refinery.Cards; + +public interface ICardsRepository +{ + /// Newest first (legacy sort ID DESC). + Task> SearchAsync(CardsQuery query, PageRequest page, CancellationToken ct = default); + Task GetAsync(long id, CancellationToken ct = default); + Task CardNumberExistsAsync(string cardNumber, CancellationToken ct = default); + /// All cards of a truck (newest first). + Task> GetByTruckAsync(long tn, CancellationToken ct = default); + Task InsertAsync(long tn, string cardNumber, decimal balance, string createdBy, CancellationToken ct = default); + Task ChangeStatusAsync(long id, string status, string userId, CancellationToken ct = default); + Task InsertLogAsync(long cardId, string method, decimal balanceBefore, decimal balanceAfter, decimal amount, string userId, CancellationToken ct = default); + Task> GetLogAsync(long cardId, PageRequest page, CancellationToken ct = default); +} + +public interface ICardsService +{ + Task> SearchAsync(CardsQuery query, PageRequest page, CancellationToken ct); + Task GetAsync(long id, CancellationToken ct); + Task> GetLogAsync(long id, PageRequest page, CancellationToken ct); + Task CreateAsync(CreateCardRequest request, CancellationToken ct); + Task ActivateAsync(long id, CancellationToken ct); + Task DeactivateAsync(long id, CancellationToken ct); + Task ExportAsync(CardsQuery query, CancellationToken ct); +} + +/// The create form: truck, card number and opening balance are required (legacy HTML required + bean length check). +public sealed class CreateCardValidator : AbstractValidator +{ + public CreateCardValidator() + { + RuleFor(x => x.Tn).GreaterThan(0).LessThan(1_000_000_000_000L).WithMessage(CardsMessages.Required); + RuleFor(x => x.CardNumber).NotEmpty().MaximumLength(CardsRules.CardNumberMaxLength).WithMessage(CardsMessages.Required); + RuleFor(x => x.CurrentBalance).GreaterThanOrEqualTo(0).LessThan(CardsRules.BalanceLimit).WithMessage(CardsMessages.Required); + } +} diff --git a/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimContracts.cs b/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimContracts.cs new file mode 100644 index 0000000..7891b22 --- /dev/null +++ b/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimContracts.cs @@ -0,0 +1,35 @@ +using NTP.Application.Refinery.WageClaims; + +namespace NTP.Application.Refinery.CommissionClaims; + +/// REFINERY_COMMISSION_CLAIM_VIEW row. is the number of wage claims (the legacy column name and grid caption "عدد مطالبات الاجور"). +public sealed class CommissionClaimRowDto +{ + public long Id { get; set; } + public long? CommissionClaimNo { get; set; } + public DateTime? CommissionClaimDate { get; set; } + public long TripCnt { get; set; } + /// NEW / COMPLETE (old rows may hold CLOSE). + public string StatusCode { get; set; } = ""; +} + +/// Filters of the legacy grid (COMMISSION_CLAIM_NO, COMMISSION_CLAIM_DATE, STATUS_CODE). +public sealed record CommissionClaimQuery(string? CommissionClaimNo, DateOnly? CommissionClaimDate, IReadOnlyList StatusCodes); + +/// Body of POST commission-claims: the wage claims to group (legacy IDS_ARR). +public sealed record CreateCommissionClaimRequest(IReadOnlyList? WageClaimIds); + +/// Data the invoice report needs (legacy factory.report). +public sealed class CommissionInvoiceSource +{ + public long CommissionClaimNo { get; set; } + /// WAGE_CLAIM_DATE of the newest wage claim (ORDER BY ID DESC) of the commission claim; null when it has no wage claim. + public DateTime? NewestWageClaimDate { get; set; } + public long TripsCount { get; set; } +} + +public sealed record InvoiceLine(string Label, long Quantity, decimal PriceWithTax, decimal TotalBeforeTax, decimal TotalWithTax); + +public sealed record CommissionInvoice( + string InvoiceNumber, DateOnly InvoiceDate, DateOnly PeriodStart, DateOnly PeriodEnd, IReadOnlyList Lines, + decimal TotalBeforeTax, decimal Tax, decimal GrandTotal); diff --git a/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimRules.cs b/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimRules.cs new file mode 100644 index 0000000..47c6c34 --- /dev/null +++ b/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimRules.cs @@ -0,0 +1,54 @@ +using NTP.Application.Common; +using NTP.Application.Refinery.WageClaims; + +namespace NTP.Application.Refinery.CommissionClaims; + +/// Pure rules of the commission claim screen (refinery_commission_claimfactory.cfc). +public static class CommissionClaimRules +{ + /// "العمولة الثابتة": fixed commission per trip, price including tax (factory.report, fixeComission). + public const decimal FixedCommission = 2.00m; + /// The prices include the 16% sales tax (invoice formula =ROUND(total/1.16,3)). + public const decimal TaxDivisor = 1.16m; + + public const string FixedLabel = "العمولة الثابتة"; + public const string CompetitiveLabel = "العمولة التنافسية"; + + /// factory.create: at least one wage claim chosen. + public static IReadOnlyList NormalizeIds(IEnumerable? ids) + { + var list = (ids ?? []).Where(i => i > 0).Distinct().ToList(); + if (list.Count == 0) throw new BusinessException("PLEASE_SELECT_CLAIM", ClaimMessages.PleaseSelectClaim); + return list; + } + + /// factory.CLAIM_COMPLETE: every wage claim of the commission claim must be CLOSE (paid). + public static bool AllWageClaimsPaid(IEnumerable wageClaimStatuses) => wageClaimStatuses.All(s => s == WageClaimRules.Close); + + /// + /// Billing period of the invoice: the month BEFORE the date of the newest wage claim (legacy: monthValue = month(date) - 1, January gives + /// December of the previous year); the invoice is dated the last day of that month. + /// + public static (DateOnly Start, DateOnly End) BillingPeriod(DateTime newestWageClaimDate) + { + var first = new DateOnly(newestWageClaimDate.Year, newestWageClaimDate.Month, 1).AddMonths(-1); + return (first, first.AddMonths(1).AddDays(-1)); + } + + /// Invoice line: total = quantity x price (with tax); before tax = ROUND(total / 1.16, 3) (Excel rounds halves away from zero). + public static InvoiceLine Line(string label, long quantity, decimal priceWithTax) + { + var total = quantity * priceWithTax; + return new InvoiceLine(label, quantity, priceWithTax, Math.Round(total / TaxDivisor, 3, MidpointRounding.AwayFromZero), total); + } + + /// Totals row of the invoice: sum before tax, tax = grand total - sum before tax, grand total = sum of the line totals. + public static CommissionInvoice BuildInvoice(long commissionClaimNo, DateTime newestWageClaimDate, long tripsCount, decimal competitiveCommission) + { + var (start, end) = BillingPeriod(newestWageClaimDate); + var lines = new[] { Line(FixedLabel, tripsCount, FixedCommission), Line(CompetitiveLabel, tripsCount, competitiveCommission) }; + var before = lines.Sum(l => l.TotalBeforeTax); + var grand = lines.Sum(l => l.TotalWithTax); + return new CommissionInvoice($"INV {commissionClaimNo}", end, start, end, lines, before, grand - before, grand); + } +} diff --git a/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimService.cs b/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimService.cs new file mode 100644 index 0000000..2497bec --- /dev/null +++ b/src/NTP.Application/Refinery/CommissionClaims/CommissionClaimService.cs @@ -0,0 +1,136 @@ +using System.Globalization; +using System.Text; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; +using NTP.Application.Refinery.WageClaims; +using static NTP.Application.Refinery.WageClaims.ClaimExcel; + +namespace NTP.Application.Refinery.CommissionClaims; + +public interface ICommissionClaimService +{ + Task> SearchAsync(CommissionClaimQuery query, PageRequest page, CancellationToken ct); + Task GetAsync(long id, CancellationToken ct); + Task> WageClaimsAsync(long id, CancellationToken ct); + Task> CandidateWageClaimsAsync(IReadOnlyList? statusCodes, CancellationToken ct); + Task> LogAsync(long id, PageRequest page, CancellationToken ct); + Task CreateAsync(CreateCommissionClaimRequest request, string? ip, CancellationToken ct); + Task CompleteAsync(long id, string? ip, CancellationToken ct); + Task ReportAsync(long id, CancellationToken ct); +} + +/// +/// Port of refinery_commission_claimfactory.cfc. Not ported: the no-op "UPDATE REFINERY_WAGE_CLAIM ... status_Code in ('NEW,CLOSE')" after the create +/// (a single quoted string never matches) and the TRIP_COMPLETE call of CLAIM_COMPLETE that passed the COMMISSION claim id as a trip id. +/// +public sealed class CommissionClaimService(ICommissionClaimRepository repo, IUnitOfWork unit, ICurrentUser user) : ICommissionClaimService +{ + /// Statuses of the wage claims the create dialog offers by default (REFINERY_COMMISSION_CLAIMMain.html: NEW and CLOSE selected). + private static readonly string[] CandidateStatuses = [WageClaimRules.New, WageClaimRules.Close]; + + public Task> SearchAsync(CommissionClaimQuery 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_COMMISSION_CLAIM", id); + + public async Task> WageClaimsAsync(long id, CancellationToken ct) + { + await GetAsync(id, ct); + return await repo.WageClaimsOfAsync(id, ct); + } + + public Task> CandidateWageClaimsAsync(IReadOnlyList? statusCodes, CancellationToken ct) + { + var wanted = (statusCodes ?? []) + .SelectMany(s => (s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + .Select(s => s.ToUpperInvariant()).Where(s => s is WageClaimRules.New or WageClaimRules.Close).Distinct().ToList(); + return repo.CandidateWageClaimsAsync(wanted.Count == 0 ? CandidateStatuses : wanted, ct); + } + + public async Task> LogAsync(long id, PageRequest page, CancellationToken ct) + { + await GetAsync(id, ct); + return await repo.LogAsync(id, page, ct); + } + + /// factory.create: groups the chosen wage claims that have no commission claim yet under a new NEW commission claim. + public async Task CreateAsync(CreateCommissionClaimRequest request, string? ip, CancellationToken ct) + { + var ids = CommissionClaimRules.NormalizeIds(request.WageClaimIds); + var id = await unit.ExecuteInTransactionAsync(async c => + { + if (await repo.CountAttachableAsync(ids, c) == 0) throw new BusinessException("NO_WAGES", ClaimMessages.NoWages); + var claimId = await repo.InsertAsync(user.UserId, c); + await repo.AttachWageClaimsAsync(claimId, ids, 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_COMPLETE: NEW claim, every wage claim CLOSE -> wage claims COMPLETE (+ their log), commission claim COMPLETE (+ log CLAIM_CLOSE). + public async Task CompleteAsync(long id, string? ip, CancellationToken ct) + { + var claim = await GetAsync(id, ct); + if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority); + // legacy returned the error in the middle of the loop; nothing is changed here unless all wage claims are paid + if (!CommissionClaimRules.AllWageClaimsPaid(await repo.WageClaimStatusesAsync(id, ct))) + throw new BusinessException("WAGE_CLAIM_NOT_CLOSE", ClaimMessages.WageClaimNotClose); + + await unit.ExecuteInTransactionAsync(async c => + { + await repo.CompleteWageClaimsAsync(id, user.UserId, user.Id, ip, c); + await repo.SetStatusAsync(id, WageClaimRules.Complete, user.UserId, c); + await repo.AddLogAsync(id, "CLAIM_CLOSE", ClaimLogJson.Status(ClaimMessages.StatusNew), ClaimLogJson.Status(ClaimMessages.StatusComplete), user.Id, ip, c); + return 0; + }, ct); + return new ClaimResult(ClaimMessages.Success, id); + } + + /// factory.report: the monthly invoice of the commissions (fixed commission and competitive commission per trip, 16% tax included). + public async Task ReportAsync(long id, CancellationToken ct) + { + var src = await repo.InvoiceSourceAsync(id, ct) ?? throw new NotFoundException("REFINERY_COMMISSION_CLAIM", id); + if (src.NewestWageClaimDate is null) throw new BusinessException("NO_TRIPS", ClaimMessages.NoTripsIssue); + var (start, _) = CommissionClaimRules.BillingPeriod(src.NewestWageClaimDate.Value); + var competitive = await repo.CommissionVariableAsync(start.Month, start.Year, ct) + ?? throw new BusinessException("COMMISSION_VARIABLE", ClaimMessages.CommissionVariableIssue); + var inv = CommissionClaimRules.BuildInvoice(src.CommissionClaimNo, src.NewestWageClaimDate.Value, src.TripsCount, competitive); + return RenderInvoice(inv, src.CommissionClaimNo); + } + + private static string Money(decimal v) => v.ToString("#,##0.000", CultureInfo.InvariantCulture); + private static string Day(DateOnly d) => d.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); + + /// Texts of the legacy invoice template (company, customer, columns, totals). Opened by Excel as an HTML table. + internal static ExportFile RenderInvoice(CommissionInvoice inv, long commissionClaimNo) + { + var h = new StringBuilder(); + h.Append(""); + h.Append(""); + h.Append(""); + h.Append($""); + h.Append($""); + h.Append($""); + h.Append(""); + h.Append(""); + h.Append(""); + h.Append(""); + h.Append(""); + h.Append(""); + h.Append(""); + foreach (var l in inv.Lines) + h.Append($""); + h.Append($""); + h.Append($""); + h.Append($""); + h.Append(""); + h.Append(""); + h.Append(""); + h.Append(""); + h.Append("
شركة نافذ للخدمات اللوجستيةالفاتورة الشهرية -عمولات صرف اجور النقل
التاريخ :{Day(inv.InvoiceDate)}رقم الضريبي :16669690
رقم الفاتورة :{E(inv.InvoiceNumber)}
من / إلى{Day(inv.PeriodStart)}/{Day(inv.PeriodEnd)}
رقم الشركة :03-100002
اسم الشركة :السادة شركة مصفاة البترول الأردنية المساهمة المحدودة
العنوان :الادارة العامة - عمان , الدوار الاول ,شارع الرينبو
رقم الهاتف : 4630151-06الفاكس : 4657939-06البريد الالكتروني:Addewan@Jopetrol.com.jo
البيانعدد الارسالياتالسعر شامل الضريبةالمجموع قبل الضريبةالمجموع شامل الضريبة
{E(l.Label)}{l.Quantity}{Money(l.PriceWithTax)}{Money(l.TotalBeforeTax)}{Money(l.TotalWithTax)}
المجموع قبل الضريبة{Money(inv.TotalBeforeTax)}
ضريبة المبيعات0.16{Money(inv.Tax)}
المجموع الأجمالي بالدينار الاردني{Money(inv.GrandTotal)}
اسم المستلم:شركة نافذ للخدمات اللوجستية
تاريخ الاستلام:
الختم والتوقيع:الختم والتوقيع:
مكتب الادارة - أبراج الحجاز، شارع مكة 158، مكتب 401 - ص.ب 995، عمان 11821، الأردن - هـ 6553629 962 - موقع www.nafith.com
"); + var bytes = new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(h.ToString())).ToArray(); + return new ExportFile(bytes, "application/vnd.ms-excel", $"refinery_commission_claim_{commissionClaimNo}.xls"); + } +} diff --git a/src/NTP.Application/Refinery/CommissionClaims/ICommissionClaimRepository.cs b/src/NTP.Application/Refinery/CommissionClaims/ICommissionClaimRepository.cs new file mode 100644 index 0000000..2042c44 --- /dev/null +++ b/src/NTP.Application/Refinery/CommissionClaims/ICommissionClaimRepository.cs @@ -0,0 +1,35 @@ +using NTP.Application.Common; +using NTP.Application.Refinery.WageClaims; + +namespace NTP.Application.Refinery.CommissionClaims; + +/// +/// SQL of refinery_commission_claimdao.cfc and the writes of refinery_commission_claimfactory.cfc. Besides its own tables it writes +/// REFINERY_WAGE_CLAIM (COMMISSION_CLAIM_ID when grouping; STATUS_CODE COMPLETE + REFINERY_WAGE_CLAIM_LOG when completing). +/// +public interface ICommissionClaimRepository +{ + Task> SearchAsync(CommissionClaimQuery query, PageRequest page, CancellationToken ct = default); + Task GetAsync(long id, CancellationToken ct = default); + /// Wage claims grouped by the commission claim (legacy searchWageClaim with COMMISSION_CLAIM_ID). + Task> WageClaimsOfAsync(long commissionClaimId, CancellationToken ct = default); + /// Wage claims without a commission claim in the given statuses (legacy searchWageClaim, create dialog). + Task> CandidateWageClaimsAsync(IReadOnlyList statuses, CancellationToken ct = default); + + Task CountAttachableAsync(IReadOnlyList wageClaimIds, CancellationToken ct = default); + /// Takes the next claim number (legacy GenerateSerialNumber) and inserts the claim as NEW; returns its id. Run inside a transaction. + Task InsertAsync(string createdBy, CancellationToken ct = default); + Task AttachWageClaimsAsync(long commissionClaimId, IReadOnlyList wageClaimIds, CancellationToken ct = default); + + Task> WageClaimStatusesAsync(long commissionClaimId, CancellationToken ct = default); + /// Every wage claim of the commission claim -> COMPLETE with a REFINERY_WAGE_CLAIM_LOG row (method COMPLETE, CLOSE -> COMPLETE). + Task CompleteWageClaimsAsync(long commissionClaimId, string userLogin, long userId, string? ip, CancellationToken ct = default); + Task SetStatusAsync(long id, string status, string userLogin, CancellationToken ct = default); + + Task AddLogAsync(long id, string method, string? oldData, string? newData, long userId, string? ip, CancellationToken ct = default); + Task> LogAsync(long id, PageRequest page, CancellationToken ct = default); + + Task InvoiceSourceAsync(long id, CancellationToken ct = default); + /// REFINERY_VARIABLES COMMISSION valid for the month / year (legacy month and year range test); null when not defined. + Task CommissionVariableAsync(int month, int year, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Refinery/Integrations/DinarakReferenceGateway.cs b/src/NTP.Application/Refinery/Integrations/DinarakReferenceGateway.cs new file mode 100644 index 0000000..cdc1fd5 --- /dev/null +++ b/src/NTP.Application/Refinery/Integrations/DinarakReferenceGateway.cs @@ -0,0 +1,15 @@ +namespace NTP.Application.Refinery.Integrations; + +/// +/// Companion of (whose signatures are fixed): REFINERY_TRIPS.DINARAK_REFERENCE_ID is a decimal (352.1, 352.11 ...) +/// because ACTIVATE_WALLET_EXCHANGE adds 0.01 to it, so the status lookup by message id needs a decimal parameter. +/// The same class implements both interfaces. +/// +public interface IDinarakReferenceGateway +{ + /// + /// Legacy getTransferByMessageID. StatusName is the Dinarak status ("Success", "Processing", "New", ...), "DISABLED" when the + /// integration is switched off (nothing is called) and "ERROR" when the answer could not be obtained or read. + /// + Task GetTransferByReferenceAsync(decimal reference, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Refinery/Integrations/RefineryGateways.cs b/src/NTP.Application/Refinery/Integrations/RefineryGateways.cs new file mode 100644 index 0000000..fbdc454 --- /dev/null +++ b/src/NTP.Application/Refinery/Integrations/RefineryGateways.cs @@ -0,0 +1,32 @@ +namespace NTP.Application.Refinery.Integrations; + +/// Result of a Dinarak e-wallet transfer. Codes as legacy RefinaryDinarakApi.ProcessTransfer: 000 ok, 101 amount mismatch, +/// 102 refused by Dinarak, 103 HTTP error, 104 invalid wallet / system error, 105 already paid, 106 integration disabled by configuration. +public sealed record DinarakTransferResult(string Code, string Message) +{ + public bool Success => Code == "000"; +} + +/// State of a transfer looked up by message id (legacy getTransferByMessageID): Success / Processing / New count as accepted. +public sealed record DinarakTransferStatus(bool Accepted, string? StatusName, string? RawResponse); + +/// +/// Dinarak payment API (legacy backend/common/RefinaryDinarakApi.cfc). The implementation lives in NTP.Infrastructure, is OFF unless +/// configuration enables it (Refinery:Dinarak:Enabled) and takes URL / user / password only from configuration (server .env). +/// Every call writes REFINERY_DINARAK_API_LOG like the legacy code. When disabled it returns code 106 and calls nothing. +/// +public interface IDinarakGateway +{ + Task TransferAsync(long tripId, string walletNumber, string nnpn, decimal amount, string receiverName, CancellationToken ct = default); + Task GetTransferByMessageIdAsync(long messageId, CancellationToken ct = default); +} + +/// +/// Jopetrol claim web service (legacy refinery_wage_claimfactory.callRefinaryUpdateStatusTo7, SOAP sendClaimandUpdateStatusTo7). +/// OFF unless configuration enables it (Refinery:Jopetrol:Enabled); URL / user / password only from configuration. Returns the text of +/// the service answer, or null when the integration is disabled. +/// +public interface IJopetrolGateway +{ + Task SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Refinery/RemainingBalance/RemainingBalanceService.cs b/src/NTP.Application/Refinery/RemainingBalance/RemainingBalanceService.cs new file mode 100644 index 0000000..b98e883 --- /dev/null +++ b/src/NTP.Application/Refinery/RemainingBalance/RemainingBalanceService.cs @@ -0,0 +1,108 @@ +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Refinery.Trips; + +namespace NTP.Application.Refinery.RemainingBalance; + +/// One truck's carried-over balance (REFINERY_REMAINING_BALANCE). +public sealed class RemainingBalanceRow +{ + public long Id { get; set; } + public long Tn { get; set; } + public decimal RemainingBalance { get; set; } + public decimal? BeforeRemainingBalance { get; set; } +} + +public interface IRemainingBalanceRepository +{ + Task GetByTruckAsync(string tn, CancellationToken ct = default); + /// Sets REMAINING_BALANCE to 0 and keeps the old value in BEFORE_REMAINING_BALANCE (legacy Zeroing). + Task ZeroAsync(string tn, string userId, CancellationToken ct = default); + /// Adds to the balance (BEFORE_REMAINING_BALANCE = old value); false when the truck has no row. + Task AddAsync(string tn, decimal delta, string userId, CancellationToken ct = default); + Task CreateAsync(string tn, decimal balance, string userId, CancellationToken ct = default); + /// REFINERY_REMAINING_BALANCE_LOG row (variableGroupId only when the change comes from a re-pricing). + Task InsertLogAsync(long balanceId, decimal amount, decimal balanceBefore, long tripId, long? variableGroupId, string loginId, CancellationToken ct = default); +} + +public interface IRemainingBalanceService +{ + /// Balance carried by the truck, or null when it has no row (legacy getByTN). + Task GetAsync(string tn, CancellationToken ct = default); + + /// + /// Legacy refinerytripfactory.setRemainigBalance: after a trip is paid, the balance it consumed is set back to 0 and logged + /// (nothing when the truck has no balance row). Runs in the caller's transaction. + /// + Task ResetAfterPaymentAsync(string tn, long tripId, CancellationToken ct = default); + + /// + /// Legacy refinery_remaining_balanceDAO.setRemainingBalance: adds to the truck's balance (creates the row + /// when missing) and writes the log row. Runs in the caller's transaction. + /// + Task AddAsync(string tn, decimal delta, long tripId, long variableGroupId, CancellationToken ct = default); + + /// + /// Legacy refinerytripfactory.calculateRemainigBalance: after the ton price (penalty price) of a period was corrected, the + /// difference of every penalised trip of the period is added to its truck's balance. The variables screen calls it after + /// saving a corrected price; also available as POST refinery/trips/remaining-balance/recalculate. + /// + Task RecalculateForPeriodAsync(DateTime startDate, DateTime endDate, long variableGroupId, CancellationToken ct = default); +} + +/// Port of refinery_remaining_balanceDAO.cfc plus setRemainigBalance / calculateRemainigBalance of refinerytripfactory.cfc. +public sealed class RemainingBalanceService( + IRemainingBalanceRepository balances, + ITripRepository trips, + IUnitOfWork unitOfWork, + ICurrentUser user) : IRemainingBalanceService +{ + public async Task GetAsync(string tn, CancellationToken ct = default) => + (await balances.GetByTruckAsync(tn, ct))?.RemainingBalance; + + // refinerytripfactory.cfc:1246-1267. The legacy call sites guard it with len(x gt 0), which is always true: the balance is + // reset after every payment whenever the truck has a balance row. + public async Task ResetAfterPaymentAsync(string tn, long tripId, CancellationToken ct = default) + { + var row = await balances.GetByTruckAsync(tn, ct); + if (row is null) return; + await balances.ZeroAsync(tn, user.Id.ToString(), ct); + // log: AMOUNT 0, balance before = what it was; CREATED_BY = login (legacy sessionstruct.userid) + await balances.InsertLogAsync(row.Id, 0, row.RemainingBalance, tripId, null, user.UserId, ct); + } + + // refinery_remaining_balanceDAO.cfc:67-98 (the legacy create() was broken for a missing row; here the row is created and logged) + public async Task AddAsync(string tn, decimal delta, long tripId, long variableGroupId, CancellationToken ct = default) + { + var userId = user.Id.ToString(); + var updated = await balances.AddAsync(tn, delta, userId, ct); + if (!updated) await balances.CreateAsync(tn, delta, userId, ct); + var row = await balances.GetByTruckAsync(tn, ct) + ?? throw new InvalidOperationException($"Remaining balance row of truck {tn} was not found after update."); + await balances.InsertLogAsync(row.Id, row.RemainingBalance, row.BeforeRemainingBalance ?? 0, tripId, variableGroupId, user.UserId, ct); + } + + // refinerytripfactory.cfc:1269-1315 + public async Task RecalculateForPeriodAsync(DateTime startDate, DateTime endDate, long variableGroupId, CancellationToken ct = default) + { + var list = await trips.GetTripsOfPeriodAsync(startDate.Date, endDate.Date, ct); + if (list.Count == 0) throw TripErrors.NoTripsInPeriod(); + if (list.Any(t => t.StatusCode is not null && TripStatus.BlockRepricing.Contains(t.StatusCode))) + throw TripErrors.NotAllExchanged(); + + return await unitOfWork.ExecuteInTransactionAsync(async c => + { + foreach (var t in list.Where(t => t.PenaltyAmount > 0)) + { + if (t.LoadingDate is null || t.Tn is null) continue; + var vars = TripVariables.FromPairs(await trips.GetVariablesAsync(t.LoadingDate.Value.Date, c)); + var weights = new TripWeights(t.NetLoadingWeight ?? 0, t.NetDischargeWeight ?? 0, t.WaterAmount ?? 0, await trips.GetWaterFlagAsync(t.Id, c)); + var corrected = TripCalculator.Calculate(weights, vars, null, useTonPriceCorrection: true); + // legacy: calculatedAmounts.NET_WAGE neq trip.NET_WAGE, then delta = corrected NET_WAGE - TRIP_NET_WAGE + if (corrected.NetWage != (t.NetWage ?? 0)) + await AddAsync(t.Tn, corrected.NetWage - (t.TripNetWage ?? 0), t.Id, variableGroupId, c); + } + return new TripsResult(TripErrors.Ok); + }, ct); + } +} diff --git a/src/NTP.Application/Refinery/Trips/TripActionService.cs b/src/NTP.Application/Refinery/Trips/TripActionService.cs new file mode 100644 index 0000000..41104d2 --- /dev/null +++ b/src/NTP.Application/Refinery/Trips/TripActionService.cs @@ -0,0 +1,322 @@ +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); +} diff --git a/src/NTP.Application/Refinery/Trips/TripAmountsService.cs b/src/NTP.Application/Refinery/Trips/TripAmountsService.cs new file mode 100644 index 0000000..011ea4b --- /dev/null +++ b/src/NTP.Application/Refinery/Trips/TripAmountsService.cs @@ -0,0 +1,22 @@ +using NTP.Application.Refinery.RemainingBalance; + +namespace NTP.Application.Refinery.Trips; + +public interface ITripAmountsService +{ + /// Legacy calculateAmounts for a trip record (variables of the loading date, weights, remaining balance of the truck). + Task ComputeAsync(TripRecord trip, CancellationToken ct); +} + +public sealed class TripAmountsService(ITripRepository trips, IRemainingBalanceRepository balances) : ITripAmountsService +{ + public async Task ComputeAsync(TripRecord t, CancellationToken ct) + { + if (t.LoadingDate is null) return TripAmounts.Zero; + var pairs = await trips.GetVariablesAsync(t.LoadingDate.Value.Date, ct); + if (pairs.Count == 0) return TripAmounts.Zero; + var weights = new TripWeights(t.NetLoadingWeight ?? 0, t.NetDischargeWeight ?? 0, t.WaterAmount ?? 0, await trips.GetWaterFlagAsync(t.Id, ct)); + decimal? remaining = t.Tn is null ? null : (await balances.GetByTruckAsync(t.Tn, ct))?.RemainingBalance; + return TripCalculator.Calculate(weights, TripVariables.FromPairs(pairs), remaining); + } +} diff --git a/src/NTP.Application/Refinery/Trips/TripCalculator.cs b/src/NTP.Application/Refinery/Trips/TripCalculator.cs new file mode 100644 index 0000000..1caa6bc --- /dev/null +++ b/src/NTP.Application/Refinery/Trips/TripCalculator.cs @@ -0,0 +1,136 @@ +using System.Globalization; + +namespace NTP.Application.Refinery.Trips; + +/// Variables of REFINERY_VARIABLES valid on a loading date (one value per KEY_NAME; absent key = 0). +public sealed record TripVariables( + decimal TonWage, + decimal TonPrice, + decimal TonPriceCorrection, + decimal DriverTip, + decimal PermitDispatch, + decimal WaybillFee, + decimal Commission, + decimal TolerancePercentage, + decimal FirstAdvancePayment, + decimal DieselLiterPrice) +{ + /// Builds the record from KEY_NAME -> KEY_VALUE pairs (first value of a key wins, like legacy query-of-queries row 1). + public static TripVariables FromPairs(IEnumerable> pairs) + { + var d = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (k, v) in pairs) + if (!d.ContainsKey(k)) d[k] = Parse(v); + decimal Get(string k) => d.TryGetValue(k, out var x) ? x : 0m; + return new TripVariables(Get("TON_WAGE"), Get("TON_PRICE"), Get("TON_PRICE_CORRECTION"), Get("DRIVER_TIP"), + Get("PERMIT_DISPATCH"), Get("WAYBILL_FEE"), Get("COMMISSION"), Get("TOLERANCE_PERCENTAGE"), + Get("FIRST_ADVANCE_PAYMENT"), Get("DIESEL_LITER_PRICE")); + } + + private static decimal Parse(string? v) => + decimal.TryParse(v?.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var x) ? x : 0m; +} + +/// Weights of a trip that the wage calculation needs. +public sealed record TripWeights(decimal NetLoadingWeight, decimal NetDischargeWeight, decimal WaterAmount, int? WaterFlag); + +/// Result of the legacy refinerytripFactory.calculateAmounts (all money values rounded to 3 decimals like numberFormat '_.000'). +public sealed record TripAmounts( + decimal TripNetWage, + decimal NetWage, + decimal RemainingBalance, + decimal PenaltyAmount, + decimal PenaltyQuantity, + decimal QuantityWage, + decimal ToleranceQuantity, + decimal TonWage, + decimal TonPrice, + decimal DriverTip, + decimal PermitDispatch, + decimal WaybillFee, + decimal Commission, + decimal TolerancePercentage, + decimal FirstAdvancePayment, + decimal SecondAdvancePayment, + decimal DieselLiterPrice, + decimal CalculatedQuantityTon) +{ + /// No price variables for the loading date: every figure is 0 (legacy returned the zero struct). + public static TripAmounts Zero { get; } = new(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); +} + +/// Pure port of refinerytripFactory.calculateAmounts (refinerytripfactory.cfc:785-881). +public static class TripCalculator +{ + /// Liters of diesel of a trip (350) priced in the wage deduction (legacy literal). + public const decimal DieselLiters = 350m; + + private static decimal R3(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero); + + /// legacy calculateMode 'TON_PRICE_CORRECTION': penalty priced with TON_PRICE_CORRECTION and the truck's remaining balance is not added. + /// REFINERY_REMAINING_BALANCE of the truck (null = no row); ignored in correction mode. + public static TripAmounts Calculate(TripWeights w, TripVariables v, decimal? remainingBalance, bool useTonPriceCorrection = false) + { + // ToleranceQuantity = Floor(NET_LOADING_WEIGHT * TOLERANCE_PERCENTAGE) + var toleranceQuantity = Math.Floor(w.NetLoadingWeight * v.TolerancePercentage); + var water = w.WaterAmount; + var allow = toleranceQuantity; + + // water that is not accompanying (flag 1) is ignored and gets no tolerance (factory 816-819) + if (w.WaterFlag == 1 && water > 0) + { + water = 0; + allow = 0; + } + + var penaltyQuantity = w.NetLoadingWeight - w.NetDischargeWeight - water; + var penaltyAmount = 0m; + if (penaltyQuantity <= allow) + { + penaltyQuantity = 0; + } + else + { + penaltyQuantity = R3(penaltyQuantity - allow); + var tonPrice = useTonPriceCorrection ? v.TonPriceCorrection : v.TonPrice; + penaltyAmount = R3(penaltyQuantity / 1000m * tonPrice); + } + + var calculatedQuantityTon = water >= (w.NetLoadingWeight - w.NetDischargeWeight) + ? w.NetLoadingWeight / 1000m + : (w.NetDischargeWeight + water) / 1000m; + + var quantityWage = R3(calculatedQuantityTon * v.TonWage); + var diesel = DieselLiters * v.DieselLiterPrice; + var secondAdvance = diesel - v.FirstAdvancePayment; + + var trip = R3(quantityWage - penaltyAmount - v.DriverTip - v.PermitDispatch - v.WaybillFee - diesel - v.Commission); + var net = trip; + var remaining = 0m; + if (!useTonPriceCorrection && remainingBalance.HasValue) + { + net = trip + remainingBalance.Value; + remaining = remainingBalance.Value; + } + + return new TripAmounts( + TripNetWage: trip, + NetWage: R3(net), + RemainingBalance: R3(remaining), + PenaltyAmount: penaltyAmount, + PenaltyQuantity: penaltyQuantity, + QuantityWage: quantityWage, + ToleranceQuantity: toleranceQuantity, + TonWage: R3(v.TonWage), + TonPrice: R3(v.TonPrice), + DriverTip: R3(v.DriverTip), + PermitDispatch: R3(v.PermitDispatch), + WaybillFee: R3(v.WaybillFee), + Commission: R3(v.Commission), + TolerancePercentage: R3(v.TolerancePercentage), + FirstAdvancePayment: v.FirstAdvancePayment, + SecondAdvancePayment: secondAdvance, + DieselLiterPrice: R3(v.DieselLiterPrice), + CalculatedQuantityTon: calculatedQuantityTon); + } +} diff --git a/src/NTP.Application/Refinery/Trips/TripQueryService.cs b/src/NTP.Application/Refinery/Trips/TripQueryService.cs new file mode 100644 index 0000000..89cb4b3 --- /dev/null +++ b/src/NTP.Application/Refinery/Trips/TripQueryService.cs @@ -0,0 +1,83 @@ +using NTP.Application.Common; +using NTP.Application.Refinery.RemainingBalance; + +namespace NTP.Application.Refinery.Trips; + +public interface ITripQueryService +{ + Task> SearchAsync(TripQuery query, PageRequest page, CancellationToken ct); + Task GetAsync(long id, CancellationToken ct); + Task> LogAsync(long id, PageRequest page, CancellationToken ct); +} + +/// Port of refinerytripFactory.search / getREFINERYTRIP / log (grid, trip form, history popup). +public sealed class TripQueryService( + ITripRepository trips, + ITripAmountsService amounts) : ITripQueryService +{ + public static void ValidateRanges(TripQuery q) + { + if (q.LoadingDateFrom > q.LoadingDateTo || q.PaymentedDateFrom > q.PaymentedDateTo) throw TripErrors.FromAfterTo(); + } + + public async Task> SearchAsync(TripQuery query, PageRequest page, CancellationToken ct) + { + ValidateRanges(query); + var r = await trips.SearchAsync(query, page, ct); + var items = r.Items.Select(x => new TripGridDto( + x.Id, x.Pn, x.DispatchDate, x.LoadingNo, x.DischargeAuthNo, x.DischargeEntryDate, x.Tn, x.Trn, x.Nnpn, + x.WageClaimId, x.WageClaimNo, x.StatusCode, x.DieselCharge, x.HavePaymentMethod != "0", + (x.WaterAmount ?? 0) != 0, x.ReversePayment == 1, x.NetWage)).ToList(); + return new PagedResult(items, r.Page, r.PageSize, r.TotalCount); + } + + public async Task GetAsync(long id, CancellationToken ct) + { + var t = await trips.GetAsync(id, ct) ?? throw new NotFoundException("RefineryTrip", id); + var status = t.StatusCode ?? string.Empty; + + // DISCHARGED / READY_TO_PAY: figures are recomputed from today's variables (factory 129-134) + decimal? netWage = t.NetWage, tripNetWage = t.TripNetWage, remaining = t.RemainingBalance; + if (TripStatus.RecalculateAmounts.Contains(status) && t.LoadingDate is not null) + { + var a = await amounts.ComputeAsync(t, ct); + netWage = a.NetWage; + tripNetWage = a.TripNetWage; + remaining = a.RemainingBalance; + } + + // CalculateRefinaryDiesel is both the "new balance" and, for the late statuses, the second payment value shown on the form + var newBalance = await trips.CalculateDieselAsync(id, ct); + var second = TripStatus.ShowSecondPayment.Contains(status) ? newBalance : null; + var first = await trips.GetFirstPaymentValueAsync(ct); + var audit = await trips.GetAuditModeAsync(ct); + + var wallet = t.Tn is null ? null : await trips.GetActiveWalletByTruckAsync(t.Tn, ct); + // a trip that was already paid shows the wallet it was paid to (factory 172-182) + if (t.RefineryWalletId is { } wid) wallet = await trips.GetWalletAsync(wid, ct) ?? wallet; + var walletDto = wallet is null + ? new TripWalletDto(null, null, null, null, null, null, null, t.DriverWalletNumber) + : new TripWalletDto(wallet.Epayment, wallet.WalletNumber, wallet.OwnerNnpn?.ToString(), wallet.OwnerName, + wallet.BankAccount, wallet.Iban, wallet.BankName, t.DriverWalletNumber); + + var hasTransfer = (status is TripStatus.Discharged or TripStatus.PendingExchange) && await trips.HasTransferLogAsync(id, ct); + var actions = TripActionRules.Available(status, t.DieselCharge, wallet?.Epayment, audit, hasTransfer); + + return new TripDetailDto( + t.Id, t.Pn, t.StatusCode, t.DispatchDate, t.ActualLoadingDate, t.ClientName, t.Tn, t.Trn, t.Nnpn, t.Drvr, t.LoadingNo, + t.GrossWeight, t.EmptyWeight, t.NetLoadingWeight, t.LitersWeight, t.DischargeAuthNo, t.DischargeEntryDate, + t.ActualGrossWeight, t.ActualEmptyWeight, t.NetDischargeWeight, t.WaterAmount, t.SedimentAmount, t.WeightDifference, + netWage, tripNetWage, remaining, t.DieselCharge, t.ReversePayment == 1, t.CardNumber, t.CurrentBalance, newBalance, + first, second, t.WageClaimId, t.WageClaimNo, t.Remarks, t.ReceivedByName, + t.ReceivedDate?.ToString("yyyy-MM-dd HH:mm"), t.PaymentedDate?.ToString("yyyy-MM-dd HH:mm"), t.PaymentOptions, + t.VoucherSerialNumber, audit, walletDto, actions); + } + + public async Task> LogAsync(long id, PageRequest page, CancellationToken ct) + { + var r = await trips.SearchLogAsync(id, page, ct); + return new PagedResult( + r.Items.Select(x => new TripLogDto(x.Id, x.MethodName, x.LogDate, x.Login, x.OldData, x.NewData)).ToList(), + r.Page, r.PageSize, r.TotalCount); + } +} diff --git a/src/NTP.Application/Refinery/Trips/TripReportService.cs b/src/NTP.Application/Refinery/Trips/TripReportService.cs new file mode 100644 index 0000000..bb029ea --- /dev/null +++ b/src/NTP.Application/Refinery/Trips/TripReportService.cs @@ -0,0 +1,114 @@ +using System.Globalization; +using NTP.Application.Grains.Orders; + +namespace NTP.Application.Refinery.Trips; + +public interface ITripReportService +{ + Task TripsAsync(TripQuery query, CancellationToken ct); + Task DieselAsync(DieselReportQuery query, CancellationToken ct); + Task CardsAsync(string? tn, CancellationToken ct); + Task BankAsync(BankReportQuery query, CancellationToken ct); +} + +/// +/// Excel reports of the trips screen: trips (factoryweb.report, manager column set), diesel card movements (REFINERY_DIESEL_REPORT_VIEW), +/// diesel balances of the cards (refineryCardsReport) and the bank report (refineryBankReport; its layout lives in a binary ColdFusion +/// report template that cannot be read, so the columns here are a reasonable set, see the module notes). +/// +public sealed class TripReportService(ITripRepository trips) : ITripReportService +{ + private static string Stamp => DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture); + + private static TripExportFile Xlsx(string name, ExportTable table) => + new(TabularExport.ToXlsx([table], rightToLeft: true), $"{name}-{Stamp}.xlsx", TabularExport.XlsxContentType); + + private static string Day(DateTime? d) => d?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) ?? string.Empty; + + public async Task TripsAsync(TripQuery query, CancellationToken ct) + { + TripQueryService.ValidateRanges(query); + var rows = await trips.ReportAsync(query, ct); + + var data = new List>(); + var n = 0; + foreach (var r in rows) + { + // NEW_TOTAL_VALUE: balance after the next diesel payment; from the 3rd step on it is just the balance + decimal? newTotal = r.DieselCharge >= 2 ? r.CurrentBalance : await trips.CalculateDieselAsync(r.Id, ct); + + // factoryweb.report 624-639: payment method text as the accountant reads it + var paid = string.IsNullOrEmpty(r.PaidEpayment) ? r.PaymentMethod : r.PaidEpayment; + string? bankName = r.BankName, iban = r.Iban, account = r.BankAccount, wallet = r.WalletNumber; + var paidText = paid?.Trim(); + if (paidText == "الكتروني") + { + if (r.PaymentOptions?.Trim() == "CACH_PAYMENT") paid = "دفع نقدي"; + bankName = iban = account = string.Empty; + } + else if (paidText == "حوالة") wallet = string.Empty; + + data.Add([ + ++n, r.Pn, r.DispatchDate, r.LoadingNo, r.DischargeAuthNo, r.DischargeEntryDate, r.NetLoadingWeight, r.NetDischargeWeight, + r.Tn, r.Trn, r.Nnpn, r.CurrentBalance, newTotal, r.NetWage, r.TripNetWage, r.RemainingBalance, + TripStatus.Captions.GetValueOrDefault(r.StatusCode ?? string.Empty, r.StatusCode ?? string.Empty), r.WageClaimNo, + Day(r.PaymentedDate), Day(r.ReceivedDate), r.ReceivedByName, r.ActualLoadingDate, paid, r.OwnerName, r.OwnerNameEnglish, + bankName, iban, account, wallet, r.OwnerNnpn + ]); + } + + string[] headers = + [ + "متسلسل", "رقم الارسالية", "تاريخ الارسالية", "رقم الحمولة", "رقم النموذج", "تاريخ النموذج", "الوزن الصافي(كغ)", + "الوزن الصافي للتفريغ(كغ)", "رقم القاطرة", "رقم المقطورة", "الرقم الوطني", "القيمة التراكمية الحالية", "القيمة التراكمية الجديدة", + "صافي قيمة الصرف الفعلي", "قيمة اجور النقل", "قيمة الذمم السابقة", "الحالة", "رقم مطالبة اجور النقل", "تاريخ الدفع", + "تاريخ الاستلام", "اسم المستلم", "تاريخ التحميل", "آلية الصرف", "صاحب الحساب", "صاحب الحساب بالانجليزي", "البنك", "IBAN", + "رقم الحساب", "رقم المحفظة", "رقم هوية المالك" + ]; + return Xlsx("refinery-trips", new ExportTable(["شاشة الارساليات"], headers, data)); + } + + public async Task DieselAsync(DieselReportQuery query, CancellationToken ct) + { + if (query.DateFrom > query.DateTo) throw TripErrors.FromAfterTo(); + var rows = await trips.DieselReportAsync(query, ct); + var data = rows.Select((r, i) => (IReadOnlyList) + [ + i + 1, r.Pn, r.DischargeAuthNo, r.Tn, r.MethodName, r.BalanceBefore, r.BalanceAfter, r.Amount, + r.CreationDate?.ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture), r.FirstName, + TripStatus.Captions.GetValueOrDefault(r.StatusCode ?? string.Empty, r.StatusCode ?? string.Empty) + ]).ToList(); + string[] headers = + [ + "متسلسل", "رقم الارسالية", "رقم النموذج", "رقم القاطرة", "نوع الحركة", "الرصيد قبل", "الرصيد بعد", "القيمة", + "تاريخ ووقت الحركة", "اسم المستخدم", "الحالة" + ]; + return Xlsx("refinery-diesel", new ExportTable(["شحن الديزل"], headers, data)); + } + + public async Task CardsAsync(string? tn, CancellationToken ct) + { + var rows = await trips.CardsAsync(string.IsNullOrWhiteSpace(tn) ? null : tn.Trim(), ct); + var data = rows.Select((r, i) => (IReadOnlyList)[i + 1, r.Tn, r.CardNumber, r.CurrentBalance]).ToList(); + string[] headers = ["متسلسل", "رقم القاطرة", "رقم بطاقة جوبترول", "القيمة التراكمية الحالية"]; + return Xlsx("refinery-cards", new ExportTable(["أرصدة الديزل"], headers, data)); + } + + public async Task BankAsync(BankReportQuery query, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(query.BankAccount)) throw TripErrors.NoBankAccount(); + if (query.PaymentedDateFrom > query.PaymentedDateTo) throw TripErrors.FromAfterTo(); + var rows = await trips.BankReportAsync(query, ct); + var data = rows.Select((r, i) => (IReadOnlyList) + [ + i + 1, r.Pn, r.DischargeAuthNo, r.Tn, r.OwnerName, r.BankName, r.Iban, r.BankAccount, r.NetWage, + Day(r.PaymentedDate), TripStatus.Captions.GetValueOrDefault(r.StatusCode ?? string.Empty, r.StatusCode ?? string.Empty) + ]).ToList(); + string[] headers = + [ + "متسلسل", "رقم الارسالية", "رقم النموذج", "رقم القاطرة", "صاحب الحساب", "البنك", "IBAN", "رقم الحساب", + "صافي قيمة الصرف الفعلي", "تاريخ الدفع", "الحالة" + ]; + return Xlsx("refinery-bank", new ExportTable(["عطاء صرف نماذج النفط الخام"], headers, data)); + } +} diff --git a/src/NTP.Application/Refinery/Trips/TripRules.cs b/src/NTP.Application/Refinery/Trips/TripRules.cs new file mode 100644 index 0000000..1fda0a8 --- /dev/null +++ b/src/NTP.Application/Refinery/Trips/TripRules.cs @@ -0,0 +1,253 @@ +using System.Globalization; +using System.Text.Json; +using NTP.Application.Common; + +namespace NTP.Application.Refinery.Trips; + +/// REFINERY_TRIPS.STATUS_CODE values used by the trip actions. +public static class TripStatus +{ + public const string Released = "RESD"; + public const string Loaded = "LOADED"; + public const string Discharged = "DISCHARGED"; + public const string PendingExchange = "PENDING_EXCHANGE"; + public const string ReadyToPay = "READY_TO_PAY"; + public const string Exchanged = "EXCHANGED"; + public const string Revoked = "RVKD"; + + /// Arabic captions REFINERYTRIP.STATUS.* / REFINERYTRIP.STATUSCODE.* (ntp.lt_caption). + public static readonly IReadOnlyDictionary Captions = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["RESD"] = "تم التسريب", + ["LOADING_FILL"] = "تم التعبئة للتحميل", + ["LOADED"] = "تم التحميل", + ["DISCHARGING_FILL"] = "تم التعبئة للتفريغ", + ["ARRIVE_LOCATION"] = "وصول شويعر", + ["DISCHARGING"] = "قيد التفريغ", + ["DISCHARGED"] = "تم التفريغ", + ["PENDING_EXCHANGE"] = "قيد التدقيق للصرف", + ["READY_TO_PAY"] = "جاهز للدفع", + ["EXCHANGED"] = "تم الصرف", + ["COMPLETE"] = "مكتمل", + ["RVKD"] = "ملغى", + }; + + /// The statuses in which the second advance value is shown on the trip form (factory getREFINERYTRIP 138). + public static readonly string[] ShowSecondPayment = + ["LOADED", "DISCHARGING_FILL", "ARRIVE_LOCATION", "EXCHANGED", "DISCHARGING", "DISCHARGED", "READY_TO_PAY"]; + + /// Statuses for which getREFINERYTRIP recomputes the wage figures (factory 129). + public static readonly string[] RecalculateAmounts = ["DISCHARGED", "READY_TO_PAY"]; + + /// calculateRemainigBalance refuses to run while a trip of the period is in one of these (factory 1289). + public static readonly string[] BlockRepricing = ["READY_TO_PAY", "PENDING_EXCHANGE", "DISCHARGING", "LOADED", "RESD", "ARRIVE_LOCATION"]; +} + +/// Legacy captions (ntp.lt_caption) of the refinery trip messages, kept verbatim. Codes without a caption in the database are marked. +public static class TripErrors +{ + public const string Ok = "تمت العملية بنجاح"; // PUBLIC.SUCCESSFUL.OPERATION + + public static BusinessException FirstAdvanceExists() => + new("FIRST_ADVANCED_PAYMENT_IS_EXIST", "تم اجراء دفعة الديزل الاولى مسبقاً"); + + /// + /// Caption ERROR.SECOND_ADVANCED_PAYMENT_IS_EXIST of the database reads "لا يوجد بطاقة ديزل معرفة" (copy/paste slip in the legacy table); + /// the plain code SECOND_ADVANCED_PAYMENT_IS_EXIST carries the meaning the legacy code intended, which is used here. + /// + public static BusinessException SecondAdvanceExists() => + new("SECOND_ADVANCED_PAYMENT_IS_EXIST", "تم اجراء دفعة الديزل الثانية مسبقاً"); + + /// No caption exists for FIRST_ADVANCED_PAYMENT_REVERSE_IS_EXIST in the legacy database; wording is new. + public static BusinessException FirstAdvanceReverseExists() => + new("FIRST_ADVANCED_PAYMENT_REVERSE_IS_EXIST", "تم إلغاء دفعة الديزل الأولى مسبقاً"); + + /// No caption exists for CANNOT_FIRST_ADVANCED_PAYMENT_REVERSE in the legacy database; wording is new. + public static BusinessException CannotReverseAdvance() => + new("CANNOT_FIRST_ADVANCED_PAYMENT_REVERSE", "لا يمكن إلغاء دفعة الديزل"); + + public static BusinessException CardNotFound() => + new("THE_REFINERY_CARD_IS_NOT_EXIST", "بطاقة تعبئة الديزل غير معرفة"); + + public static BusinessException WrongLoadingDate() => + new("WRONG_LOADING_DATE", "السعر غير معرف لتاريخ التحميل"); + + /// Legacy code ERROR.REFINERY_PRICE_IS_NOT_DECALRE_FOR_THIS_PERIOD resolves to the plain caption of the same name. + public static BusinessException PriceNotDeclared() => + new("REFINERY_PRICE_IS_NOT_DECALRE_FOR_THIS_PERIOD", "السعر غير معرف لتاريخ التحميل"); + + public static BusinessException NegativeAmount() => + new("PAYMENT_ISNOT_ALLOW_FOR_MINUS_AMOUNT", "الدفع مسموح للمبالغ اكبر من صفر"); + + public static BusinessException BigAmount(decimal max) => + new("PAYMENT_ISNOT_ALLOW_FOR_BIG_AMOUNT", + "الدفع مسموح فقط للمبالغ اقل من " + max.ToString("0.###", CultureInfo.InvariantCulture) + " دينار"); + + public static BusinessException NoPaymentMethod() => + new("CANNOT_COMPLETE_ACTION_NO_PAYMENT_METHOD", "لا يمكن استكمال الاجراء بدون تحديد طريقه الدفع"); + + public static BusinessException ReloadForm() => + new("THERE_IS_EWALLET_PLEASE_RELOAD_FORM", "لا يمكن استكمال الاجراء ، يرجى اغلاق نموذج الارسالية واعاده فتحة مرة اخرى"); + + public static BusinessException WalletNumberEmpty() => + new("WALLET_NUMBER_IS_EMPTY", "لا يوجد رقم محفظة الكترونية"); + + public static BusinessException OwnerNnpnEmpty() => + new("OWNER_NNPN_IS_EMPTY", "لا يوجد رقم وطني لصاحب المحفظة الالكترونية لغاية الدفع"); + + public static BusinessException OwnerNameEmpty() => + new("REFINERY_OWNER_NNPN_WALLET_IS_EMPTY", "لا يوجد اسم لصاحب المحفظة الالكترونية لغاية الدفع"); + + /// Legacy answered ERROR.NO_AUTHORITY when the trip was not in a status the action allows from. + public static BusinessException WrongStatus() => + new("NO_AUTHORITY", "ليس لديك صلاحية لاتمام هذه العملية"); + + public static BusinessException PaymentAlreadySent() => + new("PAYMENT_ALREADY_SENT", "لايمكن تفعيل الصرف, تم الصرف مسبقا"); + + /// No caption exists for ERROR_BACK_FROM_DINARAK in the legacy database; wording is new (legacy appended the Dinarak text after it). + public static BusinessException DinarakRefused(string dinarakMessage) => + new("ERROR_BACK_FROM_DINARAK", "تعذر إتمام الحوالة عبر دينارك" + "\n" + dinarakMessage.ToUpperInvariant()); + + /// No caption exists for REFINERY_NO_FAILED_TRANSFER in the legacy database; wording is new. + public static BusinessException NoFailedTransfer() => + new("REFINERY_NO_FAILED_TRANSFER", "لا توجد حوالة مسجلة لهذه الارسالية"); + + /// New: legacy continued when the Dinarak status lookup failed (risk of paying twice); this port refuses. + public static BusinessException DinarakStatusUnknown() => + new("DINARAK_STATUS_UNKNOWN", "تعذر التحقق من حالة الحوالة لدى دينارك، حاول لاحقاً"); + + public static BusinessException NoTripsInPeriod() => + new("THERE_IS_NO_ANY_TRIP_IN_THIS_PERIOD", "لا يوجد ارساليات ضمن هذه الفترة"); + + public static BusinessException NotAllExchanged() => + new("NO_TON_PRICE_EDIT_NOT_ALL_TRIPS_EXCHANGED", "لا يمكن اعادة تسعير سعر النفط ، يجب ان تكون جميع الارساليات ضمن الفترة مسددة"); + + public static BusinessException FromAfterTo() => + new("FROM_CAN_NOT_GREATER_THAN_TO", "لا يجوز ان يكون تاريخ من أكبر من تارخ الى"); + + public static BusinessException NoBankAccount() => + new("NO_BANK_ACCOUNT", "يجب ادخال رقم الحساب"); +} + +/// Rules shared by the payment actions (refinerytripfactory.cfc exchange / PAYMENT / CACH_PAYMENT). +public static class TripPaymentRules +{ + /// + /// 0 = no price for the loading date, negative = nothing to pay, above = too big + /// (legacy application.REFINERY_MAX_PAYMENT_AMOUNT, caption says 500 dinars). false = ORANGE_PAYMENT (zero check only). + /// + public static void EnsurePayable(decimal netWage, decimal max, bool checkSign = true) + { + if (netWage == 0) throw TripErrors.PriceNotDeclared(); + if (!checkSign) return; + if (netWage < 0) throw TripErrors.NegativeAmount(); + if (netWage > max) throw TripErrors.BigAmount(max); + } + + /// Wallet checks before a wallet payment (exchange / cash / orange): must be 1. + public static void EnsureWalletReady(bool walletExists, int? epayment, string? walletNumber, string? ownerNnpn, string? ownerName) + { + if (!walletExists) throw TripErrors.NoPaymentMethod(); + if (epayment == 0) throw TripErrors.ReloadForm(); + if (string.IsNullOrEmpty(walletNumber)) throw TripErrors.WalletNumberEmpty(); + if (string.IsNullOrEmpty(ownerNnpn)) throw TripErrors.OwnerNnpnEmpty(); + if (string.IsNullOrEmpty(ownerName)) throw TripErrors.OwnerNameEmpty(); + } +} + +/// +/// Builds the OLD_DATA / NEW_DATA JSON of REFINERY_TRIPS_LOG like legacy logs.saveLog: only the fields passed as arguments that exist on the +/// trip record and whose value changed; STATUS_CODE and REMARKS are stored as Arabic captions. PRINT stores the arguments as they are. +/// +public static class TripLogBuilder +{ + private static readonly JsonSerializerOptions Json = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + + public static string? RemarksCaption(string? code) => code switch + { + "SUCCESSFULL_EXCHANGE_OPERATION" => "تمت عملية الصرف بنجاح", // caption SUCCESSFULL_EXCHANGE_OPERATION + _ => code + }; + + private static string Caption(string key, object? v) + { + var s = Text(v); + return key switch + { + "STATUS_CODE" => TripStatus.Captions.TryGetValue(s, out var c) ? c : s, + "REMARKS" => RemarksCaption(s) ?? string.Empty, + _ => s + }; + } + + private static string Text(object? v) => v switch + { + null => string.Empty, + decimal d => d.ToString("0.#########", CultureInfo.InvariantCulture), + IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), + _ => v.ToString() ?? string.Empty + }; + + private static bool Same(object? a, object? b) + { + if (decimal.TryParse(Text(a), NumberStyles.Any, CultureInfo.InvariantCulture, out var x) && + decimal.TryParse(Text(b), NumberStyles.Any, CultureInfo.InvariantCulture, out var y)) return x == y; + return string.Equals(Text(a), Text(b), StringComparison.Ordinal); + } + + /// Current value of a trip column (view column name, upper case) or null when the record has no such column. + /// New values by upper-case column name. + public static (string OldJson, string NewJson)? Build(string methodName, Func oldValue, + IReadOnlyDictionary args) + { + if (methodName.Equals("PRINT", StringComparison.OrdinalIgnoreCase)) + { + var all = args.ToDictionary(a => a.Key, a => Text(a.Value)); + return all.Count == 0 ? null : ("{}", JsonSerializer.Serialize(all, Json)); + } + + var oldD = new Dictionary(); + var newD = new Dictionary(); + foreach (var (key, value) in args) + { + var (exists, old) = oldValue(key); + if (!exists || Same(old, value)) continue; + oldD[key] = Caption(key, old); + newD[key] = Caption(key, value); + } + return newD.Count == 0 ? null : (JsonSerializer.Serialize(oldD, Json), JsonSerializer.Serialize(newD, Json)); + } +} + +/// Which action buttons the trip form offers (legacy getREFINERYTRIP ACTIONS / REVERSE_ACTIONS + REFINERYTRIP.js status switch). The caller still needs the permission key. +public static class TripActionRules +{ + public static IReadOnlyList Available(string status, int dieselCharge, int? epayment, bool auditMode, bool hasTransferLog) + { + var list = new List(); + if (dieselCharge == 0 && status != TripStatus.Revoked) list.Add("firstAdvance"); + if (dieselCharge == 1 && status != TripStatus.Released) list.Add("secondAdvance"); + if (dieselCharge == 1) list.Add("firstAdvanceReverse"); + if (dieselCharge == 2) list.Add("secondAdvanceReverse"); + + if (status == TripStatus.Discharged) + { + if (epayment == 1) + { + list.Add(auditMode ? "exchangeAudit" : "exchange"); + list.Add("cashPayment"); + } + else list.Add("receipt"); + list.Add("print"); + } + if (status == TripStatus.PendingExchange && epayment == 1) list.Add("exchange"); + if ((status is TripStatus.Discharged or TripStatus.PendingExchange) && epayment == 1) + { + list.Add("activateWalletExchange"); + if (hasTransferLog) list.Add("confirmExchange"); + } + if (status == TripStatus.ReadyToPay) list.Add("payment"); + return list; + } +} diff --git a/src/NTP.Application/Refinery/Trips/TripsContracts.cs b/src/NTP.Application/Refinery/Trips/TripsContracts.cs new file mode 100644 index 0000000..ae4a90f --- /dev/null +++ b/src/NTP.Application/Refinery/Trips/TripsContracts.cs @@ -0,0 +1,272 @@ +namespace NTP.Application.Refinery.Trips; + +/// Envelope of write operations: message is the legacy Arabic success text (toasted by the client). +public sealed record TripsResult(string Message, long? Id = null); + +// ---------------------------------------------------------------- filters +/// +/// Grid / report filters (legacy factoryweb.search whitelist, mapped on REFINERY_TRIPS_VIEW). StatusCode and +/// PaymentMethodCode accept a comma separated list (multi-select). Dates are days (yyyy-MM-dd). +/// +public sealed record TripQuery( + string? Pn = null, + string? Tn = null, + string? Trn = null, + string? Nnpn = null, + string? LoadingNo = null, + string? DischargeAuthNo = null, + DateTime? DispatchDate = null, + DateTime? DischargeEntryDate = null, + DateTime? LoadingDateFrom = null, + DateTime? LoadingDateTo = null, + DateTime? PaymentedDateFrom = null, + DateTime? PaymentedDateTo = null, + string? StatusCode = null, + string? PaymentMethodCode = null, + string? HasWageClaim = null, + string? HavePaymentMethod = null, + string? DieselCharge = null, + string? WageClaimNo = null, + long? WageClaimId = null, + string? BankAccount = null, + string? WaterExist = null, + long? Id = null); + +// ---------------------------------------------------------------- grid +/// One grid row. The icons of the legacy action column derive from DieselCharge / HavePaymentMethod / WaterAmount / ReversePayment. +public sealed class TripRow +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? DispatchDate { get; set; } + public long? LoadingNo { get; set; } + public string? DischargeAuthNo { get; set; } + public string? DischargeEntryDate { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Nnpn { get; set; } + public long? WageClaimId { get; set; } + public long? WageClaimNo { get; set; } + public string? StatusCode { get; set; } + public int DieselCharge { get; set; } + public string? HavePaymentMethod { get; set; } + public decimal? WaterAmount { get; set; } + public int? ReversePayment { get; set; } + public decimal? NetWage { get; set; } +} + +public sealed record TripGridDto( + long Id, string? Pn, string? DispatchDate, long? LoadingNo, string? DischargeAuthNo, string? DischargeEntryDate, + string? Tn, string? Trn, string? Nnpn, long? WageClaimId, long? WageClaimNo, string? StatusCode, + int DieselCharge, bool HasPaymentMethod, bool HasWater, bool Reversed, decimal? NetWage); + +// ---------------------------------------------------------------- one trip +/// Raw row of REFINERY_TRIPS_VIEW for the form and the actions. +public sealed class TripRecord +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? StatusCode { get; set; } + public string? DispatchDate { get; set; } + public string? ActualLoadingDate { get; set; } + public DateTime? LoadingDate { get; set; } + public string? ClientName { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Nnpn { get; set; } + public string? Drvr { get; set; } + public long? LoadingNo { get; set; } + public decimal? GrossWeight { get; set; } + public decimal? EmptyWeight { get; set; } + public decimal? NetLoadingWeight { get; set; } + public decimal? LitersWeight { get; set; } + public string? DischargeAuthNo { get; set; } + public string? DischargeEntryDate { get; set; } + public decimal? ActualGrossWeight { get; set; } + public decimal? ActualEmptyWeight { get; set; } + public decimal? NetDischargeWeight { get; set; } + public decimal? WaterAmount { get; set; } + public decimal? SedimentAmount { get; set; } + public decimal? WeightDifference { get; set; } + public decimal? NetWage { get; set; } + public decimal? TripNetWage { get; set; } + public decimal? RemainingBalance { get; set; } + public int DieselCharge { get; set; } + public int? ReversePayment { get; set; } + public decimal? FirstAdvancePayment { get; set; } + public decimal? SecondAdvancePayment { get; set; } + public decimal? PenaltyAmount { get; set; } + public decimal? PenaltyQuantity { get; set; } + public string? HavePaymentMethod { get; set; } + public string? DriverWalletNumber { get; set; } + public long? WageClaimId { get; set; } + public long? WageClaimNo { get; set; } + public string? CardNumber { get; set; } + public decimal? CurrentBalance { get; set; } + public long? RefineryWalletId { get; set; } + public decimal? DinarakReferenceId { get; set; } + public string? Remarks { get; set; } + public string? ReceivedByName { get; set; } + public DateTime? ReceivedDate { get; set; } + public DateTime? PaymentedDate { get; set; } + public string? PaymentOptions { get; set; } + public long? VoucherSerialNumber { get; set; } + public string? PaidEpayment { get; set; } + public string? PaymentMethod { get; set; } + public string? OwnerName { get; set; } +} + +/// Active REFINERY_WALLET of the truck (legacy checkEWallet) or the wallet the trip was paid to. +public sealed class TripWallet +{ + public long Id { get; set; } + public int? Epayment { get; set; } + public string? WalletNumber { get; set; } + public long? OwnerNnpn { get; set; } + public string? OwnerName { get; set; } + public string? DriverName { get; set; } + public long? DriverNnpn { get; set; } + public string? BankAccount { get; set; } + public string? Iban { get; set; } + public string? BankName { get; set; } +} + +public sealed record TripWalletDto( + int? Epayment, string? WalletNumber, string? OwnerNnpn, string? OwnerName, string? BankAccount, string? Iban, string? BankName, + string? DriverWalletNumber); + +public sealed record TripDetailDto( + long Id, + string? Pn, + string? StatusCode, + string? DispatchDate, + string? ActualLoadingDate, + string? ClientName, + string? Tn, + string? Trn, + string? Nnpn, + string? DriverName, + long? LoadingNo, + decimal? GrossWeight, + decimal? EmptyWeight, + decimal? NetLoadingWeight, + decimal? LitersWeight, + string? DischargeAuthNo, + string? DischargeEntryDate, + decimal? ActualGrossWeight, + decimal? ActualEmptyWeight, + decimal? NetDischargeWeight, + decimal? WaterAmount, + decimal? SedimentAmount, + decimal? WeightDifference, + decimal? NetWage, + decimal? TripNetWage, + decimal? RemainingBalance, + int DieselCharge, + bool Reversed, + string? CardNumber, + decimal? CurrentBalance, + decimal? NewBalance, + decimal? FirstPaymentValue, + decimal? SecondPaymentValue, + long? WageClaimId, + long? WageClaimNo, + string? Remarks, + string? ReceivedByName, + string? ReceivedDate, + string? PaymentedDate, + string? PaymentOptions, + long? VoucherSerialNumber, + bool AuditMode, + TripWalletDto? Wallet, + IReadOnlyList Actions); + +// ---------------------------------------------------------------- log +public sealed class TripLogRow +{ + public long Id { get; set; } + public string? MethodName { get; set; } + public string? LogDate { get; set; } + public string? Login { get; set; } + public string? OldData { get; set; } + public string? NewData { get; set; } +} + +public sealed record TripLogDto(long Id, string? MethodName, string? LogDate, string? Login, string? OldData, string? NewData); + +// ---------------------------------------------------------------- print +/// Cash voucher "سند صرف نقدي" (legacy print): the page prints it, the serial is stored on the trip. +public sealed record TripVoucherDto( + long Id, string Pn, string Serial, string Date, decimal Amount, string? DischargeAuthNo, string? OwnerName); + +// ---------------------------------------------------------------- reports +public sealed record DieselReportQuery( + string? Pn = null, string? Tn = null, string? StatusCode = null, string? DischargeAuthNo = null, string? DieselCharge = null, + DateTime? DateFrom = null, DateTime? DateTo = null); + +public sealed class DieselReportRow +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? Tn { get; set; } + public string? StatusCode { get; set; } + public string? DischargeAuthNo { get; set; } + public DateTime? CreationDate { get; set; } + public string? FirstName { get; set; } + public string? MethodName { get; set; } + public decimal? BalanceBefore { get; set; } + public decimal? BalanceAfter { get; set; } + public decimal? Amount { get; set; } +} + +public sealed class CardRow +{ + public long Id { get; set; } + public long Tn { get; set; } + public string? CardNumber { get; set; } + public decimal? CurrentBalance { get; set; } +} + +/// Row of the trips excel report (legacy report(), manager column set). +public sealed class TripReportRow +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? DispatchDate { get; set; } + public long? LoadingNo { get; set; } + public string? DischargeAuthNo { get; set; } + public string? DischargeEntryDate { get; set; } + public decimal? NetLoadingWeight { get; set; } + public decimal? NetDischargeWeight { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Nnpn { get; set; } + public decimal? CurrentBalance { get; set; } + public int DieselCharge { get; set; } + public decimal? NetWage { get; set; } + public decimal? TripNetWage { get; set; } + public decimal? RemainingBalance { get; set; } + public string? StatusCode { get; set; } + public long? WageClaimNo { get; set; } + public DateTime? PaymentedDate { get; set; } + public DateTime? ReceivedDate { get; set; } + public string? ReceivedByName { get; set; } + public string? ActualLoadingDate { get; set; } + public string? PaymentMethod { get; set; } + public string? PaidEpayment { get; set; } + public string? PaymentOptions { get; set; } + public string? OwnerName { get; set; } + public string? OwnerNameEnglish { get; set; } + public string? BankName { get; set; } + public string? Iban { get; set; } + public string? BankAccount { get; set; } + public string? WalletNumber { get; set; } + public long? OwnerNnpn { get; set; } +} + +public sealed record BankReportQuery(string? BankAccount, string? StatusCode, string? HasWageClaim, DateTime? PaymentedDateFrom, DateTime? PaymentedDateTo); + +public sealed record RecalculateBalanceRequest(DateTime StartDate, DateTime EndDate, long VariableGroupId); + +/// Result of an export: file content, name and content type. +public sealed record TripExportFile(byte[] Content, string FileName, string ContentType); diff --git a/src/NTP.Application/Refinery/Trips/TripsRepositories.cs b/src/NTP.Application/Refinery/Trips/TripsRepositories.cs new file mode 100644 index 0000000..5bd1ecf --- /dev/null +++ b/src/NTP.Application/Refinery/Trips/TripsRepositories.cs @@ -0,0 +1,89 @@ +using NTP.Application.Common; + +namespace NTP.Application.Refinery.Trips; + +/// Configuration of the trips slice (section "Refinery:Trips"). +public sealed class TripOptions +{ + public const string SectionName = "Refinery:Trips"; + + /// + /// Largest net wage a payment action accepts (legacy application.REFINERY_MAX_PAYMENT_AMOUNT, defined outside the repository; + /// the caption ERROR.PAYMENT_ISNOT_ALLOW_FOR_BIG_AMOUNT says 500 dinars). UNVERIFIED default. + /// + public decimal MaxPaymentAmount { get; set; } = 500m; +} + +/// Reads (Application has no Options package; implemented in Infrastructure). +public interface ITripSettingsService +{ + TripOptions Value { get; } +} + +public sealed record TripLock(string? StatusCode, int DieselCharge); + +public sealed record CardInfo(long Id, decimal CurrentBalance); + +/// Data access of the refinery trips (REFINERY_TRIPS and its view, cards, logs, DB functions). +public interface ITripRepository +{ + // ---- reads + Task> SearchAsync(TripQuery query, PageRequest page, CancellationToken ct = default); + Task GetAsync(long id, CancellationToken ct = default); + /// SELECT ... FOR UPDATE of the trip (inside a transaction): serialises two operators acting on the same trip. + Task LockAsync(long id, CancellationToken ct = default); + Task GetActiveWalletByTruckAsync(string tn, CancellationToken ct = default); + Task GetWalletAsync(long walletId, CancellationToken ct = default); + /// REFINERY_VARIABLES AUTDIT_MODE = 1 (legacy checkAuditMode). + Task GetAuditModeAsync(CancellationToken ct = default); + /// FIRST_ADVANCE_PAYMENT valid today (legacy getFirstPaymentValue). + Task GetFirstPaymentValueAsync(CancellationToken ct = default); + /// All KEY_NAME / KEY_VALUE of the variables valid on the (truncated) loading date. + Task>> GetVariablesAsync(DateTime loadingDate, CancellationToken ct = default); + /// WATER_FLAG of the trip, or null when the column does not exist yet in this database / is empty. + Task GetWaterFlagAsync(long id, CancellationToken ct = default); + /// CalculateRefinaryDiesel(id); null when the function finds no price (ORA-01403). + Task CalculateDieselAsync(long id, CancellationToken ct = default); + /// CalculateRefinaryAmount(id); null when the function finds no price (ORA-01403). + Task CalculateAmountAsync(long id, CancellationToken ct = default); + Task HasTransferLogAsync(long id, CancellationToken ct = default); + Task> GetTripsOfPeriodAsync(DateTime from, DateTime to, CancellationToken ct = default); + + // ---- diesel cards + Task GetActiveCardAsync(string tn, CancellationToken ct = default); + Task GetLastCardLogAmountAsync(string pn, string methodName, CancellationToken ct = default); + Task InsertCardLogAsync(long cardId, string methodName, decimal before, decimal after, decimal amount, string userId, string pn, CancellationToken ct = default); + Task UpdateCardBalanceAsync(long cardId, decimal balance, string userId, long tripId, CancellationToken ct = default); + + // ---- writes on the trip + Task MarkFirstAdvanceAsync(long id, string userId, CancellationToken ct = default); + Task MarkSecondAdvanceAsync(long id, string userId, decimal secondPaymentValue, CancellationToken ct = default); + Task MarkAdvanceReversedAsync(long id, string userId, int dieselCharge, CancellationToken ct = default); + /// Legacy NetWageAmount: stores the computed figures on the trip. + Task SaveAmountsAsync(long id, string userId, TripAmounts amounts, CancellationToken ct = default); + /// RECEIPT (READY_TO_PAY) and EXCHANGE_AUDIT (PENDING_EXCHANGE): new status + received by / date. + Task SetStatusReceivedAsync(long id, string userId, string status, CancellationToken ct = default); + /// Status EXCHANGED. also fills RECEIVED_BY/DATE (not done by the bank-transfer PAYMENT). + Task MarkExchangedAsync(long id, string userId, string? remarks, string? paymentOptions, bool setReceived, long? walletId, CancellationToken ct = default); + Task BumpDinarakReferenceAsync(long id, string userId, CancellationToken ct = default); + Task SetVoucherSerialAsync(long id, long serial, CancellationToken ct = default); + /// Legacy DAO.CONFIRM_EXCHANGE: EXCHANGED with wallet / user / date taken from the last Dinarak log and EXCHANGE log rows. + Task ConfirmExchangeAsync(long id, string userId, CancellationToken ct = default); + + // ---- history + Task InsertLogAsync(long tripId, string methodName, string userId, string oldJson, string newJson, CancellationToken ct = default); + Task> SearchLogAsync(long tripId, PageRequest page, CancellationToken ct = default); + + // ---- reports + Task> ReportAsync(TripQuery query, CancellationToken ct = default); + Task> DieselReportAsync(DieselReportQuery query, CancellationToken ct = default); + Task> CardsAsync(string? tn, CancellationToken ct = default); + Task> BankReportAsync(BankReportQuery query, CancellationToken ct = default); +} + +/// Voucher serial of the cash voucher (NTP.SYSTEM_VARIABLES VOUCHER_SERIAL_NO, legacy GenerateSerialNumber('VOUCHER')). NTP-schema connection. +public interface IVoucherSerialRepository +{ + /// Takes the next number (locks the row until commit) and returns {yyyy}{seq:00000} as a number. + Task NextAsync(CancellationToken ct = default); +} diff --git a/src/NTP.Application/Refinery/Variables/IVariables.cs b/src/NTP.Application/Refinery/Variables/IVariables.cs new file mode 100644 index 0000000..5c98dfc --- /dev/null +++ b/src/NTP.Application/Refinery/Variables/IVariables.cs @@ -0,0 +1,43 @@ +using NTP.Application.Common; +using NTP.Application.Grains.Orders; + +namespace NTP.Application.Refinery.Variables; + +public interface IVariablesRepository +{ + /// Pricing periods, newest group first (legacy sort GROUP_ID DESC). + Task> SearchAsync(VariablesQuery query, PageRequest page, CancellationToken ct = default); + Task GetAsync(long groupId, CancellationToken ct = default); + /// Periods of every group (AUTDIT_MODE ignored), optionally without one group. + Task> GetPeriodsAsync(long? excludeGroupId, CancellationToken ct = default); + /// Any REFINERY_TRIPS row loaded (ACTUAL_LOADING_DATE) inside the period. + Task HasTripsAsync(DateTime start, DateTime end, CancellationToken ct = default); + Task GetTripsOfPeriodAsync(DateTime start, DateTime end, CancellationToken ct = default); + Task NextGroupIdAsync(CancellationToken ct = default); + Task InsertSetAsync(long groupId, DateOnly start, DateOnly end, IReadOnlyDictionary values, string createdBy, CancellationToken ct = default); + Task UpdateSetAsync(long groupId, DateOnly start, DateOnly end, IReadOnlyDictionary values, string updatedBy, CancellationToken ct = default); + /// Writes TON_PRICE_CORRECTION = value and TON_PRICE_CORRECTION_SET = 1 (rows are inserted when missing). + Task SetTonPriceCorrectionAsync(long groupId, string value, DateTime start, DateTime end, string userId, CancellationToken ct = default); + Task> GetRemainingBalancesAsync(CancellationToken ct = default); +} + +public interface IVariablesService +{ + Task> SearchAsync(VariablesQuery query, PageRequest page, CancellationToken ct); + Task GetAsync(long groupId, CancellationToken ct); + Task CreateAsync(SaveVariablesRequest request, CancellationToken ct); + Task UpdateAsync(long groupId, SaveVariablesRequest request, CancellationToken ct); + Task SetTonPriceCorrectionAsync(long groupId, TonPriceCorrectionRequest request, CancellationToken ct); + Task ExportAsync(VariablesQuery query, CancellationToken ct); + Task ExportRemainingBalanceAsync(CancellationToken ct); +} + +/// +/// Step of UPDATE_TON_PRICE_CORRECTION that recalculates the previous balances of the trucks of a period +/// (legacy refinerytripFactory.calculateRemainigBalance). Throws when it must stop the action. +/// The calculation of the trip amounts belongs to the trips module: see TonPriceRecalculationService. +/// +public interface ITonPriceRecalculationService +{ + Task RecalculateAsync(long groupId, DateTime start, DateTime end, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Refinery/Variables/TonPriceRecalculationService.cs b/src/NTP.Application/Refinery/Variables/TonPriceRecalculationService.cs new file mode 100644 index 0000000..48a84d3 --- /dev/null +++ b/src/NTP.Application/Refinery/Variables/TonPriceRecalculationService.cs @@ -0,0 +1,29 @@ +using NTP.Application.Common; + +namespace NTP.Application.Refinery.Variables; + +/// +/// Port of the checks of refinerytripFactory.calculateRemainigBalance (refinerytripfactory.cfc:1269-1300) that run when the actual ton price +/// is set: there must be trips in the period (ERROR.THERE_IS_NO_ANY_TRIP_IN_THIS_PERIOD) and all of them must be exchanged +/// (ERROR.NO_TON_PRICE_EDIT_NOT_ALL_TRIPS_EXCHANGED). +/// +/// NOT ported here: for every trip with PENALTY_AMOUNT > 0 legacy calls calculateAmounts(trip, 'TON_PRICE_CORRECTION') and, when the net wage +/// changes, writes the difference into REFINERY_REMAINING_BALANCE (+ its log) per truck. That calculation is the trips module's +/// (calculateAmounts). Until it is wired in here, a period that HAS such trips is refused with a clear message instead of being +/// priced without recalculating the balances; a period without penalty trips (nothing to recalculate) works as legacy. +/// Replace the throw below with the trips module's recalculation to finish the port. +/// +/// +public sealed class TonPriceRecalculationService(IVariablesRepository repository) : ITonPriceRecalculationService +{ + public async Task RecalculateAsync(long groupId, DateTime start, DateTime end, CancellationToken ct = default) + { + var info = await repository.GetTripsOfPeriodAsync(start, end, ct); + if (info.TripCount == 0) + throw new BusinessException(VariablesErrors.NoTripsInPeriod, VariablesMessages.NoTripsInPeriod); + if (info.NotExchangedCount > 0) + throw new BusinessException(VariablesErrors.NotAllTripsExchanged, VariablesMessages.NotAllTripsExchanged); + if (info.PenaltyTripCount > 0) + throw new BusinessException(VariablesErrors.RecalculationNotAvailable, VariablesMessages.RecalculationNotAvailable); + } +} diff --git a/src/NTP.Application/Refinery/Variables/VariablesContracts.cs b/src/NTP.Application/Refinery/Variables/VariablesContracts.cs new file mode 100644 index 0000000..33d072a --- /dev/null +++ b/src/NTP.Application/Refinery/Variables/VariablesContracts.cs @@ -0,0 +1,83 @@ +namespace NTP.Application.Refinery.Variables; + +/// +/// One pricing period ("variables set"): the rows of REFINERY_VARIABLES that share a GROUP_ID, pivoted like the legacy +/// REFINERY_VARIABLES_VIEW (plus the ton price correction, which the view leaves out). Class with settable properties (Dapper + Oracle NUMBER). +/// +public class VariablesSetRow +{ + public long GroupId { get; set; } + public DateTime? StartDate { get; set; } + public DateTime? EndDate { get; set; } + public decimal? DieselLiterPrice { get; set; } + public decimal? TonWage { get; set; } + public decimal? TonPrice { get; set; } + public decimal? DriverTip { get; set; } + public decimal? PermitDispatch { get; set; } + public decimal? WaybillFee { get; set; } + public decimal? Commission { get; set; } + public decimal? TolerancePercentage { get; set; } + public decimal? FirstAdvancePayment { get; set; } + /// TON_PRICE_CORRECTION (actual ton price), null when never set. + public decimal? TonPriceCorrection { get; set; } + /// TON_PRICE_CORRECTION_SET = 1: the correction was applied, it cannot be set again (legacy ERROR.YOU_CANNOT_RESET_TON_PRICE). + public bool TonPriceCorrectionSet { get; set; } +} + +/// Detail of one period: the row plus what the caller may still do with it. +public sealed class VariablesSetDetail : VariablesSetRow +{ + /// No trip was loaded inside the period (legacy getrefinery_variables sets ACTIONS = UPDATE). + public bool CanUpdate { get; set; } + /// The ton price correction was not applied yet. + public bool CanSetTonPriceCorrection { get; set; } +} + +/// Period of a set (legacy overlap checks). +public sealed record VariablesPeriod(long GroupId, DateTime Start, DateTime End); + +/// Grid filters (legacy START_DATE_STRING / END_DATE_STRING of the search form). +/// Both dates: periods starting inside [StartDate, EndDate]. Only this: periods starting on this day. +/// Only this: periods ending on this day. +public sealed record VariablesQuery(DateOnly? StartDate, DateOnly? EndDate); + +/// Body of create / update. Dates as yyyy-MM-dd. +public sealed class SaveVariablesRequest +{ + public DateOnly StartDate { get; set; } + public DateOnly EndDate { get; set; } + public decimal DieselLiterPrice { get; set; } + public decimal FirstAdvancePayment { get; set; } + public decimal TonWage { get; set; } + public decimal TonPrice { get; set; } + public decimal DriverTip { get; set; } + public decimal PermitDispatch { get; set; } + public decimal WaybillFee { get; set; } + public decimal Commission { get; set; } + public decimal TolerancePercentage { get; set; } +} + +public sealed class TonPriceCorrectionRequest +{ + public decimal TonPriceCorrection { get; set; } +} + +public sealed record VariablesResult(string Message, long? Id = null); + +/// What the ton price recalculation needs to know about the trips of a period (legacy refinerytripFactory.calculateRemainigBalance). +public sealed class TripsOfPeriodInfo +{ + public long TripCount { get; set; } + /// Trips still in READY_TO_PAY, PENDING_EXCHANGE, DISCHARGING, LOADED, RESD or ARRIVE_LOCATION. + public long NotExchangedCount { get; set; } + /// Trips with PENALTY_AMOUNT > 0: the only ones whose balance is recalculated. + public long PenaltyTripCount { get; set; } +} + +/// Row of REFINERY_REMAINING_BALANCE (previous balances per truck). +public sealed class RemainingBalanceRow +{ + public long Id { get; set; } + public long Tn { get; set; } + public decimal RemainingBalance { get; set; } +} diff --git a/src/NTP.Application/Refinery/Variables/VariablesRules.cs b/src/NTP.Application/Refinery/Variables/VariablesRules.cs new file mode 100644 index 0000000..d2d3a83 --- /dev/null +++ b/src/NTP.Application/Refinery/Variables/VariablesRules.cs @@ -0,0 +1,100 @@ +using System.Globalization; + +namespace NTP.Application.Refinery.Variables; + +/// User-facing texts (legacy captions, verbatim; the ones marked * have no row in LT_CAPTION and are new wording). +public static class VariablesMessages +{ + public const string DateOverlap = "يوجد تداخل في فترة التسعير"; // ERROR.DATE_IS_EXIT_IN_PREVIOUS_PERIOD + public const string StartDateInPreviousPeriod = "تاريخ بداية فترة التسعير يقع ضمن فترة تسعير سابقة"; // * ERROR.START_DATE_IS_EXIT_IN_PREVIOUS_PERIOD + public const string EndDateInPreviousPeriod = "تاريخ نهاية فترة التسعير يقع ضمن فترة تسعير سابقة"; // * ERROR.END_DATE_IS_EXIT_IN_PREVIOUS_PERIOD + public const string DieselPriceNotCorrect = "سعر لتر الديزل غير صحيح"; // * ERROR.DIESEL_LITER_PRICE_IS_NOT_CORRECT + public const string TonWageNotCorrect = "اجور الطن غير صحيحة"; // * ERROR.TON_WAGE_IS_NOT_CORRECT + public const string StartAfterEnd = "لا يجوز أن يكون تاريخ بداية الفترة أكبر من تاريخ نهايتها"; // * ERROR.START_DATE_CAN_NOT_GREATER_THAN_END_DATE + public const string TripsExist = "لا يمكن تعديل القيم بسبب وجود ارساليات مسعره عليها"; // ERROR.YOU_CANNOT_UPDATE_VARIABLES_THERE_IS_TRIPS + public const string CannotResetTonPrice = "تم تعديل سعر الطن الفعلي سابقا"; // ERROR.YOU_CANNOT_RESET_TON_PRICE + public const string NoTripsInPeriod = "لا يوجد ارساليات ضمن هذه الفترة"; // ERROR.THERE_IS_NO_ANY_TRIP_IN_THIS_PERIOD + public const string NotAllTripsExchanged = "لا يمكن اعادة تسعير سعر النفط ، يجب ان تكون جميع الارساليات ضمن الفترة مسددة"; // ERROR.NO_TON_PRICE_EDIT_NOT_ALL_TRIPS_EXCHANGED + public const string RecalculationNotAvailable = "إعادة احتساب الذمم السابقة غير متوفرة بعد، لا يمكن تعديل سعر الطن الفعلي لفترة فيها ارساليات مغرمة"; // * (balance recalculation belongs to the trips module) + public const string NotFound = "فترة التسعير غير موجودة"; // * + public const string Done = ""; +} + +public static class VariablesErrors +{ + public const string DateOverlap = "DATE_IS_EXIT_IN_PREVIOUS_PERIOD"; + public const string StartDateInPreviousPeriod = "START_DATE_IS_EXIT_IN_PREVIOUS_PERIOD"; + public const string EndDateInPreviousPeriod = "END_DATE_IS_EXIT_IN_PREVIOUS_PERIOD"; + public const string DieselPriceNotCorrect = "DIESEL_LITER_PRICE_IS_NOT_CORRECT"; + public const string TonWageNotCorrect = "TON_WAGE_IS_NOT_CORRECT"; + public const string StartAfterEnd = "START_DATE_CAN_NOT_GREATER_THAN_END_DATE"; + public const string TripsExist = "YOU_CANNOT_UPDATE_VARIABLES_THERE_IS_TRIPS"; + public const string CannotResetTonPrice = "YOU_CANNOT_RESET_TON_PRICE"; + public const string NoTripsInPeriod = "THERE_IS_NO_ANY_TRIP_IN_THIS_PERIOD"; + public const string NotAllTripsExchanged = "NO_TON_PRICE_EDIT_NOT_ALL_TRIPS_EXCHANGED"; + public const string RecalculationNotAvailable = "TON_PRICE_RECALCULATION_NOT_AVAILABLE"; + public const string NotFound = "REFINERY_VARIABLES_NOT_FOUND"; +} + +/// Pure rules of the pricing periods (refinery_variablesfactory.cfc create / update / UPDATE_TON_PRICE_CORRECTION). +public static class VariablesRules +{ + /// Row of the same table that is not a pricing period: read by the trips module, ignored by the period checks. + public const string AuditModeKey = "AUTDIT_MODE"; + public const string TonPriceCorrectionKey = "TON_PRICE_CORRECTION"; + public const string TonPriceCorrectionSetKey = "TON_PRICE_CORRECTION_SET"; + + /// The keys a period holds (legacy DAO create / update whitelist). + public static readonly string[] SetKeys = + [ + "COMMISSION", "DIESEL_LITER_PRICE", "TON_WAGE", "TON_PRICE", "DRIVER_TIP", "WAYBILL_FEE", "FIRST_ADVANCE_PAYMENT", + "PERMIT_DISPATCH", "TOLERANCE_PERCENTAGE", + ]; + + /// KEY_VALUE is a VARCHAR2: the number as plain invariant text (legacy stored what the user typed). + public static string FormatValue(decimal value) => value.ToString(CultureInfo.InvariantCulture); + + public static Dictionary ToValues(SaveVariablesRequest r) => new() + { + ["COMMISSION"] = FormatValue(r.Commission), + ["DIESEL_LITER_PRICE"] = FormatValue(r.DieselLiterPrice), + ["TON_WAGE"] = FormatValue(r.TonWage), + ["TON_PRICE"] = FormatValue(r.TonPrice), + ["DRIVER_TIP"] = FormatValue(r.DriverTip), + ["WAYBILL_FEE"] = FormatValue(r.WaybillFee), + ["FIRST_ADVANCE_PAYMENT"] = FormatValue(r.FirstAdvancePayment), + ["PERMIT_DISPATCH"] = FormatValue(r.PermitDispatch), + ["TOLERANCE_PERCENTAGE"] = FormatValue(r.TolerancePercentage), + }; + + /// + /// The first failing rule, in the legacy order (refinery_variablesfactory.cfc:112-143): start inside another period, end inside another + /// period, another period wholly inside the new one, diesel price in (0, 2), ton wage in (0, 100), start after end. + /// must already exclude the period being updated. + /// + public static (string Code, string Message)? FirstError(IEnumerable otherPeriods, SaveVariablesRequest r) + { + var start = r.StartDate.ToDateTime(TimeOnly.MinValue); + var end = r.EndDate.ToDateTime(TimeOnly.MinValue); + var others = otherPeriods.ToList(); + if (others.Any(p => p.Start.Date <= start && start <= p.End.Date)) + return (VariablesErrors.StartDateInPreviousPeriod, VariablesMessages.StartDateInPreviousPeriod); + if (others.Any(p => p.Start.Date <= end && end <= p.End.Date)) + return (VariablesErrors.EndDateInPreviousPeriod, VariablesMessages.EndDateInPreviousPeriod); + if (others.Any(p => p.Start.Date > start && p.End.Date < end)) + return (VariablesErrors.DateOverlap, VariablesMessages.DateOverlap); + if (r.DieselLiterPrice <= 0 || r.DieselLiterPrice >= 2) + return (VariablesErrors.DieselPriceNotCorrect, VariablesMessages.DieselPriceNotCorrect); + if (r.TonWage <= 0 || r.TonWage >= 100) + return (VariablesErrors.TonWageNotCorrect, VariablesMessages.TonWageNotCorrect); + if (start > end) + return (VariablesErrors.StartAfterEnd, VariablesMessages.StartAfterEnd); + return null; + } + + /// + /// Legacy compares the stored TON_PRICE with the typed correction; the balances are only recalculated when they differ + /// (refinery_variablesfactory.cfc:307). + /// + public static bool TonPriceChanges(decimal? currentTonPrice, decimal correction) => currentTonPrice is not null && currentTonPrice.Value != correction; +} diff --git a/src/NTP.Application/Refinery/Variables/VariablesService.cs b/src/NTP.Application/Refinery/Variables/VariablesService.cs new file mode 100644 index 0000000..e18a516 --- /dev/null +++ b/src/NTP.Application/Refinery/Variables/VariablesService.cs @@ -0,0 +1,153 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; +using NTP.Application.Grains.Reports; + +namespace NTP.Application.Refinery.Variables; + +/// +/// Port of refinery_variablesfactory.cfc / refinery_variablesfactoryweb.cfc (screen REFINERY_VARIABLES, تسعير عطاء النفط الخام). +/// Access is decided only by the permission keys on the controller (SU / PTADM); the legacy REFINERY_MGR / REFINERY_AC role branches are not ported. +/// There is no log: the legacy log call is commented out and no REFINERY_VARIABLES_LOG table exists. +/// +public sealed class VariablesService( + IVariablesRepository repository, + ITonPriceRecalculationService recalculation, + IUnitOfWork unitOfWork, + ICurrentUser user, + IReportExcelService excel, + IValidator saveValidator, + IValidator correctionValidator) : IVariablesService +{ + private const string ExcelType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + public Task> SearchAsync(VariablesQuery query, PageRequest page, CancellationToken ct) => + repository.SearchAsync(query, page, ct); + + public async Task GetAsync(long groupId, CancellationToken ct) + { + var row = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId); + var canUpdate = row.StartDate is not null && row.EndDate is not null + && !await repository.HasTripsAsync(row.StartDate.Value, row.EndDate.Value, ct); + return new VariablesSetDetail + { + GroupId = row.GroupId, StartDate = row.StartDate, EndDate = row.EndDate, DieselLiterPrice = row.DieselLiterPrice, + TonWage = row.TonWage, TonPrice = row.TonPrice, DriverTip = row.DriverTip, PermitDispatch = row.PermitDispatch, + WaybillFee = row.WaybillFee, Commission = row.Commission, TolerancePercentage = row.TolerancePercentage, + FirstAdvancePayment = row.FirstAdvancePayment, TonPriceCorrection = row.TonPriceCorrection, + TonPriceCorrectionSet = row.TonPriceCorrectionSet, + CanUpdate = canUpdate, + CanSetTonPriceCorrection = !row.TonPriceCorrectionSet, + }; + } + + public async Task CreateAsync(SaveVariablesRequest request, CancellationToken ct) + { + await saveValidator.ValidateAndThrowAsync(request, ct); + var error = VariablesRules.FirstError(await repository.GetPeriodsAsync(null, ct), request); + if (error is { } e) throw new BusinessException(e.Code, e.Message); + + var groupId = await unitOfWork.ExecuteInTransactionAsync(async token => + { + var id = await repository.NextGroupIdAsync(token); + await repository.InsertSetAsync(id, request.StartDate, request.EndDate, VariablesRules.ToValues(request), user.UserId, token); + return id; + }, ct); + return new VariablesResult(VariablesMessages.Done, groupId); + } + + public async Task UpdateAsync(long groupId, SaveVariablesRequest request, CancellationToken ct) + { + await saveValidator.ValidateAndThrowAsync(request, ct); + var current = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId); + var error = VariablesRules.FirstError(await repository.GetPeriodsAsync(groupId, ct), request); + if (error is { } e) throw new BusinessException(e.Code, e.Message); + + // refinery_variablesfactory.cfc:162-170: the stored period must not hold a trip (checked on the dates before the change) + if (current.StartDate is not null && current.EndDate is not null + && await repository.HasTripsAsync(current.StartDate.Value, current.EndDate.Value, ct)) + throw new BusinessException(VariablesErrors.TripsExist, VariablesMessages.TripsExist); + + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.UpdateSetAsync(groupId, request.StartDate, request.EndDate, VariablesRules.ToValues(request), user.UserId, token); + return true; + }, ct); + return new VariablesResult(VariablesMessages.Done, groupId); + } + + /// UPDATE_TON_PRICE_CORRECTION: sets the actual ton price once; the balances of the trucks are recalculated when it differs from TON_PRICE. + public async Task SetTonPriceCorrectionAsync(long groupId, TonPriceCorrectionRequest request, CancellationToken ct) + { + await correctionValidator.ValidateAndThrowAsync(request, ct); + var current = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId); + if (current.TonPriceCorrectionSet) + throw new BusinessException(VariablesErrors.CannotResetTonPrice, VariablesMessages.CannotResetTonPrice); + if (current.StartDate is null || current.EndDate is null) + throw new BusinessException(VariablesErrors.NotFound, VariablesMessages.NotFound); + + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.SetTonPriceCorrectionAsync(groupId, VariablesRules.FormatValue(request.TonPriceCorrection), + current.StartDate.Value, current.EndDate.Value, user.UserId, token); + // legacy: a failed recalculation resets both rows to 0 (DELETE_ON_PRICE_CORRECTION) and returns the error; here the transaction is rolled back + if (VariablesRules.TonPriceChanges(current.TonPrice, request.TonPriceCorrection)) + await recalculation.RecalculateAsync(groupId, current.StartDate.Value, current.EndDate.Value, token); + return true; + }, ct); + return new VariablesResult(VariablesMessages.Done, groupId); + } + + // ------------------------------------------------------------------ reports (Excel) + + public async Task ExportAsync(VariablesQuery query, CancellationToken ct) + { + var rows = new List(); + for (var p = 1; rows.Count < 20000; p++) + { + var r = await repository.SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct); + rows.AddRange(r.Items); + if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break; + } + var cols = new List + { + new("startDate", "بداية فترة التسعير", "Start", "date"), new("endDate", "نهاية فترة التسعير", "End", "date"), + new("dieselLiterPrice", "سعر لتر الديزل", "Diesel liter price"), new("tonWage", "اجور الطن", "Ton wage"), + new("tonPrice", "سعر الطن", "Ton price"), new("driverTip", "اكرامية السائق", "Driver tip"), + new("permitDispatch", "سعر تسريب الصهريج", "Permit dispatch"), new("waybillFee", "اصدار وثيقة", "Waybill fee"), + new("commission", "عمولة الصرف التنافسي", "Commission"), new("tolerancePercentage", "نسبة السماح", "Tolerance"), + new("firstAdvancePayment", "قيمة شحن الديزل للتحميل", "First advance payment"), + }; + var data = rows.Select(r => (IReadOnlyDictionary)new Dictionary + { + ["startDate"] = r.StartDate, ["endDate"] = r.EndDate, ["dieselLiterPrice"] = r.DieselLiterPrice, ["tonWage"] = r.TonWage, + ["tonPrice"] = r.TonPrice, ["driverTip"] = r.DriverTip, ["permitDispatch"] = r.PermitDispatch, ["waybillFee"] = r.WaybillFee, + ["commission"] = r.Commission, ["tolerancePercentage"] = r.TolerancePercentage, ["firstAdvancePayment"] = r.FirstAdvancePayment, + }).ToList(); + return Build("REFINERY_VARIABLES", "تسعير عطاء النفط الخام", "Crude oil tender pricing", cols, data); + } + + /// refineryRemainingBalanceReport: REFINERY_REMAINING_BALANCE ordered by balance, biggest first. + public async Task ExportRemainingBalanceAsync(CancellationToken ct) + { + var rows = await repository.GetRemainingBalancesAsync(ct); + var cols = new List + { + new("counter", "متسلسل", "#"), new("tn", "رقم الشاحنة", "Truck"), new("remainingBalance", "قيمة الذمم السابقة", "Previous balance"), + }; + var n = 0; + var data = rows.Select(r => (IReadOnlyDictionary)new Dictionary + { + ["counter"] = ++n, ["tn"] = r.Tn, ["remainingBalance"] = r.RemainingBalance, + }).ToList(); + return Build("REMAINING_BALANCE", "قيمة الذمم السابقة", "Previous balance", cols, data); + } + + private ExportFile Build(string key, string titleAr, string titleEn, IReadOnlyList cols, IReadOnlyList> rows) + { + var table = new ReportTable { Key = key, TitleAr = titleAr, TitleEn = titleEn, Columns = cols, Rows = rows }; + var bytes = excel.Build(table, user.UserId, DateTime.Now, true); + return new ExportFile(bytes, ExcelType, key + ".xlsx"); + } +} diff --git a/src/NTP.Application/Refinery/Variables/VariablesValidators.cs b/src/NTP.Application/Refinery/Variables/VariablesValidators.cs new file mode 100644 index 0000000..b1e3aab --- /dev/null +++ b/src/NTP.Application/Refinery/Variables/VariablesValidators.cs @@ -0,0 +1,34 @@ +using FluentValidation; + +namespace NTP.Application.Refinery.Variables; + +/// The form of the screen: every field is required (legacy HTML required), numbers are not negative (class floatnumber, maxlength 7). +public sealed class SaveVariablesValidator : AbstractValidator +{ + public const string Required = "الرجاء ادخال جميع الحقول"; // REPORT.VALIDATION + + public SaveVariablesValidator() + { + RuleFor(x => x.StartDate).NotEqual(default(DateOnly)).WithMessage(Required); + RuleFor(x => x.EndDate).NotEqual(default(DateOnly)).WithMessage(Required); + // the value range checks of diesel price and ton wage are in VariablesRules (legacy messages, legacy order) + RuleFor(x => x.DieselLiterPrice).GreaterThanOrEqualTo(0).WithMessage(Required); + RuleFor(x => x.TonWage).GreaterThanOrEqualTo(0).WithMessage(Required); + RuleFor(x => x.FirstAdvancePayment).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required); + RuleFor(x => x.TonPrice).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required); + RuleFor(x => x.DriverTip).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required); + RuleFor(x => x.PermitDispatch).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required); + RuleFor(x => x.WaybillFee).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required); + RuleFor(x => x.Commission).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required); + RuleFor(x => x.TolerancePercentage).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required); + } +} + +public sealed class TonPriceCorrectionValidator : AbstractValidator +{ + public TonPriceCorrectionValidator() + { + // 0 is what DELETE_ON_PRICE_CORRECTION writes to mean "no correction", so it is not a value to set + RuleFor(x => x.TonPriceCorrection).GreaterThan(0).LessThan(10_000_000m).WithMessage(SaveVariablesValidator.Required); + } +} diff --git a/src/NTP.Application/Refinery/WageClaims/ClaimExcel.cs b/src/NTP.Application/Refinery/WageClaims/ClaimExcel.cs new file mode 100644 index 0000000..0cec167 --- /dev/null +++ b/src/NTP.Application/Refinery/WageClaims/ClaimExcel.cs @@ -0,0 +1,45 @@ +using System.Globalization; +using System.Net; +using System.Text; +using NTP.Application.Grains.Orders; + +namespace NTP.Application.Refinery.WageClaims; + +/// Excel (HTML table opened by Excel, like the other V1 exports) of a claim report: company and report title, filter lines, header, rows, footer. +internal static class ClaimExcel +{ + public static string E(object? v) => WebUtility.HtmlEncode(Convert.ToString(v, CultureInfo.InvariantCulture) ?? string.Empty); + + public static string N(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture); + + public static string D(DateTime? d) => d is null ? string.Empty : d.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); + + public static ExportFile Build(string title, IEnumerable infoLines, string[] headers, IEnumerable rows, string user, string fileName) + { + var n = headers.Length; + var h = new StringBuilder(); + h.Append(""); + h.Append(""); + h.Append(""); + h.Append($""); + h.Append($""); + foreach (var line in infoLines) h.Append($""); + h.Append(""); + foreach (var c in headers) h.Append($""); + h.Append(""); + var count = 0; + foreach (var r in rows) + { + count++; + h.Append(""); + foreach (var v in r) h.Append($""); + h.Append(""); + } + if (count == 0) h.Append($""); + h.Append($""); + h.Append("
شركة نافذ للخدمات اللوجستية
{E(title)}
{E(line)}
{E(c)}
{E(v)}
لا يوجد معلومات
بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm} - عدد النتائج : {count} - طبع التقرير بواسطة : {E(user)}
"); + var bytes = new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(h.ToString())).ToArray(); + return new ExportFile(bytes, "application/vnd.ms-excel", fileName + ".xls"); + } +} diff --git a/src/NTP.Application/Refinery/WageClaims/IWageClaimRepository.cs b/src/NTP.Application/Refinery/WageClaims/IWageClaimRepository.cs new file mode 100644 index 0000000..f9e6a71 --- /dev/null +++ b/src/NTP.Application/Refinery/WageClaims/IWageClaimRepository.cs @@ -0,0 +1,44 @@ +using NTP.Application.Common; + +namespace NTP.Application.Refinery.WageClaims; + +/// A trip of a claim waiting for the Jopetrol transfer (REFINERY_TRIPS.TRIP_STATUS = 6). +public sealed class TransferTripRow +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? StatusCode { get; set; } +} + +/// +/// SQL of refinery_wage_claimdao.cfc (+ the writes of refinery_wage_claimfactory.cfc). REFINERY_TRIPS is only read, except for the columns the +/// legacy claim code writes: WAGE_CLAIM_ID, STATUS_CODE (COMPLETE), TRIP_STATUS (7), LAST_UPDATE_DATE, UPDATED_BY. +/// +public interface IWageClaimRepository +{ + Task> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct = default); + Task GetAsync(long id, CancellationToken ct = default); + Task> ClaimTripsAsync(long claimId, PageRequest page, CancellationToken ct = default); + + /// Trips of the given statuses without a wage claim (optionally limited to a loading date range): the create preview. + Task> CandidateTripsAsync(IReadOnlyList statuses, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct = default); + Task CountCandidateTripsAsync(IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default); + + /// Takes the next claim number (legacy GenerateSerialNumber) and inserts the claim as NEW; returns its id. Run inside a transaction. + Task InsertClaimAsync(string createdBy, CancellationToken ct = default); + Task AttachTripsAsync(long claimId, IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default); + + Task> ClaimTripStatusesAsync(long claimId, CancellationToken ct = default); + /// TRIP_COMPLETE for every trip of the claim: status COMPLETE plus one REFINERY_TRIPS_LOG row each. Returns the number of trips. + Task CompleteClaimTripsAsync(long claimId, string userLogin, long userId, string? ip, CancellationToken ct = default); + Task SetClaimStatusAsync(long claimId, string status, string userLogin, CancellationToken ct = default); + + Task> TripsToTransferAsync(long claimId, CancellationToken ct = default); + /// TRIP_STATUS 7 + REFINERY_TRIPS_LOG row TRANSFER_TO_REFINERY. Run inside a transaction. + Task MarkTripTransferredAsync(TransferTripRow trip, long userId, string? ip, CancellationToken ct = default); + + Task AddLogAsync(long claimId, string method, string? oldData, string? newData, long userId, string? ip, CancellationToken ct = default); + Task> LogAsync(long claimId, PageRequest page, CancellationToken ct = default); + + Task> ReportRowsAsync(long claimId, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Refinery/WageClaims/WageClaimContracts.cs b/src/NTP.Application/Refinery/WageClaims/WageClaimContracts.cs new file mode 100644 index 0000000..459ef96 --- /dev/null +++ b/src/NTP.Application/Refinery/WageClaims/WageClaimContracts.cs @@ -0,0 +1,90 @@ +namespace NTP.Application.Refinery.WageClaims; + +// ------------------------------------------------------------------ wage claim list / view (REFINERY_WAGE_CLAIM_VIEW) + +public sealed class WageClaimRowDto +{ + public long Id { get; set; } + public long? WageClaimNo { get; set; } + public DateTime? WageClaimDate { get; set; } + public long TripCnt { get; set; } + public long? CommissionClaimId { get; set; } + public long? CommissionClaimNo { get; set; } + /// NEW / CLOSE / COMPLETE. + public string StatusCode { get; set; } = ""; +} + +/// Filters of the legacy grid (WAGE_CLAIM_NO, WAGE_CLAIM_DATE, STATUS_CODE, COMMISSION_CLAIM_NO, HAS_COMMISSION_CLAIM). +public sealed record WageClaimQuery( + string? WageClaimNo, DateOnly? WageClaimDate, IReadOnlyList StatusCodes, string? CommissionClaimNo, bool? HasCommissionClaim); + +/// A trip as shown inside a claim (legacy searchClaimTrips columns) and in the create preview. +public sealed class ClaimTripRowDto +{ + public long Id { get; set; } + public string? Pn { get; set; } + public DateTime? PaymentedDate { get; set; } + public long? LoadingNo { get; set; } + public string? DischargeAuthoriztionNo { get; set; } + public DateTime? DischargeEntryDate { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Nnpn { get; set; } + public string StatusCode { get; set; } = ""; +} + +/// One row of the log popup (REFINERY_WAGE_CLAIM_LOG_VIEW / REFINERY_COMMISSION_LOG_VIEW). +public sealed class ClaimLogRowDto +{ + public long Id { get; set; } + public string MethodName { get; set; } = ""; + public DateTime? LogDate { get; set; } + public string? Login { get; set; } + public string? OldData { get; set; } + public string? NewData { get; set; } +} + +/// Body of POST wage-claims (legacy create: STATUS_CODE list + LOADING_DATE_FROM / TO). +public sealed record CreateWageClaimRequest(IReadOnlyList? StatusCodes, DateOnly? LoadingDateFrom, DateOnly? LoadingDateTo); + +/// Answer of the write endpoints: the (Arabic) message to toast and the id of the created record. +public sealed record ClaimResult(string Message, long? Id = null); + +// ------------------------------------------------------------------ export + +/// Raw values of one trip of the claim report (legacy REFINERY_CLAIMS_REPORT_VIEW). +public sealed class WageClaimReportRaw +{ + public long Id { get; set; } + public string? Drvr { get; set; } + public string? Tn { get; set; } + public string? DischargeAuthoriztionNo { get; set; } + public long? DischargeAuthoriztionYear { get; set; } + public DateTime? DischargeEntryDate { get; set; } + public string? ClientNo { get; set; } + public long? LoadingNo { get; set; } + public DateTime? ActualLoadingDate { get; set; } + public decimal? NetLoadingWeight { get; set; } + public decimal? WaterAmount { get; set; } + public decimal? NetDischargeWeight { get; set; } + public decimal? CalculatedQuantityTon { get; set; } + public decimal? ToleranceQuantity { get; set; } + public decimal? PenaltyQuantity { get; set; } + public decimal? TonPrice { get; set; } + public decimal? PenaltyAmount { get; set; } + public decimal? DriverTip { get; set; } + public decimal? PermitDispatch { get; set; } + public decimal? WaybillFee { get; set; } + public decimal? DieselLiterPrice { get; set; } + /// sum(REFINERY_CARDS_LOG.AMOUNT) of the trip. + public decimal? AdvancePaymentForDiesel { get; set; } + public decimal? Commission { get; set; } + public decimal? NetWage { get; set; } +} + +/// Values of one report line after the legacy sign changes (deductions are shown negative). +public sealed record WageClaimReportLine( + string? Drvr, string? Tn, string? DischargeAuthoriztionNo, long? DischargeAuthoriztionYear, DateTime? DischargeEntryDate, string? ClientNo, + long? LoadingNo, DateTime? ActualLoadingDate, decimal NetLoadingWeight, decimal WaterAmount, decimal NetDischargeWeight, decimal WeightDifference, + decimal CalculatedQuantityTon, decimal ToleranceQuantity, bool WaterExist, decimal PenaltyQuantity, decimal TonPrice, decimal PenaltyAmount, + decimal DriverTip, decimal PermitDispatch, decimal WaybillFee, decimal DieselLiterPrice, decimal AdvancePaymentForDiesel, decimal Commission, decimal NetWage); diff --git a/src/NTP.Application/Refinery/WageClaims/WageClaimRules.cs b/src/NTP.Application/Refinery/WageClaims/WageClaimRules.cs new file mode 100644 index 0000000..091bd7b --- /dev/null +++ b/src/NTP.Application/Refinery/WageClaims/WageClaimRules.cs @@ -0,0 +1,100 @@ +using NTP.Application.Common; + +namespace NTP.Application.Refinery.WageClaims; + +/// User-facing texts of the claim screens: the legacy captions (NTP.LT_CAPTION), verbatim. +public static class ClaimMessages +{ + public const string Success = "تمت العملية بنجاح"; // PUBLIC.SUCCESSFUL.OPERATION + public const string StatusRequired = "يجب اختيار الحالة"; // ERROR.STATUS_REQUIRED + public const string DateRequired = "يجب اختيار التاريخ"; // ERROR.DATE_REQUIRED + public const string FromGreaterThanTo = "لا يجوز ان يكون تاريخ من أكبر من تارخ الى"; // ERROR.FROM_CAN_NOT_GREATER_THAN_TO + public const string NoTripsNeedWage = "لا يوجد ارساليات جاهزة لانشاء مطالبة مالية"; // ERROR.THERS_IS_NOT_TRIPS_NEED_WAGE + public const string CloseClaim = "لا يمكن تسديد هذه المطالبة يوجد ارساليات ضمن المطالبة حالتها جاهز للدفع او تم التفريغ"; // ERROR.CLOSE_CLAIM + public const string NoAuthority = "ليس لديك صلاحية لاتمام هذه العملية"; // ERROR.NO_AUTHORITY + public const string NoWages = "لا يوجد مطالبات اجور"; // ERROR.THERE_ARE_NO_WAGES + public const string PleaseSelectClaim = "يرجى اختيار المطالبة"; // ERROR.PLEASE_SELECT_CLAIM + public const string WageClaimNotClose = "لا يمكن تسديد هذه المطالبة يوجد مطالبات اجور غير مسددة"; // ERROR.WAGE_CLAIM_IS_NOT_CLOSE + public const string NoTripsIssue = "لا يوجد ارساليات"; // ERROR.NO_TRIPS_THERE_IS_ISSUE + public const string CommissionVariableIssue = "يوجد خطأ في تعريف قيمة عمولة الاجور"; // ERROR.REFINERY_VARIABLES_COMMISSION_ISSUE + /// New text (the legacy code had no such case): the Jopetrol integration is switched off by configuration. + public const string JopetrolDisabled = "خدمة الترحيل إلى المصفاة غير مفعلة في هذه البيئة، لم يتم تغيير أي شيء"; + public const string NotFound = "المطالبة غير موجودة"; + + // log captions (method names of the *_LOG tables) + public const string StatusNew = "جديد"; // REFINERY_WAGE_CLAIM.STATUSCODE.NEW + public const string StatusClose = "تم التسديد"; // ...STATUSCODE.CLOSE + public const string StatusComplete = "مكتمل"; // ...STATUSCODE.COMPLETE + public const string TripExchanged = "تم الصرف"; // REFINERYTRIP.STATUSCODE.EXCHANGED + public const string TripComplete = "مكتمل"; // REFINERYTRIP.STATUSCODE.COMPLETE +} + +/// Pure rules of the wage claim screen (refinery_wage_claimfactory.cfc). +public static class WageClaimRules +{ + public const string New = "NEW"; + public const string Close = "CLOSE"; + public const string Complete = "COMPLETE"; + + /// Trip statuses the create dialog offers (REFINERY_WAGE_CLAIMMain.html); trips of other statuses are never attached. + public static readonly IReadOnlyList ClaimableTripStatuses = ["EXCHANGED", "READY_TO_PAY", "DISCHARGED"]; + + /// Distinct upper-case statuses, only the claimable ones (the legacy select-all option "ALL" and unknown values are dropped). + public static IReadOnlyList NormalizeTripStatuses(IEnumerable? raw) => + (raw ?? []) + .SelectMany(s => (s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + .Select(s => s.ToUpperInvariant()) + .Where(s => ClaimableTripStatuses.Contains(s)) + .Distinct() + .ToList(); + + /// factory.create: status required, both dates required, from not after to (messages in this order). + public static void ValidateCreate(IReadOnlyList statuses, DateOnly? from, DateOnly? to) + { + if (statuses.Count == 0) throw new BusinessException("STATUS_REQUIRED", ClaimMessages.StatusRequired); + if (from is null || to is null) throw new BusinessException("DATE_REQUIRED", ClaimMessages.DateRequired); + if (from.Value > to.Value) throw new BusinessException("FROM_GREATER_THAN_TO", ClaimMessages.FromGreaterThanTo); + } + + /// factory.CLAIM_CLOSE: a claim is paid only when it has trips and every one of them is EXCHANGED. + public static bool CanCloseClaim(IEnumerable tripStatuses) + { + var distinct = tripStatuses.Distinct().ToList(); + return distinct.Count == 1 && distinct[0] == "EXCHANGED"; + } + + /// factory.TRANSFER: the Jopetrol answer must contain this text (findNoCase) for the trip to move to TRIP_STATUS 7. + public static bool IsStatus7Success(string? serviceAnswer) => + serviceAnswer is not null && serviceAnswer.Contains("Status Updated successfully To 7", StringComparison.OrdinalIgnoreCase); + + /// Last day (inclusive) of a [from, to] day range as an exclusive upper bound (legacy: between FROM000000 and TO235959). + public static DateTime ExclusiveEnd(DateOnly to) => to.AddDays(1).ToDateTime(TimeOnly.MinValue); + + /// + /// Report line of one trip, as legacy factoryweb.report prepares it: the deductions (driver tip, permit dispatch, waybill fee, diesel liter price, + /// diesel advance when > 0, commission) are multiplied by -1; the penalty quantity is 0 when the weight difference is below the tolerance + /// (REFINERY_CLAIMS_REPORT_VIEW). + /// + public static WageClaimReportLine ToReportLine(WageClaimReportRaw r) + { + decimal V(decimal? d) => d ?? 0m; + var diff = V(r.NetLoadingWeight) - V(r.NetDischargeWeight); + var penaltyQty = diff < V(r.ToleranceQuantity) ? 0m : V(r.PenaltyQuantity); + var advance = V(r.AdvancePaymentForDiesel); + return new WageClaimReportLine( + r.Drvr, r.Tn, r.DischargeAuthoriztionNo, r.DischargeAuthoriztionYear, r.DischargeEntryDate, r.ClientNo, + r.LoadingNo, r.ActualLoadingDate, V(r.NetLoadingWeight), V(r.WaterAmount), V(r.NetDischargeWeight), diff, + V(r.CalculatedQuantityTon), V(r.ToleranceQuantity), V(r.WaterAmount) > 0, penaltyQty, V(r.TonPrice), V(r.PenaltyAmount), + -V(r.DriverTip), -V(r.PermitDispatch), -V(r.WaybillFee), -V(r.DieselLiterPrice), + advance > 0 ? -advance : advance, -V(r.Commission), V(r.NetWage)); + } + + /// Caption of a claim status (REFINERY_WAGE_CLAIM.STATUS.* / REFINERY_COMMISSION_CLAIM.STATUS.*). + public static string ClaimStatusCaption(string? code) => code switch + { + New => ClaimMessages.StatusNew, + Close => ClaimMessages.StatusClose, + Complete => ClaimMessages.StatusComplete, + _ => code ?? "", + }; +} diff --git a/src/NTP.Application/Refinery/WageClaims/WageClaimService.cs b/src/NTP.Application/Refinery/WageClaims/WageClaimService.cs new file mode 100644 index 0000000..f8013a9 --- /dev/null +++ b/src/NTP.Application/Refinery/WageClaims/WageClaimService.cs @@ -0,0 +1,160 @@ +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 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); + } + + /// + /// 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}"); + } +} diff --git a/src/NTP.Application/Refinery/Wallets/IWallets.cs b/src/NTP.Application/Refinery/Wallets/IWallets.cs new file mode 100644 index 0000000..cc6ccf6 --- /dev/null +++ b/src/NTP.Application/Refinery/Wallets/IWallets.cs @@ -0,0 +1,77 @@ +using FluentValidation; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; + +namespace NTP.Application.Refinery.Wallets; + +public interface IWalletsRepository +{ + /// Oldest first (legacy sort ID ASC). + Task> SearchAsync(WalletsQuery query, PageRequest page, CancellationToken ct = default); + Task GetAsync(long id, CancellationToken ct = default); + /// Ids of the ACTIVE records of a truck. + Task> GetActiveIdsByTruckAsync(long tn, CancellationToken ct = default); + /// Ids of the ACTIVE records of a driver (national number). + Task> GetActiveIdsByDriverAsync(long nnpn, CancellationToken ct = default); + Task InsertAsync(WalletWrite record, string createdBy, CancellationToken ct = default); + Task SetStatusAsync(long id, string status, string userId, CancellationToken ct = default); + Task InsertLogAsync(long entityId, string method, string userId, string? userIp, string oldData, string newData, CancellationToken ct = default); + Task> GetLogAsync(long entityId, PageRequest page, CancellationToken ct = default); +} + +public interface IWalletsService +{ + Task> SearchAsync(WalletsQuery query, PageRequest page, CancellationToken ct); + Task GetAsync(long id, CancellationToken ct); + Task> GetLogAsync(long id, PageRequest page, CancellationToken ct); + Task CreateAsync(SaveWalletRequest request, string? userIp, CancellationToken ct); + Task UpdateAsync(long id, SaveWalletRequest request, string? userIp, CancellationToken ct); + Task ActivateAsync(long id, string? userIp, CancellationToken ct); + Task DeactivateAsync(long id, string? userIp, CancellationToken ct); + Task ExportAsync(WalletsQuery query, CancellationToken ct); +} + +/// +/// The form of REFINERY_WALLET.js: required fields per payment method, mobile / bank account / digits formats. Stricter than legacy in two places +/// only: the truck number (WALLET, BANK) and the wallet number (WALLET, DRIVER_TIP) are required, because the duplicate rule and the payment +/// need them (every stored record has them). +/// +public sealed class SaveWalletValidator : AbstractValidator +{ + public SaveWalletValidator() + { + RuleFor(x => x.PaymentMethod).Must(m => m is WalletValues.MethodWallet or WalletValues.MethodBank or WalletValues.MethodDriverTip) + .WithMessage(WalletsMessages.Required); + + When(x => x.PaymentMethod is WalletValues.MethodWallet or WalletValues.MethodBank, () => + { + RuleFor(x => x.Tn).Must(v => WalletsRules.IsDigits(v?.Trim(), 10)).WithMessage(WalletsMessages.Required); + RuleFor(x => x.OwnerName).NotEmpty().MaximumLength(450).WithMessage(WalletsMessages.Required); + RuleFor(x => x.OwnerNnpn).Must(v => string.IsNullOrWhiteSpace(v) || WalletsRules.IsDigits(v.Trim(), 15)).WithMessage(WalletsMessages.NumbersOnly); + }); + + When(x => x.PaymentMethod == WalletValues.MethodWallet, () => + { + RuleFor(x => x.WalletNumber).NotEmpty().WithMessage(WalletsMessages.Required) + .Must(v => WalletsRules.IsMobile(v?.Trim())).WithMessage(WalletsMessages.WrongMobile); + }); + + When(x => x.PaymentMethod == WalletValues.MethodBank, () => + { + RuleFor(x => x.Iban).NotEmpty().MaximumLength(50).WithMessage(WalletsMessages.Required); + RuleFor(x => x.BankAccount).NotEmpty().MaximumLength(50).WithMessage(WalletsMessages.Required) + .Must(v => WalletsRules.IsBankAccount(v?.Trim())).WithMessage(WalletsMessages.WrongBankAccount); + RuleFor(x => x.BankName).MaximumLength(300); + RuleFor(x => x.BankBranch).MaximumLength(50); + RuleFor(x => x.OwnerNameEnglish).MaximumLength(150); + }); + + When(x => x.PaymentMethod == WalletValues.MethodDriverTip, () => + { + RuleFor(x => x.DriverName).NotEmpty().MaximumLength(450).WithMessage(WalletsMessages.Required); + RuleFor(x => x.DriverNnpn).Must(v => WalletsRules.IsDigits(v?.Trim(), 15)).WithMessage(WalletsMessages.Required); + RuleFor(x => x.WalletNumber).NotEmpty().WithMessage(WalletsMessages.Required) + .Must(v => WalletsRules.IsMobile(v?.Trim())).WithMessage(WalletsMessages.WrongMobile); + }); + } +} diff --git a/src/NTP.Application/Refinery/Wallets/WalletsContracts.cs b/src/NTP.Application/Refinery/Wallets/WalletsContracts.cs new file mode 100644 index 0000000..9112d78 --- /dev/null +++ b/src/NTP.Application/Refinery/Wallets/WalletsContracts.cs @@ -0,0 +1,118 @@ +namespace NTP.Application.Refinery.Wallets; + +/// +/// Row of REFINERY_WALLET: how a truck owner (or a driver, for the tip) gets paid: e-wallet, bank transfer or driver wallet. Same columns as the legacy +/// REFINERY_WALLET_VIEW (OwnerNnpn / OwnerName fall back to the driver's when the owner's are empty). Class with settable properties. +/// +public class WalletRow +{ + public long Id { get; set; } + public long? Tn { get; set; } + public long? CompanyCode { get; set; } + /// 0 = bank transfer, 1 = e-wallet (also the driver wallet). Legacy EPAYMENT. + public int Epayment { get; set; } + /// Stored OWNER_NNPN (empty for a driver wallet). + public long? OwnerNnpn { get; set; } + public string? WalletNumber { get; set; } + /// Stored OWNER_NAME (empty for a driver wallet). + public string? OwnerName { get; set; } + /// What the legacy grid shows as national no.: the owner's, else the driver's (view column OWNER_NNPN / NNPN). + public long? HolderNnpn { get; set; } + /// What the legacy grid shows as owner name: the owner's, else the driver's (view column OWNER_NAME). + public string? HolderName { get; set; } + public string? OwnerNameEnglish { get; set; } + public string? DriverName { get; set; } + public long? DriverNnpn { get; set; } + public string? Iban { get; set; } + public string? BankAccount { get; set; } + public string? BankName { get; set; } + public string? BankBranch { get; set; } + public DateTime? CreationDate { get; set; } + public string? CreatedBy { get; set; } + public DateTime? UpdateDate { get; set; } + public string? UpdatedBy { get; set; } + public string? StatusCode { get; set; } + /// BANK, EWALLET or DRAIVER_WALLET (legacy view spelling): the kind of the record, see . + public string? PaymentMethod { get; set; } +} + +/// One record plus what may be done with it. +public sealed class WalletDetail : WalletRow +{ + /// ACTIVE record: edit (deactivates it and creates a new one). + public bool CanUpdate { get; set; } + public bool CanDeactivate { get; set; } + /// INACTIVE record and the truck / driver has no other ACTIVE record (legacy getREFINERY_WALLET sets ACTIONS = ACTIVATE). + public bool CanActivate { get; set; } +} + +public class WalletLogRow +{ + public long Id { get; set; } + public long EntityId { get; set; } + public string? MethodName { get; set; } + public string? Login { get; set; } + public DateTime? LogDate { get; set; } + public string? UserId { get; set; } + public string? UserIp { get; set; } + /// JSON text (property name -> value); legacy rows may hold one-element arrays as values. + public string? OldData { get; set; } + public string? NewData { get; set; } +} + +/// Grid filters: tn, walletNumber, bankAccount, nnpn, paymentMethod, statusCode exact; ownerName contains. +public sealed record WalletsQuery(string? Tn, string? WalletNumber, string? OwnerName, string? BankAccount, string? PaymentMethod, string? StatusCode, string? Nnpn); + +/// +/// Create / update body. WALLET (e-wallet of a truck), BANK (bank transfer of a truck) or DRIVER_TIP (driver wallet). +/// Fields not used by the chosen method are ignored. Numbers travel as text (digits only). +/// +public sealed class SaveWalletRequest +{ + public string? PaymentMethod { get; set; } + /// WALLET / BANK: truck number. + public string? Tn { get; set; } + /// WALLET / BANK: national number of the owner (optional). + public string? OwnerNnpn { get; set; } + /// WALLET / DRIVER_TIP: mobile number of the wallet (07xxxxxxxx or 7xxxxxxxx, 77/78/79). + public string? WalletNumber { get; set; } + /// WALLET / BANK: account owner. + public string? OwnerName { get; set; } + public string? OwnerNameEnglish { get; set; } + public string? BankName { get; set; } + public string? BankBranch { get; set; } + public string? Iban { get; set; } + public string? BankAccount { get; set; } + /// DRIVER_TIP. + public string? DriverName { get; set; } + public string? DriverNnpn { get; set; } +} + +/// Normalised record to insert (what the legacy factory builds into the bean per payment method). +public sealed record WalletWrite( + int Epayment, long? Tn, long? OwnerNnpn, string? WalletNumber, string? OwnerName, string? OwnerNameEnglish, + long? DriverNnpn, string? DriverName, string? Iban, string? BankAccount, string? BankName, string? BankBranch); + +public sealed record WalletsResult(string Message, long? Id = null); + +public static class WalletValues +{ + public const string Active = "ACTIVE"; + public const string Inactive = "INACTIVE"; + + // request codes (the select of the legacy form) + public const string MethodWallet = "WALLET"; + public const string MethodBank = "BANK"; + public const string MethodDriverTip = "DRIVER_TIP"; + + // kinds of a stored record (legacy REFINERY_WALLET_VIEW.PAYMENT_METHOD, spelling kept) + public const string KindBank = "BANK"; + public const string KindEWallet = "EWALLET"; + public const string KindDriverWallet = "DRAIVER_WALLET"; + + // log METHOD_NAME values + public const string LogCreate = "CREATE"; + public const string LogUpdate = "UPDATE"; + public const string LogActivate = "ACTIVATE"; + public const string LogDeactivate = "DEACTIVATE"; +} diff --git a/src/NTP.Application/Refinery/Wallets/WalletsRules.cs b/src/NTP.Application/Refinery/Wallets/WalletsRules.cs new file mode 100644 index 0000000..6217ccb --- /dev/null +++ b/src/NTP.Application/Refinery/Wallets/WalletsRules.cs @@ -0,0 +1,129 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace NTP.Application.Refinery.Wallets; + +/// User-facing texts (legacy captions verbatim; * = no row in LT_CAPTION, new wording). +public static class WalletsMessages +{ + public const string Required = "الرجاء ادخال جميع الحقول"; // REPORT.VALIDATION + public const string WrongMobile = "رقم المحفظة غير صحيح"; // PUBLIC.WRONG_MOBILE_NUMBER + public const string WrongBankAccount = "رقم الحساب غير صحيح مسموح بالارقام والاحرف وال / فقط"; // VAILD.LETTERS_NYMBERS_SLASH_ONLY + public const string NumbersOnly = "الحقل لا يقبل أحرف"; // PUBLIC.NUMBERSONLY + public const string TruckHasActive = "رقم الشاحنة المدخل له آلية صرف فعالة"; // TRUCK_ALREADY_HAS_ACTIVE_RECORD + public const string DriverHasActive = "الرقم الوطني المدخل له آلية صرف فعالة"; // DRIVER_ALREADY_HAS_ACTIVE_RECORD + public const string NotFound = "آلية الصرف غير موجودة"; // * + public const string StatusNotAllowed = "لا يمكن تنفيذ هذا الإجراء على السجل في حالته الحالية"; // * (legacy: STATUS_ACTION_MATRIX refusal) + public const string Done = ""; +} + +public static class WalletsErrors +{ + public const string TruckHasActive = "TRUCK_ALREADY_HAS_ACTIVE_RECORD"; + public const string DriverHasActive = "DRIVER_ALREADY_HAS_ACTIVE_RECORD"; + public const string NotFound = "REFINERY_WALLET_NOT_FOUND"; + public const string StatusNotAllowed = "REFINERY_WALLET_STATUS_NOT_ALLOWED"; +} + +/// Pure rules of refinery_walletfactory.cfc and the checks of REFINERY_WALLET.js. +public static partial class WalletsRules +{ + // REFINERY_WALLET.js createRefineryWallet: ^(07){1}[7-9]{1}[0-9]{7}$ or ^(7){1}[7-9]{1}[0-9]{7}$ + [GeneratedRegex(@"^0?7[7-9][0-9]{7}$")] + private static partial Regex MobileRegex(); + // ^[//a-zA-Z 0-9]*$ + [GeneratedRegex(@"^[/a-zA-Z 0-9]*$")] + private static partial Regex BankAccountRegex(); + [GeneratedRegex(@"^\d+$")] + private static partial Regex DigitsRegex(); + + public static bool IsMobile(string? v) => v is not null && MobileRegex().IsMatch(v); + public static bool IsBankAccount(string? v) => v is not null && BankAccountRegex().IsMatch(v); + public static bool IsDigits(string? v, int max) => v is not null && v.Length <= max && DigitsRegex().IsMatch(v); + + private static string? Clean(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + private static long? ToLong(string? v) => Clean(v) is { } s && long.TryParse(s, out var n) ? n : null; + + /// + /// What the legacy factory copies into the bean for each payment method (refinery_walletfactory.cfc:67-95): BANK = EPAYMENT 0 with the + /// bank data; WALLET = EPAYMENT 1 with the wallet number; DRIVER_TIP = EPAYMENT 1, driver data only, no truck. Fields that belong to another + /// method are dropped (the DB defaults then give '-' for IBAN, BANK_ACCOUNT and BANK_NAME). + /// + public static WalletWrite ToWrite(SaveWalletRequest r) => r.PaymentMethod switch + { + WalletValues.MethodBank => new WalletWrite(0, ToLong(r.Tn), ToLong(r.OwnerNnpn), null, Clean(r.OwnerName), Clean(r.OwnerNameEnglish), + null, null, Clean(r.Iban), Clean(r.BankAccount), Clean(r.BankName), Clean(r.BankBranch)), + WalletValues.MethodWallet => new WalletWrite(1, ToLong(r.Tn), ToLong(r.OwnerNnpn), Clean(r.WalletNumber), Clean(r.OwnerName), null, + null, null, null, null, null, null), + _ => new WalletWrite(1, null, null, Clean(r.WalletNumber), null, null, ToLong(r.DriverNnpn), Clean(r.DriverName), null, null, null, null), + }; + + /// The payment method code of the form for a stored record (a bank record has EPAYMENT 0, a driver record has no truck). + public static string MethodOf(WalletRow w) => + w.Epayment == 0 ? WalletValues.MethodBank : w.Tn is null && w.DriverNnpn is not null ? WalletValues.MethodDriverTip : WalletValues.MethodWallet; + + // ------------------------------------------------------------------ log JSON (aqabaTCSBCommon.logs.saveLog) + + private static readonly JsonSerializerOptions Json = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + + public static string ToJson(IReadOnlyDictionary values) => JsonSerializer.Serialize(values, Json); + + public static string EmptyJson => "{}"; + + /// CREATE log of a new record (legacy: only {"STATUS_CODE":"ACTIVE"} when created from the form). + public static string CreateNewData() => ToJson(new Dictionary { ["STATUS_CODE"] = "ACTIVE" }); + + /// + /// CREATE log of the record that replaces an updated one: the whole bean (system columns empty, as legacy), keys upper-case. + /// + public static string ReplacementNewData(WalletWrite w, string createdBy) => ToJson(new Dictionary + { + ["TN"] = w.Tn?.ToString() ?? "", ["COMPANY_CODE"] = "", ["EPAYMENT"] = w.Epayment.ToString(), + ["OWNER_NNPN"] = w.OwnerNnpn?.ToString() ?? "", ["WALLET_NUMBER"] = w.WalletNumber ?? "", ["OWNER_NAME"] = w.OwnerName ?? "", + ["CREATION_DATE"] = "", ["DRIVER_NAME"] = w.DriverName ?? "", ["DRIVER_NNPN"] = w.DriverNnpn?.ToString() ?? "", + ["IBAN"] = w.Iban ?? "-", ["BANK_ACCOUNT"] = w.BankAccount ?? "-", ["BANK_NAME"] = w.BankName ?? "-", ["CREATED_BY"] = createdBy, + ["UPDATE_DATE"] = "", ["UPDATED_BY"] = "", ["STATUS_CODE"] = "", ["BANK_BRANCH"] = w.BankBranch ?? "", + ["OWNER_NAME_ENGLISH"] = w.OwnerNameEnglish ?? "", + }); + + /// The data columns the UPDATE log compares (legacy: the bean columns that also exist in the old record, minus system columns). + public static IReadOnlyDictionary DataColumns(WalletRow w) => new Dictionary + { + ["TN"] = w.Tn?.ToString() ?? "", ["EPAYMENT"] = w.Epayment.ToString(), + ["OWNER_NNPN"] = w.OwnerNnpn?.ToString() ?? "", ["WALLET_NUMBER"] = w.WalletNumber ?? "", ["OWNER_NAME"] = w.OwnerName ?? "", + ["DRIVER_NAME"] = w.DriverName ?? "", ["DRIVER_NNPN"] = w.DriverNnpn?.ToString() ?? "", + ["IBAN"] = w.Iban ?? "", ["BANK_ACCOUNT"] = w.BankAccount ?? "", ["BANK_NAME"] = w.BankName ?? "", + ["BANK_BRANCH"] = w.BankBranch ?? "", ["OWNER_NAME_ENGLISH"] = w.OwnerNameEnglish ?? "", + }; + + public static IReadOnlyDictionary DataColumns(WalletWrite w) => new Dictionary + { + ["TN"] = w.Tn?.ToString() ?? "", ["EPAYMENT"] = w.Epayment.ToString(), + ["OWNER_NNPN"] = w.OwnerNnpn?.ToString() ?? "", ["WALLET_NUMBER"] = w.WalletNumber ?? "", ["OWNER_NAME"] = w.OwnerName ?? "", + ["DRIVER_NAME"] = w.DriverName ?? "", ["DRIVER_NNPN"] = w.DriverNnpn?.ToString() ?? "", + ["IBAN"] = w.Iban ?? "-", ["BANK_ACCOUNT"] = w.BankAccount ?? "-", ["BANK_NAME"] = w.BankName ?? "-", + ["BANK_BRANCH"] = w.BankBranch ?? "", ["OWNER_NAME_ENGLISH"] = w.OwnerNameEnglish ?? "", + }; + + /// UPDATE log of the replaced record: only the columns whose value changed, old and new (null when nothing changed). + public static (string OldData, string NewData)? Diff(WalletRow old, WalletWrite updated) + { + var before = DataColumns(old); + var after = DataColumns(updated); + var o = new Dictionary(); + var n = new Dictionary(); + foreach (var (key, b) in before) + if (!string.Equals(b, after[key], StringComparison.OrdinalIgnoreCase)) { o[key] = b; n[key] = after[key]; } + return o.Count == 0 ? null : (ToJson(o), ToJson(n)); + } + + /// Caption of REFINERY_WALLET.STATUSCODE.* (logs.saveLog translates STATUS_CODE). + public static string StatusCaption(string status) => + string.Equals(status, WalletValues.Active, StringComparison.OrdinalIgnoreCase) ? "فعال" : "غير فعال"; + + /// Status change log: old and new caption of STATUS_CODE. + public static (string OldData, string NewData) StatusChange(string from, string to) => + (ToJson(new Dictionary { ["STATUS_CODE"] = StatusCaption(from) }), + ToJson(new Dictionary { ["STATUS_CODE"] = StatusCaption(to) })); +} diff --git a/src/NTP.Application/Refinery/Wallets/WalletsService.cs b/src/NTP.Application/Refinery/Wallets/WalletsService.cs new file mode 100644 index 0000000..d121706 --- /dev/null +++ b/src/NTP.Application/Refinery/Wallets/WalletsService.cs @@ -0,0 +1,175 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; +using NTP.Application.Grains.Reports; + +namespace NTP.Application.Refinery.Wallets; + +/// +/// Port of refinery_walletfactory.cfc / refinery_walletfactoryweb.cfc (screen REFINERY_WALLET, شاشة طرق الدفع). Access by permission keys only +/// (legacy REFINERY_MGR / REFINERY_AC branches not ported). CREATED_BY / UPDATED_BY and the log USER_ID are the numeric NTPUSERS id +/// (legacy session.userrecordid), the log USER_IP the caller's address. The Dinarak API is not called from here. +/// +public sealed class WalletsService( + IWalletsRepository repository, + IUnitOfWork unitOfWork, + ICurrentUser user, + IReportExcelService excel, + IValidator validator) : IWalletsService +{ + private string Me => user.Id.ToString(System.Globalization.CultureInfo.InvariantCulture); + + public Task> SearchAsync(WalletsQuery query, PageRequest page, CancellationToken ct) => + repository.SearchAsync(query, page, ct); + + public async Task GetAsync(long id, CancellationToken ct) + { + var w = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id); + var active = string.Equals(w.StatusCode, WalletValues.Active, StringComparison.OrdinalIgnoreCase); + var canActivate = false; + if (!active) + canActivate = (await ActiveIdsOfSameOwnerAsync(w.Tn, w.DriverNnpn, ct)).Count == 0; + return new WalletDetail + { + Id = w.Id, Tn = w.Tn, CompanyCode = w.CompanyCode, Epayment = w.Epayment, OwnerNnpn = w.OwnerNnpn, WalletNumber = w.WalletNumber, + OwnerName = w.OwnerName, HolderNnpn = w.HolderNnpn, HolderName = w.HolderName, OwnerNameEnglish = w.OwnerNameEnglish, DriverName = w.DriverName, DriverNnpn = w.DriverNnpn, Iban = w.Iban, + BankAccount = w.BankAccount, BankName = w.BankName, BankBranch = w.BankBranch, CreationDate = w.CreationDate, CreatedBy = w.CreatedBy, + UpdateDate = w.UpdateDate, UpdatedBy = w.UpdatedBy, StatusCode = w.StatusCode, PaymentMethod = w.PaymentMethod, + CanUpdate = active, CanDeactivate = active, CanActivate = canActivate, + }; + } + + public async Task> GetLogAsync(long id, PageRequest page, CancellationToken ct) + { + _ = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id); + return await repository.GetLogAsync(id, page, ct); + } + + private async Task> ActiveIdsOfSameOwnerAsync(long? tn, long? driverNnpn, CancellationToken ct) => + tn is not null ? await repository.GetActiveIdsByTruckAsync(tn.Value, ct) + : driverNnpn is not null ? await repository.GetActiveIdsByDriverAsync(driverNnpn.Value, ct) + : []; + + /// refinery_walletfactory.cfc:100-117 / 188-203: a truck and a driver have one ACTIVE record each. + private async Task EnsureNoOtherActiveAsync(WalletWrite w, long? exceptId, CancellationToken ct) + { + if (w.Tn is not null && (await repository.GetActiveIdsByTruckAsync(w.Tn.Value, ct)).Any(i => i != exceptId)) + throw new BusinessException(WalletsErrors.TruckHasActive, WalletsMessages.TruckHasActive); + if (w.DriverNnpn is not null && (await repository.GetActiveIdsByDriverAsync(w.DriverNnpn.Value, ct)).Any(i => i != exceptId)) + throw new BusinessException(WalletsErrors.DriverHasActive, WalletsMessages.DriverHasActive); + } + + public async Task CreateAsync(SaveWalletRequest request, string? userIp, CancellationToken ct) + { + await validator.ValidateAndThrowAsync(request, ct); + var record = WalletsRules.ToWrite(request); + await EnsureNoOtherActiveAsync(record, null, ct); + + var id = await unitOfWork.ExecuteInTransactionAsync(async token => + { + var newId = await repository.InsertAsync(record, Me, token); + await repository.InsertLogAsync(newId, WalletValues.LogCreate, Me, userIp, WalletsRules.EmptyJson, WalletsRules.CreateNewData(), token); + return newId; + }, ct); + return new WalletsResult(WalletsMessages.Done, id); + } + + /// + /// Legacy update keeps the history: the record is set INACTIVE and a new ACTIVE record with the new data is inserted (two log rows: + /// CREATE on the new id, UPDATE with the changed columns on the old id). The payment method of a record cannot change (the select is disabled). + /// + public async Task UpdateAsync(long id, SaveWalletRequest request, string? userIp, CancellationToken ct) + { + var old = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id); + if (!string.Equals(old.StatusCode, WalletValues.Active, StringComparison.OrdinalIgnoreCase)) + throw new BusinessException(WalletsErrors.StatusNotAllowed, WalletsMessages.StatusNotAllowed); + request.PaymentMethod = WalletsRules.MethodOf(old); + await validator.ValidateAndThrowAsync(request, ct); + var record = WalletsRules.ToWrite(request); + await EnsureNoOtherActiveAsync(record, id, ct); + + var newId = await unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.SetStatusAsync(id, WalletValues.Inactive, Me, token); + var created = await repository.InsertAsync(record, Me, token); + await repository.InsertLogAsync(created, WalletValues.LogCreate, Me, userIp, WalletsRules.EmptyJson, WalletsRules.ReplacementNewData(record, Me), token); + if (WalletsRules.Diff(old, record) is { } diff) + await repository.InsertLogAsync(id, WalletValues.LogUpdate, Me, userIp, diff.OldData, diff.NewData, token); + return created; + }, ct); + return new WalletsResult(WalletsMessages.Done, newId); + } + + public async Task ActivateAsync(long id, string? userIp, CancellationToken ct) + { + var w = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id); + // STATUS_ACTION_MATRIX: CHSTAT only INACTIVE -> ACTIVE + if (!string.Equals(w.StatusCode, WalletValues.Inactive, StringComparison.OrdinalIgnoreCase)) + throw new BusinessException(WalletsErrors.StatusNotAllowed, WalletsMessages.StatusNotAllowed); + // refinery_walletfactory.cfc:296-306: no other ACTIVE record for the same truck (or driver when there is no truck) + if ((await ActiveIdsOfSameOwnerAsync(w.Tn, w.DriverNnpn, ct)).Count > 0) + throw w.Tn is not null + ? new BusinessException(WalletsErrors.TruckHasActive, WalletsMessages.TruckHasActive) + : new BusinessException(WalletsErrors.DriverHasActive, WalletsMessages.DriverHasActive); + await ChangeStatusAsync(id, WalletValues.Inactive, WalletValues.Active, WalletValues.LogActivate, userIp, ct); + return new WalletsResult(WalletsMessages.Done, id); + } + + public async Task DeactivateAsync(long id, string? userIp, CancellationToken ct) + { + var w = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id); + // STATUS_ACTION_MATRIX: DEACTIVATE only from ACTIVE + if (!string.Equals(w.StatusCode, WalletValues.Active, StringComparison.OrdinalIgnoreCase)) + throw new BusinessException(WalletsErrors.StatusNotAllowed, WalletsMessages.StatusNotAllowed); + await ChangeStatusAsync(id, WalletValues.Active, WalletValues.Inactive, WalletValues.LogDeactivate, userIp, ct); + return new WalletsResult(WalletsMessages.Done, id); + } + + private Task ChangeStatusAsync(long id, string from, string to, string method, string? userIp, CancellationToken ct) => + unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.SetStatusAsync(id, to, Me, token); + var (o, n) = WalletsRules.StatusChange(from, to); + await repository.InsertLogAsync(id, method, Me, userIp, o, n, token); + return true; + }, ct); + + public async Task ExportAsync(WalletsQuery query, CancellationToken ct) + { + var rows = new List(); + for (var p = 1; rows.Count < 20000; p++) + { + var r = await repository.SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct); + rows.AddRange(r.Items); + if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break; + } + // legacy report columns: counter, TN, payment method, owner national no., owner name, wallet no., IBAN, bank account, bank name, status + var cols = new List + { + new("counter", "متسلسل", "#"), new("tn", "رقم الشاحنة", "Truck"), new("paymentMethod", "طريقة الدفع", "Payment method"), + new("ownerNnpn", "الرقم الوطني للمالك", "Owner national no."), new("ownerName", "اسم المالك", "Owner name"), + new("walletNumber", "رقم المحفظة", "Wallet number"), new("iban", "IBAN", "IBAN"), new("bankAccount", "رقم الحساب", "Bank account"), + new("bankName", "اسم البنك", "Bank name"), new("status", "الحالة", "Status"), + }; + var n = 0; + var data = rows.Select(r => (IReadOnlyDictionary)new Dictionary + { + ["counter"] = ++n, ["tn"] = r.Tn, ["paymentMethod"] = KindCaption(r.PaymentMethod), ["ownerNnpn"] = r.HolderNnpn, + ["ownerName"] = r.HolderName, ["walletNumber"] = r.WalletNumber, ["iban"] = r.Iban, ["bankAccount"] = r.BankAccount, + ["bankName"] = r.BankName, ["status"] = WalletsRules.StatusCaption(r.StatusCode ?? string.Empty), + }).ToList(); + var table = new ReportTable { Key = "REFINERY_WALLET", TitleAr = "شاشة طرق الدفع", TitleEn = "Payment methods", Columns = cols, Rows = data }; + return new ExportFile(excel.Build(table, user.UserId, DateTime.Now, true), + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "REFINERY_WALLET.xlsx"); + } + + /// Captions REFINERY_WALLET.BANK / EWALLET / DRAIVER_WALLET. + public static string KindCaption(string? kind) => kind switch + { + WalletValues.KindBank => "حوالة بنكية", + WalletValues.KindEWallet => "محفظة الالكترونية", + WalletValues.KindDriverWallet => "محفظة سائق", + _ => kind ?? string.Empty, + }; +} diff --git a/src/NTP.Infrastructure/Integrations/DinarakClient.cs b/src/NTP.Infrastructure/Integrations/DinarakClient.cs new file mode 100644 index 0000000..6fd5c11 --- /dev/null +++ b/src/NTP.Infrastructure/Integrations/DinarakClient.cs @@ -0,0 +1,42 @@ +using System.Net.Http.Headers; +using System.Text; + +namespace NTP.Infrastructure.Integrations; + +/// HTTP status and body of one Dinarak call. +public sealed record DinarakHttpResult(int Status, string Body); + +/// +/// The four HTTP calls of legacy RefinaryDinarakApi.cfc, no database, no business rules (those are in ). +/// Headers as legacy: JSON content, Accept-Language "ar" for /token and "en" for the others, Authorization "bearer {token}". +/// +public sealed class DinarakClient(HttpClient http, DinarakOptions options) +{ + private string Url(string path) => (options.BaseUrl ?? string.Empty).TrimEnd('/') + path; + + private async Task SendAsync(HttpMethod method, string url, string? json, string? bearer, string language, CancellationToken ct) + { + using var request = new HttpRequestMessage(method, url); + request.Headers.TryAddWithoutValidation("Accept-Language", language); + if (bearer is not null) request.Headers.TryAddWithoutValidation("Authorization", bearer); + if (json is not null) request.Content = new StringContent(json, Encoding.UTF8, new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" }); + using var response = await http.SendAsync(request, ct); + return new DinarakHttpResult((int)response.StatusCode, await response.Content.ReadAsStringAsync(ct)); + } + + /// POST /token with the configured user and password. + public Task GetTokenAsync(CancellationToken ct = default) => + SendAsync(HttpMethod.Post, Url("/token"), DinarakProtocol.BuildTokenRequest(options.UserName ?? string.Empty, options.Password ?? string.Empty), null, "ar", ct); + + /// GET /Transfer/AliasResolve?aliastype=MOBL&value={wallet}. + public Task AliasResolveAsync(string bearer, string walletNumber, CancellationToken ct = default) => + SendAsync(HttpMethod.Get, Url("/Transfer/AliasResolve?aliastype=MOBL&value=" + Uri.EscapeDataString(walletNumber)), null, bearer, "en", ct); + + /// POST /transfer/transfer. + public Task TransferAsync(string bearer, string requestJson, CancellationToken ct = default) => + SendAsync(HttpMethod.Post, Url("/transfer/transfer"), requestJson, bearer, "en", ct); + + /// GET /transfer/transferByMessageID?MessageID={id}. + public Task GetByMessageIdAsync(string bearer, string messageId, CancellationToken ct = default) => + SendAsync(HttpMethod.Get, Url("/transfer/transferByMessageID?MessageID=" + Uri.EscapeDataString(messageId)), null, bearer, "en", ct); +} diff --git a/src/NTP.Infrastructure/Integrations/DinarakGateway.cs b/src/NTP.Infrastructure/Integrations/DinarakGateway.cs new file mode 100644 index 0000000..43094d1 --- /dev/null +++ b/src/NTP.Infrastructure/Integrations/DinarakGateway.cs @@ -0,0 +1,162 @@ +using System.Text.Json; +using Dapper; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NTP.Application.Refinery.Integrations; +using NTP.Infrastructure.Persistence; +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Infrastructure.Integrations; + +/// +/// Port of RefinaryDinarakApi.cfc: ProcessTransfer (duplicate check, amount check against CalculateRefinaryAmount, token, AliasResolve, +/// transfer) and getTransferByMessageID, with the REFINERY_DINARAK_API_LOG rows of the legacy code. Switched off unless +/// Refinery:Dinarak:Enabled is true (answers code 106 and calls nothing). Not registered by convention (no "Service" suffix): see DependencyInjection. +/// +public sealed class DinarakGateway( + IDbSession session, + IHttpClientFactory httpFactory, + IOptions options, + ILogger logger) + : OracleRepositoryBase(session, logger), IDinarakGateway, IDinarakReferenceGateway +{ + // legacy : one transfer at a time, so two clicks cannot both pass the duplicate check + private static readonly SemaphoreSlim TransferLock = new(1, 1); + private const int Limit = 3000; // keeps the CLOB binds small + + private sealed class TripRef { public decimal? ReferenceId { get; set; } public string? LoadingNo { get; set; } } + + private DinarakOptions Options => options.Value; + + private DinarakClient Client() => new(httpFactory.CreateClient(DinarakOptions.HttpClientName), Options); + + private static string Cut(string? s) => s is null ? string.Empty : s.Length <= Limit ? s : s[..Limit]; + + private static string Packed(int status, string body) => + JsonSerializer.Serialize(new { statusCode = status, body = Cut(body) }, new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); + + private Task LogCallAsync(long logId, string status, string service, string wallet, decimal amount, string nnpn, string request, string response, long tripId, CancellationToken ct) => + ExecuteAsync(""" + INSERT INTO REFINERY_DINARAK_API_LOG (ID, CREATION_DATE, STATUS_CODE, SERVICE_NAME, EWALLET_NUMBER, AMOUNT, NNPN, REQUEST_DATA, RESPONSE_DATA, REFINERY_TRIP_ID) + VALUES (:Id, SYSDATE, :Status, :Service, :Wallet, :Amount, :Nnpn, :Request, :Response, :TripId) + """, new { Id = logId, Status = status, Service = service, Wallet = wallet, Amount = amount, Nnpn = nnpn, Request = Cut(request), Response = Cut(response), TripId = tripId }, ct); + + private Task NextLogIdAsync(CancellationToken ct) => + ExecuteScalarAsync("SELECT SEQ_REFINARY_DINARK_API_LOG_ID.NEXTVAL FROM DUAL", null, ct); + + /// GetAPIToken: also writes the TOKEN log row (without the password, and without the token of the answer). + private async Task TokenAsync(DinarakClient client, long tripId, string wallet, string nnpn, decimal amount, CancellationToken ct) + { + string? bearer = null; + var status = "FAILED"; + var responseLog = string.Empty; + try + { + var r = await client.GetTokenAsync(ct); + responseLog = Packed(r.Status, "[token answer not stored]"); + if (r.Status == 200) + { + bearer = DinarakProtocol.ParseBearer(r.Body); + if (bearer is not null) status = "PROCESSED"; + } + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException) + { + responseLog = Packed(0, ex.GetType().Name); + } + finally + { + await LogCallAsync(await NextLogIdAsync(ct), status, "TOKEN", wallet, amount, nnpn, + DinarakProtocol.BuildTokenRequestForLog(Options.UserName ?? string.Empty), responseLog, tripId, ct); + } + return bearer; + } + + private async Task TokenWithoutLogAsync(DinarakClient client, CancellationToken ct) + { + try + { + var r = await client.GetTokenAsync(ct); + return r.Status == 200 ? DinarakProtocol.ParseBearer(r.Body) : null; + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException) + { + return null; + } + } + + public async Task TransferAsync(long tripId, string walletNumber, string nnpn, decimal amount, string receiverName, CancellationToken ct = default) + { + if (!Options.Enabled) return new("106", "DINARAK_DISABLED"); + if (!await TransferLock.WaitAsync(TimeSpan.FromSeconds(10), ct)) return new("104", "SYSTEM_ERROR_BUSY"); + try + { + // already paid? + var paid = await ExecuteScalarAsync( + "SELECT COUNT(*) FROM REFINERY_DINARAK_API_LOG WHERE SERVICE_NAME = 'TRANSFER' AND STATUS_CODE = 'PROCESSED' AND REFINERY_TRIP_ID = :Id", new { Id = tripId }, ct); + if (paid > 0) return new("105", "The transaction has already been paid!"); + + // the amount the screen sends must be the amount the database calculates + var calculated = await QueryFirstAsync("SELECT ROUND(CalculateRefinaryAmount(:Id), 3) FROM DUAL", new { Id = tripId }, ct); + if (calculated is null || !DinarakProtocol.AmountMatches(calculated.Value, amount)) return new("101", "Amount_Not_Match"); + + var trip = await QueryFirstAsync( + "SELECT DINARAK_REFERENCE_ID AS ReferenceId, NVL(DISCHARGE_AUTHORIZTION_NO, '0') AS LoadingNo FROM REFINERY_TRIPS WHERE ID = :Id", new { Id = tripId }, ct); + var reference = trip?.ReferenceId ?? tripId; + var loadingNo = trip?.LoadingNo ?? "0"; + + var client = Client(); + // the legacy code went on with an empty token (and answered "Invalid Wallet"); here a missing token is reported as such + var bearer = await TokenAsync(client, tripId, walletNumber, nnpn, amount, ct); + if (bearer is null) return new("103", "TOKEN_ERROR"); + + string operation; + if (Options.InternalSalaryWallets.Contains(walletNumber, StringComparer.Ordinal)) operation = DinarakProtocol.SalaryOperation; + else + { + var alias = await client.AliasResolveAsync(bearer, walletNumber, ct); + var pic = alias.Status == 200 ? DinarakProtocol.ParsePicCode(alias.Body) : null; + if (pic is null) return new("104", "Invalid Wallet"); + operation = DinarakProtocol.OperationFor(pic); + } + + var logId = await NextLogIdAsync(ct); + var requestJson = DinarakProtocol.BuildTransferRequest(receiverName, amount, loadingNo, reference, walletNumber, operation); + var http = await client.TransferAsync(bearer, requestJson, ct); + var result = DinarakProtocol.MapTransferResponse(http.Status, http.Body); + + await LogCallAsync(logId, result.Success ? "PROCESSED" : "FAILED", "TRANSFER", walletNumber, amount, nnpn, requestJson, Packed(http.Status, http.Body), tripId, ct); + return result; + } + catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) + { + logger.LogError(ex, "Dinarak transfer of trip {TripId} failed", tripId); + return new("104", "SYSTEM_ERROR_" + ex.Message); + } + finally + { + TransferLock.Release(); + } + } + + public Task GetTransferByMessageIdAsync(long messageId, CancellationToken ct = default) => + GetTransferByReferenceAsync(messageId, ct); + + public async Task GetTransferByReferenceAsync(decimal reference, CancellationToken ct = default) + { + if (!Options.Enabled) return new(false, "DISABLED", null); + try + { + var client = Client(); + var bearer = await TokenWithoutLogAsync(client, ct); + if (bearer is null) return new(false, "ERROR", null); + var r = await client.GetByMessageIdAsync(bearer, DinarakProtocol.FormatMessageId(reference), ct); + return DinarakProtocol.MapStatusResponse(r.Status, r.Body); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + logger.LogWarning(ex, "Dinarak status lookup failed"); + return new(false, "ERROR", null); + } + } +} diff --git a/src/NTP.Infrastructure/Integrations/DinarakOptions.cs b/src/NTP.Infrastructure/Integrations/DinarakOptions.cs new file mode 100644 index 0000000..410b3b4 --- /dev/null +++ b/src/NTP.Infrastructure/Integrations/DinarakOptions.cs @@ -0,0 +1,25 @@ +namespace NTP.Infrastructure.Integrations; + +/// +/// Dinarak payment API (config section "Refinery:Dinarak"; legacy application.DINARAK_API {url, username, password}). +/// The user name and password are SECRETS: set them through the environment (Refinery__Dinarak__UserName, Refinery__Dinarak__Password), +/// never in a file of the repository. Off by default: nothing is called while is false. +/// +public sealed class DinarakOptions +{ + public const string SectionName = "Refinery:Dinarak"; + public const string HttpClientName = "Dinarak"; + + public bool Enabled { get; set; } + /// Base address of the API, without a trailing slash (the legacy "url"; /token, /Transfer/AliasResolve, /transfer/transfer are appended). + public string? BaseUrl { get; set; } + public string? UserName { get; set; } + public string? Password { get; set; } + public int TimeoutSeconds { get; set; } = 30; + + /// + /// Wallet numbers that skip the AliasResolve call and always use the operation "bank salary internal" (the legacy code hard-coded one + /// such number). Empty by default; fill it in the environment if that wallet is still used (Refinery__Dinarak__InternalSalaryWallets__0). + /// + public string[] InternalSalaryWallets { get; set; } = []; +} diff --git a/src/NTP.Infrastructure/Integrations/DinarakProtocol.cs b/src/NTP.Infrastructure/Integrations/DinarakProtocol.cs new file mode 100644 index 0000000..0496abf --- /dev/null +++ b/src/NTP.Infrastructure/Integrations/DinarakProtocol.cs @@ -0,0 +1,141 @@ +using System.Globalization; +using System.Text.Encodings.Web; +using System.Text.Json; +using NTP.Application.Refinery.Integrations; + +namespace NTP.Infrastructure.Integrations; + +/// +/// The pure parts of legacy backend/common/RefinaryDinarakApi.cfc: request bodies, wallet type to operation mapping, response mapping and +/// the amount comparison. No I/O, so they are unit tested without a server. +/// +public static class DinarakProtocol +{ + /// picCode values of the Jordanian wallet providers that are paid with the operation "Transfer" (RefinaryDinarakApi.cfc:132). + public static readonly string[] TransferWalletTypes = + ["ZAINJOPX", "ORNGJOPX", "DNRKJOPX", "GDHAJOPX", "MEPSJOPX", "ALWPJOPX", "UWLTJOPX", "MDFTJOPX"]; + + public const string TransferOperation = "Transfer"; + public const string SalaryOperation = "bank salary internal"; + + /// Statuses of getTransferByMessageID that count as "already sent" (RefinaryDinarakApi.cfc:233). + public static readonly string[] AcceptedStatuses = ["Success", "Processing", "New"]; + + private static readonly JsonWriterOptions Raw = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + + private static string Write(Action body) + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms, Raw)) body(w); + return System.Text.Encoding.UTF8.GetString(ms.ToArray()); + } + + /// Body of POST /token. + public static string BuildTokenRequest(string userName, string password) => Write(w => + { + w.WriteStartObject(); + w.WriteString("username", userName); + w.WriteString("password", password); + w.WriteString("grant_type", "password"); + w.WriteEndObject(); + }); + + /// Token request as it is kept in REFINERY_DINARAK_API_LOG: the legacy code stored the password there, this one does not. + public static string BuildTokenRequestForLog(string userName) => BuildTokenRequest(userName, "***"); + + /// "Transfer" for a known wallet provider, otherwise "bank salary internal" (picCode of AliasResolve, case-insensitive). + public static string OperationFor(string? picCode) => + picCode is not null && TransferWalletTypes.Contains(picCode.Trim(), StringComparer.OrdinalIgnoreCase) ? TransferOperation : SalaryOperation; + + /// picCode of the AliasResolve answer, or null when the body is not the expected JSON (legacy: "Invalid Wallet"). + public static string? ParsePicCode(string body) + { + try + { + using var doc = JsonDocument.Parse(body); + return doc.RootElement.TryGetProperty("picCode", out var p) && p.ValueKind == JsonValueKind.String ? p.GetString() : null; + } + catch (JsonException) { return null; } + } + + /// "352.1": the message id / reference of a trip (a decimal because ACTIVATE_WALLET_EXCHANGE adds 0.01). + public static string FormatMessageId(decimal id) => id.ToString("0.##########", CultureInfo.InvariantCulture); + + /// + /// Body of POST /transfer/transfer, same property order as the legacy struct. Description is " {loadingNumber}" (leading space as in + /// the legacy code); MessageId and Reference both carry the trip's Dinarak reference id. + /// + public static string BuildTransferRequest(string receiverName, decimal amount, string loadingNumber, decimal reference, string walletNumber, string operationName) => + Write(w => + { + var id = FormatMessageId(reference); + w.WriteStartObject(); + w.WriteString("Name", receiverName); + w.WriteNumber("Amount", amount); + w.WriteString("Description", " " + loadingNumber); + w.WriteString("MessageId", id); + w.WriteString("Reference", id); + w.WriteString("ReceiverID", walletNumber); + w.WriteString("OperationName", operationName); + w.WriteStartArray("Conditions"); + w.WriteStartObject(); + w.WriteString("NationalId", string.Empty); + w.WriteEndObject(); + w.WriteEndArray(); + w.WriteEndObject(); + }); + + /// Same value check as legacy: |calculated - requested| rounded to 3 decimals must not exceed 0.001. + public static bool AmountMatches(decimal calculated, decimal requested) => + Math.Round(Math.Abs(calculated - requested), 3, MidpointRounding.AwayFromZero) <= 0.001m; + + private static string Underscored(string? text) => (text ?? string.Empty).Replace(' ', '_'); + + /// Answer of POST /transfer/transfer: 200 + status.name Success = 000; other status = 102 (error text with underscores); HTTP error = 103. + public static DinarakTransferResult MapTransferResponse(int httpStatus, string body) + { + if (httpStatus != 200) return new("103", Underscored(body)); + try + { + using var doc = JsonDocument.Parse(body); + var status = doc.RootElement.GetProperty("status"); + var name = status.GetProperty("name").GetString(); + if (string.Equals(name, "Success", StringComparison.Ordinal)) return new("000", "SUCCESS"); + var error = status.TryGetProperty("errorMessage", out var e) && e.ValueKind == JsonValueKind.String ? e.GetString() : name; + return new("102", Underscored(error)); + } + catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException) + { + return new("104", "SYSTEM_ERROR_INVALID_RESPONSE"); + } + } + + /// Answer of GET /transfer/transferByMessageID. A non-200 answer means "nothing found" (legacy: not accepted); StatusName "HTTP_{code}". + public static DinarakTransferStatus MapStatusResponse(int httpStatus, string body) + { + if (httpStatus != 200) return new(false, $"HTTP_{httpStatus}", body); + try + { + using var doc = JsonDocument.Parse(body); + var name = doc.RootElement.GetProperty("status").GetProperty("name").GetString(); + return new(name is not null && AcceptedStatuses.Contains(name, StringComparer.Ordinal), name, body); + } + catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException) + { + return new(false, "ERROR", body); + } + } + + /// The access token of the POST /token answer, as the Authorization header value the legacy code built ("bearer {token}"), or null. + public static string? ParseBearer(string body) + { + try + { + using var doc = JsonDocument.Parse(body); + return doc.RootElement.TryGetProperty("access_token", out var t) && t.ValueKind == JsonValueKind.String && !string.IsNullOrEmpty(t.GetString()) + ? "bearer " + t.GetString() + : null; + } + catch (JsonException) { return null; } + } +} diff --git a/src/NTP.Infrastructure/Integrations/JopetrolGateway.cs b/src/NTP.Infrastructure/Integrations/JopetrolGateway.cs new file mode 100644 index 0000000..47f9a9f --- /dev/null +++ b/src/NTP.Infrastructure/Integrations/JopetrolGateway.cs @@ -0,0 +1,82 @@ +using System.Security; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NTP.Application.Refinery.Integrations; + +namespace NTP.Infrastructure.Integrations; + +/// +/// Section Refinery:Jopetrol. OFF by default. and are secrets: they come only from the +/// environment / server .env (Refinery__Jopetrol__UserName, Refinery__Jopetrol__Password), never from a file in the repository. +/// +public sealed class JopetrolOptions +{ + public const string SectionName = "Refinery:Jopetrol"; + public const string HttpClientName = "Jopetrol"; + + public bool Enabled { get; set; } + /// The ASMX endpoint of the Jopetrol TransportPaymentWS service. + public string Url { get; set; } = ""; + public string UserName { get; set; } = ""; + public string Password { get; set; } = ""; + public int TimeoutSeconds { get; set; } = 30; +} + +/// Request building and answer parsing of the Jopetrol SOAP call (kept apart from the HTTP code so it can be tested). +public static class JopetrolSoap +{ + public const string SoapNamespace = "http://www.w3.org/2003/05/soap-envelope"; + public const string ServiceNamespace = "http://jopetrol.com.jo/TransportPaymentWS"; + + /// The envelope of legacy callRefinaryUpdateStatusTo7 (SOAP 1.2, AuthHeader + sendClaimandUpdateStatusTo7 with TransNumber and claimNo). + public static string BuildEnvelope(string userName, string password, string pn, string claimNo) + { + static string E(string s) => SecurityElement.Escape(s) ?? ""; + return $""" + + {E(userName)}{E(password)} + {E(pn)}{E(claimNo)} + + """; + } + + /// Text of sendClaimandUpdateStatusTo7Result (legacy xmlSearch "//*[local-name()=...]"); null when the answer does not contain it. + public static string? ParseResult(string xml) + { + var doc = XDocument.Parse(xml); + return doc.Descendants().FirstOrDefault(e => e.Name.LocalName == "sendClaimandUpdateStatusTo7Result")?.Value; + } +} + +/// +/// Jopetrol claim web service (legacy refinery_wage_claimfactory.callRefinaryUpdateStatusTo7). Returns null WITHOUT any call when +/// Refinery:Jopetrol:Enabled is false. HTTP errors, time-outs and unreadable answers are thrown (the caller decides what to tell the user). +/// +public sealed class JopetrolGateway(IHttpClientFactory httpClients, IOptions options, ILogger logger) : IJopetrolGateway +{ + public async Task SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default) + { + var o = options.Value; + if (!o.Enabled) return null; + if (string.IsNullOrWhiteSpace(o.Url) || string.IsNullOrWhiteSpace(o.UserName) || string.IsNullOrWhiteSpace(o.Password)) + throw new InvalidOperationException("Refinery:Jopetrol is enabled but Url / UserName / Password are not configured."); + + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(o.TimeoutSeconds is > 0 and <= 300 ? o.TimeoutSeconds : 30)); + + using var request = new HttpRequestMessage(HttpMethod.Post, o.Url) + { + Content = new StringContent(JopetrolSoap.BuildEnvelope(o.UserName, o.Password, pn, claimNo), Encoding.UTF8, "text/xml"), + }; + using var response = await httpClients.CreateClient(JopetrolOptions.HttpClientName).SendAsync(request, cts.Token); + var body = await response.Content.ReadAsStringAsync(cts.Token); + logger.LogInformation("Jopetrol sendClaimandUpdateStatusTo7 for permit {Pn}: HTTP {Status}", pn, (int)response.StatusCode); + + // legacy parsed whatever came back; a SOAP fault or an HTML error page has no result element + try { return JopetrolSoap.ParseResult(body) ?? ""; } + catch (XmlException) { throw new InvalidOperationException($"Jopetrol answered HTTP {(int)response.StatusCode} with an unreadable body."); } + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Cards/CardsRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Cards/CardsRepository.cs new file mode 100644 index 0000000..8075325 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Cards/CardsRepository.cs @@ -0,0 +1,95 @@ +using System.Data; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Refinery.Cards; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.Cards; + +/// REFINERY_CARDS / REFINERY_CARDS_LOG of refinery_cardsdao.cfc and refinery_cardsfactory.cfc. +internal sealed class CardsRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), ICardsRepository +{ + private const string Columns = """ + c.ID AS Id, c.TN AS Tn, c.CARD_NUMBER AS CardNumber, c.BOX_NO AS BoxNo, c.CURRENT_BALANCE AS CurrentBalance, + c.CREATION_DATE AS CreationDate, c.CREATED_BY AS CreatedBy, c.UPDATE_DATE AS UpdateDate, c.UPDATED_BY AS UpdatedBy, + c.STATUS_CODE AS StatusCode, c.LAST_TRIP_ID AS LastTripId + """; + + public async Task> SearchAsync(CardsQuery query, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE 1 = 1"); + var p = new DynamicParameters(); + if (!string.IsNullOrWhiteSpace(query.Tn)) + { + // TN is a NUMBER column (legacy compared lower(TN) = lower('text')): a non-numeric text matches nothing + if (long.TryParse(query.Tn.Trim(), out var tn)) { where.Append(" AND c.TN = :Tn"); p.Add("Tn", tn); } + else where.Append(" AND 1 = 0"); + } + if (!string.IsNullOrWhiteSpace(query.CardNumber)) { where.Append(" AND LOWER(c.CARD_NUMBER) = LOWER(:CardNumber)"); p.Add("CardNumber", query.CardNumber.Trim()); } + var statuses = query.StatusCodes.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).Distinct().ToList(); + if (statuses.Count > 0) + { + var names = statuses.Select((_, i) => ":St" + i).ToList(); + where.Append($" AND c.STATUS_CODE IN ({string.Join(",", names)})"); + for (var i = 0; i < statuses.Count; i++) p.Add("St" + i, statuses[i]); + } + var baseSql = $"SELECT {Columns} FROM REFINERY_CARDS c{where}"; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY c.ID DESC"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public Task GetAsync(long id, CancellationToken ct = default) => + QueryFirstAsync($"SELECT {Columns} FROM REFINERY_CARDS c WHERE c.ID = :Id", new { Id = id }, ct); + + public async Task CardNumberExistsAsync(string cardNumber, CancellationToken ct = default) => + await ExecuteScalarAsync("SELECT COUNT(*) FROM REFINERY_CARDS WHERE CARD_NUMBER = :CardNumber", new { CardNumber = cardNumber }, ct) > 0; + + public Task> GetByTruckAsync(long tn, CancellationToken ct = default) => + QueryAsync($"SELECT {Columns} FROM REFINERY_CARDS c WHERE c.TN = :Tn ORDER BY c.ID DESC", new { Tn = tn }, ct); + + public async Task InsertAsync(long tn, string cardNumber, decimal balance, string createdBy, CancellationToken ct = default) + { + // BOX_NO is always 0 (refinery_cardsfactory.cfc:167); STATUS_CODE and CREATION_DATE come from the column defaults (ACTIVE, SYSDATE) + var p = new DynamicParameters(new { Tn = tn, CardNumber = cardNumber, Balance = balance, CreatedBy = Fit(createdBy, 20) }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + INSERT INTO REFINERY_CARDS (ID, TN, CARD_NUMBER, BOX_NO, CURRENT_BALANCE, CREATED_BY) + VALUES (SEQ_REFINERY_CARDS.NEXTVAL, :Tn, :CardNumber, 0, :Balance, :CreatedBy) + RETURNING ID INTO :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public Task ChangeStatusAsync(long id, string status, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_CARDS SET STATUS_CODE = :Status, UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId WHERE ID = :Id + """, new { Status = status, UserId = Fit(userId, 20), Id = id }, ct); + + public Task InsertLogAsync(long cardId, string method, decimal balanceBefore, decimal balanceAfter, decimal amount, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO REFINERY_CARDS_LOG (ID, ENTITIY_ID, METHOD_NAME, BALANCE_BEFORE, BALANCE_AFTER, AMOUNT, PN, CREATED_BY, LAST_UPDATE_DATE, UPDATED_BY) + VALUES (SEQ_REFINERY_CARDS_LOG.NEXTVAL, :CardId, :Method, :Before, :After, :Amount, '0', :UserId, SYSDATE, :UserId) + """, new { CardId = cardId, Method = method, Before = balanceBefore, After = balanceAfter, Amount = amount, UserId = Fit(userId, 50) }, ct); + + public async Task> GetLogAsync(long cardId, PageRequest page, CancellationToken ct = default) + { + const string baseSql = """ + SELECT l.ID AS Id, l.ENTITIY_ID AS EntityId, l.METHOD_NAME AS MethodName, l.BALANCE_BEFORE AS BalanceBefore, + l.BALANCE_AFTER AS BalanceAfter, l.AMOUNT AS Amount, l.PN AS Pn, l.UPDATED_BY AS UpdatedBy, l.LAST_UPDATE_DATE AS LastUpdateDate + FROM REFINERY_CARDS_LOG l WHERE l.ENTITIY_ID = :CardId + """; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), new { CardId = cardId }, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY l.ID DESC"), + new { CardId = cardId, page.MinRow, page.MaxRow }, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + private static string Fit(string value, int max) => value.Length <= max ? value : value[..max]; +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/CommissionClaims/CommissionClaimRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/CommissionClaims/CommissionClaimRepository.cs new file mode 100644 index 0000000..e22f14b --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/CommissionClaims/CommissionClaimRepository.cs @@ -0,0 +1,176 @@ +using System.Globalization; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Refinery.CommissionClaims; +using NTP.Application.Refinery.WageClaims; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.CommissionClaims; + +/// Dapper port of refinery_commission_claimdao.cfc and the SQL of refinery_commission_claimfactory.cfc (NAFITHTCS connection). +internal sealed class CommissionClaimRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), ICommissionClaimRepository +{ + // REFINERY_COMMISSION_CLAIM_VIEW (trip_cnt = number of wage claims of the commission claim) + private const string ClaimSelect = """ + SELECT c.ID AS Id, c.COMMISSION_CLAIM_NO AS CommissionClaimNo, c.COMMISSION_CLAIM_DATE AS CommissionClaimDate, c.STATUS_CODE AS StatusCode, + (SELECT COUNT(*) FROM REFINERY_WAGE_CLAIM w WHERE w.COMMISSION_CLAIM_ID = c.ID) AS TripCnt + FROM REFINERY_COMMISSION_CLAIM c + """; + + private const string WageClaimSelect = """ + SELECT w.ID AS Id, w.WAGE_CLAIM_NO AS WageClaimNo, w.WAGE_CLAIM_DATE AS WageClaimDate, w.STATUS_CODE AS StatusCode, + w.COMMISSION_CLAIM_ID AS CommissionClaimId, + (SELECT COUNT(*) FROM REFINERY_TRIPS t WHERE t.WAGE_CLAIM_ID = w.ID) AS TripCnt + FROM REFINERY_WAGE_CLAIM w + """; + + private static string I(long v) => v.ToString(CultureInfo.InvariantCulture); + + public async Task> SearchAsync(CommissionClaimQuery q, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE 1 = 1"); + var p = new DynamicParameters(); + if (!string.IsNullOrWhiteSpace(q.CommissionClaimNo)) { where.Append(" AND TO_CHAR(c.COMMISSION_CLAIM_NO) = :No"); p.Add("No", q.CommissionClaimNo.Trim()); } + if (q.CommissionClaimDate is { } d) + { + where.Append(" AND c.COMMISSION_CLAIM_DATE >= :DayFrom AND c.COMMISSION_CLAIM_DATE < :DayTo"); + p.Add("DayFrom", d.ToDateTime(TimeOnly.MinValue)); + p.Add("DayTo", d.AddDays(1).ToDateTime(TimeOnly.MinValue)); + } + if (q.StatusCodes.Count > 0) where.Append(" AND c.STATUS_CODE IN (").Append(AddList(p, "St", q.StatusCodes)).Append(')'); + + var baseSql = ClaimSelect + where; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + // legacy sort: COMMISSION_CLAIM_NO ASC + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY c.COMMISSION_CLAIM_NO, c.ID"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public Task GetAsync(long id, CancellationToken ct = default) => + QueryFirstAsync(ClaimSelect + " WHERE c.ID = :Id", new { Id = id }, ct); + + public async Task> WageClaimsOfAsync(long commissionClaimId, CancellationToken ct = default) => + await QueryAsync(WageClaimSelect + " WHERE w.COMMISSION_CLAIM_ID = :Id ORDER BY w.WAGE_CLAIM_NO, w.ID", new { Id = commissionClaimId }, ct); + + public async Task> CandidateWageClaimsAsync(IReadOnlyList statuses, CancellationToken ct = default) + { + var p = new DynamicParameters(); + var sql = WageClaimSelect + " WHERE w.COMMISSION_CLAIM_ID IS NULL AND w.STATUS_CODE IN (" + AddList(p, "St", statuses) + ") ORDER BY w.WAGE_CLAIM_NO, w.ID"; + return await QueryAsync(sql, p, ct); + } + + public Task CountAttachableAsync(IReadOnlyList wageClaimIds, CancellationToken ct = default) + { + var p = new DynamicParameters(); + return ExecuteScalarAsync("SELECT COUNT(*) FROM REFINERY_WAGE_CLAIM w WHERE w.COMMISSION_CLAIM_ID IS NULL AND w.ID IN (" + AddIdList(p, wageClaimIds) + ")", p, ct); + } + + public async Task InsertAsync(string createdBy, CancellationToken ct = default) + { + await ExecuteAsync("LOCK TABLE REFINERY_COMMISSION_CLAIM IN SHARE ROW EXCLUSIVE MODE", null, ct); + var id = await ExecuteScalarAsync("SELECT SEQ_REFINERY_COMMISSION_CLAIM.NEXTVAL FROM DUAL", null, ct); + // GenerateSerialNumber('REFINERY_COMMISSION_CLAIM'): yyyy + '02' + 5 digits for the first claim of the year, then max + 1 + await ExecuteAsync(""" + INSERT INTO REFINERY_COMMISSION_CLAIM (ID, COMMISSION_CLAIM_NO, STATUS_CODE, CREATED_BY) + SELECT :Id, + NVL(MAX(t.COMMISSION_CLAIM_NO) + 1, TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY') || '02' || '00001')), + 'NEW', :CreatedBy + FROM REFINERY_COMMISSION_CLAIM t + WHERE TO_CHAR(t.COMMISSION_CLAIM_DATE, 'yyyy') = TO_CHAR(SYSDATE, 'YYYY') + """, new { Id = id, CreatedBy = createdBy }, ct); + return id; + } + + public Task AttachWageClaimsAsync(long commissionClaimId, IReadOnlyList wageClaimIds, CancellationToken ct = default) + { + var p = new DynamicParameters(); + p.Add("ClaimId", commissionClaimId); + return ExecuteAsync("UPDATE REFINERY_WAGE_CLAIM SET COMMISSION_CLAIM_ID = :ClaimId WHERE COMMISSION_CLAIM_ID IS NULL AND ID IN (" + AddIdList(p, wageClaimIds) + ")", p, ct); + } + + public async Task> WageClaimStatusesAsync(long commissionClaimId, CancellationToken ct = default) => + await QueryAsync("SELECT STATUS_CODE FROM REFINERY_WAGE_CLAIM WHERE COMMISSION_CLAIM_ID = :Id", new { Id = commissionClaimId }, ct); + + public async Task CompleteWageClaimsAsync(long commissionClaimId, string userLogin, long userId, string? ip, CancellationToken ct = default) + { + // legacy: raw 'CLOSE' / 'COMPLETE' (not JSON) in OLD_DATA / NEW_DATA, ids from SEQ_LOG_REFINERY_WAGE_CLAIM + await ExecuteAsync(""" + INSERT INTO REFINERY_WAGE_CLAIM_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, USER_ID, USER_IP, OLD_DATA, NEW_DATA) + SELECT SEQ_LOG_REFINERY_WAGE_CLAIM.NEXTVAL, w.ID, 'COMPLETE', SYSDATE, :UserId, :Ip, 'CLOSE', 'COMPLETE' + FROM REFINERY_WAGE_CLAIM w WHERE w.COMMISSION_CLAIM_ID = :Id AND w.STATUS_CODE = 'CLOSE' + """, new { UserId = I(userId), Ip = Cut(ip, 50), Id = commissionClaimId }, ct); + return await ExecuteAsync(""" + UPDATE REFINERY_WAGE_CLAIM SET STATUS_CODE = 'COMPLETE', LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserLogin + WHERE COMMISSION_CLAIM_ID = :Id AND STATUS_CODE = 'CLOSE' + """, new { UserLogin = userLogin, Id = commissionClaimId }, ct); + } + + public Task SetStatusAsync(long id, string status, string userLogin, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_COMMISSION_CLAIM SET STATUS_CODE = :Status, LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserLogin WHERE ID = :Id + """, new { Status = status, UserLogin = userLogin, Id = id }, ct); + + public Task AddLogAsync(long id, string method, string? oldData, string? newData, long userId, string? ip, CancellationToken ct = default) => + // legacy takes the ids of this log from SEQ_REFINERY_TRIPS_LOG (saveLog was called with that sequence name) + ExecuteAsync(""" + INSERT INTO REFINERY_COMMISSION_CLAIM_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, USER_ID, USER_IP, OLD_DATA, NEW_DATA) + VALUES (SEQ_REFINERY_TRIPS_LOG.NEXTVAL, :Id, :Method, SYSDATE, :UserId, :Ip, :OldData, :NewData) + """, new { Id = id, Method = method, UserId = I(userId), Ip = Cut(ip, 50), OldData = oldData, NewData = newData }, ct); + + public async Task> LogAsync(long id, PageRequest page, CancellationToken ct = default) + { + var p = new DynamicParameters(); + p.Add("Id", id); + var total = await ExecuteScalarAsync("SELECT COUNT(*) FROM REFINERY_COMMISSION_CLAIM_LOG WHERE ENTITIY_ID = :Id", p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(""" + SELECT t.ID AS Id, t.METHOD_NAME AS MethodName, t.LOG_DATE AS LogDate, + (SELECT MIN(n.LOGIN) FROM NTP.NTPUSERS n WHERE TO_CHAR(n.ID) = t.USER_ID) AS Login, + DBMS_LOB.SUBSTR(t.OLD_DATA, 4000, 1) AS OldData, DBMS_LOB.SUBSTR(t.NEW_DATA, 4000, 1) AS NewData + FROM REFINERY_COMMISSION_CLAIM_LOG t WHERE t.ENTITIY_ID = :Id ORDER BY t.ID DESC + """), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task InvoiceSourceAsync(long id, CancellationToken ct = default) => + await QueryFirstAsync(""" + SELECT c.COMMISSION_CLAIM_NO AS CommissionClaimNo, + (SELECT MAX(w.WAGE_CLAIM_DATE) KEEP (DENSE_RANK LAST ORDER BY w.ID) FROM REFINERY_WAGE_CLAIM w WHERE w.COMMISSION_CLAIM_ID = c.ID) AS NewestWageClaimDate, + (SELECT COUNT(*) FROM REFINERY_TRIPS t WHERE t.WAGE_CLAIM_ID IN (SELECT w.ID FROM REFINERY_WAGE_CLAIM w WHERE w.COMMISSION_CLAIM_ID = c.ID)) AS TripsCount + FROM REFINERY_COMMISSION_CLAIM c WHERE c.ID = :Id + """, new { Id = id }, ct); + + public async Task CommissionVariableAsync(int month, int year, CancellationToken ct = default) => + // legacy test, kept as is: the month lies between the months of start / end date and the year between the years of start / end date + await QueryFirstAsync(""" + SELECT * FROM ( + SELECT v.KEY_VALUE FROM REFINERY_VARIABLES v + WHERE v.KEY_NAME = 'COMMISSION' + AND :Mo BETWEEN EXTRACT(MONTH FROM v.START_DATE) AND EXTRACT(MONTH FROM v.END_DATE) + AND :Yr BETWEEN EXTRACT(YEAR FROM v.START_DATE) AND EXTRACT(YEAR FROM v.END_DATE) + ORDER BY v.START_DATE DESC) WHERE ROWNUM = 1 + """, new { Mo = month, Yr = year }, ct); + + private static string AddList(DynamicParameters p, string prefix, IEnumerable values) + { + var names = new List(); + foreach (var v in values) { var n = prefix + names.Count; p.Add(n, v); names.Add(":" + n); } + return string.Join(", ", names); + } + + private static string AddIdList(DynamicParameters p, IEnumerable ids) + { + var names = new List(); + foreach (var v in ids) { var n = "Wid" + names.Count; p.Add(n, v); names.Add(":" + n); } + return string.Join(", ", names); + } + + private static string? Cut(string? s, int max) => s is null ? null : s.Length <= max ? s : s[..max]; +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/RemainingBalance/RemainingBalanceRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/RemainingBalance/RemainingBalanceRepository.cs new file mode 100644 index 0000000..44c8869 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/RemainingBalance/RemainingBalanceRepository.cs @@ -0,0 +1,46 @@ +using System.Globalization; +using Microsoft.Extensions.Logging; +using NTP.Application.Refinery.RemainingBalance; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.RemainingBalance; + +/// Port of refinery_remaining_balanceDAO.cfc (REFINERY_REMAINING_BALANCE, REFINERY_REMAINING_BALANCE_LOG). +internal sealed class RemainingBalanceRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IRemainingBalanceRepository +{ + private static bool TryTruck(string tn, out long truck) => long.TryParse(tn, NumberStyles.Integer, CultureInfo.InvariantCulture, out truck); + private static long Truck(string tn) => long.Parse(tn, CultureInfo.InvariantCulture); + + public async Task GetByTruckAsync(string tn, CancellationToken ct = default) => + TryTruck(tn, out var truck) + ? await QueryFirstAsync( + "SELECT ID AS Id, TN AS Tn, ROUND(REMAINING_BALANCE, 3) AS RemainingBalance, ROUND(BEFORE_REMAINING_BALANCE, 3) AS BeforeRemainingBalance " + + "FROM REFINERY_REMAINING_BALANCE WHERE TN = :Tn ORDER BY ID", new { Tn = truck }, ct) + : null; + + public Task ZeroAsync(string tn, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_REMAINING_BALANCE SET BEFORE_REMAINING_BALANCE = REMAINING_BALANCE, REMAINING_BALANCE = 0, + LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId + WHERE TN = :Tn + """, new { UserId = userId, Tn = Truck(tn) }, ct); + + public async Task AddAsync(string tn, decimal delta, string userId, CancellationToken ct = default) => + await ExecuteAsync(""" + UPDATE REFINERY_REMAINING_BALANCE SET BEFORE_REMAINING_BALANCE = REMAINING_BALANCE, + REMAINING_BALANCE = REMAINING_BALANCE + :Delta, LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId + WHERE TN = :Tn + """, new { Delta = delta, UserId = userId, Tn = Truck(tn) }, ct) > 0; + + public Task CreateAsync(string tn, decimal balance, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO REFINERY_REMAINING_BALANCE (ID, TN, REMAINING_BALANCE, CREATION_DATE, CREATED_BY, BEFORE_REMAINING_BALANCE) + VALUES (SEQ_REFINERY_REMAINING_BALANCE.NEXTVAL, :Tn, :Balance, SYSDATE, :UserId, 0) + """, new { Tn = Truck(tn), Balance = balance, UserId = userId }, ct); + + public Task InsertLogAsync(long balanceId, decimal amount, decimal balanceBefore, long tripId, long? variableGroupId, string loginId, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO REFINERY_REMAINING_BALANCE_LOG (ID, ENTITIY_ID, AMOUNT, BALANCE_BEFORE, TRIP_ID, REF_VARIABLES_GROUP_ID, CREATED_BY, CREATION_DATE) + VALUES (SEQ_REF_REMAINING_BALANCE_LOG.NEXTVAL, :BalanceId, :Amount, :Before, :TripId, :GroupId, :LoginId, SYSDATE) + """, new { BalanceId = balanceId, Amount = amount, Before = balanceBefore, TripId = tripId, GroupId = variableGroupId, LoginId = loginId }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/TripRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/TripRepository.cs new file mode 100644 index 0000000..d159d05 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/TripRepository.cs @@ -0,0 +1,412 @@ +using System.Globalization; +using System.Text; +using Dapper; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Refinery.Trips; +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.Trips; + +/// +/// Port of refinerytripdao.cfc on REFINERY_TRIPS / REFINERY_TRIPS_VIEW (the legacy view is reused for the grid, the form and the reports: +/// it joins wallets, cards, driver, wage claim and the paid wallet). Money columns are ROUNDed to 3 decimals in SQL where ODP.NET could +/// meet a 38-digit float (CalculateRefinary* return FLOAT, REFINERY_CARDS.CURRENT_BALANCE is an unconstrained NUMBER). +/// +internal sealed class TripRepository(IDbSession session, IHttpContextAccessor http, ILogger logger) + : OracleRepositoryBase(session, logger), ITripRepository +{ + private static bool? _hasWaterFlag; + + private sealed class LockRow { public string? StatusCode { get; set; } public int DieselCharge { get; set; } } + private sealed class CardRowDb { public long Id { get; set; } public decimal CurrentBalance { get; set; } } + private sealed class VariableRow { public string KeyName { get; set; } = string.Empty; public string? KeyValue { get; set; } } + + // ------------------------------------------------------------------ filters (legacy common.getGridData on the view) + private static List SplitList(string? list) => + (list ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList(); + + private static void AddIn(StringBuilder sql, DynamicParameters p, string column, string prefix, IReadOnlyList values, bool numeric) + { + if (values.Count == 0) return; + if (numeric) + { + var nums = values.Select(v => decimal.TryParse(v, NumberStyles.Any, CultureInfo.InvariantCulture, out var d) ? (decimal?)d : null).ToList(); + if (nums.Any(n => n is null)) { sql.Append(" AND 1 = 0"); return; } + var names = new List(); + for (var i = 0; i < nums.Count; i++) { p.Add($"{prefix}{i}", nums[i]!.Value); names.Add($":{prefix}{i}"); } + sql.Append($" AND {column} IN ({string.Join(", ", names)})"); + } + else + { + var names = new List(); + for (var i = 0; i < values.Count; i++) { p.Add($"{prefix}{i}", values[i]); names.Add($":{prefix}{i}"); } + sql.Append($" AND {column} IN ({string.Join(", ", names)})"); + } + } + + private static (string Where, DynamicParameters P) Filter(TripQuery q) + { + var sql = new StringBuilder(" WHERE 1 = 1"); + var p = new DynamicParameters(); + if (q.Id is { } id) { sql.Append(" AND p.ID = :Id"); p.Add("Id", id); } + if (!string.IsNullOrWhiteSpace(q.Pn)) { sql.Append(" AND LOWER(p.PN) = LOWER(:Pn)"); p.Add("Pn", q.Pn.Trim()); } + if (!string.IsNullOrWhiteSpace(q.Tn)) { sql.Append(" AND p.TN = :Tn"); p.Add("Tn", q.Tn.Trim()); } + if (!string.IsNullOrWhiteSpace(q.Trn)) { sql.Append(" AND LOWER(p.TRN) = LOWER(:Trn)"); p.Add("Trn", q.Trn.Trim()); } + if (!string.IsNullOrWhiteSpace(q.Nnpn)) { sql.Append(" AND p.NNPN = :Nnpn"); p.Add("Nnpn", q.Nnpn.Trim()); } + if (!string.IsNullOrWhiteSpace(q.LoadingNo)) + { + if (long.TryParse(q.LoadingNo.Trim(), out var ln)) { sql.Append(" AND p.LOADING_NO = :LoadingNo"); p.Add("LoadingNo", ln); } + else sql.Append(" AND 1 = 0"); + } + if (!string.IsNullOrWhiteSpace(q.DischargeAuthNo)) { sql.Append(" AND p.DISCHARGE_AUTHORIZTION_NO = :DischargeAuthNo"); p.Add("DischargeAuthNo", q.DischargeAuthNo.Trim()); } + if (q.DispatchDate is { } dd) { sql.Append(" AND p.DISPATCH_DATE = :DispatchDate"); p.Add("DispatchDate", dd.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)); } + if (q.DischargeEntryDate is { } de) + { + sql.Append(" AND p.DISCHARGE_ENTRY_DATE >= :DeFrom AND p.DISCHARGE_ENTRY_DATE < :DeTo"); + p.Add("DeFrom", de.Date); p.Add("DeTo", de.Date.AddDays(1)); + } + if (q.LoadingDateFrom is { } lf) { sql.Append(" AND p.LOADING_DATE >= :LdFrom"); p.Add("LdFrom", lf.Date); } + if (q.LoadingDateTo is { } lt) { sql.Append(" AND p.LOADING_DATE < :LdTo"); p.Add("LdTo", lt.Date.AddDays(1)); } + if (q.PaymentedDateFrom is { } pf) { sql.Append(" AND p.PAYMENTED_DATE >= :PdFrom"); p.Add("PdFrom", pf.Date); } + if (q.PaymentedDateTo is { } pt) { sql.Append(" AND p.PAYMENTED_DATE < :PdTo"); p.Add("PdTo", pt.Date.AddDays(1)); } + AddIn(sql, p, "p.STATUS_CODE", "St", SplitList(q.StatusCode), numeric: false); + AddIn(sql, p, "p.PAYMENT_METHOD_CODE", "Pm", SplitList(q.PaymentMethodCode), numeric: true); + AddIn(sql, p, "p.DIESEL_CHARGE", "Dc", SplitList(q.DieselCharge), numeric: true); + if (!string.IsNullOrWhiteSpace(q.HasWageClaim)) { sql.Append(" AND p.HAS_WAGE_CLAIM = :HasWageClaim"); p.Add("HasWageClaim", q.HasWageClaim.Trim()); } + if (!string.IsNullOrWhiteSpace(q.HavePaymentMethod)) { sql.Append(" AND p.HAVE_PAYMENT_METHOD = :HavePm"); p.Add("HavePm", q.HavePaymentMethod.Trim()); } + if (!string.IsNullOrWhiteSpace(q.WageClaimNo)) + { + if (long.TryParse(q.WageClaimNo.Trim(), out var wn)) { sql.Append(" AND p.WAGE_CLAIM_NO = :WageClaimNo"); p.Add("WageClaimNo", wn); } + else sql.Append(" AND 1 = 0"); + } + if (q.WageClaimId is { } wid) { sql.Append(" AND p.WAGE_CLAIM_ID = :WageClaimId"); p.Add("WageClaimId", wid); } + if (!string.IsNullOrWhiteSpace(q.BankAccount)) { sql.Append(" AND LOWER(p.BANK_ACCOUNT) = LOWER(:BankAccount)"); p.Add("BankAccount", q.BankAccount.Trim()); } + if (!string.IsNullOrWhiteSpace(q.WaterExist)) + { + if (int.TryParse(q.WaterExist.Trim(), out var we)) { sql.Append(" AND p.WATER_EXIST = :WaterExist"); p.Add("WaterExist", we); } + else sql.Append(" AND 1 = 0"); + } + return (sql.ToString(), p); + } + + // ------------------------------------------------------------------ grid + private const string GridSelect = """ + SELECT p.ID AS Id, p.PN AS Pn, p.DISPATCH_DATE AS DispatchDate, p.LOADING_NO AS LoadingNo, + p.DISCHARGE_AUTHORIZTION_NO AS DischargeAuthNo, p.DISCHARGE_ENTRY_DATE_DISPLAY AS DischargeEntryDate, + p.TN AS Tn, p.TRN AS Trn, p.NNPN AS Nnpn, p.WAGE_CLAIM_ID AS WageClaimId, p.WAGE_CLAIM_NO AS WageClaimNo, + p.STATUS_CODE AS StatusCode, p.DIESEL_CHARGE AS DieselCharge, p.HAVE_PAYMENT_METHOD AS HavePaymentMethod, + p.WATER_AMOUNT AS WaterAmount, p.REVERSE_PAYMENT AS ReversePayment, p.NET_WAGE AS NetWage + FROM REFINERY_TRIPS_VIEW p + """; + + public async Task> SearchAsync(TripQuery query, PageRequest page, CancellationToken ct = default) + { + var (where, p) = Filter(query); + var sql = GridSelect + where; + var total = await ExecuteScalarAsync(OracleSql.Count(sql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(sql + " ORDER BY p.ID DESC"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + // ------------------------------------------------------------------ one trip + private const string RecordSelect = """ + SELECT t.ID AS Id, t.PN AS Pn, t.STATUS_CODE AS StatusCode, t.DISPATCH_DATE AS DispatchDate, + t.ACTUAL_LOADING_DATE AS ActualLoadingDate, t.LOADING_DATE AS LoadingDate, t.CLIENT_NAME AS ClientName, + t.TN AS Tn, t.TRN AS Trn, t.NNPN AS Nnpn, t.DRVR AS Drvr, t.LOADING_NO AS LoadingNo, + t.GROSS_WEIGHT AS GrossWeight, t.EMPTY_WEIGHT AS EmptyWeight, t.NET_LOADING_WEIGHT AS NetLoadingWeight, + t.LITERS_WEIGHT AS LitersWeight, t.DISCHARGE_AUTHORIZTION_NO AS DischargeAuthNo, + t.DISCHARGE_ENTRY_DATE_DISPLAY AS DischargeEntryDate, t.ACTUAL_GROSS_WEIGHT AS ActualGrossWeight, + t.ACTUAL_EMPTY_WEIGHT AS ActualEmptyWeight, t.NET_DISCHARGE_WEIGHT AS NetDischargeWeight, + t.WATER_AMOUNT AS WaterAmount, t.SEDIMENT_AMOUNT AS SedimentAmount, t.WEIGHT_DIIERANCE AS WeightDifference, + t.NET_WAGE AS NetWage, t.TRIP_NET_WAGE AS TripNetWage, t.REMAINING_BALANCE AS RemainingBalance, + t.DIESEL_CHARGE AS DieselCharge, t.REVERSE_PAYMENT AS ReversePayment, t.FIRST_ADVANCE_PAYMENT AS FirstAdvancePayment, + t.SECOND_ADVANCE_PAYMENT AS SecondAdvancePayment, t.PENALTY_AMOUNT AS PenaltyAmount, t.PENALTY_QUANTITY AS PenaltyQuantity, + t.HAVE_PAYMENT_METHOD AS HavePaymentMethod, t.DRIVER_WALLET_NUMBER AS DriverWalletNumber, + t.WAGE_CLAIM_ID AS WageClaimId, t.WAGE_CLAIM_NO AS WageClaimNo, t.CARD_NUMBER AS CardNumber, + ROUND(t.CURRENT_BALANCE, 3) AS CurrentBalance, t.REFINERY_WALLET_ID AS RefineryWalletId, + t.DINARAK_REFERENCE_ID AS DinarakReferenceId, t.REMARKS AS Remarks, t.RECEIVED_BY_NAME AS ReceivedByName, + t.RECEIVED_DATE AS ReceivedDate, t.PAYMENTED_DATE AS PaymentedDate, t.PAYMENT_OPTIONS AS PaymentOptions, + t.VOUCHER_SERIAL_NUMBER AS VoucherSerialNumber, t.PAID_EPAYMENT AS PaidEpayment, t.PAYMENT_METHOD AS PaymentMethod, + t.OWNER_NAME AS OwnerName + FROM REFINERY_TRIPS_VIEW t + """; + + public Task GetAsync(long id, CancellationToken ct = default) => + QueryFirstAsync(RecordSelect + " WHERE t.ID = :Id", new { Id = id }, ct); + + public async Task LockAsync(long id, CancellationToken ct = default) + { + var r = await QueryFirstAsync( + "SELECT STATUS_CODE AS StatusCode, DIESEL_CHARGE AS DieselCharge FROM REFINERY_TRIPS WHERE ID = :Id FOR UPDATE", new { Id = id }, ct); + return r is null ? null : new TripLock(r.StatusCode, r.DieselCharge); + } + + public async Task> GetTripsOfPeriodAsync(DateTime from, DateTime to, CancellationToken ct = default) => + await QueryAsync(RecordSelect + " WHERE t.LOADING_DATE >= :From AND t.LOADING_DATE < :To ORDER BY t.ID", + new { From = from.Date, To = to.Date.AddDays(1) }, ct); + + // ------------------------------------------------------------------ wallets / variables + private const string WalletSelect = """ + SELECT ID AS Id, EPAYMENT AS Epayment, WALLET_NUMBER AS WalletNumber, OWNER_NNPN AS OwnerNnpn, OWNER_NAME AS OwnerName, + DRIVER_NAME AS DriverName, DRIVER_NNPN AS DriverNnpn, BANK_ACCOUNT AS BankAccount, IBAN AS Iban, BANK_NAME AS BankName + FROM REFINERY_WALLET + """; + + public async Task GetActiveWalletByTruckAsync(string tn, CancellationToken ct = default) => + long.TryParse(tn, out var truck) + ? await QueryFirstAsync(WalletSelect + " WHERE TN = :Tn AND STATUS_CODE = 'ACTIVE' ORDER BY ID DESC", new { Tn = truck }, ct) + : null; + + public Task GetWalletAsync(long walletId, CancellationToken ct = default) => + QueryFirstAsync(WalletSelect + " WHERE ID = :Id", new { Id = walletId }, ct); + + public async Task GetAuditModeAsync(CancellationToken ct = default) + { + var v = await QueryFirstAsync( + "SELECT KEY_VALUE FROM (SELECT KEY_VALUE FROM REFINERY_VARIABLES WHERE KEY_NAME = 'AUTDIT_MODE' ORDER BY ID DESC) WHERE ROWNUM = 1", null, ct); + return v?.Trim() == "1"; + } + + public async Task GetFirstPaymentValueAsync(CancellationToken ct = default) + { + var v = await QueryFirstAsync( + "SELECT KEY_VALUE FROM (SELECT KEY_VALUE FROM REFINERY_VARIABLES WHERE KEY_NAME = 'FIRST_ADVANCE_PAYMENT' " + + "AND SYSDATE BETWEEN START_DATE AND END_DATE ORDER BY ID DESC) WHERE ROWNUM = 1", null, ct); + return decimal.TryParse(v?.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var d) ? d : null; + } + + public async Task>> GetVariablesAsync(DateTime loadingDate, CancellationToken ct = default) + { + var rows = await QueryAsync( + "SELECT KEY_NAME AS KeyName, KEY_VALUE AS KeyValue FROM REFINERY_VARIABLES WHERE :D BETWEEN START_DATE AND END_DATE ORDER BY ID", + new { D = loadingDate.Date }, ct); + return rows.Select(r => new KeyValuePair(r.KeyName, r.KeyValue)).ToList(); + } + + /// WATER_FLAG is written by the legacy import job of a newer release; this database may not have the column yet. + public async Task GetWaterFlagAsync(long id, CancellationToken ct = default) + { + _hasWaterFlag ??= await ExecuteScalarAsync( + "SELECT COUNT(*) FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'REFINERY_TRIPS' AND COLUMN_NAME = 'WATER_FLAG'", null, ct) > 0; + if (_hasWaterFlag != true) return null; + return await QueryFirstAsync("SELECT WATER_FLAG FROM REFINERY_TRIPS WHERE ID = :Id", new { Id = id }, ct); + } + + // ------------------------------------------------------------------ DB functions + private async Task FunctionAsync(string sql, long id, CancellationToken ct) + { + try { return await QueryFirstAsync(sql, new { Id = id }, ct); } + catch (OracleException ex) when (ex.Number == 1403) { return null; } // no price for the date: NO_DATA_FOUND inside the function + } + + public Task CalculateDieselAsync(long id, CancellationToken ct = default) => + FunctionAsync("SELECT ROUND(CalculateRefinaryDiesel(:Id), 3) FROM DUAL", id, ct); + + public Task CalculateAmountAsync(long id, CancellationToken ct = default) => + FunctionAsync("SELECT ROUND(CalculateRefinaryAmount(:Id), 3) FROM DUAL", id, ct); + + public async Task HasTransferLogAsync(long id, CancellationToken ct = default) => + await ExecuteScalarAsync("SELECT COUNT(*) FROM REFINERY_DINARAK_API_LOG WHERE REFINERY_TRIP_ID = :Id AND SERVICE_NAME = 'TRANSFER'", new { Id = id }, ct) > 0; + + // ------------------------------------------------------------------ diesel cards + public async Task GetActiveCardAsync(string tn, CancellationToken ct = default) + { + if (!long.TryParse(tn, out var truck)) return null; + var r = await QueryFirstAsync( + "SELECT ID AS Id, ROUND(CURRENT_BALANCE, 3) AS CurrentBalance FROM REFINERY_CARDS WHERE TN = :Tn AND STATUS_CODE = 'ACTIVE' ORDER BY ID DESC", + new { Tn = truck }, ct); + return r is null ? null : new CardInfo(r.Id, r.CurrentBalance); + } + + public Task GetLastCardLogAmountAsync(string pn, string methodName, CancellationToken ct = default) => + QueryFirstAsync( + "SELECT ROUND(AMOUNT, 3) FROM (SELECT AMOUNT FROM REFINERY_CARDS_LOG WHERE PN = :Pn AND METHOD_NAME = :Method ORDER BY ID DESC) WHERE ROWNUM = 1", + new { Pn = pn, Method = methodName }, ct); + + // CREATION_DATE has its table default (the legacy insert does not set it either) + public Task InsertCardLogAsync(long cardId, string methodName, decimal before, decimal after, decimal amount, string userId, string pn, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO REFINERY_CARDS_LOG (ID, ENTITIY_ID, METHOD_NAME, BALANCE_BEFORE, BALANCE_AFTER, AMOUNT, CREATED_BY, PN) + VALUES (SEQ_REFINERY_CARDS_LOG.NEXTVAL, :CardId, :Method, :Before, :After, :Amount, :UserId, :Pn) + """, new { CardId = cardId, Method = methodName, Before = before, After = after, Amount = amount, UserId = userId, Pn = pn }, ct); + + // the legacy update hit every card of the truck (also inactive ones); only the active card whose balance was logged is changed here + public Task UpdateCardBalanceAsync(long cardId, decimal balance, string userId, long tripId, CancellationToken ct = default) => + ExecuteAsync("UPDATE REFINERY_CARDS SET CURRENT_BALANCE = :Balance, UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId, LAST_TRIP_ID = :TripId WHERE ID = :CardId", + new { Balance = balance, UserId = userId, TripId = tripId, CardId = cardId }, ct); + + // ------------------------------------------------------------------ writes on the trip + // FIRST_ADVANCE_PAYMENT = value valid today (end_date + 1 like CalculateRefinaryDiesel; the legacy dao used end_date and stored NULL on the last day) + public Task MarkFirstAdvanceAsync(long id, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_TRIPS SET LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId, DIESEL_CHARGE = 1, REVERSE_PAYMENT = 0, + FIRST_ADVANCE_PAYMENT = (SELECT TO_NUMBER(MAX(KEY_VALUE)) FROM REFINERY_VARIABLES + WHERE KEY_NAME = 'FIRST_ADVANCE_PAYMENT' AND SYSDATE BETWEEN START_DATE AND END_DATE + 1) + WHERE ID = :Id + """, new { UserId = userId, Id = id }, ct); + + public Task MarkSecondAdvanceAsync(long id, string userId, decimal secondPaymentValue, CancellationToken ct = default) => + ExecuteAsync("UPDATE REFINERY_TRIPS SET LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId, DIESEL_CHARGE = 2, SECOND_ADVANCE_PAYMENT = :Second, REVERSE_PAYMENT = 0 WHERE ID = :Id", + new { UserId = userId, Second = secondPaymentValue, Id = id }, ct); + + public Task MarkAdvanceReversedAsync(long id, string userId, int dieselCharge, CancellationToken ct = default) => + ExecuteAsync("UPDATE REFINERY_TRIPS SET LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId, DIESEL_CHARGE = :Charge, REVERSE_PAYMENT = 1 WHERE ID = :Id", + new { UserId = userId, Charge = dieselCharge, Id = id }, ct); + + public Task SaveAmountsAsync(long id, string userId, TripAmounts a, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_TRIPS SET LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId, + TRIP_NET_WAGE = :TripNetWage, REMAINING_BALANCE = :RemainingBalance, NET_WAGE = :NetWage, + PENALTY_AMOUNT = :PenaltyAmount, PENALTY_QUANTITY = :PenaltyQuantity, QUANTITY_WAGE = :QuantityWage, + TOLERANCE_QUANTITY = :ToleranceQuantity, TON_WAGE = :TonWage, CALCULATED_QUANTITY_TON = :CalculatedQuantityTon, + TON_PRICE = :TonPrice, DRIVER_TIP = :DriverTip, PERMIT_DISPATCH = :PermitDispatch, WAYBILL_FEE = :WaybillFee, + COMMISSION = :Commission, FIRST_ADVANCE_PAYMENT = :FirstAdvancePayment, SECOND_ADVANCE_PAYMENT = :SecondAdvancePayment, + DIESEL_LITER_PRICE = :DieselLiterPrice + WHERE ID = :Id + """, new + { + UserId = userId, Id = id, a.TripNetWage, a.RemainingBalance, a.NetWage, a.PenaltyAmount, a.PenaltyQuantity, a.QuantityWage, + a.ToleranceQuantity, a.TonWage, a.CalculatedQuantityTon, a.TonPrice, a.DriverTip, a.PermitDispatch, a.WaybillFee, + a.Commission, a.FirstAdvancePayment, a.SecondAdvancePayment, a.DieselLiterPrice + }, ct); + + public Task SetStatusReceivedAsync(long id, string userId, string status, CancellationToken ct = default) => + ExecuteAsync("UPDATE REFINERY_TRIPS SET STATUS_CODE = :Status, LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId, RECEIVED_BY = :UserId, RECEIVED_DATE = SYSDATE WHERE ID = :Id", + new { Status = status, UserId = userId, Id = id }, ct); + + public Task MarkExchangedAsync(long id, string userId, string? remarks, string? paymentOptions, bool setReceived, long? walletId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_TRIPS SET STATUS_CODE = 'EXCHANGED', LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId, + PAYMENTED_BY = :UserId, PAYMENTED_DATE = SYSDATE, + REMARKS = NVL(:Remarks, REMARKS), + RECEIVED_BY = CASE WHEN :SetReceived = 1 THEN :UserId ELSE RECEIVED_BY END, + RECEIVED_DATE = CASE WHEN :SetReceived = 1 THEN SYSDATE ELSE RECEIVED_DATE END, + PAYMENT_OPTIONS = NVL(:PaymentOptions, PAYMENT_OPTIONS), + REFINERY_WALLET_ID = NVL(:WalletId, REFINERY_WALLET_ID) + WHERE ID = :Id + """, new { UserId = userId, Remarks = remarks, SetReceived = OracleSql.ToNumber(setReceived), PaymentOptions = paymentOptions, WalletId = walletId, Id = id }, ct); + + public async Task BumpDinarakReferenceAsync(long id, string userId, CancellationToken ct = default) + { + await ExecuteAsync("UPDATE REFINERY_TRIPS SET DINARAK_REFERENCE_ID = DINARAK_REFERENCE_ID + 0.01 WHERE ID = :Id", new { Id = id }, ct); + return await ExecuteScalarAsync("SELECT DINARAK_REFERENCE_ID FROM REFINERY_TRIPS WHERE ID = :Id", new { Id = id }, ct); + } + + public Task SetVoucherSerialAsync(long id, long serial, CancellationToken ct = default) => + ExecuteAsync("UPDATE REFINERY_TRIPS SET VOUCHER_SERIAL_NUMBER = :Serial WHERE ID = :Id", new { Serial = serial, Id = id }, ct); + + // dao CONFIRM_EXCHANGE (refinerytripdao.cfc:94-132); user / date fall back to the caller / now when no EXCHANGE log row exists + public Task ConfirmExchangeAsync(long id, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_TRIPS R SET + R.STATUS_CODE = 'EXCHANGED', R.LAST_UPDATE_DATE = SYSDATE, R.UPDATED_BY = :UserId, + R.REFINERY_WALLET_ID = NVL((SELECT MAX(W.ID) FROM REFINERY_WALLET W + WHERE W.STATUS_CODE = 'ACTIVE' + AND W.TN = (SELECT TO_NUMBER(TN) FROM REFINERY_TRIPS WHERE ID = :Id) + AND W.WALLET_NUMBER = (SELECT EWALLET_NUMBER FROM + (SELECT D.EWALLET_NUMBER FROM REFINERY_DINARAK_API_LOG D + WHERE D.REFINERY_TRIP_ID = :Id ORDER BY D.ID DESC) WHERE ROWNUM = 1)), + R.REFINERY_WALLET_ID), + R.RECEIVED_BY = NVL((SELECT USER_ID FROM (SELECT L.USER_ID FROM REFINERY_TRIPS_LOG L + WHERE L.ENTITIY_ID = :Id AND L.METHOD_NAME = 'EXCHANGE' ORDER BY L.ID DESC) WHERE ROWNUM = 1), :UserId), + R.PAYMENTED_BY = NVL((SELECT USER_ID FROM (SELECT L.USER_ID FROM REFINERY_TRIPS_LOG L + WHERE L.ENTITIY_ID = :Id AND L.METHOD_NAME = 'EXCHANGE' ORDER BY L.ID DESC) WHERE ROWNUM = 1), :UserId), + R.RECEIVED_DATE = NVL((SELECT LOG_DATE FROM (SELECT L.LOG_DATE FROM REFINERY_TRIPS_LOG L + WHERE L.ENTITIY_ID = :Id AND L.METHOD_NAME = 'EXCHANGE' ORDER BY L.ID DESC) WHERE ROWNUM = 1), SYSDATE), + R.PAYMENTED_DATE = NVL((SELECT LOG_DATE FROM (SELECT L.LOG_DATE FROM REFINERY_TRIPS_LOG L + WHERE L.ENTITIY_ID = :Id AND L.METHOD_NAME = 'EXCHANGE' ORDER BY L.ID DESC) WHERE ROWNUM = 1), SYSDATE) + WHERE R.ID = :Id + """, new { UserId = userId, Id = id }, ct); + + // ------------------------------------------------------------------ history (REFINERY_TRIPS_LOG) + public Task InsertLogAsync(long tripId, string methodName, string userId, string oldJson, string newJson, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO REFINERY_TRIPS_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, USER_ID, USER_IP, OLD_DATA, NEW_DATA) + VALUES (SEQ_REFINERY_TRIPS_LOG.NEXTVAL, :TripId, :Method, SYSDATE, :UserId, :Ip, :OldData, :NewData) + """, new + { + TripId = tripId, Method = methodName, UserId = userId, + Ip = http.HttpContext?.Connection.RemoteIpAddress?.ToString(), OldData = oldJson, NewData = newJson + }, ct); + + public async Task> SearchLogAsync(long tripId, PageRequest page, CancellationToken ct = default) + { + const string select = """ + SELECT t.ID AS Id, t.METHOD_NAME AS MethodName, TO_CHAR(t.LOG_DATE, 'dd/mm/yyyy HH24:MI') AS LogDate, n.LOGIN AS Login, + DBMS_LOB.SUBSTR(t.OLD_DATA, 4000, 1) AS OldData, DBMS_LOB.SUBSTR(t.NEW_DATA, 4000, 1) AS NewData + FROM REFINERY_TRIPS_LOG t, NTP.NTPUSERS n + WHERE t.ENTITIY_ID = :TripId AND t.USER_ID = TO_CHAR(n.ID(+)) + """; + var p = new DynamicParameters(); + p.Add("TripId", tripId); + var total = await ExecuteScalarAsync(OracleSql.Count(select), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(select + " ORDER BY t.ID DESC"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + // ------------------------------------------------------------------ reports + private const string ReportSelect = """ + SELECT p.ID AS Id, p.PN AS Pn, p.DISPATCH_DATE AS DispatchDate, p.LOADING_NO AS LoadingNo, + p.DISCHARGE_AUTHORIZTION_NO AS DischargeAuthNo, p.DISCHARGE_ENTRY_DATE_DISPLAY AS DischargeEntryDate, + p.NET_LOADING_WEIGHT AS NetLoadingWeight, p.NET_DISCHARGE_WEIGHT AS NetDischargeWeight, + p.TN AS Tn, p.TRN AS Trn, p.NNPN AS Nnpn, ROUND(p.CURRENT_BALANCE, 3) AS CurrentBalance, + p.DIESEL_CHARGE AS DieselCharge, p.NET_WAGE AS NetWage, p.TRIP_NET_WAGE AS TripNetWage, + p.REMAINING_BALANCE AS RemainingBalance, p.STATUS_CODE AS StatusCode, p.WAGE_CLAIM_NO AS WageClaimNo, + p.PAYMENTED_DATE AS PaymentedDate, p.RECEIVED_DATE AS ReceivedDate, p.RECEIVED_BY_NAME AS ReceivedByName, + p.ACTUAL_LOADING_DATE AS ActualLoadingDate, p.PAYMENT_METHOD AS PaymentMethod, p.PAID_EPAYMENT AS PaidEpayment, + p.PAYMENT_OPTIONS AS PaymentOptions, p.OWNER_NAME AS OwnerName, p.OWNER_NAME_ENGLISH AS OwnerNameEnglish, + p.BANK_NAME AS BankName, p.IBAN AS Iban, p.BANK_ACCOUNT AS BankAccount, p.WALLET_NUMBER AS WalletNumber, + p.OWNER_NNPN AS OwnerNnpn + FROM REFINERY_TRIPS_VIEW p + """; + + public async Task> ReportAsync(TripQuery query, CancellationToken ct = default) + { + var (where, p) = Filter(query); + return await QueryAsync(ReportSelect + where + " ORDER BY p.ID", p, ct); + } + + public async Task> BankReportAsync(BankReportQuery q, CancellationToken ct = default) + { + var (where, p) = Filter(new TripQuery(BankAccount: q.BankAccount, StatusCode: q.StatusCode, HasWageClaim: q.HasWageClaim, + PaymentedDateFrom: q.PaymentedDateFrom, PaymentedDateTo: q.PaymentedDateTo)); + return await QueryAsync(ReportSelect + where + " ORDER BY p.ID", p, ct); + } + + public async Task> DieselReportAsync(DieselReportQuery q, CancellationToken ct = default) + { + var sql = new StringBuilder(""" + SELECT p.ID AS Id, p.PN AS Pn, p.TN AS Tn, p.STATUS_CODE AS StatusCode, p.DISCHARGE_AUTHORIZTION_NO AS DischargeAuthNo, + p.CREATION_DATE AS CreationDate, p.FIRSTNAME AS FirstName, p.METHOD_NAME AS MethodName, + ROUND(p.BALANCE_BEFORE, 3) AS BalanceBefore, ROUND(p.BALANCE_AFTER, 3) AS BalanceAfter, ROUND(p.AMOUNT, 3) AS Amount + FROM REFINERY_DIESEL_REPORT_VIEW p WHERE 1 = 1 + """); + var p = new DynamicParameters(); + if (!string.IsNullOrWhiteSpace(q.Pn)) { sql.Append(" AND LOWER(p.PN) = LOWER(:Pn)"); p.Add("Pn", q.Pn.Trim()); } + if (!string.IsNullOrWhiteSpace(q.Tn)) { sql.Append(" AND p.TN = :Tn"); p.Add("Tn", q.Tn.Trim()); } + if (!string.IsNullOrWhiteSpace(q.DischargeAuthNo)) { sql.Append(" AND p.DISCHARGE_AUTHORIZTION_NO = :Da"); p.Add("Da", q.DischargeAuthNo.Trim()); } + AddIn(sql, p, "p.STATUS_CODE", "St", SplitList(q.StatusCode), numeric: false); + AddIn(sql, p, "p.DIESEL_CHARGE", "Dc", SplitList(q.DieselCharge), numeric: true); + if (q.DateFrom is { } f) { sql.Append(" AND p.CREATION_DATE >= :DFrom"); p.Add("DFrom", f.Date); } + if (q.DateTo is { } t) { sql.Append(" AND p.CREATION_DATE < :DTo"); p.Add("DTo", t.Date.AddDays(1)); } + sql.Append(" ORDER BY p.CREATION_DATE, p.ID"); + return await QueryAsync(sql.ToString(), p, ct); + } + + public async Task> CardsAsync(string? tn, CancellationToken ct = default) + { + const string select = "SELECT ID AS Id, TN AS Tn, CARD_NUMBER AS CardNumber, ROUND(CURRENT_BALANCE, 3) AS CurrentBalance FROM REFINERY_CARDS"; + if (tn is null) return await QueryAsync(select + " WHERE STATUS_CODE = 'ACTIVE' ORDER BY TN", null, ct); + return long.TryParse(tn, out var truck) + ? await QueryAsync(select + " WHERE TN = :Tn ORDER BY ID", new { Tn = truck }, ct) + : []; + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/TripSettingsService.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/TripSettingsService.cs new file mode 100644 index 0000000..3b7cf10 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/TripSettingsService.cs @@ -0,0 +1,16 @@ +using Microsoft.Extensions.Configuration; +using NTP.Application.Refinery.Trips; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.Trips; + +/// Binds configuration section "Refinery:Trips" (see ). +internal sealed class TripSettingsService : ITripSettingsService +{ + public TripSettingsService(IConfiguration configuration) + { + Value = new TripOptions(); + configuration.GetSection(TripOptions.SectionName).Bind(Value); + } + + public TripOptions Value { get; } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/VoucherSerialRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/VoucherSerialRepository.cs new file mode 100644 index 0000000..1e8d9c9 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Trips/VoucherSerialRepository.cs @@ -0,0 +1,21 @@ +using System.Globalization; +using Microsoft.Extensions.Logging; +using NTP.Application.Abstractions; +using NTP.Application.Refinery.Trips; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.Trips; + +/// Port of common.GenerateSerialNumber('VOUCHER'): NTP.SYSTEM_VARIABLES VOUCHER_SERIAL_NO, number = {yyyy}{seq 5 digits} (e.g. 202200095). +internal sealed class VoucherSerialRepository(INtpDbSession session, INtpUnitOfWork unitOfWork, ILogger logger) + : NtpRepositoryBase(session, logger), IVoucherSerialRepository +{ + public Task NextAsync(CancellationToken ct = default) => unitOfWork.ExecuteInTransactionAsync(async c => + { + // FOR UPDATE: two operators printing at the same time must not get the same number (the legacy code could) + var current = await ExecuteScalarAsync("SELECT TO_NUMBER(VALUE) FROM SYSTEM_VARIABLES WHERE NAME = 'VOUCHER_SERIAL_NO' FOR UPDATE", null, c); + await ExecuteAsync("UPDATE SYSTEM_VARIABLES SET VALUE = :Value WHERE NAME = 'VOUCHER_SERIAL_NO'", + new { Value = (current + 1).ToString(CultureInfo.InvariantCulture) }, c); + return long.Parse(DateTime.Now.Year.ToString(CultureInfo.InvariantCulture) + current.ToString("D5", CultureInfo.InvariantCulture), + CultureInfo.InvariantCulture); + }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Variables/VariablesRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Variables/VariablesRepository.cs new file mode 100644 index 0000000..6f0742d --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Variables/VariablesRepository.cs @@ -0,0 +1,192 @@ +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Refinery.Variables; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.Variables; + +/// +/// REFINERY_VARIABLES (key / value rows grouped by GROUP_ID) of refinery_variablesdao.cfc. The grid pivots the rows like the legacy +/// REFINERY_VARIABLES_VIEW (docs/refinery-db-objects.txt) but also returns the ton price correction. +/// +internal sealed class VariablesRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IVariablesRepository +{ + /// KEY_VALUE is text; parse it with '.' as decimal separator whatever the session NLS is. + private static string Num(string key) => + $"MAX(CASE WHEN KEY_NAME = '{key}' THEN TO_NUMBER(TRIM(KEY_VALUE), '999999999990D9999999', 'NLS_NUMERIC_CHARACTERS=''.,''') END)"; + + private static readonly string PivotSql = $""" + SELECT GROUP_ID AS GroupId, MIN(START_DATE) AS StartDate, MIN(END_DATE) AS EndDate, + {Num("DIESEL_LITER_PRICE")} AS DieselLiterPrice, {Num("TON_WAGE")} AS TonWage, {Num("TON_PRICE")} AS TonPrice, + {Num("DRIVER_TIP")} AS DriverTip, {Num("PERMIT_DISPATCH")} AS PermitDispatch, {Num("WAYBILL_FEE")} AS WaybillFee, + {Num("COMMISSION")} AS Commission, {Num("TOLERANCE_PERCENTAGE")} AS TolerancePercentage, + {Num("FIRST_ADVANCE_PAYMENT")} AS FirstAdvancePayment, {Num("TON_PRICE_CORRECTION")} AS TonPriceCorrection, + MAX(CASE WHEN KEY_NAME = 'TON_PRICE_CORRECTION_SET' AND TRIM(KEY_VALUE) = '1' THEN 1 ELSE 0 END) AS TonPriceCorrectionSet + FROM REFINERY_VARIABLES + WHERE GROUP_ID IS NOT NULL AND KEY_NAME <> 'AUTDIT_MODE' + GROUP BY GROUP_ID + """; + + private sealed class SetRowDb + { + public long GroupId { get; set; } + public DateTime? StartDate { get; set; } + public DateTime? EndDate { get; set; } + public decimal? DieselLiterPrice { get; set; } + public decimal? TonWage { get; set; } + public decimal? TonPrice { get; set; } + public decimal? DriverTip { get; set; } + public decimal? PermitDispatch { get; set; } + public decimal? WaybillFee { get; set; } + public decimal? Commission { get; set; } + public decimal? TolerancePercentage { get; set; } + public decimal? FirstAdvancePayment { get; set; } + public decimal? TonPriceCorrection { get; set; } + public long TonPriceCorrectionSet { get; set; } + + public VariablesSetRow ToRow() => new() + { + GroupId = GroupId, StartDate = StartDate, EndDate = EndDate, DieselLiterPrice = DieselLiterPrice, TonWage = TonWage, + TonPrice = TonPrice, DriverTip = DriverTip, PermitDispatch = PermitDispatch, WaybillFee = WaybillFee, + Commission = Commission, TolerancePercentage = TolerancePercentage, FirstAdvancePayment = FirstAdvancePayment, + TonPriceCorrection = TonPriceCorrection, TonPriceCorrectionSet = TonPriceCorrectionSet == 1, + }; + } + + public async Task> SearchAsync(VariablesQuery query, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE 1 = 1"); + var p = new DynamicParameters(); + // legacy: both dates = periods starting inside the range, one date = exact match on that column + if (query.StartDate is { } s && query.EndDate is { } e) + { + where.Append(" AND g.StartDate >= :FromDay AND g.StartDate < :ToDayExcl"); + p.Add("FromDay", s.ToDateTime(TimeOnly.MinValue)); + p.Add("ToDayExcl", e.ToDateTime(TimeOnly.MinValue).AddDays(1)); + } + else if (query.StartDate is { } s1) + { + where.Append(" AND g.StartDate >= :StartDay AND g.StartDate < :StartDayExcl"); + p.Add("StartDay", s1.ToDateTime(TimeOnly.MinValue)); + p.Add("StartDayExcl", s1.ToDateTime(TimeOnly.MinValue).AddDays(1)); + } + else if (query.EndDate is { } e1) + { + where.Append(" AND g.EndDate >= :EndDay AND g.EndDate < :EndDayExcl"); + p.Add("EndDay", e1.ToDateTime(TimeOnly.MinValue)); + p.Add("EndDayExcl", e1.ToDateTime(TimeOnly.MinValue).AddDays(1)); + } + var baseSql = $"SELECT g.* FROM ({PivotSql}) g{where}"; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY g.GroupId DESC"), p, ct); + return new PagedResult(items.Select(i => i.ToRow()).ToList(), page.SafePage, page.SafePageSize, total); + } + + public async Task GetAsync(long groupId, CancellationToken ct = default) + { + var row = await QueryFirstAsync($"SELECT g.* FROM ({PivotSql}) g WHERE g.GroupId = :GroupId ORDER BY g.StartDate", new { GroupId = groupId }, ct); + return row?.ToRow(); + } + + private sealed class PeriodDb + { + public long GroupId { get; set; } + public DateTime? StartDate { get; set; } + public DateTime? EndDate { get; set; } + } + + public async Task> GetPeriodsAsync(long? excludeGroupId, CancellationToken ct = default) + { + var exclude = excludeGroupId is null ? string.Empty : " AND GROUP_ID <> :ExcludeId"; + var rows = await QueryAsync($""" + SELECT GROUP_ID AS GroupId, START_DATE AS StartDate, END_DATE AS EndDate + FROM REFINERY_VARIABLES + WHERE KEY_NAME <> 'AUTDIT_MODE' AND GROUP_ID IS NOT NULL AND START_DATE IS NOT NULL AND END_DATE IS NOT NULL{exclude} + GROUP BY GROUP_ID, START_DATE, END_DATE + """, excludeGroupId is null ? null : new { ExcludeId = excludeGroupId.Value }, ct); + return rows.Select(r => new VariablesPeriod(r.GroupId, r.StartDate!.Value, r.EndDate!.Value)).ToList(); + } + + public async Task HasTripsAsync(DateTime start, DateTime end, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM (SELECT 1 FROM REFINERY_TRIPS WHERE ACTUAL_LOADING_DATE BETWEEN :StartDate AND :EndDate AND ROWNUM = 1) + """, new { StartDate = start, EndDate = end }, ct) > 0; + + public async Task GetTripsOfPeriodAsync(DateTime start, DateTime end, CancellationToken ct = default) + { + // legacy reads REFINERY_TRIPS_VIEW (same STATUS_CODE / PENALTY_AMOUNT columns as the table) with to_date(ACTUAL_LOADING_DATE) between + var row = await QueryFirstAsync(""" + SELECT COUNT(*) AS TripCount, + NVL(SUM(CASE WHEN STATUS_CODE IN ('READY_TO_PAY','PENDING_EXCHANGE','DISCHARGING','LOADED','RESD','ARRIVE_LOCATION') THEN 1 ELSE 0 END), 0) AS NotExchangedCount, + NVL(SUM(CASE WHEN PENALTY_AMOUNT > 0 THEN 1 ELSE 0 END), 0) AS PenaltyTripCount + FROM REFINERY_TRIPS + WHERE TRUNC(ACTUAL_LOADING_DATE) BETWEEN TRUNC(:StartDate) AND TRUNC(:EndDate) + """, new { StartDate = start, EndDate = end }, ct); + return new TripsOfPeriodInfo { TripCount = row?.TripCount ?? 0, NotExchangedCount = row?.NotExchangedCount ?? 0, PenaltyTripCount = row?.PenaltyTripCount ?? 0 }; + } + + private sealed class TripsOfPeriodDb + { + public long TripCount { get; set; } + public long NotExchangedCount { get; set; } + public long PenaltyTripCount { get; set; } + } + + public Task NextGroupIdAsync(CancellationToken ct = default) => + ExecuteScalarAsync("SELECT SEQ_REFINERY_VARIABLES_GID.NEXTVAL FROM DUAL", null, ct); + + private Task InsertRowAsync(long groupId, string key, string value, DateTime start, DateTime end, string createdBy, CancellationToken ct) => + ExecuteAsync(""" + INSERT INTO REFINERY_VARIABLES (ID, KEY_NAME, KEY_VALUE, CREATION_DATE, CREATED_BY, START_DATE, END_DATE, GROUP_ID) + VALUES (SEQ_REFINERY_VARIABLES.NEXTVAL, :KeyName, :KeyValue, SYSDATE, :CreatedBy, :StartDate, :EndDate, :GroupId) + """, new { KeyName = key, KeyValue = value, CreatedBy = createdBy, StartDate = start, EndDate = end, GroupId = groupId }, ct); + + public async Task InsertSetAsync(long groupId, DateOnly start, DateOnly end, IReadOnlyDictionary values, string createdBy, CancellationToken ct = default) + { + var s = start.ToDateTime(TimeOnly.MinValue); + var e = end.ToDateTime(TimeOnly.MinValue); + foreach (var (key, value) in values) await InsertRowAsync(groupId, key, value, s, e, createdBy, ct); + } + + public async Task UpdateSetAsync(long groupId, DateOnly start, DateOnly end, IReadOnlyDictionary values, string updatedBy, CancellationToken ct = default) + { + var s = start.ToDateTime(TimeOnly.MinValue); + var e = end.ToDateTime(TimeOnly.MinValue); + foreach (var (key, value) in values) + { + var n = await ExecuteAsync(""" + UPDATE REFINERY_VARIABLES + SET KEY_VALUE = :KeyValue, UPDATE_DATE = SYSDATE, UPDATED_BY = :UpdatedBy, START_DATE = :StartDate, END_DATE = :EndDate + WHERE GROUP_ID = :GroupId AND KEY_NAME = :KeyName + """, new { KeyValue = value, UpdatedBy = updatedBy, StartDate = s, EndDate = e, GroupId = groupId, KeyName = key }, ct); + // legacy only updated existing rows; a key missing from the group is created so the period stays complete + if (n == 0) await InsertRowAsync(groupId, key, value, s, e, updatedBy, ct); + } + // the correction rows belong to the same period: keep their dates equal (legacy left them with the old dates) + await ExecuteAsync(""" + UPDATE REFINERY_VARIABLES SET START_DATE = :StartDate, END_DATE = :EndDate + WHERE GROUP_ID = :GroupId AND KEY_NAME IN ('TON_PRICE_CORRECTION', 'TON_PRICE_CORRECTION_SET') + """, new { StartDate = s, EndDate = e, GroupId = groupId }, ct); + } + + public async Task SetTonPriceCorrectionAsync(long groupId, string value, DateTime start, DateTime end, string userId, CancellationToken ct = default) + { + foreach (var (key, v) in new[] { (VariablesRules.TonPriceCorrectionKey, value), (VariablesRules.TonPriceCorrectionSetKey, "1") }) + { + var n = await ExecuteAsync(""" + UPDATE REFINERY_VARIABLES SET KEY_VALUE = :KeyValue, UPDATE_DATE = SYSDATE, UPDATED_BY = :UpdatedBy + WHERE GROUP_ID = :GroupId AND KEY_NAME = :KeyName + """, new { KeyValue = v, UpdatedBy = userId, GroupId = groupId, KeyName = key }, ct); + if (n == 0) await InsertRowAsync(groupId, key, v, start, end, userId, ct); + } + } + + public async Task> GetRemainingBalancesAsync(CancellationToken ct = default) => + await QueryAsync( + "SELECT ID AS Id, TN AS Tn, REMAINING_BALANCE AS RemainingBalance FROM REFINERY_REMAINING_BALANCE ORDER BY REMAINING_BALANCE DESC, ID", null, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/WageClaims/WageClaimRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/WageClaims/WageClaimRepository.cs new file mode 100644 index 0000000..3800a1f --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/WageClaims/WageClaimRepository.cs @@ -0,0 +1,221 @@ +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Refinery.WageClaims; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.WageClaims; + +/// Dapper port of refinery_wage_claimdao.cfc and the SQL of refinery_wage_claimfactory.cfc (NAFITHTCS connection). +internal sealed class WageClaimRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IWageClaimRepository +{ + // REFINERY_WAGE_CLAIM_VIEW: claim + trip count + the commission claim number + private const string ClaimSelect = """ + SELECT w.ID AS Id, w.WAGE_CLAIM_NO AS WageClaimNo, w.WAGE_CLAIM_DATE AS WageClaimDate, w.STATUS_CODE AS StatusCode, + w.COMMISSION_CLAIM_ID AS CommissionClaimId, c.COMMISSION_CLAIM_NO AS CommissionClaimNo, + (SELECT COUNT(*) FROM REFINERY_TRIPS t WHERE t.WAGE_CLAIM_ID = w.ID) AS TripCnt + FROM REFINERY_WAGE_CLAIM w + LEFT JOIN REFINERY_COMMISSION_CLAIM c ON c.ID = w.COMMISSION_CLAIM_ID + """; + + // columns of the trips grid inside a claim (searchClaimTrips): PN, payment date, loading no, form no / date, TN, TRN, NNPN, status + private const string TripSelect = """ + SELECT t.ID AS Id, t.PN AS Pn, t.PAYMENTED_DATE AS PaymentedDate, t.LOADING_NO AS LoadingNo, + t.DISCHARGE_AUTHORIZTION_NO AS DischargeAuthoriztionNo, t.DISCHARGE_ENTRY_DATE AS DischargeEntryDate, + t.TN AS Tn, t.TRN AS Trn, t.NNPN AS Nnpn, t.STATUS_CODE AS StatusCode + FROM REFINERY_TRIPS t + """; + + public async Task> SearchAsync(WageClaimQuery q, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE 1 = 1"); + var p = new DynamicParameters(); + if (!string.IsNullOrWhiteSpace(q.WageClaimNo)) { where.Append(" AND TO_CHAR(w.WAGE_CLAIM_NO) = :No"); p.Add("No", q.WageClaimNo.Trim()); } + if (q.WageClaimDate is { } d) + { + where.Append(" AND w.WAGE_CLAIM_DATE >= :DayFrom AND w.WAGE_CLAIM_DATE < :DayTo"); + p.Add("DayFrom", d.ToDateTime(TimeOnly.MinValue)); + p.Add("DayTo", d.AddDays(1).ToDateTime(TimeOnly.MinValue)); + } + if (q.StatusCodes.Count > 0) where.Append(" AND w.STATUS_CODE IN (").Append(AddList(p, "St", q.StatusCodes)).Append(')'); + if (!string.IsNullOrWhiteSpace(q.CommissionClaimNo)) { where.Append(" AND TO_CHAR(c.COMMISSION_CLAIM_NO) = :CNo"); p.Add("CNo", q.CommissionClaimNo.Trim()); } + if (q.HasCommissionClaim is { } has) where.Append(has ? " AND w.COMMISSION_CLAIM_ID IS NOT NULL" : " AND w.COMMISSION_CLAIM_ID IS NULL"); + + var baseSql = ClaimSelect + where; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + // legacy sort: WAGE_CLAIM_NO ASC + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY w.WAGE_CLAIM_NO, w.ID"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public Task GetAsync(long id, CancellationToken ct = default) => + QueryFirstAsync(ClaimSelect + " WHERE w.ID = :Id", new { Id = id }, ct); + + public async Task> ClaimTripsAsync(long claimId, PageRequest page, CancellationToken ct = default) + { + var p = new DynamicParameters(); + p.Add("ClaimId", claimId); + var baseSql = TripSelect + " WHERE t.WAGE_CLAIM_ID = :ClaimId"; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY t.ID"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + /// + /// WHERE of the trips a new claim takes (legacy: status in (...), WAGE_CLAIM_ID null, PAYMENTED_DATE_STRING between FROM000000 and TO235959; + /// that view column is DateToString(ACTUAL_LOADING_DATE), so it is the loading date). + /// + private static string CandidateWhere(DynamicParameters p, IReadOnlyList statuses, DateOnly? from, DateOnly? to) + { + var w = new StringBuilder(" WHERE t.STATUS_CODE IN (").Append(AddList(p, "Ts", statuses)).Append(") AND t.WAGE_CLAIM_ID IS NULL"); + if (from is { } f) { w.Append(" AND t.ACTUAL_LOADING_DATE >= :LoadFrom"); p.Add("LoadFrom", f.ToDateTime(TimeOnly.MinValue)); } + if (to is { } t) { w.Append(" AND t.ACTUAL_LOADING_DATE < :LoadTo"); p.Add("LoadTo", WageClaimRules.ExclusiveEnd(t)); } + return w.ToString(); + } + + public async Task> CandidateTripsAsync(IReadOnlyList statuses, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct = default) + { + var p = new DynamicParameters(); + var baseSql = TripSelect + CandidateWhere(p, statuses, from, to); + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY t.ID"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public Task CountCandidateTripsAsync(IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default) + { + var p = new DynamicParameters(); + return ExecuteScalarAsync("SELECT COUNT(*) FROM REFINERY_TRIPS t" + CandidateWhere(p, statuses, from, to), p, ct); + } + + public async Task InsertClaimAsync(string createdBy, CancellationToken ct = default) + { + // serial numbers are taken while this table is locked, so two claims created at the same time never get the same number + await ExecuteAsync("LOCK TABLE REFINERY_WAGE_CLAIM IN SHARE ROW EXCLUSIVE MODE", null, ct); + var id = await ExecuteScalarAsync("SELECT SEQ_REFINERY_WAGE_CLAIM.NEXTVAL FROM DUAL", null, ct); + // GenerateSerialNumber('REFINERY_WAGE_CLAIM'): yyyy + '01' + 5 digits for the first claim of the year, then max + 1 + await ExecuteAsync(""" + INSERT INTO REFINERY_WAGE_CLAIM (ID, WAGE_CLAIM_NO, STATUS_CODE, CREATED_BY) + SELECT :Id, + NVL(MAX(t.WAGE_CLAIM_NO) + 1, TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY') || '01' || '00001')), + 'NEW', :CreatedBy + FROM REFINERY_WAGE_CLAIM t + WHERE TO_CHAR(t.WAGE_CLAIM_DATE, 'yyyy') = TO_CHAR(SYSDATE, 'YYYY') + """, new { Id = id, CreatedBy = createdBy }, ct); + return id; + } + + public Task AttachTripsAsync(long claimId, IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default) + { + var p = new DynamicParameters(); + p.Add("ClaimId", claimId); + return ExecuteAsync("UPDATE REFINERY_TRIPS t SET t.WAGE_CLAIM_ID = :ClaimId" + CandidateWhere(p, statuses, from, to), p, ct); + } + + public async Task> ClaimTripStatusesAsync(long claimId, CancellationToken ct = default) => + await QueryAsync("SELECT DISTINCT STATUS_CODE FROM REFINERY_TRIPS WHERE WAGE_CLAIM_ID = :ClaimId", new { ClaimId = claimId }, ct); + + public async Task CompleteClaimTripsAsync(long claimId, string userLogin, long userId, string? ip, CancellationToken ct = default) + { + // logs.saveLog(session, 'REFINERYTRIP', 'TRIP_COMPLETE', ...): old/new status captions, ids from SEQ_REFINERY_TRIPS_LOG + await ExecuteAsync(""" + INSERT INTO REFINERY_TRIPS_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, USER_ID, USER_IP, OLD_DATA, NEW_DATA) + SELECT SEQ_REFINERY_TRIPS_LOG.NEXTVAL, t.ID, 'TRIP_COMPLETE', SYSDATE, :UserId, :Ip, :OldData, :NewData + FROM REFINERY_TRIPS t WHERE t.WAGE_CLAIM_ID = :ClaimId + """, new + { + UserId = userId.ToString(System.Globalization.CultureInfo.InvariantCulture), Ip = Cut(ip, 50), ClaimId = claimId, + OldData = ClaimLogJson.Status(ClaimMessages.TripExchanged), NewData = ClaimLogJson.Status(ClaimMessages.TripComplete), + }, ct); + return await ExecuteAsync(""" + UPDATE REFINERY_TRIPS SET STATUS_CODE = 'COMPLETE', LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserLogin + WHERE WAGE_CLAIM_ID = :ClaimId + """, new { UserLogin = userLogin, ClaimId = claimId }, ct); + } + + public Task SetClaimStatusAsync(long claimId, string status, string userLogin, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_WAGE_CLAIM SET STATUS_CODE = :Status, LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserLogin WHERE ID = :Id + """, new { Status = status, UserLogin = userLogin, Id = claimId }, ct); + + public async Task> TripsToTransferAsync(long claimId, CancellationToken ct = default) => + await QueryAsync(""" + SELECT ID AS Id, PN AS Pn, STATUS_CODE AS StatusCode FROM REFINERY_TRIPS + WHERE WAGE_CLAIM_ID = :ClaimId AND TRIP_STATUS = '6' ORDER BY ID + """, new { ClaimId = claimId }, ct); + + public async Task MarkTripTransferredAsync(TransferTripRow trip, long userId, string? ip, CancellationToken ct = default) + { + await ExecuteAsync("UPDATE REFINERY_TRIPS SET TRIP_STATUS = '7' WHERE ID = :Id", new { trip.Id }, ct); + await ExecuteAsync(""" + INSERT INTO REFINERY_TRIPS_LOG (ID, ENTITIY_ID, METHOD_NAME, STATUS_CODE, OLD_DATA, NEW_DATA, TRIP_STATUS, USER_ID, USER_IP) + VALUES (SEQ_REFINERY_TRIPS_LOG.NEXTVAL, :Id, 'TRANSFER_TO_REFINERY', :StatusCode, NULL, NULL, '7', :UserId, :Ip) + """, new { trip.Id, trip.StatusCode, UserId = userId.ToString(System.Globalization.CultureInfo.InvariantCulture), Ip = Cut(ip, 50) }, ct); + } + + public Task AddLogAsync(long claimId, string method, string? oldData, string? newData, long userId, string? ip, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO REFINERY_WAGE_CLAIM_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, USER_ID, USER_IP, OLD_DATA, NEW_DATA) + VALUES (SEQ_LOG_REFINERY_WAGE_CLAIM.NEXTVAL, :ClaimId, :Method, SYSDATE, :UserId, :Ip, :OldData, :NewData) + """, new + { + ClaimId = claimId, Method = method, UserId = userId.ToString(System.Globalization.CultureInfo.InvariantCulture), Ip = Cut(ip, 50), + OldData = oldData, NewData = newData, + }, ct); + + public async Task> LogAsync(long claimId, PageRequest page, CancellationToken ct = default) + { + // REFINERY_WAGE_CLAIM_LOG_VIEW: log rows newest first, with the login of the user (USER_ID holds NTPUSERS.ID as text) + var p = new DynamicParameters(); + p.Add("ClaimId", claimId); + const string from = " FROM REFINERY_WAGE_CLAIM_LOG t WHERE t.ENTITIY_ID = :ClaimId"; + var total = await ExecuteScalarAsync("SELECT COUNT(*)" + from, p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(""" + SELECT t.ID AS Id, t.METHOD_NAME AS MethodName, t.LOG_DATE AS LogDate, + (SELECT MIN(n.LOGIN) FROM NTP.NTPUSERS n WHERE TO_CHAR(n.ID) = t.USER_ID) AS Login, + DBMS_LOB.SUBSTR(t.OLD_DATA, 4000, 1) AS OldData, DBMS_LOB.SUBSTR(t.NEW_DATA, 4000, 1) AS NewData + FROM REFINERY_WAGE_CLAIM_LOG t WHERE t.ENTITIY_ID = :ClaimId ORDER BY t.ID DESC + """), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task> ReportRowsAsync(long claimId, CancellationToken ct = default) => + // REFINERY_CLAIMS_REPORT_VIEW (trips of the claim, ordered by ID); the driver name comes from the COMPLETED DRIVERS_INFO row + await QueryAsync(""" + SELECT t.ID AS Id, + (SELECT MIN(i.NAME_AR) FROM DRIVERS_INFO i WHERE i.NNPN = t.NNPN AND i.STATUS_CODE = 'COMPLETED') AS Drvr, + t.TN AS Tn, t.DISCHARGE_AUTHORIZTION_NO AS DischargeAuthoriztionNo, t.DISCHARGE_AUTHORIZTION_YEAR AS DischargeAuthoriztionYear, + t.DISCHARGE_ENTRY_DATE AS DischargeEntryDate, t.CLIENT_NO AS ClientNo, t.LOADING_NO AS LoadingNo, + t.ACTUAL_LOADING_DATE AS ActualLoadingDate, t.NET_LOADING_WEIGHT AS NetLoadingWeight, t.WATER_AMOUNT AS WaterAmount, + t.NET_DISCHARGE_WEIGHT AS NetDischargeWeight, t.CALCULATED_QUANTITY_TON AS CalculatedQuantityTon, + t.TOLERANCE_QUANTITY AS ToleranceQuantity, t.PENALTY_QUANTITY AS PenaltyQuantity, t.TON_PRICE AS TonPrice, + t.PENALTY_AMOUNT AS PenaltyAmount, t.DRIVER_TIP AS DriverTip, t.PERMIT_DISPATCH AS PermitDispatch, t.WAYBILL_FEE AS WaybillFee, + t.DIESEL_LITER_PRICE AS DieselLiterPrice, + (SELECT SUM(l.AMOUNT) FROM REFINERY_CARDS_LOG l WHERE l.PN = t.PN) AS AdvancePaymentForDiesel, + t.COMMISSION AS Commission, t.NET_WAGE AS NetWage + FROM REFINERY_TRIPS t WHERE t.WAGE_CLAIM_ID = :ClaimId ORDER BY t.ID + """, new { ClaimId = claimId }, ct); + + /// Adds the values as :{prefix}0, :{prefix}1 ... and returns the comma separated placeholder list. + private static string AddList(DynamicParameters p, string prefix, IEnumerable values) + { + var names = new List(); + foreach (var v in values) { var n = prefix + names.Count; p.Add(n, v); names.Add(":" + n); } + return string.Join(", ", names); + } + + private static string? Cut(string? s, int max) => s is null ? null : s.Length <= max ? s : s[..max]; +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Wallets/WalletsRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Wallets/WalletsRepository.cs new file mode 100644 index 0000000..ec8242d --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/Wallets/WalletsRepository.cs @@ -0,0 +1,125 @@ +using System.Data; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Refinery.Wallets; + +namespace NTP.Infrastructure.Persistence.Repositories.Refinery.Wallets; + +/// +/// REFINERY_WALLET / REFINERY_WALLET_LOG of refinery_walletdao.cfc. The SELECT mirrors the legacy REFINERY_WALLET_VIEW (docs/refinery-db-objects.txt) +/// on the table, and also returns the stored (not fallback) owner columns that the update log compares. +/// +internal sealed class WalletsRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IWalletsRepository +{ + private const string Columns = """ + w.ID AS Id, w.TN AS Tn, w.COMPANY_CODE AS CompanyCode, w.EPAYMENT AS Epayment, + w.OWNER_NNPN AS OwnerNnpn, w.WALLET_NUMBER AS WalletNumber, w.OWNER_NAME AS OwnerName, + NVL(w.OWNER_NNPN, w.DRIVER_NNPN) AS HolderNnpn, NVL(w.OWNER_NAME, w.DRIVER_NAME) AS HolderName, + w.OWNER_NAME_ENGLISH AS OwnerNameEnglish, w.DRIVER_NAME AS DriverName, w.DRIVER_NNPN AS DriverNnpn, + w.IBAN AS Iban, w.BANK_ACCOUNT AS BankAccount, w.BANK_NAME AS BankName, w.BANK_BRANCH AS BankBranch, + w.CREATION_DATE AS CreationDate, w.CREATED_BY AS CreatedBy, w.UPDATE_DATE AS UpdateDate, w.UPDATED_BY AS UpdatedBy, + w.STATUS_CODE AS StatusCode, + CASE WHEN w.DRIVER_NNPN IS NOT NULL THEN 'DRAIVER_WALLET' WHEN w.EPAYMENT = 0 THEN 'BANK' ELSE 'EWALLET' END AS PaymentMethod + """; + + public async Task> SearchAsync(WalletsQuery query, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE 1 = 1"); + var p = new DynamicParameters(); + // legacy getGridData: exact, case-insensitive match; OWNER_NAME is a contains match ('%text%') + if (!string.IsNullOrWhiteSpace(query.Tn)) + { + if (long.TryParse(query.Tn.Trim(), out var tn)) { where.Append(" AND w.TN = :Tn"); p.Add("Tn", tn); } + else where.Append(" AND 1 = 0"); + } + if (!string.IsNullOrWhiteSpace(query.Nnpn)) + { + if (long.TryParse(query.Nnpn.Trim(), out var nnpn)) { where.Append(" AND NVL(w.OWNER_NNPN, w.DRIVER_NNPN) = :Nnpn"); p.Add("Nnpn", nnpn); } + else where.Append(" AND 1 = 0"); + } + if (!string.IsNullOrWhiteSpace(query.WalletNumber)) { where.Append(" AND LOWER(w.WALLET_NUMBER) = LOWER(:WalletNumber)"); p.Add("WalletNumber", query.WalletNumber.Trim()); } + if (!string.IsNullOrWhiteSpace(query.BankAccount)) { where.Append(" AND LOWER(w.BANK_ACCOUNT) = LOWER(:BankAccount)"); p.Add("BankAccount", query.BankAccount.Trim()); } + if (!string.IsNullOrWhiteSpace(query.OwnerName)) + { + where.Append(" AND LOWER(NVL(w.OWNER_NAME, w.DRIVER_NAME)) LIKE LOWER(:OwnerName) ESCAPE '\\'"); + p.Add("OwnerName", "%" + OracleSql.EscapeLike(query.OwnerName.Trim()) + "%"); + } + if (!string.IsNullOrWhiteSpace(query.StatusCode)) { where.Append(" AND w.STATUS_CODE = :Status"); p.Add("Status", query.StatusCode.Trim()); } + if (!string.IsNullOrWhiteSpace(query.PaymentMethod)) + { + where.Append(" AND (CASE WHEN w.DRIVER_NNPN IS NOT NULL THEN 'DRAIVER_WALLET' WHEN w.EPAYMENT = 0 THEN 'BANK' ELSE 'EWALLET' END) = :Kind"); + p.Add("Kind", query.PaymentMethod.Trim()); + } + var baseSql = $"SELECT {Columns} FROM REFINERY_WALLET w{where}"; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY w.ID"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public Task GetAsync(long id, CancellationToken ct = default) => + QueryFirstAsync($"SELECT {Columns} FROM REFINERY_WALLET w WHERE w.ID = :Id", new { Id = id }, ct); + + public Task> GetActiveIdsByTruckAsync(long tn, CancellationToken ct = default) => + QueryAsync("SELECT ID FROM REFINERY_WALLET WHERE TN = :Tn AND STATUS_CODE = 'ACTIVE' ORDER BY ID", new { Tn = tn }, ct); + + public Task> GetActiveIdsByDriverAsync(long nnpn, CancellationToken ct = default) => + QueryAsync("SELECT ID FROM REFINERY_WALLET WHERE DRIVER_NNPN = :Nnpn AND STATUS_CODE = 'ACTIVE' ORDER BY ID", new { Nnpn = nnpn }, ct); + + public async Task InsertAsync(WalletWrite w, string createdBy, CancellationToken ct = default) + { + // STATUS_CODE (ACTIVE) and CREATION_DATE come from the column defaults; IBAN, BANK_ACCOUNT and BANK_NAME default to '-' when not given + // (legacy omitted empty values from the INSERT). CREATED_BY is VARCHAR2(10) (the numeric user id). + var p = new DynamicParameters(new + { + w.Tn, w.Epayment, w.OwnerNnpn, w.WalletNumber, w.OwnerName, w.DriverName, w.DriverNnpn, w.Iban, w.BankAccount, w.BankName, + w.BankBranch, w.OwnerNameEnglish, CreatedBy = Fit(createdBy, 10), + }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + INSERT INTO REFINERY_WALLET + (ID, TN, EPAYMENT, OWNER_NNPN, WALLET_NUMBER, OWNER_NAME, DRIVER_NAME, DRIVER_NNPN, IBAN, BANK_ACCOUNT, BANK_NAME, + BANK_BRANCH, OWNER_NAME_ENGLISH, CREATED_BY) + VALUES + (SEQ_REFINERY_WALLET.NEXTVAL, :Tn, :Epayment, :OwnerNnpn, :WalletNumber, :OwnerName, :DriverName, :DriverNnpn, + NVL(:Iban, '-'), NVL(:BankAccount, '-'), NVL(:BankName, '-'), :BankBranch, :OwnerNameEnglish, :CreatedBy) + RETURNING ID INTO :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public Task SetStatusAsync(long id, string status, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE REFINERY_WALLET SET STATUS_CODE = :Status, UPDATE_DATE = SYSDATE, UPDATED_BY = :UserId WHERE ID = :Id + """, new { Status = status, UserId = Fit(userId, 10), Id = id }, ct); + + public Task InsertLogAsync(long entityId, string method, string userId, string? userIp, string oldData, string newData, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO REFINERY_WALLET_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, USER_ID, USER_IP, OLD_DATA, NEW_DATA) + VALUES (SEQ_LOG_REFINERY_WALLET.NEXTVAL, :EntityId, :Method, SYSDATE, :UserId, :UserIp, :OldData, :NewData) + """, new { EntityId = entityId, Method = method, UserId = Fit(userId, 50), UserIp = userIp is null ? null : Fit(userIp, 50), OldData = oldData, NewData = newData }, ct); + + public async Task> GetLogAsync(long entityId, PageRequest page, CancellationToken ct = default) + { + // legacy REFINERY_WALLET_LOG_VIEW: log joined to NTP.NTPUSERS for the login (USER_ID holds the numeric user id) + const string baseSql = """ + SELECT t.ID AS Id, t.ENTITIY_ID AS EntityId, t.METHOD_NAME AS MethodName, n.LOGIN AS Login, t.LOG_DATE AS LogDate, + t.USER_ID AS UserId, t.USER_IP AS UserIp, + DBMS_LOB.SUBSTR(t.OLD_DATA, 4000, 1) AS OldData, DBMS_LOB.SUBSTR(t.NEW_DATA, 4000, 1) AS NewData + FROM REFINERY_WALLET_LOG t LEFT JOIN NTP.NTPUSERS n ON n.ID = t.USER_ID + WHERE t.ENTITIY_ID = :EntityId + """; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), new { EntityId = entityId }, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY t.ID DESC"), + new { EntityId = entityId, page.MinRow, page.MaxRow }, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + private static string Fit(string value, int max) => value.Length <= max ? value : value[..max]; +} diff --git a/tests/NTP.Tests/Refinery/CardsRulesTests.cs b/tests/NTP.Tests/Refinery/CardsRulesTests.cs new file mode 100644 index 0000000..813eacd --- /dev/null +++ b/tests/NTP.Tests/Refinery/CardsRulesTests.cs @@ -0,0 +1,41 @@ +using NTP.Application.Refinery.Cards; + +namespace NTP.Tests.Refinery; + +public class CardsRulesTests +{ + [Theory] + [InlineData("INACTIVE", true)] + [InlineData("inactive", true)] + [InlineData("ACTIVE", false)] + [InlineData(null, false)] + public void Only_an_inactive_card_can_be_activated(string? status, bool expected) => Assert.Equal(expected, CardsRules.CanActivate(status)); + + [Theory] + [InlineData("ACTIVE", true)] + [InlineData("INACTIVE", false)] + [InlineData("", false)] + public void Only_an_active_card_can_be_deactivated(string status, bool expected) => Assert.Equal(expected, CardsRules.CanDeactivate(status)); + + [Fact] + public void A_truck_without_previous_cards_may_start_with_any_balance() => Assert.True(CardsRules.BalanceMatchesPrevious(null, 250)); + + [Fact] + public void A_new_card_keeps_the_balance_of_the_previous_one() + { + Assert.True(CardsRules.BalanceMatchesPrevious(13174m, 13174m)); + Assert.False(CardsRules.BalanceMatchesPrevious(13174m, 0m)); + } + + [Fact] + public void Create_form_checks() + { + var v = new CreateCardValidator(); + Assert.True(v.Validate(new CreateCardRequest { Tn = 6066854, CardNumber = "52317", CurrentBalance = 100 }).IsValid); + Assert.False(v.Validate(new CreateCardRequest { Tn = 0, CardNumber = "52317", CurrentBalance = 100 }).IsValid); + Assert.False(v.Validate(new CreateCardRequest { Tn = 1, CardNumber = "", CurrentBalance = 100 }).IsValid); + Assert.False(v.Validate(new CreateCardRequest { Tn = 1, CardNumber = "12345678901", CurrentBalance = 100 }).IsValid); // VARCHAR2(10) + Assert.False(v.Validate(new CreateCardRequest { Tn = 1, CardNumber = "1", CurrentBalance = -1 }).IsValid); + Assert.False(v.Validate(new CreateCardRequest { Tn = 1, CardNumber = "1", CurrentBalance = 10_000_000 }).IsValid); // log column NUMBER(10,3) + } +} diff --git a/tests/NTP.Tests/Refinery/CommissionClaimRulesTests.cs b/tests/NTP.Tests/Refinery/CommissionClaimRulesTests.cs new file mode 100644 index 0000000..880ce33 --- /dev/null +++ b/tests/NTP.Tests/Refinery/CommissionClaimRulesTests.cs @@ -0,0 +1,68 @@ +using NTP.Application.Common; +using NTP.Application.Refinery.CommissionClaims; + +namespace NTP.Tests.Refinery; + +public class CommissionClaimRulesTests +{ + [Fact] + public void Billing_period_is_the_month_before_the_newest_wage_claim() + { + var (s, e) = CommissionClaimRules.BillingPeriod(new DateTime(2023, 8, 27, 16, 42, 0)); + Assert.Equal(new DateOnly(2023, 7, 1), s); + Assert.Equal(new DateOnly(2023, 7, 31), e); + } + + [Fact] + public void Billing_period_of_january_is_december_of_the_year_before() + { + var (s, e) = CommissionClaimRules.BillingPeriod(new DateTime(2024, 1, 5)); + Assert.Equal(new DateOnly(2023, 12, 1), s); + Assert.Equal(new DateOnly(2023, 12, 31), e); + } + + [Fact] + public void Billing_period_handles_a_leap_february() + { + var (_, e) = CommissionClaimRules.BillingPeriod(new DateTime(2024, 3, 2)); + Assert.Equal(new DateOnly(2024, 2, 29), e); + } + + [Fact] + public void Invoice_lines_total_with_tax_and_round_the_net_to_three_decimals() + { + var l = CommissionClaimRules.Line("x", 100, 2.00m); + Assert.Equal(200m, l.TotalWithTax); + Assert.Equal(172.414m, l.TotalBeforeTax); // ROUND(200 / 1.16, 3) + } + + [Fact] + public void Invoice_totals_follow_the_legacy_template() + { + var inv = CommissionClaimRules.BuildInvoice(20230200009, new DateTime(2023, 8, 31), 100, 3.5m); + Assert.Equal("INV 20230200009", inv.InvoiceNumber); + Assert.Equal(new DateOnly(2023, 7, 31), inv.InvoiceDate); + Assert.Equal(["العمولة الثابتة", "العمولة التنافسية"], inv.Lines.Select(l => l.Label)); + Assert.Equal([100L, 100L], inv.Lines.Select(l => l.Quantity)); + Assert.Equal(172.414m + 301.724m, inv.TotalBeforeTax); + Assert.Equal(550m, inv.GrandTotal); + Assert.Equal(550m - (172.414m + 301.724m), inv.Tax); + } + + [Fact] + public void Wage_claim_selection_is_required() + { + var ex = Assert.Throws(() => CommissionClaimRules.NormalizeIds(null)); + Assert.Equal("يرجى اختيار المطالبة", ex.Message); + Assert.Throws(() => CommissionClaimRules.NormalizeIds([0, -1])); + Assert.Equal([3L, 5L], CommissionClaimRules.NormalizeIds([3, 5, 3, 0])); + } + + [Fact] + public void Commission_claim_completes_only_when_every_wage_claim_is_paid() + { + Assert.True(CommissionClaimRules.AllWageClaimsPaid(["CLOSE", "CLOSE"])); + Assert.True(CommissionClaimRules.AllWageClaimsPaid([])); + Assert.False(CommissionClaimRules.AllWageClaimsPaid(["CLOSE", "NEW"])); + } +} diff --git a/tests/NTP.Tests/Refinery/DinarakTests.cs b/tests/NTP.Tests/Refinery/DinarakTests.cs new file mode 100644 index 0000000..88eda7f --- /dev/null +++ b/tests/NTP.Tests/Refinery/DinarakTests.cs @@ -0,0 +1,190 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using NTP.Infrastructure.Integrations; + +namespace NTP.Tests.Refinery; + +public class DinarakProtocolTests +{ + [Fact] + public void Transfer_request_keeps_the_legacy_property_order_and_values() + { + var json = DinarakProtocol.BuildTransferRequest("محمد احمد", 271.975m, "26968", 352.1m, "795000000", DinarakProtocol.TransferOperation); + + Assert.Equal( + "{\"Name\":\"محمد احمد\",\"Amount\":271.975,\"Description\":\" 26968\",\"MessageId\":\"352.1\",\"Reference\":\"352.1\"," + + "\"ReceiverID\":\"795000000\",\"OperationName\":\"Transfer\",\"Conditions\":[{\"NationalId\":\"\"}]}", json); + } + + [Fact] + public void Token_request_for_the_log_never_carries_the_password() + { + var real = DinarakProtocol.BuildTokenRequest("user", "s3cret"); + var logged = DinarakProtocol.BuildTokenRequestForLog("user"); + + Assert.Equal("{\"username\":\"user\",\"password\":\"s3cret\",\"grant_type\":\"password\"}", real); + Assert.DoesNotContain("s3cret", logged); + Assert.Contains("\"username\":\"user\"", logged); + } + + [Theory] + [InlineData("ZAINJOPX", "Transfer")] + [InlineData("ORNGJOPX", "Transfer")] + [InlineData("dnrkjopx", "Transfer")] + [InlineData("MDFTJOPX", "Transfer")] + [InlineData("BANKJOPX", "bank salary internal")] + [InlineData(null, "bank salary internal")] + public void Wallet_type_decides_the_operation(string? picCode, string expected) => + Assert.Equal(expected, DinarakProtocol.OperationFor(picCode)); + + [Fact] + public void Pic_code_is_read_from_the_alias_answer_and_garbage_gives_null() + { + Assert.Equal("ZAINJOPX", DinarakProtocol.ParsePicCode("{\"picCode\":\"ZAINJOPX\",\"name\":\"x\"}")); + Assert.Null(DinarakProtocol.ParsePicCode("{\"other\":1}")); + Assert.Null(DinarakProtocol.ParsePicCode("")); + } + + [Theory] + [InlineData(271.975, 271.975, true)] + [InlineData(271.975, 271.976, true)] + [InlineData(271.975, 271.977, false)] // 0.002 > 0.001 + [InlineData(10, 11, false)] + public void Amount_check_allows_a_thousandth(double calculated, double requested, bool ok) => + Assert.Equal(ok, DinarakProtocol.AmountMatches((decimal)calculated, (decimal)requested)); + + [Fact] + public void Message_ids_are_plain_decimals() + { + Assert.Equal("352.1", DinarakProtocol.FormatMessageId(352.1m)); + Assert.Equal("352.11", DinarakProtocol.FormatMessageId(352.11m)); + Assert.Equal("78388", DinarakProtocol.FormatMessageId(78388m)); + } + + [Fact] + public void Transfer_answers_map_to_the_legacy_codes() + { + Assert.Equal(("000", "SUCCESS"), Pair(DinarakProtocol.MapTransferResponse(200, "{\"status\":{\"name\":\"Success\"}}"))); + Assert.True(DinarakProtocol.MapTransferResponse(200, "{\"status\":{\"name\":\"Success\"}}").Success); + + var refused = DinarakProtocol.MapTransferResponse(200, "{\"status\":{\"name\":\"Failed\",\"errorMessage\":\"Insufficient funds here\"}}"); + Assert.Equal(("102", "Insufficient_funds_here"), Pair(refused)); + + Assert.Equal(("103", "Bad_gateway"), Pair(DinarakProtocol.MapTransferResponse(502, "Bad gateway"))); + Assert.Equal("104", DinarakProtocol.MapTransferResponse(200, "not json").Code); + } + + [Theory] + [InlineData("Success", true)] + [InlineData("Processing", true)] + [InlineData("New", true)] + [InlineData("Failed", false)] + public void Status_lookup_accepts_success_processing_and_new(string name, bool accepted) + { + var s = DinarakProtocol.MapStatusResponse(200, "{\"status\":{\"name\":\"" + name + "\"}}"); + Assert.Equal(accepted, s.Accepted); + Assert.Equal(name, s.StatusName); + } + + [Fact] + public void Status_lookup_with_an_http_error_is_not_accepted() + { + var s = DinarakProtocol.MapStatusResponse(404, "nothing"); + Assert.False(s.Accepted); + Assert.Equal("HTTP_404", s.StatusName); + Assert.Equal("ERROR", DinarakProtocol.MapStatusResponse(200, "").StatusName); + } + + [Fact] + public void Bearer_header_value_is_built_from_the_access_token() + { + Assert.Equal("bearer abc", DinarakProtocol.ParseBearer("{\"access_token\":\"abc\",\"expires_in\":1}")); + Assert.Null(DinarakProtocol.ParseBearer("{\"access_token\":\"\"}")); + Assert.Null(DinarakProtocol.ParseBearer("nope")); + } + + private static (string, string) Pair(NTP.Application.Refinery.Integrations.DinarakTransferResult r) => (r.Code, r.Message); +} + +public class DinarakClientTests +{ + private sealed class Recorder(Func answer) : HttpMessageHandler + { + public List<(HttpMethod Method, string Url, string? Body, Dictionary Headers)> Calls { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken); + var headers = request.Headers.ToDictionary(h => h.Key, h => string.Join(",", h.Value), StringComparer.OrdinalIgnoreCase); + if (request.Content is not null) headers["Content-Type"] = request.Content.Headers.ContentType!.ToString(); + Calls.Add((request.Method, request.RequestUri!.ToString(), body, headers)); + return answer(request); + } + } + + private static HttpResponseMessage Json(string body, HttpStatusCode code = HttpStatusCode.OK) => + new(code) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + + private static DinarakClient Client(Recorder handler) => + new(new HttpClient(handler), new DinarakOptions { BaseUrl = "https://dinarak.invalid/api/", UserName = "u", Password = "p" }); + + [Fact] + public async Task Token_call_posts_the_login_json_to_token_with_arabic_accept_language() + { + var h = new Recorder(_ => Json("{\"access_token\":\"tok\"}")); + var r = await Client(h).GetTokenAsync(); + + Assert.Equal(200, r.Status); + var call = Assert.Single(h.Calls); + Assert.Equal(HttpMethod.Post, call.Method); + Assert.Equal("https://dinarak.invalid/api/token", call.Url); + Assert.Equal("{\"username\":\"u\",\"password\":\"p\",\"grant_type\":\"password\"}", call.Body); + Assert.Equal("ar", call.Headers["Accept-Language"]); + Assert.StartsWith("application/json", call.Headers["Content-Type"]); + Assert.False(call.Headers.ContainsKey("Authorization")); + } + + [Fact] + public async Task Alias_resolve_and_status_lookup_use_get_with_the_bearer_token() + { + var h = new Recorder(_ => Json("{}")); + var c = Client(h); + await c.AliasResolveAsync("bearer tok", "795000000"); + await c.GetByMessageIdAsync("bearer tok", "352.1"); + + Assert.Equal("https://dinarak.invalid/api/Transfer/AliasResolve?aliastype=MOBL&value=795000000", h.Calls[0].Url); + Assert.Equal("https://dinarak.invalid/api/transfer/transferByMessageID?MessageID=352.1", h.Calls[1].Url); + Assert.All(h.Calls, x => + { + Assert.Equal(HttpMethod.Get, x.Method); + Assert.Equal("bearer tok", x.Headers["Authorization"]); + Assert.Equal("en", x.Headers["Accept-Language"]); + }); + } + + [Fact] + public async Task Transfer_posts_the_request_json_and_returns_status_and_body() + { + var h = new Recorder(_ => Json("{\"status\":{\"name\":\"Success\"}}")); + var json = DinarakProtocol.BuildTransferRequest("x", 1.5m, "1", 5m, "795000000", DinarakProtocol.SalaryOperation); + + var r = await Client(h).TransferAsync("bearer tok", json); + + Assert.Equal("https://dinarak.invalid/api/transfer/transfer", h.Calls[0].Url); + Assert.Equal(json, h.Calls[0].Body); + Assert.Equal("000", DinarakProtocol.MapTransferResponse(r.Status, r.Body).Code); + using var doc = JsonDocument.Parse(h.Calls[0].Body!); + Assert.Equal("bank salary internal", doc.RootElement.GetProperty("OperationName").GetString()); + } + + [Fact] + public async Task Http_errors_are_returned_not_thrown() + { + var h = new Recorder(_ => Json("down", HttpStatusCode.BadGateway)); + var r = await Client(h).TransferAsync("bearer tok", "{}"); + + Assert.Equal(502, r.Status); + Assert.Equal("103", DinarakProtocol.MapTransferResponse(r.Status, r.Body).Code); + } +} diff --git a/tests/NTP.Tests/Refinery/JopetrolGatewayTests.cs b/tests/NTP.Tests/Refinery/JopetrolGatewayTests.cs new file mode 100644 index 0000000..31b5929 --- /dev/null +++ b/tests/NTP.Tests/Refinery/JopetrolGatewayTests.cs @@ -0,0 +1,121 @@ +using System.Net; +using System.Text; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NTP.Infrastructure.Integrations; + +namespace NTP.Tests.Refinery; + +public class JopetrolGatewayTests +{ + private sealed class FakeHandler(Func respond) : HttpMessageHandler + { + public readonly List<(HttpRequestMessage Request, string Body)> Calls = []; + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(cancellationToken); + Calls.Add((request, body)); + return respond(request, body); + } + } + + private sealed class FakeFactory(HttpMessageHandler handler) : IHttpClientFactory + { + public HttpClient CreateClient(string name) => new(handler, disposeHandler: false); + } + + private static JopetrolGateway Gateway(FakeHandler h, bool enabled = true, string user = "test-user", string password = "test-pass", string url = "https://jopetrol.test/ws.asmx") => + new(new FakeFactory(h), Options.Create(new JopetrolOptions { Enabled = enabled, Url = url, UserName = user, Password = password, TimeoutSeconds = 5 }), + NullLogger.Instance); + + private static string Answer(string text) => + $"""{text}"""; + + private static HttpResponseMessage Ok(string xml) => new(HttpStatusCode.OK) { Content = new StringContent(xml, Encoding.UTF8, "text/xml") }; + + [Fact] + public void Envelope_carries_the_header_credentials_and_the_two_arguments() + { + var xml = JopetrolSoap.BuildEnvelope("test-user", "test-pass", "1234567", "20230100041"); + var doc = System.Xml.Linq.XDocument.Parse(xml); // well formed + var tran = System.Xml.Linq.XNamespace.Get(JopetrolSoap.ServiceNamespace); + Assert.Equal("test-user", doc.Descendants(tran + "UserName").Single().Value); + Assert.Equal("test-pass", doc.Descendants(tran + "Password").Single().Value); + Assert.Equal("1234567", doc.Descendants(tran + "TransNumber").Single().Value); + Assert.Equal("20230100041", doc.Descendants(tran + "claimNo").Single().Value); + Assert.NotNull(doc.Descendants(tran + "sendClaimandUpdateStatusTo7").SingleOrDefault()); + } + + [Fact] + public void Envelope_escapes_xml_in_the_values() + { + var xml = JopetrolSoap.BuildEnvelope("a&b", "

", "1", "2"); + var tran = System.Xml.Linq.XNamespace.Get(JopetrolSoap.ServiceNamespace); + var doc = System.Xml.Linq.XDocument.Parse(xml); + Assert.Equal("a&b", doc.Descendants(tran + "UserName").Single().Value); + Assert.Equal("

", doc.Descendants(tran + "Password").Single().Value); + } + + [Fact] + public void Answer_is_read_by_local_name() + { + Assert.Equal("Status Updated successfully To 7", JopetrolSoap.ParseResult(Answer("Status Updated successfully To 7"))); + Assert.Null(JopetrolSoap.ParseResult("")); + } + + [Fact] + public async Task Disabled_integration_returns_null_and_calls_nothing() + { + var h = new FakeHandler((_, _) => Ok(Answer("never"))); + var result = await Gateway(h, enabled: false).SendClaimAndUpdateStatusTo7Async("1", "2"); + Assert.Null(result); + Assert.Empty(h.Calls); + } + + [Fact] + public async Task Enabled_integration_posts_the_envelope_and_returns_the_result_text() + { + var h = new FakeHandler((_, _) => Ok(Answer("Status Updated successfully To 7"))); + var result = await Gateway(h).SendClaimAndUpdateStatusTo7Async("1234567", "20230100041"); + + Assert.Equal("Status Updated successfully To 7", result); + var call = Assert.Single(h.Calls); + Assert.Equal(HttpMethod.Post, call.Request.Method); + Assert.Equal("https://jopetrol.test/ws.asmx", call.Request.RequestUri!.ToString()); + Assert.StartsWith("text/xml", call.Request.Content!.Headers.ContentType!.MediaType); + Assert.Contains("1234567", call.Body); + Assert.Contains("20230100041", call.Body); + } + + [Fact] + public async Task Answer_without_a_result_element_is_an_empty_text() + { + var h = new FakeHandler((_, _) => Ok("Server error")); + Assert.Equal("", await Gateway(h).SendClaimAndUpdateStatusTo7Async("1", "2")); + } + + [Fact] + public async Task Unreadable_answer_is_an_error() + { + var h = new FakeHandler((_, _) => Ok("not xml at all <<")); + await Assert.ThrowsAsync(() => Gateway(h).SendClaimAndUpdateStatusTo7Async("1", "2")); + } + + [Fact] + public async Task Enabled_without_credentials_is_refused_before_any_call() + { + var h = new FakeHandler((_, _) => Ok(Answer("x"))); + await Assert.ThrowsAsync(() => Gateway(h, user: "", password: "").SendClaimAndUpdateStatusTo7Async("1", "2")); + Assert.Empty(h.Calls); + } + + [Fact] + public void Options_are_off_by_default() + { + var o = new JopetrolOptions(); + Assert.False(o.Enabled); + Assert.Equal("", o.UserName); + Assert.Equal("", o.Password); + Assert.Equal(30, o.TimeoutSeconds); + } +} diff --git a/tests/NTP.Tests/Refinery/TripActionServiceTests.cs b/tests/NTP.Tests/Refinery/TripActionServiceTests.cs new file mode 100644 index 0000000..b710e06 --- /dev/null +++ b/tests/NTP.Tests/Refinery/TripActionServiceTests.cs @@ -0,0 +1,373 @@ +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Refinery.Integrations; +using NTP.Application.Refinery.RemainingBalance; +using NTP.Application.Refinery.Trips; + +namespace NTP.Tests.Refinery; + +///

The action service against in-memory fakes: card arithmetic, status rules, what is (not) written when Dinarak refuses. +public class TripActionServiceTests +{ + private sealed class FakeTrips : ITripRepository + { + public TripRecord Trip { get; set; } = new() { Id = 1, Pn = "633472", Tn = "6021151", StatusCode = "RESD", CurrentBalance = 100m, LoadingDate = new DateTime(2023, 8, 2), NetLoadingWeight = 34560, NetDischargeWeight = 34290, DischargeAuthNo = "26968", OwnerName = "Owner" }; + public CardInfo? Card { get; set; } = new(7, 100m); + public decimal? Diesel { get; set; } = 250m; + public decimal? LastCardLogAmount { get; set; } = 150m; + public TripWallet? Wallet { get; set; } + public List Calls { get; } = []; + public List<(string Method, string Old, string New)> Logs { get; } = []; + public List<(string Method, decimal Before, decimal After, decimal Amount)> CardLogs { get; } = []; + public decimal? CardBalanceSet { get; private set; } + public int? ReversedTo { get; private set; } + + public Task GetAsync(long id, CancellationToken ct = default) => Task.FromResult(Trip); + public Task LockAsync(long id, CancellationToken ct = default) { Calls.Add("lock"); return Task.FromResult(new(Trip.StatusCode, Trip.DieselCharge)); } + public Task GetActiveWalletByTruckAsync(string tn, CancellationToken ct = default) => Task.FromResult(Wallet); + public Task GetWalletAsync(long walletId, CancellationToken ct = default) => Task.FromResult(Wallet); + public Task GetAuditModeAsync(CancellationToken ct = default) => Task.FromResult(false); + public Task GetFirstPaymentValueAsync(CancellationToken ct = default) => Task.FromResult(100m); + public Task>> GetVariablesAsync(DateTime loadingDate, CancellationToken ct = default) => + Task.FromResult>>( + [ + new("COMMISSION", "0.95"), new("DIESEL_LITER_PRICE", "0.715"), new("DRIVER_TIP", "20"), new("FIRST_ADVANCE_PAYMENT", "100"), + new("PERMIT_DISPATCH", "2.5"), new("TOLERANCE_PERCENTAGE", "0.005"), new("TON_PRICE", "700"), new("TON_WAGE", "17.936"), new("WAYBILL_FEE", "0.75") + ]); + public Task GetWaterFlagAsync(long id, CancellationToken ct = default) => Task.FromResult(null); + public Task CalculateDieselAsync(long id, CancellationToken ct = default) => Task.FromResult(Diesel); + public Task CalculateAmountAsync(long id, CancellationToken ct = default) => Task.FromResult(271.975m); + public Task HasTransferLogAsync(long id, CancellationToken ct = default) => Task.FromResult(true); + public Task> GetTripsOfPeriodAsync(DateTime from, DateTime to, CancellationToken ct = default) => Task.FromResult>([]); + public Task GetActiveCardAsync(string tn, CancellationToken ct = default) => Task.FromResult(Card); + public Task GetLastCardLogAmountAsync(string pn, string methodName, CancellationToken ct = default) => Task.FromResult(LastCardLogAmount); + public Task InsertCardLogAsync(long cardId, string methodName, decimal before, decimal after, decimal amount, string userId, string pn, CancellationToken ct = default) + { CardLogs.Add((methodName, before, after, amount)); return Task.CompletedTask; } + public Task UpdateCardBalanceAsync(long cardId, decimal balance, string userId, long tripId, CancellationToken ct = default) { CardBalanceSet = balance; return Task.CompletedTask; } + public Task MarkFirstAdvanceAsync(long id, string userId, CancellationToken ct = default) { Calls.Add("first"); return Task.CompletedTask; } + public Task MarkSecondAdvanceAsync(long id, string userId, decimal secondPaymentValue, CancellationToken ct = default) { Calls.Add("second:" + secondPaymentValue); return Task.CompletedTask; } + public Task MarkAdvanceReversedAsync(long id, string userId, int dieselCharge, CancellationToken ct = default) { ReversedTo = dieselCharge; return Task.CompletedTask; } + public Task SaveAmountsAsync(long id, string userId, TripAmounts amounts, CancellationToken ct = default) { Calls.Add("amounts:" + amounts.NetWage); return Task.CompletedTask; } + public Task SetStatusReceivedAsync(long id, string userId, string status, CancellationToken ct = default) { Calls.Add("status:" + status); return Task.CompletedTask; } + public Task MarkExchangedAsync(long id, string userId, string? remarks, string? paymentOptions, bool setReceived, long? walletId, CancellationToken ct = default) { Calls.Add($"exchanged:{paymentOptions}:{setReceived}:{walletId}"); return Task.CompletedTask; } + public Task BumpDinarakReferenceAsync(long id, string userId, CancellationToken ct = default) { Calls.Add("bump"); return Task.FromResult(352.11m); } + public Task SetVoucherSerialAsync(long id, long serial, CancellationToken ct = default) { Calls.Add("serial:" + serial); return Task.CompletedTask; } + public Task ConfirmExchangeAsync(long id, string userId, CancellationToken ct = default) { Calls.Add("confirm"); return Task.CompletedTask; } + public Task InsertLogAsync(long tripId, string methodName, string userId, string oldJson, string newJson, CancellationToken ct = default) + { Logs.Add((methodName, oldJson, newJson)); return Task.CompletedTask; } + public Task> SearchLogAsync(long tripId, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException(); + public Task> SearchAsync(TripQuery query, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException(); + public Task> ReportAsync(TripQuery query, CancellationToken ct = default) => throw new NotSupportedException(); + public Task> DieselReportAsync(DieselReportQuery query, CancellationToken ct = default) => throw new NotSupportedException(); + public Task> CardsAsync(string? tn, CancellationToken ct = default) => throw new NotSupportedException(); + public Task> BankReportAsync(BankReportQuery query, CancellationToken ct = default) => throw new NotSupportedException(); + } + + private sealed class FakeBalances(List calls) : IRemainingBalanceService + { + public Task GetAsync(string tn, CancellationToken ct = default) => Task.FromResult(null); + public Task ResetAfterPaymentAsync(string tn, long tripId, CancellationToken ct = default) { calls.Add("reset-balance"); return Task.CompletedTask; } + public Task AddAsync(string tn, decimal delta, long tripId, long variableGroupId, CancellationToken ct = default) => Task.CompletedTask; + public Task RecalculateForPeriodAsync(DateTime startDate, DateTime endDate, long variableGroupId, CancellationToken ct = default) => throw new NotSupportedException(); + } + + private sealed class FakeAmounts : ITripAmountsService + { + public Task ComputeAsync(TripRecord trip, CancellationToken ct) => + Task.FromResult(TripCalculator.Calculate(new TripWeights(trip.NetLoadingWeight ?? 0, trip.NetDischargeWeight ?? 0, 0, null), + TripVariables.FromPairs([new("TON_WAGE", "17.936"), new("TON_PRICE", "700"), new("TOLERANCE_PERCENTAGE", "0.005"), new("DRIVER_TIP", "20"), + new("PERMIT_DISPATCH", "2.5"), new("WAYBILL_FEE", "0.75"), new("COMMISSION", "0.95"), new("DIESEL_LITER_PRICE", "0.715"), new("FIRST_ADVANCE_PAYMENT", "100")]), null)); + } + + private sealed class FakeDinarak(DinarakTransferResult result, DinarakTransferStatus? status = null) : IDinarakGateway, IDinarakReferenceGateway + { + public int Transfers { get; private set; } + public (string Wallet, decimal Amount)? Last { get; private set; } + public Task TransferAsync(long tripId, string walletNumber, string nnpn, decimal amount, string receiverName, CancellationToken ct = default) + { Transfers++; Last = (walletNumber, amount); return Task.FromResult(result); } + public Task GetTransferByMessageIdAsync(long messageId, CancellationToken ct = default) => Task.FromResult(status ?? new(false, "Failed", null)); + public Task GetTransferByReferenceAsync(decimal reference, CancellationToken ct = default) => Task.FromResult(status ?? new(false, "Failed", null)); + } + + private sealed class FakeVoucher : IVoucherSerialRepository { public Task NextAsync(CancellationToken ct = default) => Task.FromResult(202600096L); } + + private sealed class FakeUow : IUnitOfWork + { + public int Committed { get; private set; } + public int RolledBack { get; private set; } + public Task BeginAsync(CancellationToken ct = default) => Task.CompletedTask; + public Task CommitAsync(CancellationToken ct = default) { Committed++; return Task.CompletedTask; } + public Task RollbackAsync(CancellationToken ct = default) { RolledBack++; return Task.CompletedTask; } + public async Task ExecuteInTransactionAsync(Func> work, CancellationToken ct = default) + { + try { var r = await work(ct); Committed++; return r; } + catch { RolledBack++; throw; } + } + } + + private sealed class FakeUser : ICurrentUser + { + public bool IsAuthenticated => true; public long Id => 16190811; public string UserId => "REF_X"; public string Name => "x"; public string RoleCode => "PTADM"; + public string RoleName => ""; 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) => false; public bool IsInAnyRole(params string[] roleCodes) => false; + } + + private sealed class FakeSettings : ITripSettingsService { public TripOptions Value { get; } = new(); } + + private static (TripActionService Svc, FakeTrips Trips, FakeUow Uow, FakeDinarak Dinarak) Build(FakeDinarak? dinarak = null) + { + var trips = new FakeTrips(); + var uow = new FakeUow(); + var d = dinarak ?? new FakeDinarak(new("000", "SUCCESS")); + var svc = new TripActionService(trips, new FakeAmounts(), new FakeBalances(trips.Calls), d, d, new FakeVoucher(), uow, new FakeUser(), new FakeSettings()); + return (svc, trips, uow, d); + } + + private static TripWallet ReadyWallet() => new() { Id = 5, Epayment = 1, WalletNumber = "795000000", OwnerNnpn = 9871012345, OwnerName = "Owner" }; + + // ---------------------------------------------------------------- diesel advances + [Fact] + public async Task First_advance_logs_the_card_movement_and_sets_the_card_to_the_calculated_value() + { + var (svc, trips, _, _) = Build(); + var r = await svc.FirstAdvanceAsync(1, default); + + Assert.Equal("تمت العملية بنجاح", r.Message); + var log = Assert.Single(trips.CardLogs); + Assert.Equal(("FIRST_ADVANCED_PAYMENT", 100m, 250m, 150m), log); + Assert.Equal(250m, trips.CardBalanceSet); + Assert.Contains("first", trips.Calls); + var tripLog = Assert.Single(trips.Logs); + Assert.Equal("FIRST_ADVANCED_PAYMENT", tripLog.Method); + Assert.Equal("{\"CURRENT_BALANCE\":\"250\"}", tripLog.New); + } + + [Fact] + public async Task First_advance_twice_is_refused_with_the_legacy_text_and_writes_nothing() + { + var (svc, trips, uow, _) = Build(); + trips.Trip.DieselCharge = 1; + + var ex = await Assert.ThrowsAsync(() => svc.FirstAdvanceAsync(1, default)); + Assert.Equal("تم اجراء دفعة الديزل الاولى مسبقاً", ex.Message); + Assert.Empty(trips.CardLogs); + Assert.Equal(1, uow.RolledBack); + } + + [Fact] + public async Task Advance_without_an_active_card_is_refused() + { + var (svc, trips, _, _) = Build(); + trips.Card = null; + var ex = await Assert.ThrowsAsync(() => svc.FirstAdvanceAsync(1, default)); + Assert.Equal("بطاقة تعبئة الديزل غير معرفة", ex.Message); + } + + [Fact] + public async Task Second_advance_needs_the_first_and_stores_the_calculated_value() + { + var (svc, trips, _, _) = Build(); + await Assert.ThrowsAsync(() => svc.SecondAdvanceAsync(1, default)); // DieselCharge 0 + + trips.Trip.DieselCharge = 1; + trips.Trip.StatusCode = "LOADED"; + await svc.SecondAdvanceAsync(1, default); + Assert.Contains("second:250", trips.Calls); + Assert.Equal("SECOND_ADVANCED_PAYMENT", trips.CardLogs[0].Method); + } + + [Fact] + public async Task First_advance_reverse_takes_back_the_logged_amount() + { + var (svc, trips, _, _) = Build(); + trips.Trip.DieselCharge = 1; + trips.Card = new CardInfo(7, 250m); + + await svc.FirstAdvanceReverseAsync(1, default); + + Assert.Equal(("FIRST_ADVANCED_PAYMENT_REVERSE", 250m, 100m, -150m), trips.CardLogs[0]); + Assert.Equal(100m, trips.CardBalanceSet); + Assert.Equal(0, trips.ReversedTo); + } + + [Fact] + public async Task Second_advance_reverse_goes_back_to_step_one() + { + var (svc, trips, _, _) = Build(); + trips.Trip.DieselCharge = 2; + trips.Card = new CardInfo(7, 450m); + trips.LastCardLogAmount = 200m; + + await svc.SecondAdvanceReverseAsync(1, default); + + Assert.Equal(("SECOND_ADVANCED_PAYMENT_REVERSE", 450m, 250m, -200m), trips.CardLogs[0]); + Assert.Equal(1, trips.ReversedTo); + } + + [Theory] + [InlineData(0, "FIRST_ADVANCED_PAYMENT_REVERSE_IS_EXIST")] + [InlineData(2, "CANNOT_FIRST_ADVANCED_PAYMENT_REVERSE")] + public async Task First_advance_reverse_checks_the_step(int step, string code) + { + var (svc, trips, _, _) = Build(); + trips.Trip.DieselCharge = step; + var ex = await Assert.ThrowsAsync(() => svc.FirstAdvanceReverseAsync(1, default)); + Assert.Equal(code, ex.Code); + } + + // ---------------------------------------------------------------- payment + [Fact] + public async Task Exchange_pays_through_dinarak_then_marks_the_trip_and_resets_the_balance() + { + var (svc, trips, _, dinarak) = Build(); + trips.Trip.StatusCode = "DISCHARGED"; + trips.Wallet = ReadyWallet(); + + await svc.ExchangeAsync(1, default); + + Assert.Equal(1, dinarak.Transfers); + Assert.Equal(("795000000", 271.975m), dinarak.Last); + Assert.Contains("exchanged::True:5", trips.Calls); + Assert.Contains("reset-balance", trips.Calls); + Assert.Equal("EXCHANGE", trips.Logs.Single().Method); + Assert.Contains("تم الصرف", trips.Logs.Single().New); + } + + [Fact] + public async Task Exchange_refused_by_dinarak_keeps_the_trip_and_logs_the_remark() + { + var (svc, trips, _, _) = Build(new FakeDinarak(new("102", "Insufficient_funds"))); + trips.Trip.StatusCode = "DISCHARGED"; + trips.Wallet = ReadyWallet(); + + var ex = await Assert.ThrowsAsync(() => svc.ExchangeAsync(1, default)); + + Assert.Contains("INSUFFICIENT_FUNDS", ex.Message); + Assert.DoesNotContain(trips.Calls, c => c.StartsWith("exchanged")); + Assert.DoesNotContain("reset-balance", trips.Calls); + Assert.Contains("Insufficient_funds", trips.Logs.Single().New); + } + + [Fact] + public async Task Exchange_with_the_integration_off_says_so() + { + var (svc, trips, _, _) = Build(new FakeDinarak(new("106", "DINARAK_DISABLED"))); + trips.Trip.StatusCode = "DISCHARGED"; + trips.Wallet = ReadyWallet(); + var ex = await Assert.ThrowsAsync(() => svc.ExchangeAsync(1, default)); + Assert.Equal("DINARAK_DISABLED", ex.Code); + } + + [Fact] + public async Task Exchange_stops_before_dinarak_when_the_wallet_is_incomplete_or_the_status_is_wrong() + { + var (svc, trips, _, dinarak) = Build(); + trips.Trip.StatusCode = "DISCHARGED"; + trips.Wallet = ReadyWallet(); + trips.Wallet.WalletNumber = ""; + await Assert.ThrowsAsync(() => svc.ExchangeAsync(1, default)); + + trips.Wallet = ReadyWallet(); + trips.Trip.StatusCode = "RESD"; + var ex = await Assert.ThrowsAsync(() => svc.ExchangeAsync(1, default)); + Assert.Equal("NO_AUTHORITY", ex.Code); + Assert.Equal(0, dinarak.Transfers); + } + + [Fact] + public async Task Receipt_is_for_bank_transfer_trucks_only() + { + var (svc, trips, _, _) = Build(); + trips.Trip.StatusCode = "DISCHARGED"; + trips.Wallet = ReadyWallet(); // e-wallet: receipt refused + await Assert.ThrowsAsync(() => svc.ReceiptAsync(1, default)); + + trips.Wallet = new TripWallet { Id = 6, Epayment = 0 }; + await svc.ReceiptAsync(1, default); + Assert.Contains("status:READY_TO_PAY", trips.Calls); + Assert.Contains("amounts:271.975", trips.Calls); + Assert.Equal("RECEIPT", trips.Logs.Single().Method); + } + + [Fact] + public async Task Payment_needs_ready_to_pay_and_resets_the_balance() + { + var (svc, trips, _, _) = Build(); + trips.Trip.StatusCode = "DISCHARGED"; + trips.Wallet = new TripWallet { Id = 6, Epayment = 0 }; + await Assert.ThrowsAsync(() => svc.PaymentAsync(1, default)); + + trips.Trip.StatusCode = "READY_TO_PAY"; + await svc.PaymentAsync(1, default); + Assert.Contains("exchanged::False:6", trips.Calls); + Assert.Contains("reset-balance", trips.Calls); + } + + [Fact] + public async Task Cash_payment_sets_the_option_and_orange_does_not_reset_the_balance() + { + var (svc, trips, _, _) = Build(); + trips.Trip.StatusCode = "DISCHARGED"; + trips.Wallet = ReadyWallet(); + + await svc.CashPaymentAsync(1, default); + Assert.Contains("exchanged:CACH_PAYMENT:True:5", trips.Calls); + Assert.Contains("reset-balance", trips.Calls); + + trips.Calls.Clear(); + await svc.OrangePaymentAsync(1, default); + Assert.Contains("exchanged:ORANGE_PAYMENT:True:5", trips.Calls); + Assert.DoesNotContain("reset-balance", trips.Calls); + } + + [Fact] + public async Task Activate_wallet_exchange_refuses_when_dinarak_already_has_the_transfer() + { + var (svc, trips, _, _) = Build(new FakeDinarak(new("000", "SUCCESS"), new DinarakTransferStatus(true, "Success", null))); + trips.Trip.StatusCode = "PENDING_EXCHANGE"; + trips.Trip.DinarakReferenceId = 352.1m; + var ex = await Assert.ThrowsAsync(() => svc.ActivateWalletExchangeAsync(1, default)); + Assert.Equal("لايمكن تفعيل الصرف, تم الصرف مسبقا", ex.Message); + Assert.DoesNotContain("bump", trips.Calls); + } + + [Fact] + public async Task Activate_wallet_exchange_moves_the_reference_when_nothing_was_sent() + { + var (svc, trips, _, _) = Build(); + trips.Trip.StatusCode = "PENDING_EXCHANGE"; + trips.Trip.DinarakReferenceId = 352.1m; + await svc.ActivateWalletExchangeAsync(1, default); + Assert.Contains("bump", trips.Calls); + Assert.Equal("{\"DINARAK_REFERENCE_ID\":\"352.11\"}", trips.Logs.Single().New); + } + + [Fact] + public async Task Activate_wallet_exchange_refuses_when_the_dinarak_state_cannot_be_read() + { + var (svc, trips, _, _) = Build(new FakeDinarak(new("000", "SUCCESS"), new DinarakTransferStatus(false, "ERROR", null))); + trips.Trip.StatusCode = "PENDING_EXCHANGE"; + trips.Trip.DinarakReferenceId = 352.1m; + var ex = await Assert.ThrowsAsync(() => svc.ActivateWalletExchangeAsync(1, default)); + Assert.Equal("DINARAK_STATUS_UNKNOWN", ex.Code); + } + + [Fact] + public async Task Print_stores_the_voucher_serial_once() + { + var (svc, trips, _, _) = Build(); + trips.Trip.StatusCode = "DISCHARGED"; + + var v = await svc.PrintAsync(1, default); + Assert.Equal("202600096", v.Serial); + Assert.Equal(271.975m, v.Amount); + Assert.Contains("serial:202600096", trips.Calls); + + trips.Calls.Clear(); + trips.Trip.VoucherSerialNumber = 202200001; + Assert.Equal("202200001", (await svc.PrintAsync(1, default)).Serial); + Assert.DoesNotContain(trips.Calls, c => c.StartsWith("serial")); + } +} diff --git a/tests/NTP.Tests/Refinery/TripCalculatorTests.cs b/tests/NTP.Tests/Refinery/TripCalculatorTests.cs new file mode 100644 index 0000000..4d56adf --- /dev/null +++ b/tests/NTP.Tests/Refinery/TripCalculatorTests.cs @@ -0,0 +1,230 @@ +using NTP.Application.Refinery.Trips; + +namespace NTP.Tests.Refinery; + +public class TripCalculatorTests +{ + // REFINERY_VARIABLES group 30 (August 2023), values as stored in the database + private static readonly TripVariables August2023 = TripVariables.FromPairs( + [ + new("COMMISSION", "0.95"), new("DIESEL_LITER_PRICE", "0.715"), new("DRIVER_TIP", "20"), new("FIRST_ADVANCE_PAYMENT", "100"), + new("PERMIT_DISPATCH", "2.5"), new("TOLERANCE_PERCENTAGE", "0.005"), new("TON_PRICE", "700"), new("TON_WAGE", "17.936"), + new("WAYBILL_FEE", "0.75") + ]); + + [Fact] + public void Penalised_trip_matches_the_stored_legacy_figures() + { + // REFINERY_TRIPS id 77314 (COMPLETE): loaded 34560 kg, discharged 34290 kg, no water + var a = TripCalculator.Calculate(new TripWeights(34560, 34290, 0, null), August2023, null); + + Assert.Equal(172m, a.ToleranceQuantity); + Assert.Equal(98m, a.PenaltyQuantity); + Assert.Equal(68.6m, a.PenaltyAmount); + Assert.Equal(34.29m, a.CalculatedQuantityTon); + Assert.Equal(615.025m, a.QuantityWage); + Assert.Equal(271.975m, a.TripNetWage); + Assert.Equal(271.975m, a.NetWage); + Assert.Equal(0m, a.RemainingBalance); + } + + [Fact] + public void Loss_inside_the_tolerance_is_not_penalised() + { + // id 77683: 39820 / 39770, tolerance floor(199.1) = 199 >= 50 + var a = TripCalculator.Calculate(new TripWeights(39820, 39770, 0, null), August2023, null); + + Assert.Equal(0m, a.PenaltyQuantity); + Assert.Equal(0m, a.PenaltyAmount); + Assert.Equal(713.315m, a.QuantityWage); + Assert.Equal(438.865m, a.TripNetWage); + } + + [Fact] + public void Remaining_balance_of_the_truck_is_added_to_the_net_wage_only() + { + var a = TripCalculator.Calculate(new TripWeights(39820, 39770, 0, null), August2023, -12.5m); + + Assert.Equal(438.865m, a.TripNetWage); + Assert.Equal(426.365m, a.NetWage); + Assert.Equal(-12.5m, a.RemainingBalance); + } + + [Fact] + public void Accompanying_water_is_paid_as_if_delivered() + { + // water 300 kg >= loss 270 kg: the whole loaded weight is paid and nothing is fined + var a = TripCalculator.Calculate(new TripWeights(34560, 34290, 300, null), August2023, null); + + Assert.Equal(34.56m, a.CalculatedQuantityTon); + Assert.Equal(0m, a.PenaltyAmount); + } + + [Fact] + public void Water_flag_1_ignores_the_water_and_the_tolerance() + { + // legacy factory 816-819: WATER_FLAG = 1 and water > 0 -> water 0 and tolerance 0, so the full loss is fined + var a = TripCalculator.Calculate(new TripWeights(34560, 34290, 300, 1), August2023, null); + + Assert.Equal(270m, a.PenaltyQuantity); + Assert.Equal(189m, a.PenaltyAmount); + Assert.Equal(34.29m, a.CalculatedQuantityTon); + } + + [Fact] + public void Ton_price_correction_changes_only_the_penalty_and_skips_the_balance() + { + var withCorrection = August2023 with { TonPriceCorrection = 800m }; + var a = TripCalculator.Calculate(new TripWeights(34560, 34290, 0, null), withCorrection, 99m, useTonPriceCorrection: true); + + Assert.Equal(78.4m, a.PenaltyAmount); // 98 kg * 800 / 1000 + Assert.Equal(a.TripNetWage, a.NetWage); + Assert.Equal(0m, a.RemainingBalance); + Assert.Equal(271.975m - 9.8m, a.TripNetWage); + } + + [Fact] + public void Second_advance_is_the_diesel_value_minus_the_first() + { + var a = TripCalculator.Calculate(new TripWeights(34560, 34290, 0, null), August2023, null); + Assert.Equal(350m * 0.715m - 100m, a.SecondAdvancePayment); + } + + [Fact] + public void Missing_variables_give_a_zero_wage_that_the_payment_rules_refuse() + { + var empty = TripVariables.FromPairs([]); + var a = TripCalculator.Calculate(new TripWeights(34560, 34290, 0, null), empty, null); + Assert.Equal(0m, a.QuantityWage); + // zero net wage = "price not declared" + Assert.Throws(() => TripPaymentRules.EnsurePayable(0, 500)); + } + + [Fact] + public void Variables_take_the_first_value_of_a_key_and_ignore_unparsable_values() + { + var v = TripVariables.FromPairs([new("TON_WAGE", "17.936"), new("TON_WAGE", "99"), new("DRIVER_TIP", "abc")]); + Assert.Equal(17.936m, v.TonWage); + Assert.Equal(0m, v.DriverTip); + } +} + +public class TripPaymentRulesTests +{ + [Fact] + public void Zero_negative_and_too_big_amounts_are_refused_with_the_legacy_texts() + { + Assert.Equal("السعر غير معرف لتاريخ التحميل", Assert.Throws(() => TripPaymentRules.EnsurePayable(0, 500)).Message); + Assert.Equal("الدفع مسموح للمبالغ اكبر من صفر", Assert.Throws(() => TripPaymentRules.EnsurePayable(-1, 500)).Message); + Assert.Equal("الدفع مسموح فقط للمبالغ اقل من 500 دينار", Assert.Throws(() => TripPaymentRules.EnsurePayable(500.001m, 500)).Message); + TripPaymentRules.EnsurePayable(500m, 500); + } + + [Fact] + public void Orange_payment_only_checks_for_zero() + { + TripPaymentRules.EnsurePayable(-5m, 500, checkSign: false); + TripPaymentRules.EnsurePayable(5000m, 500, checkSign: false); + Assert.Throws(() => TripPaymentRules.EnsurePayable(0, 500, checkSign: false)); + } + + [Theory] + [InlineData(false, 1, "795891836", "1", "x", "CANNOT_COMPLETE_ACTION_NO_PAYMENT_METHOD")] + [InlineData(true, 0, "795891836", "1", "x", "THERE_IS_EWALLET_PLEASE_RELOAD_FORM")] + [InlineData(true, 1, "", "1", "x", "WALLET_NUMBER_IS_EMPTY")] + [InlineData(true, 1, "795891836", "", "x", "OWNER_NNPN_IS_EMPTY")] + [InlineData(true, 1, "795891836", "1", "", "REFINERY_OWNER_NNPN_WALLET_IS_EMPTY")] + public void Wallet_checks_follow_the_legacy_order(bool exists, int epayment, string wallet, string nnpn, string name, string code) + { + var ex = Assert.Throws(() => TripPaymentRules.EnsureWalletReady(exists, epayment, wallet, nnpn, name)); + Assert.Equal(code, ex.Code); + } + + [Fact] + public void Ready_wallet_passes() => TripPaymentRules.EnsureWalletReady(true, 1, "795891836", "9871012345", "اسم"); +} + +public class TripLogBuilderTests +{ + private static (bool, object?) Old(string key) => key switch + { + "STATUS_CODE" => (true, "DISCHARGED"), + "REMARKS" => (true, ""), + "CURRENT_BALANCE" => (true, 100m), + _ => (false, null) + }; + + [Fact] + public void Status_and_remarks_are_stored_as_arabic_captions() + { + var log = TripLogBuilder.Build("EXCHANGE", Old, new Dictionary + { + ["STATUS_CODE"] = "EXCHANGED", ["REMARKS"] = "SUCCESSFULL_EXCHANGE_OPERATION" + }); + + Assert.NotNull(log); + Assert.Contains("\"STATUS_CODE\":\"تم التفريغ\"", log!.Value.OldJson); + Assert.Contains("\"STATUS_CODE\":\"تم الصرف\"", log.Value.NewJson); + Assert.Contains("\"REMARKS\":\"تمت عملية الصرف بنجاح\"", log.Value.NewJson); + } + + [Fact] + public void Unchanged_values_and_unknown_columns_are_left_out() + { + Assert.Null(TripLogBuilder.Build("FIRST_ADVANCED_PAYMENT", Old, new Dictionary { ["CURRENT_BALANCE"] = 100.0m })); + Assert.Null(TripLogBuilder.Build("X", Old, new Dictionary { ["NOPE"] = "1" })); + + var changed = TripLogBuilder.Build("FIRST_ADVANCED_PAYMENT", Old, new Dictionary { ["CURRENT_BALANCE"] = 350.5m }); + Assert.Equal("{\"CURRENT_BALANCE\":\"100\"}", changed!.Value.OldJson); + Assert.Equal("{\"CURRENT_BALANCE\":\"350.5\"}", changed.Value.NewJson); + } + + [Fact] + public void Print_stores_its_arguments_with_empty_old_data() + { + var log = TripLogBuilder.Build("PRINT", _ => (false, null), new Dictionary { ["NOTES"] = "" }); + Assert.Equal("{}", log!.Value.OldJson); + Assert.Equal("{\"NOTES\":\"\"}", log.Value.NewJson); + } +} + +public class TripActionRulesTests +{ + [Fact] + public void Diesel_buttons_follow_the_diesel_charge_step() + { + Assert.Contains("firstAdvance", TripActionRules.Available("RESD", 0, null, false, false)); + var step1 = TripActionRules.Available("LOADED", 1, null, false, false); + Assert.Contains("secondAdvance", step1); + Assert.Contains("firstAdvanceReverse", step1); + Assert.DoesNotContain("secondAdvance", TripActionRules.Available("RESD", 1, null, false, false)); + Assert.Contains("secondAdvanceReverse", TripActionRules.Available("DISCHARGED", 2, 1, false, false)); + Assert.DoesNotContain("firstAdvance", TripActionRules.Available("RVKD", 0, null, false, false)); + } + + [Fact] + public void Discharged_trip_offers_exchange_or_audit_for_a_wallet_and_receipt_otherwise() + { + var wallet = TripActionRules.Available("DISCHARGED", 2, 1, auditMode: false, hasTransferLog: false); + Assert.Contains("exchange", wallet); + Assert.DoesNotContain("exchangeAudit", wallet); + Assert.DoesNotContain("receipt", wallet); + Assert.Contains("print", wallet); + + Assert.Contains("exchangeAudit", TripActionRules.Available("DISCHARGED", 2, 1, auditMode: true, hasTransferLog: false)); + var bank = TripActionRules.Available("DISCHARGED", 2, 0, false, false); + Assert.Contains("receipt", bank); + Assert.DoesNotContain("exchange", bank); + } + + [Fact] + public void Payment_follows_receipt_and_confirm_needs_a_transfer_log() + { + Assert.Contains("payment", TripActionRules.Available("READY_TO_PAY", 2, 0, false, false)); + var pending = TripActionRules.Available("PENDING_EXCHANGE", 2, 1, true, hasTransferLog: true); + Assert.Contains("exchange", pending); + Assert.Contains("activateWalletExchange", pending); + Assert.Contains("confirmExchange", pending); + Assert.DoesNotContain("confirmExchange", TripActionRules.Available("PENDING_EXCHANGE", 2, 1, true, hasTransferLog: false)); + } +} diff --git a/tests/NTP.Tests/Refinery/TripsWiringTests.cs b/tests/NTP.Tests/Refinery/TripsWiringTests.cs new file mode 100644 index 0000000..3c98a33 --- /dev/null +++ b/tests/NTP.Tests/Refinery/TripsWiringTests.cs @@ -0,0 +1,71 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NTP.Application; +using NTP.Application.Abstractions; +using NTP.Application.Refinery.Integrations; +using NTP.Application.Refinery.RemainingBalance; +using NTP.Application.Refinery.Trips; +using NTP.Infrastructure; +using NTP.Infrastructure.Integrations; + +namespace NTP.Tests.Refinery; + +/// The conventionally registered services of the trips slice and the Dinarak gateway resolve (no connection is opened). +public class TripsWiringTests +{ + private static ServiceProvider Build(bool dinarak = false) + { + var cfg = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["ConnectionStrings:NAFITHTCS"] = "User Id=x;Password=x;Data Source=localhost:1521/x", + ["ConnectionStrings:NtpSchema"] = "User Id=x;Password=x;Data Source=localhost:1521/x", + ["Refinery:Dinarak:Enabled"] = dinarak ? "true" : "false", + ["Refinery:Trips:MaxPaymentAmount"] = "250", + }).Build(); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(cfg); + services.AddApplication(); + services.AddInfrastructure(cfg); + services.AddHttpContextAccessor(); + services.AddScoped(_ => null!); + return services.BuildServiceProvider(); + } + + [Theory] + [InlineData(typeof(ITripQueryService))] + [InlineData(typeof(ITripActionService))] + [InlineData(typeof(ITripReportService))] + [InlineData(typeof(ITripAmountsService))] + [InlineData(typeof(IRemainingBalanceService))] + [InlineData(typeof(ITripRepository))] + [InlineData(typeof(IVoucherSerialRepository))] + [InlineData(typeof(IDinarakGateway))] + [InlineData(typeof(IDinarakReferenceGateway))] + public void Services_resolve(Type service) + { + using var sp = Build(); + using var scope = sp.CreateScope(); + Assert.NotNull(scope.ServiceProvider.GetRequiredService(service)); + } + + [Fact] + public void Settings_are_bound_and_dinarak_is_off_by_default() + { + using var sp = Build(); + using var scope = sp.CreateScope(); + Assert.Equal(250m, scope.ServiceProvider.GetRequiredService().Value.MaxPaymentAmount); + Assert.False(scope.ServiceProvider.GetRequiredService>().Value.Enabled); + } + + [Fact] + public async Task Disabled_gateway_answers_106_without_touching_the_database() + { + using var sp = Build(); + using var scope = sp.CreateScope(); + var r = await scope.ServiceProvider.GetRequiredService().TransferAsync(1, "795000000", "1", 5m, "x"); + Assert.Equal("106", r.Code); + var s = await scope.ServiceProvider.GetRequiredService().GetTransferByReferenceAsync(1.1m); + Assert.Equal("DISABLED", s.StatusName); + } +} diff --git a/tests/NTP.Tests/Refinery/VariablesRulesTests.cs b/tests/NTP.Tests/Refinery/VariablesRulesTests.cs new file mode 100644 index 0000000..85bcddb --- /dev/null +++ b/tests/NTP.Tests/Refinery/VariablesRulesTests.cs @@ -0,0 +1,100 @@ +using NTP.Application.Refinery.Variables; + +namespace NTP.Tests.Refinery; + +public class VariablesRulesTests +{ + private static SaveVariablesRequest Request(string start, string end, decimal diesel = 0.615m, decimal wage = 16.855m) => new() + { + StartDate = DateOnly.Parse(start), EndDate = DateOnly.Parse(end), DieselLiterPrice = diesel, TonWage = wage, TonPrice = 700, + DriverTip = 20, PermitDispatch = 2.5m, WaybillFee = 0.75m, Commission = 0.45m, TolerancePercentage = 0.005m, FirstAdvancePayment = 100, + }; + + private static readonly VariablesPeriod[] Existing = + [ + new(1, new DateTime(2023, 7, 1), new DateTime(2023, 7, 31)), + new(2, new DateTime(2023, 8, 1), new DateTime(2023, 8, 31)), + ]; + + [Fact] + public void A_free_period_is_accepted() => + Assert.Null(VariablesRules.FirstError(Existing, Request("2023-09-01", "2023-09-30"))); + + [Fact] + public void Start_inside_another_period_is_refused_first() + { + var e = VariablesRules.FirstError(Existing, Request("2023-07-15", "2023-09-30")); + Assert.Equal(VariablesErrors.StartDateInPreviousPeriod, e!.Value.Code); + } + + [Fact] + public void End_inside_another_period_is_refused() + { + var e = VariablesRules.FirstError(Existing, Request("2023-06-01", "2023-07-01")); + Assert.Equal(VariablesErrors.EndDateInPreviousPeriod, e!.Value.Code); + } + + [Fact] + public void Period_that_swallows_another_is_refused() + { + var e = VariablesRules.FirstError(Existing, Request("2023-06-15", "2023-09-15")); + // the end (09-15) is free and the start (06-15) is free, but both July and August lie inside + Assert.Equal(VariablesErrors.DateOverlap, e!.Value.Code); + } + + [Fact] + public void Period_edges_are_inclusive() + { + Assert.Equal(VariablesErrors.StartDateInPreviousPeriod, VariablesRules.FirstError(Existing, Request("2023-08-31", "2023-09-30"))!.Value.Code); + Assert.Null(VariablesRules.FirstError(Existing, Request("2023-09-01", "2023-09-01"))); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(2)] + [InlineData(3.5)] + public void Diesel_price_must_be_between_0_and_2_exclusive(double price) + { + var e = VariablesRules.FirstError([], Request("2024-01-01", "2024-01-31", diesel: (decimal)price)); + Assert.Equal(VariablesErrors.DieselPriceNotCorrect, e!.Value.Code); + } + + [Theory] + [InlineData(0)] + [InlineData(100)] + [InlineData(250)] + public void Ton_wage_must_be_between_0_and_100_exclusive(double wage) + { + var e = VariablesRules.FirstError([], Request("2024-01-01", "2024-01-31", wage: (decimal)wage)); + Assert.Equal(VariablesErrors.TonWageNotCorrect, e!.Value.Code); + } + + [Fact] + public void Start_after_end_is_refused_last() + { + var e = VariablesRules.FirstError([], Request("2024-02-01", "2024-01-31")); + Assert.Equal(VariablesErrors.StartAfterEnd, e!.Value.Code); + // a bad price is reported before the date order + Assert.Equal(VariablesErrors.DieselPriceNotCorrect, VariablesRules.FirstError([], Request("2024-02-01", "2024-01-31", diesel: 5))!.Value.Code); + } + + [Fact] + public void Values_are_stored_as_plain_invariant_text_for_the_nine_keys() + { + var v = VariablesRules.ToValues(Request("2024-01-01", "2024-01-31")); + Assert.Equal(VariablesRules.SetKeys.OrderBy(k => k), v.Keys.OrderBy(k => k)); + Assert.Equal("0.615", v["DIESEL_LITER_PRICE"]); + Assert.Equal("700", v["TON_PRICE"]); + Assert.Equal("0.005", v["TOLERANCE_PERCENTAGE"]); + } + + [Theory] + [InlineData(700, 700, false)] + [InlineData(700, 750, true)] + public void Balances_are_recalculated_only_when_the_correction_differs_from_the_ton_price(double price, double correction, bool changes) => + Assert.Equal(changes, VariablesRules.TonPriceChanges((decimal)price, (decimal)correction)); + + [Fact] + public void Without_a_ton_price_row_nothing_is_recalculated() => Assert.False(VariablesRules.TonPriceChanges(null, 750)); +} diff --git a/tests/NTP.Tests/Refinery/WageClaimRulesTests.cs b/tests/NTP.Tests/Refinery/WageClaimRulesTests.cs new file mode 100644 index 0000000..75668c3 --- /dev/null +++ b/tests/NTP.Tests/Refinery/WageClaimRulesTests.cs @@ -0,0 +1,96 @@ +using NTP.Application.Common; +using NTP.Application.Refinery.WageClaims; + +namespace NTP.Tests.Refinery; + +public class WageClaimRulesTests +{ + [Fact] + public void Trip_statuses_keep_only_the_claimable_ones() + { + var r = WageClaimRules.NormalizeTripStatuses(["ALL", "exchanged", "EXCHANGED,READY_TO_PAY", "RVKD", " discharged "]); + Assert.Equal(["EXCHANGED", "READY_TO_PAY", "DISCHARGED"], r); + Assert.Empty(WageClaimRules.NormalizeTripStatuses(null)); + Assert.Empty(WageClaimRules.NormalizeTripStatuses(["ALL"])); + } + + [Fact] + public void Create_validation_follows_the_legacy_order_and_texts() + { + var ok = new[] { "EXCHANGED" }; + var from = new DateOnly(2024, 3, 1); + var to = new DateOnly(2024, 3, 31); + + Assert.Equal("يجب اختيار الحالة", Assert.Throws(() => WageClaimRules.ValidateCreate([], null, null)).Message); + Assert.Equal("يجب اختيار التاريخ", Assert.Throws(() => WageClaimRules.ValidateCreate(ok, from, null)).Message); + Assert.Equal("يجب اختيار التاريخ", Assert.Throws(() => WageClaimRules.ValidateCreate(ok, null, to)).Message); + Assert.Equal("لا يجوز ان يكون تاريخ من أكبر من تارخ الى", Assert.Throws(() => WageClaimRules.ValidateCreate(ok, to, from)).Message); + WageClaimRules.ValidateCreate(ok, from, from); // same day is fine + WageClaimRules.ValidateCreate(ok, from, to); + } + + [Fact] + public void Claim_closes_only_when_it_has_trips_and_all_are_exchanged() + { + Assert.True(WageClaimRules.CanCloseClaim(["EXCHANGED", "EXCHANGED"])); + Assert.False(WageClaimRules.CanCloseClaim([])); + Assert.False(WageClaimRules.CanCloseClaim(["EXCHANGED", "DISCHARGED"])); + Assert.False(WageClaimRules.CanCloseClaim(["READY_TO_PAY"])); + } + + [Theory] + [InlineData("Status Updated successfully To 7", true)] + [InlineData("OK: status updated SUCCESSFULLY to 7 for 123", true)] + [InlineData("Status Updated successfully To 6", false)] + [InlineData("", false)] + [InlineData(null, false)] + public void Jopetrol_answer_is_matched_like_findNoCase(string? answer, bool expected) => + Assert.Equal(expected, WageClaimRules.IsStatus7Success(answer)); + + [Fact] + public void Loading_date_range_ends_at_the_end_of_the_last_day() + { + // legacy: between 'yyyymmdd000000' and 'yyyymmdd235959' + Assert.Equal(new DateTime(2024, 4, 1), WageClaimRules.ExclusiveEnd(new DateOnly(2024, 3, 31))); + } + + [Fact] + public void Report_line_shows_deductions_negative_like_the_legacy_report() + { + var line = WageClaimRules.ToReportLine(new WageClaimReportRaw + { + NetLoadingWeight = 30000, NetDischargeWeight = 29900, ToleranceQuantity = 150, PenaltyQuantity = 12, WaterAmount = 0, + DriverTip = 1.5m, PermitDispatch = 2, WaybillFee = 3, DieselLiterPrice = 0.8m, AdvancePaymentForDiesel = 280, Commission = 4, NetWage = 100, + }); + Assert.Equal(100m, line.WeightDifference); + Assert.Equal(0m, line.PenaltyQuantity); // difference below the tolerance: no penalty + Assert.False(line.WaterExist); + Assert.Equal([-1.5m, -2m, -3m, -0.8m, -280m, -4m], [line.DriverTip, line.PermitDispatch, line.WaybillFee, line.DieselLiterPrice, line.AdvancePaymentForDiesel, line.Commission]); + Assert.Equal(100m, line.NetWage); + } + + [Fact] + public void Report_line_keeps_the_penalty_above_the_tolerance_and_a_missing_diesel_advance() + { + var line = WageClaimRules.ToReportLine(new WageClaimReportRaw + { + NetLoadingWeight = 30000, NetDischargeWeight = 29700, ToleranceQuantity = 150, PenaltyQuantity = 150, WaterAmount = 20, AdvancePaymentForDiesel = null, + }); + Assert.Equal(300m, line.WeightDifference); + Assert.Equal(150m, line.PenaltyQuantity); + Assert.True(line.WaterExist); + Assert.Equal(0m, line.AdvancePaymentForDiesel); + } + + [Theory] + [InlineData("NEW", "جديد")] + [InlineData("CLOSE", "تم التسديد")] + [InlineData("COMPLETE", "مكتمل")] + public void Claim_status_captions(string code, string caption) => Assert.Equal(caption, WageClaimRules.ClaimStatusCaption(code)); + + [Fact] + public void Log_json_keeps_arabic_unescaped() + { + Assert.Equal("{\"STATUS_CODE\":\"تم التسديد\"}", ClaimLogJson.Status("تم التسديد")); + } +} diff --git a/tests/NTP.Tests/Refinery/WageClaimServiceTests.cs b/tests/NTP.Tests/Refinery/WageClaimServiceTests.cs new file mode 100644 index 0000000..a02da65 --- /dev/null +++ b/tests/NTP.Tests/Refinery/WageClaimServiceTests.cs @@ -0,0 +1,172 @@ +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 => "PTADM"; + public string RoleName => "PTADM"; + 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 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 }); + 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 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 Task> ReportRowsAsync(long claimId, CancellationToken ct = default) => Task.FromResult>([]); + } + + 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); + } + + [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"); + } +} diff --git a/tests/NTP.Tests/Refinery/WalletsRulesTests.cs b/tests/NTP.Tests/Refinery/WalletsRulesTests.cs new file mode 100644 index 0000000..e005bd2 --- /dev/null +++ b/tests/NTP.Tests/Refinery/WalletsRulesTests.cs @@ -0,0 +1,137 @@ +using System.Text.Json; +using NTP.Application.Refinery.Wallets; + +namespace NTP.Tests.Refinery; + +public class WalletsRulesTests +{ + private readonly SaveWalletValidator _validator = new(); + + private static SaveWalletRequest Wallet() => new() + { + PaymentMethod = "WALLET", Tn = "6039498", OwnerNnpn = "9671029403", WalletNumber = "0795600199", OwnerName = "نايل محمد", + }; + + private static SaveWalletRequest Bank() => new() + { + PaymentMethod = "BANK", Tn = "6060436", OwnerName = "شركة", OwnerNameEnglish = "Company", BankName = "البنك الاسلامي", BankBranch = "الرمثا", + Iban = "JO22JIBA0750000979075410400005", BankAccount = "0750979075410400005", + }; + + private static SaveWalletRequest Driver() => new() + { + PaymentMethod = "DRIVER_TIP", DriverName = "ناصر عطيه", DriverNnpn = "9871001698", WalletNumber = "795144330", + }; + + [Theory] + [InlineData("0795600199", true)] + [InlineData("795600199", true)] + [InlineData("0775600199", true)] + [InlineData("0765600199", false)] // 76 is not 77/78/79 + [InlineData("079560019", false)] + [InlineData("07956001999", false)] + [InlineData("abc", false)] + public void Mobile_wallet_number_format(string value, bool ok) => Assert.Equal(ok, WalletsRules.IsMobile(value)); + + [Theory] + [InlineData("0750979075410400005", true)] + [InlineData("12/AB 34", true)] + [InlineData("12-34", false)] + public void Bank_account_allows_letters_digits_slash_and_space(string value, bool ok) => Assert.Equal(ok, WalletsRules.IsBankAccount(value)); + + [Fact] + public void The_three_forms_are_valid() + { + Assert.True(_validator.Validate(Wallet()).IsValid); + Assert.True(_validator.Validate(Bank()).IsValid); + Assert.True(_validator.Validate(Driver()).IsValid); + } + + [Fact] + public void Required_fields_per_method() + { + var w = Wallet(); w.OwnerName = ""; Assert.False(_validator.Validate(w).IsValid); + w = Wallet(); w.Tn = ""; Assert.False(_validator.Validate(w).IsValid); + w = Wallet(); w.WalletNumber = "123"; Assert.Contains("رقم المحفظة غير صحيح", _validator.Validate(w).Errors.Select(e => e.ErrorMessage)); + var b = Bank(); b.Iban = ""; Assert.False(_validator.Validate(b).IsValid); + b = Bank(); b.BankAccount = "12-3"; Assert.False(_validator.Validate(b).IsValid); + b = Bank(); b.OwnerNnpn = "12ab"; Assert.False(_validator.Validate(b).IsValid); + var d = Driver(); d.DriverNnpn = ""; Assert.False(_validator.Validate(d).IsValid); + d = Driver(); d.DriverName = ""; Assert.False(_validator.Validate(d).IsValid); + Assert.False(_validator.Validate(new SaveWalletRequest { PaymentMethod = "CASH" }).IsValid); + } + + [Fact] + public void Wallet_maps_to_epayment_1_with_the_wallet_number_and_no_bank_data() + { + var w = WalletsRules.ToWrite(Wallet()); + Assert.Equal(1, w.Epayment); + Assert.Equal(6039498, w.Tn); + Assert.Equal(9671029403, w.OwnerNnpn); + Assert.Equal("0795600199", w.WalletNumber); + Assert.Null(w.Iban); + Assert.Null(w.DriverNnpn); + } + + [Fact] + public void Bank_maps_to_epayment_0_without_wallet_number() + { + var w = WalletsRules.ToWrite(Bank()); + Assert.Equal(0, w.Epayment); + Assert.Null(w.WalletNumber); + Assert.Equal("Company", w.OwnerNameEnglish); + Assert.Equal("0750979075410400005", w.BankAccount); + } + + [Fact] + public void Driver_wallet_has_no_truck_and_no_owner() + { + var w = WalletsRules.ToWrite(Driver()); + Assert.Equal(1, w.Epayment); + Assert.Null(w.Tn); + Assert.Null(w.OwnerNnpn); + Assert.Equal(9871001698, w.DriverNnpn); + Assert.Equal("795144330", w.WalletNumber); + } + + [Fact] + public void Method_of_a_stored_record() + { + Assert.Equal("BANK", WalletsRules.MethodOf(new WalletRow { Epayment = 0, Tn = 1 })); + Assert.Equal("WALLET", WalletsRules.MethodOf(new WalletRow { Epayment = 1, Tn = 1 })); + Assert.Equal("DRIVER_TIP", WalletsRules.MethodOf(new WalletRow { Epayment = 1, Tn = null, DriverNnpn = 5 })); + } + + [Fact] + public void Update_log_lists_only_the_changed_columns() + { + var old = new WalletRow { Id = 469, Tn = 6039498, Epayment = 1, OwnerNnpn = 9481009065, OwnerName = "داوود", WalletNumber = "797564486", Iban = "-", BankAccount = "-", BankName = "-" }; + var req = Wallet(); req.OwnerNnpn = "9731033500"; req.OwnerName = "هاشم"; req.WalletNumber = "0796792005"; req.Tn = "6039498"; + var diff = WalletsRules.Diff(old, WalletsRules.ToWrite(req)); + Assert.NotNull(diff); + var o = JsonSerializer.Deserialize>(diff!.Value.OldData)!; + var n = JsonSerializer.Deserialize>(diff.Value.NewData)!; + Assert.Equal(["OWNER_NAME", "OWNER_NNPN", "WALLET_NUMBER"], o.Keys.OrderBy(k => k)); + Assert.Equal("داوود", o["OWNER_NAME"]); + Assert.Equal("هاشم", n["OWNER_NAME"]); + Assert.Equal("9731033500", n["OWNER_NNPN"]); + } + + [Fact] + public void Update_without_changes_has_no_update_log() + { + var old = new WalletRow { Tn = 6039498, Epayment = 1, OwnerNnpn = 9671029403, OwnerName = "نايل محمد", WalletNumber = "0795600199", Iban = "-", BankAccount = "-", BankName = "-" }; + Assert.Null(WalletsRules.Diff(old, WalletsRules.ToWrite(Wallet()))); + } + + [Fact] + public void Status_logs_carry_the_arabic_status_captions() + { + var (o, n) = WalletsRules.StatusChange("ACTIVE", "INACTIVE"); + Assert.Equal("{\"STATUS_CODE\":\"فعال\"}", o); + Assert.Equal("{\"STATUS_CODE\":\"غير فعال\"}", n); + } + + [Fact] + public void Create_log_is_the_legacy_status_only_json() => Assert.Equal("{\"STATUS_CODE\":\"ACTIVE\"}", WalletsRules.CreateNewData()); +} diff --git a/web/src/features/refinery/cards/api.ts b/web/src/features/refinery/cards/api.ts new file mode 100644 index 0000000..456ba63 --- /dev/null +++ b/web/src/features/refinery/cards/api.ts @@ -0,0 +1,56 @@ +import { useQuery } from '@tanstack/react-query'; +import { api, type PagedResult } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; + +export const BASE = '/refinery/cards'; +export const GRID_CARDS = 'refinery.cards'; + +export interface CardRow { + id: number; + tn: number; + cardNumber: string | null; + boxNo: number | null; + currentBalance: number; + creationDate: string | null; + createdBy: string | null; + updateDate: string | null; + updatedBy: string | null; + statusCode: string | null; + lastTripId: number | null; +} + +export interface CardLogRow { + id: number; + entityId: number; + methodName: string | null; + balanceBefore: number; + balanceAfter: number; + amount: number; + pn: string | null; + updatedBy: string | null; + lastUpdateDate: string | null; +} + +export interface CardsResult { + message: string; + id: number | null; +} + +const keys = () => [gridKey(GRID_CARDS), ['refinery.cards.one'], ['refinery.cards.log']]; + +export const useCard = (id: number | null) => + useQuery({ queryKey: ['refinery.cards.one', id], queryFn: () => api.get(`${BASE}/${id}`), enabled: id !== null }); + +export const useCardLog = (id: number | null, page: number, pageSize: number) => + useQuery({ + queryKey: ['refinery.cards.log', id, page, pageSize], + queryFn: () => api.get>(`${BASE}/${id}/log`, { page, pageSize }, { silent: true }), + enabled: id !== null, + }); + +export const useCreateCard = () => + useWrite((p: { tn: number; cardNumber: string; currentBalance: number }) => api.post(BASE, p), { invalidate: keys() }); + +export const useCardAction = () => + useWrite((v: { id: number; action: 'activate' | 'deactivate' }) => api.post(`${BASE}/${v.id}/${v.action}`), { invalidate: keys() }); diff --git a/web/src/features/refinery/cards/index.ts b/web/src/features/refinery/cards/index.ts new file mode 100644 index 0000000..c229ecd --- /dev/null +++ b/web/src/features/refinery/cards/index.ts @@ -0,0 +1,24 @@ +import { createElement } from 'react'; +import type { RouteObject } from 'react-router-dom'; +import CreditCardIcon from '@mui/icons-material/CreditCard'; +import type { MenuItem } from '@/shell/types'; +import { CardPage, CardsPage } from './pages'; +import strings from './strings'; + +/** Refinery diesel cards (بطاقات الديزل). The lead composes the refinery group and routes file. */ +export const routes: RouteObject[] = [ + { path: '/refinery/cards', element: createElement(CardsPage) }, + { path: '/refinery/cards/new', element: createElement(CardPage), handle: { crumb: strings['rc.crumb.new'] } }, + { path: '/refinery/cards/:id', element: createElement(CardPage), handle: { crumb: strings['rc.crumb.details'] } }, +]; + +export const menuItems: MenuItem[] = [ + { + key: 'refinery.cards', + title: strings['rc.menu'], + icon: CreditCardIcon, + path: '/refinery/cards', + createPath: '/refinery/cards/new', + createKey: 'refinery.cards.create', + }, +]; diff --git a/web/src/features/refinery/cards/meta.ts b/web/src/features/refinery/cards/meta.ts new file mode 100644 index 0000000..868b23c --- /dev/null +++ b/web/src/features/refinery/cards/meta.ts @@ -0,0 +1,55 @@ +import type { FormMeta, GridMeta, StatusMeta } from '@/components/meta/types'; +import strings from './strings'; +import { GRID_CARDS, type CardRow } from './api'; + +const s = strings; + +export const cardStatuses: StatusMeta[] = [ + { value: 'ACTIVE', label: s['rc.status.ACTIVE'], color: 'success' }, + { value: 'INACTIVE', label: s['rc.status.INACTIVE'], color: 'default' }, +]; + +/** Legacy REFINERY_CARDSGRID: truck, card number, balance, status; filters TN, card number, status. */ +export function cardsGrid(h: { onOpen: (r: CardRow) => void }): GridMeta { + return { + key: GRID_CARDS, + endpoint: '/refinery/cards', + rowKey: (r) => r.id, + onRowClick: h.onOpen, + pageSize: 16, + emptyAsGrid: true, + status: { param: 'statusCode', options: cardStatuses }, + filters: [ + { name: 'tn', type: 'text', label: s['rc.tn'], ltr: true }, + { name: 'cardNumber', type: 'text', label: s['rc.cardNumber'], ltr: true }, + ], + columns: [ + { key: 'tn', header: s['rc.tn'], ltr: true }, + { key: 'cardNumber', header: s['rc.cardNumber'], ltr: true }, + { key: 'currentBalance', header: s['rc.currentBalance'], format: 'number', ltr: true }, + { key: 'statusCode', header: s['rc.status'], format: 'status', statuses: cardStatuses }, + ], + }; +} + +/** Legacy REFINERY_CARDSMain.html: truck, card number and opening balance, all required. */ +export function cardForm(o: { isCreate: boolean }): FormMeta { + return { + key: 'refinery.cards.form', + sections: [ + { + key: 'card', + title: s['rc.basic'], + columns: 2, + fields: [ + { + name: 'tn', type: 'text', label: s['rc.tn'], required: true, maxLength: 12, inputKind: 'code', readOnly: !o.isCreate, + pattern: { regex: /^\d{1,12}$/, message: { en: 'Digits only', ar: 'الحقل لا يقبل أحرف' } }, + }, + { name: 'cardNumber', type: 'text', label: s['rc.cardNumber'], required: true, maxLength: 10, inputKind: 'code', readOnly: !o.isCreate }, + { name: 'currentBalance', type: 'number', label: s['rc.currentBalance'], required: true, min: 0, max: 9999999, readOnly: !o.isCreate }, + ], + }, + ], + }; +} diff --git a/web/src/features/refinery/cards/pages.tsx b/web/src/features/refinery/cards/pages.tsx new file mode 100644 index 0000000..f6f9cd8 --- /dev/null +++ b/web/src/features/refinery/cards/pages.tsx @@ -0,0 +1,192 @@ +import { useMemo, useState } from 'react'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { + Alert, Button, Paper, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TablePagination, TableRow, Typography, +} from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import BlockIcon from '@mui/icons-material/Block'; +import CheckCircleIcon from '@mui/icons-material/CheckCircle'; +import DownloadIcon from '@mui/icons-material/Download'; +import HistoryIcon from '@mui/icons-material/History'; +import type { ApiError } from '@/api/client'; +import { DataGrid, gridReturnUrl } from '@/components/DataGrid'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { MetaForm } from '@/components/MetaForm'; +import { PageHeader } from '@/components/PageHeader'; +import { SectionPaper } from '@/components/SectionPaper'; +import { SectionTitle } from '@/components/SectionTitle'; +import { StatusChip } from '@/components/StatusChip'; +import { formatDateTime, formatNumber } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { downloadFile } from '../../grains-orders/api'; +import { BASE, useCard, useCardAction, useCardLog, useCreateCard } from './api'; +import { cardForm, cardStatuses, cardsGrid } from './meta'; +import strings from './strings'; + +const ROOT = '/refinery/cards'; +const fieldErrorsOf = (e: ApiError) => ({ ...e.fieldErrors }) as Record; + +function ExportButton() { + const { t } = useFeatureUi(strings); + const { can } = useAuth(); + const toast = useToast(); + const [sp] = useSearchParams(); + const [busy, setBusy] = useState(false); + if (!can('refinery.cards.report')) return null; + const run = async () => { + setBusy(true); + const params: Record = {}; + sp.forEach((v, k) => { if (k !== 'page' && k !== 'pageSize' && k !== 'f') params[k] = v; }); + try { await downloadFile(`${BASE}/export`, params, 'REFINERY_CARDS.xlsx'); } + catch (e) { toast.error(e instanceof Error ? e.message : String(e)); } + finally { setBusy(false); } + }; + return ; +} + +export function CardsPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const { can } = useAuth(); + const meta = useMemo(() => cardsGrid({ onOpen: (r) => navigate(`${ROOT}/${r.id}`) }), [navigate]); + return ( + <> + + + {can('refinery.cards.create') && ( + + )} + + )} + /> + + + ); +} + +/** Movements of a card (legacy REFINERY_CARDS_logGrid, 5 per page). */ +function CardLog({ id }: { id: number }) { + const { t, lang } = useFeatureUi(strings); + const [page, setPage] = useState(0); + const [pageSize, setPageSize] = useState(5); + const q = useCardLog(id, page + 1, pageSize); + const rows = q.data?.items ?? []; + const method = (m: string | null) => { + const key = `rc.method.${m ?? ''}`; + return key in strings ? t(key as keyof typeof strings) : (m ?? ''); + }; + return ( + + + {q.isLoading ? : rows.length === 0 ? {t('rc.log.empty')} : ( + <> + + + + + {t('rc.log.method')} + {t('rc.log.date')} + {t('rc.log.user')} + {t('rc.log.before')} + {t('rc.log.after')} + {t('rc.log.amount')} + {t('rc.log.pn')} + + + + {rows.map((r) => ( + + {method(r.methodName)} + {formatDateTime(r.lastUpdateDate)} + {r.updatedBy} + {formatNumber(r.balanceBefore, lang)} + {formatNumber(r.balanceAfter, lang)} + {formatNumber(r.amount, lang)} + {r.pn && r.pn !== '0' ? r.pn : ''} + + ))} + +
+
+ setPage(p)} onRowsPerPageChange={(e) => { setPageSize(Number(e.target.value)); setPage(0); }} + /> + + )} +
+ ); +} + +export function CardPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const params = useParams(); + const id = params.id ? Number(params.id) : null; + const isNew = id === null; + const { can } = useAuth(); + const confirm = useConfirm(); + const q = useCard(id); + const create = useCreateCard(); + const action = useCardAction(); + const [serverErrors, setServerErrors] = useState>({}); + const meta = useMemo(() => cardForm({ isCreate: isNew }), [isNew]); + const c = q.data; + const initial = useMemo(() => (c ? { tn: String(c.tn), cardNumber: c.cardNumber ?? '', currentBalance: String(c.currentBalance) } : {}), [c]); + + if (!isNew && q.isLoading) return ; + if (!isNew && !c) return {q.error?.message ?? t('rc.loadFailed')}; + + const submit = (payload: Record) => + new Promise((resolve) => { + setServerErrors({}); + create.mutate({ tn: Number(payload.tn), cardNumber: String(payload.cardNumber ?? ''), currentBalance: Number(payload.currentBalance) }, { + onSuccess: (res) => { resolve(); navigate(res.id ? `${ROOT}/${res.id}` : gridReturnUrl(ROOT), { replace: true }); }, + onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); }, + }); + }); + + const run = async (kind: 'activate' | 'deactivate') => { + if (await confirm({ message: t(kind === 'activate' ? 'rc.activateConfirm' : 'rc.deactivateConfirm'), danger: kind === 'deactivate' })) { + action.mutate({ id: id!, action: kind }); + } + }; + const status = c?.statusCode?.toUpperCase(); + + return ( + + : undefined} + backTo={ROOT} + actions={!isNew && ( + <> + {status === 'INACTIVE' && can('refinery.cards.activate') && ( + + )} + {status === 'ACTIVE' && can('refinery.cards.deactivate') && ( + + )} + + )} + /> + navigate(gridReturnUrl(ROOT))} + onSubmit={submit} + /> + {!isNew && } + + ); +} diff --git a/web/src/features/refinery/cards/strings.ts b/web/src/features/refinery/cards/strings.ts new file mode 100644 index 0000000..709fcd7 --- /dev/null +++ b/web/src/features/refinery/cards/strings.ts @@ -0,0 +1,46 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Strings of the refinery diesel cards screen (legacy captions REFINERY_CARDS.* / LOG.* / PUBLIC.*, verbatim in Arabic where they exist). */ +export default defineStrings({ + 'rc.menu': { en: 'Diesel cards', ar: 'بطاقات الديزل' }, + 'rc.title': { en: 'Diesel cards', ar: 'بطاقات الديزل' }, + 'rc.subtitle': { en: 'Jopetrol diesel cards of the trucks', ar: 'بطاقات جوبترول لتعبئة الديزل للشاحنات' }, + 'rc.new': { en: 'New card', ar: 'بطاقة جديدة' }, + 'rc.createTitle': { en: 'New diesel card', ar: 'بطاقة ديزل جديدة' }, + 'rc.detailTitle': { en: 'Card {number}', ar: 'البطاقة {number}' }, + 'rc.crumb.new': { en: 'New', ar: 'جديد' }, + 'rc.crumb.details': { en: 'Details', ar: 'التفاصيل' }, + 'rc.loadFailed': { en: 'The card could not be loaded.', ar: 'تعذر تحميل البطاقة.' }, + 'rc.return': { en: 'Back', ar: 'عودة' }, + 'rc.basic': { en: 'Basic information', ar: 'المعلومات الأساسية' }, + + 'rc.tn': { en: 'Truck number', ar: 'رقم الشاحنة' }, + 'rc.cardNumber': { en: 'Card number', ar: 'رقم بطاقة جوبترول' }, + 'rc.currentBalance': { en: 'Current balance', ar: 'الرصيد الحالي' }, + 'rc.status': { en: 'Status', ar: 'الحالة' }, + 'rc.status.ACTIVE': { en: 'Active', ar: 'فعال' }, + 'rc.status.INACTIVE': { en: 'Inactive', ar: 'غير فعال' }, + + 'rc.activate': { en: 'Activate', ar: 'تفعيل' }, + 'rc.deactivate': { en: 'Deactivate', ar: 'ايقاف' }, + 'rc.activateConfirm': { en: 'Activate this card?', ar: 'هل تريد تفعيل البطاقة؟' }, + 'rc.deactivateConfirm': { en: 'Deactivate this card?', ar: 'هل تريد ايقاف البطاقة؟' }, + 'rc.export': { en: 'Excel', ar: 'تصدير Excel' }, + + 'rc.log': { en: 'Movements log', ar: 'سجل الحركات' }, + 'rc.log.empty': { en: 'No movements', ar: 'لا يوجد معلومات' }, + 'rc.log.method': { en: 'Movement', ar: 'نوع الحركة' }, + 'rc.log.date': { en: 'Date', ar: 'تاريخ التعديل' }, + 'rc.log.user': { en: 'User', ar: 'اسم المستخدم' }, + 'rc.log.before': { en: 'Balance before', ar: 'الرصيد السابق' }, + 'rc.log.after': { en: 'Balance after', ar: 'الرصيد الحالي' }, + 'rc.log.amount': { en: 'Amount', ar: 'المبلغ' }, + 'rc.log.pn': { en: 'Trip number', ar: 'رقم الارسالية' }, + 'rc.method.CREATE': { en: 'Created', ar: 'إنشاء' }, + 'rc.method.ACTIVE': { en: 'Activated', ar: 'تفعيل' }, + 'rc.method.DEACTIVE': { en: 'Deactivated', ar: 'ايقاف' }, + 'rc.method.FIRST_ADVANCED_PAYMENT': { en: 'Diesel top-up for loading', ar: 'تعبئة بطاقة الديزل للتحميل' }, + 'rc.method.FIRST_ADVANCED_PAYMENT_REVERSE': { en: 'Loading top-up cancelled', ar: 'الغاء شحن الديزل تحميل' }, + 'rc.method.SECOND_ADVANCED_PAYMENT': { en: 'Diesel top-up for unloading', ar: 'تعبئة بطاقة الديزل للتفريغ' }, + 'rc.method.SECOND_ADVANCED_PAYMENT_REVERSE': { en: 'Unloading top-up cancelled', ar: 'الغاء شحن الديزل تفريغ' }, +}); diff --git a/web/src/features/refinery/commission-claims/api.ts b/web/src/features/refinery/commission-claims/api.ts new file mode 100644 index 0000000..1fe6b9f --- /dev/null +++ b/web/src/features/refinery/commission-claims/api.ts @@ -0,0 +1,40 @@ +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { api } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; +import type { ClaimResult, WageClaimRow } from '../wage-claims/types'; +import type { CommissionClaimRow } from './types'; + +export const BASE = '/refinery/commission-claims'; +export const GRID_COMMISSION_CLAIMS = 'refinery.commissionClaims'; + +export const useCommissionClaim = (id: number | null) => + useQuery({ queryKey: ['refinery.commissionClaim', id], queryFn: () => api.get(`${BASE}/${id}`), enabled: id !== null }); + +export const useClaimWageClaims = (id: number | null) => + useQuery({ queryKey: ['refinery.commissionClaim.wageClaims', id], queryFn: () => api.get(`${BASE}/${id}/wage-claims`), enabled: id !== null }); + +/** Create dialog: wage claims without a commission claim in the given statuses (NEW and / or CLOSE). */ +export const useWageClaimCandidates = (statuses: string[], applied: number) => + useQuery({ + queryKey: ['refinery.commissionClaim.candidates', statuses.join(','), applied], + queryFn: () => api.get(`${BASE}/wage-claim-candidates`, { statusCode: statuses.join(',') }, { silent: true }), + }); + +export function useCreateCommissionClaim() { + return useWrite((wageClaimIds: number[]) => api.post(BASE, { wageClaimIds }), { + invalidate: [gridKey(GRID_COMMISSION_CLAIMS), ['refinery.commissionClaim.candidates'], gridKey('refinery.wageClaims')], + }); +} + +export function useCompleteCommissionClaim() { + const qc = useQueryClient(); + return useWrite((id: number) => api.post(`${BASE}/${id}/complete`), { + invalidate: [gridKey(GRID_COMMISSION_CLAIMS), gridKey('refinery.wageClaims')], + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ['refinery.commissionClaim'] }); + void qc.invalidateQueries({ queryKey: ['refinery.commissionClaim.wageClaims'] }); + void qc.invalidateQueries({ queryKey: ['refinery.wageClaim.log'] }); + }, + }); +} diff --git a/web/src/features/refinery/commission-claims/index.ts b/web/src/features/refinery/commission-claims/index.ts new file mode 100644 index 0000000..d71c25c --- /dev/null +++ b/web/src/features/refinery/commission-claims/index.ts @@ -0,0 +1 @@ +export { routes, menuItems } from './routes'; diff --git a/web/src/features/refinery/commission-claims/meta.ts b/web/src/features/refinery/commission-claims/meta.ts new file mode 100644 index 0000000..ee8c85e --- /dev/null +++ b/web/src/features/refinery/commission-claims/meta.ts @@ -0,0 +1,38 @@ +import type { FilterMeta, GridMeta, StatusMeta } from '@/components/meta/types'; +import { GRID_COMMISSION_CLAIMS } from './api'; +import strings from './strings'; +import type { CommissionClaimRow } from './types'; + +const l = (key: keyof typeof strings) => strings[key]; + +/** REFINERY_COMMISSION_CLAIM.STATUS.* */ +export const commissionStatuses: StatusMeta[] = [ + { value: 'NEW', label: l('cc.statusNew'), color: 'warning' }, + { value: 'COMPLETE', label: l('cc.statusComplete'), color: 'success' }, + { value: 'CLOSE', label: l('cc.statusClose'), color: 'info' }, +]; + +const filters: FilterMeta[] = [ + { name: 'commissionClaimNo', type: 'text', label: l('cc.no'), inputKind: 'code' }, + { name: 'commissionClaimDate', type: 'date', label: l('cc.date') }, +]; + +/** Legacy REFINERY_COMMISSION_CLAIMGRID: no, date, wage claim count, status; NEW claims on opening (args STATUS_CODE NEW). */ +export function commissionClaimGrid(onOpen: (r: CommissionClaimRow) => void): GridMeta { + return { + key: GRID_COMMISSION_CLAIMS, + endpoint: '/refinery/commission-claims', + rowKey: (r) => r.id, + status: { param: 'statusCode', options: commissionStatuses }, + defaultFilters: { statusCode: 'NEW' }, + filters, + emptyAsGrid: true, + columns: [ + { key: 'commissionClaimNo', header: l('cc.no'), ltr: true }, + { key: 'commissionClaimDate', header: l('cc.date'), format: 'date', ltr: true }, + { key: 'tripCnt', header: l('cc.wageCount'), format: 'number', align: 'center' }, + { key: 'statusCode', header: l('cc.status'), format: 'status', statuses: commissionStatuses }, + ], + onRowClick: onOpen, + }; +} diff --git a/web/src/features/refinery/commission-claims/pages.tsx b/web/src/features/refinery/commission-claims/pages.tsx new file mode 100644 index 0000000..32797d9 --- /dev/null +++ b/web/src/features/refinery/commission-claims/pages.tsx @@ -0,0 +1,212 @@ +import { useMemo, useState } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; +import { + Alert, Button, Checkbox, FormControlLabel, FormGroup, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography, +} from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import DownloadIcon from '@mui/icons-material/Download'; +import PaymentsIcon from '@mui/icons-material/Payments'; +import SearchIcon from '@mui/icons-material/Search'; +import { DataGrid } from '@/components/DataGrid'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { PageHeader } from '@/components/PageHeader'; +import { StatusChip } from '@/components/StatusChip'; +import { ViewItem } from '@/components/ViewItem'; +import { formatDate, formatNumber } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { downloadFile } from '../../grains-orders/api'; +import { Block, ClaimLogSection } from '../wage-claims/components'; +import { claimStatuses } from '../wage-claims/meta'; +import type { WageClaimRow } from '../wage-claims/types'; +import { + BASE, useClaimWageClaims, useCommissionClaim, useCompleteCommissionClaim, useCreateCommissionClaim, useWageClaimCandidates, +} from './api'; +import { commissionClaimGrid, commissionStatuses } from './meta'; +import strings from './strings'; + +const ROOT = '/refinery/commission-claims'; +const WAGE_ROOT = '/refinery/wage-claims'; + +/** Wage claims of the legacy grid COMMISSION_CLAIM_TRIPS_GRID (no, date, status), with an optional tick column. */ +function WageClaimsTable(p: { + rows: WageClaimRow[]; selected?: Set; onToggle?: (id: number) => void; onToggleAll?: (on: boolean) => void; onOpen?: (r: WageClaimRow) => void; +}) { + const { t } = useFeatureUi(strings); + const ltr = { direction: 'ltr', textAlign: 'start' } as const; + const selectable = !!p.selected; + const allOn = selectable && p.rows.length > 0 && p.rows.every((r) => p.selected!.has(r.id)); + return ( + + + + + {selectable && ( + + p.selected!.has(r.id))} onChange={(_, on) => p.onToggleAll?.(on)} /> + + )} + {t('cc.wage.no')} + {t('cc.wage.date')} + {t('cc.wage.tripCnt')} + {t('cc.wage.status')} + + + + {p.rows.length === 0 && {t('cc.wage.empty')}} + {p.rows.map((r) => ( + p.onOpen!(r) : undefined}> + {selectable && ( + p.onToggle?.(r.id)} /> + )} + {r.wageClaimNo} + {formatDate(r.wageClaimDate)} + {r.tripCnt} + + + ))} + +
+
+ ); +} + +// ================================================================= list (REFINERY_COMMISSION_CLAIMGRID) +export function CommissionClaimsPage() { + const { t } = useFeatureUi(strings); + const { can } = useAuth(); + const navigate = useNavigate(); + const meta = useMemo(() => commissionClaimGrid((r) => navigate(`${ROOT}/${r.id}`)), [navigate]); + return ( + <> + } onClick={() => navigate(`${ROOT}/new`)}>{t('cc.new')} + : undefined} + /> + + + ); +} + +// ================================================================= create (dialog with id 0: wage claims with a tick each) +export function CommissionClaimCreatePage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const toast = useToast(); + const confirm = useConfirm(); + const create = useCreateCommissionClaim(); + + // legacy dialog: NEW and CLOSE are selected on opening + const [statuses, setStatuses] = useState(['NEW', 'CLOSE']); + const [applied, setApplied] = useState(0); + const [selected, setSelected] = useState>(new Set()); + const candidates = useWageClaimCandidates(statuses, applied); + const rows = candidates.data ?? []; + + const toggleStatus = (s: string) => setStatuses((cur) => (cur.includes(s) ? cur.filter((x) => x !== s) : [...cur, s])); + const save = async () => { + if (selected.size === 0) { toast.error(t('cc.create.select')); return; } + if (!(await confirm({ message: t('cc.create.confirm') }))) return; + create.mutate([...selected], { onSuccess: (r) => navigate(r.id ? `${ROOT}/${r.id}` : ROOT) }); + }; + + return ( + <> + void save()}>{t('cc.create.save')}} + /> + + + + + toggleStatus('NEW')} />} /> + toggleStatus('CLOSE')} />} /> + + + {t('cc.create.selected', { n: selected.size })} + + + + {candidates.isLoading ? : ( + setSelected((cur) => { const n = new Set(cur); if (!n.delete(id)) n.add(id); return n; })} + onToggleAll={(on) => setSelected(on ? new Set(rows.map((r) => r.id)) : new Set())} + /> + )} + + + + ); +} + +// ================================================================= view +export function CommissionClaimPage() { + const { t } = useFeatureUi(strings); + const { can } = useAuth(); + const navigate = useNavigate(); + const toast = useToast(); + const confirm = useConfirm(); + const { id: idParam } = useParams(); + const id = Number(idParam); + const valid = Number.isFinite(id) ? id : null; + const claim = useCommissionClaim(valid); + const wages = useClaimWageClaims(valid); + const complete = useCompleteCommissionClaim(); + const [exporting, setExporting] = useState(false); + + if (claim.isLoading) return ; + if (claim.isError || !claim.data) return {t('cc.notFound')}; + const c = claim.data; + const isNew = c.statusCode === 'NEW'; // CLAIM_CLOSE exists only on NEW claims (STATUS_ACTION_MATRIX) + + const runReport = async () => { + setExporting(true); + try { await downloadFile(`${BASE}/${c.id}/report`, {}, `refinery_commission_claim_${c.commissionClaimNo}.xls`); } + catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + finally { setExporting(false); } + }; + + return ( + <> + } + actions={ + <> + {can('refinery.commissionClaims.report') && ( + + )} + {isNew && can('refinery.commissionClaims.complete') && ( + + )} + + } + /> + + + + {c.commissionClaimNo} + {formatDate(c.commissionClaimDate)} + {formatNumber(c.tripCnt, 'ar')} + + + + {wages.isLoading ? : ( + navigate(`${WAGE_ROOT}/${r.id}`) : undefined} /> + )} + + + + + ); +} diff --git a/web/src/features/refinery/commission-claims/routes.tsx b/web/src/features/refinery/commission-claims/routes.tsx new file mode 100644 index 0000000..bba0684 --- /dev/null +++ b/web/src/features/refinery/commission-claims/routes.tsx @@ -0,0 +1,20 @@ +import type { RouteObject } from 'react-router-dom'; +import PercentIcon from '@mui/icons-material/Percent'; +import type { MenuItem } from '@/shell/types'; +import { CommissionClaimCreatePage, CommissionClaimPage, CommissionClaimsPage } from './pages'; +import strings from './strings'; + +/** Refinery commission claims (مطالبة العمولة). Absolute paths; the wage claim view links here by /refinery/commission-claims/:id. */ +export const routes: RouteObject[] = [ + { path: '/refinery/commission-claims', element: }, + { path: '/refinery/commission-claims/new', element: , handle: { crumb: strings['cc.crumb.new'] } }, + { path: '/refinery/commission-claims/:id', element: , handle: { crumb: strings['cc.crumb.details'] } }, +]; + +/** Leaf entry only: the lead composes the refinery group. key = the screen key (PermissionKeys.RefineryCommissionClaims). */ +export const menuItems: MenuItem[] = [ + { + key: 'refinery.commissionClaims', title: strings['cc.menu'], icon: PercentIcon, path: '/refinery/commission-claims', + createPath: '/refinery/commission-claims/new', createKey: 'refinery.commissionClaims.create', + }, +]; diff --git a/web/src/features/refinery/commission-claims/strings.ts b/web/src/features/refinery/commission-claims/strings.ts new file mode 100644 index 0000000..e3e32ae --- /dev/null +++ b/web/src/features/refinery/commission-claims/strings.ts @@ -0,0 +1,49 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** + * Strings of the refinery commission claims screen (مطالبات عمولات الصرف). Arabic = the legacy captions (NTP.LT_CAPTION) verbatim; + * texts the legacy screen never had are marked "new". + */ +export default defineStrings({ + // ---- menu / titles + 'cc.menu': { en: 'Commission claims', ar: 'مطالبات عمولات الصرف' }, // MENU.REFINERY_COMMISSION_CLAIM + 'cc.title': { en: 'Exchange commission claims', ar: 'مطالبات عمولات الصرف' }, + 'cc.subtitle': { en: 'Claims that group wage claims for the monthly commission invoice', ar: 'مطالبات تجمع مطالبات الاجور لفاتورة العمولة الشهرية' }, + 'cc.details': { en: 'Commission claim details', ar: 'معلومات مطالبة صرف عمولات اجور النقل' }, // REFINERY_COMMISSION_CLAIM_DETAILS + 'cc.crumb.new': { en: 'New', ar: 'جديد' }, + 'cc.crumb.details': { en: 'Details', ar: 'التفاصيل' }, + 'cc.new': { en: 'New claim', ar: 'جديد' }, + + // ---- grid + 'cc.no': { en: 'Commission claim number', ar: 'رقم مطالبة عمولات الصرف' }, // PUBLIC.COMMISSION_CLAIM_NO + 'cc.date': { en: 'Claim date', ar: 'تاريخ المطالبة' }, // PUBLIC.CLAIM_DATE + 'cc.wageCount': { en: 'Number of wage claims', ar: 'عدد مطالبات الاجور' }, // PUBLIC.WAGE_CLAIM_COUNT + 'cc.status': { en: 'Status', ar: 'الحالة' }, + 'cc.statusNew': { en: 'New', ar: 'جديد' }, + 'cc.statusComplete': { en: 'Complete', ar: 'مكتمل' }, + 'cc.statusClose': { en: 'Paid', ar: 'تم التسديد' }, + + // ---- wage claims inside the claim / create dialog + 'cc.wage.no': { en: 'Wage claim number', ar: 'رقم مطالبة اجور النقل' }, // PUBLIC.WAGE_CLAIM_NO + 'cc.wage.date': { en: 'Claim date', ar: 'تاريخ المطالبة' }, // PUBLIC.WAGE_CLAIM_DATE + 'cc.wage.status': { en: 'Status', ar: 'الحالة' }, + 'cc.wage.tripCnt': { en: 'Number of trips', ar: 'عدد الارساليات' }, + 'cc.wage.title': { en: 'Wage claims', ar: 'مطالبات الاجور' }, // new + 'cc.wage.empty': { en: 'No wage claims', ar: 'لا يوجد مطالبات اجور' }, // ERROR.THERE_ARE_NO_WAGES + + // ---- create + 'cc.create.title': { en: 'New commission claim', ar: 'إنشاء مطالبة عمولات الصرف' }, // new + 'cc.create.subtitle': { en: 'Tick the wage claims to group in the commission claim', ar: 'حدد مطالبات الاجور التي تضمها مطالبة العمولة' }, + 'cc.create.status': { en: 'Status', ar: 'الحالة' }, + 'cc.create.search': { en: 'Search', ar: 'بحث' }, + 'cc.create.save': { en: 'Create claim', ar: 'إنشاء' }, // PUBLIC.CREATE + 'cc.create.select': { en: 'Choose the claim', ar: 'يرجى اختيار المطالبة' }, // ERROR.PLEASE_SELECT_CLAIM + 'cc.create.selected': { en: 'Selected: {n}', ar: 'المحدد: {n}' }, // new + 'cc.create.confirm': { en: 'Create a commission claim with the selected wage claims?', ar: 'هل تريد إنشاء مطالبة عمولة تضم مطالبات الاجور المحددة؟' }, // new + + // ---- actions + 'cc.complete': { en: 'Pay', ar: 'تسديد' }, // REFINERY_WAGE_CLAIM.CLAIM_CLOSE + 'cc.completeConfirm': { en: 'Do you want to mark this claim as paid? Its wage claims become complete.', ar: 'هل تريد تسديد هذه المطالبة؟ ستصبح مطالبات الاجور التابعة لها مكتملة.' }, // new + 'cc.report': { en: 'Invoice', ar: 'تقرير' }, // PUBLIC.REPORT + 'cc.notFound': { en: 'The claim could not be loaded.', ar: 'تعذر تحميل المطالبة.' }, // new +}); diff --git a/web/src/features/refinery/commission-claims/types.ts b/web/src/features/refinery/commission-claims/types.ts new file mode 100644 index 0000000..c7969ac --- /dev/null +++ b/web/src/features/refinery/commission-claims/types.ts @@ -0,0 +1,11 @@ +/** Wire types of api/v1/refinery/commission-claims (camelCase JSON of the backend DTOs). Dates are ISO strings. */ + +export interface CommissionClaimRow { + id: number; + commissionClaimNo: number | null; + commissionClaimDate: string | null; + /** number of wage claims grouped by the commission claim (legacy column name TRIP_CNT) */ + tripCnt: number; + /** NEW / COMPLETE (old rows may hold CLOSE) */ + statusCode: string; +} diff --git a/web/src/features/refinery/trips/api.ts b/web/src/features/refinery/trips/api.ts new file mode 100644 index 0000000..c48f976 --- /dev/null +++ b/web/src/features/refinery/trips/api.ts @@ -0,0 +1,78 @@ +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { api } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; +import type { PagedResult } from '@/api/client'; +import { useLanguage } from '@/providers/LanguageProvider'; +import type { TripDetail, TripLogRow, TripsResult, TripVoucher } from './types'; + +export const BASE = '/refinery/trips'; +export const GRID_TRIPS = 'refinery.trips'; + +export const useTrip = (id: number | null) => + useQuery({ queryKey: ['refinery.trip', id], queryFn: () => api.get(`${BASE}/${id}`), enabled: id !== null }); + +export function useTripLog(id: number, page: number, enabled: boolean) { + const { langReady } = useLanguage(); + return useQuery({ + queryKey: ['refinery.trip.log', id, page], + queryFn: () => api.get>(`${BASE}/${id}/log`, { page, pageSize: 10 }), + enabled: enabled && langReady, + }); +} + +/** Action code of the form (TripDetail.actions) -> endpoint segment. */ +export const actionPaths: Record = { + firstAdvance: 'first-advance', + secondAdvance: 'second-advance', + firstAdvanceReverse: 'first-advance-reverse', + secondAdvanceReverse: 'second-advance-reverse', + exchange: 'exchange', + exchangeAudit: 'exchange-audit', + receipt: 'receipt', + payment: 'payment', + activateWalletExchange: 'activate-wallet-exchange', + cashPayment: 'cash-payment', + confirmExchange: 'confirm-exchange', +}; + +/** Permission key of every action code (PermissionKeys.Refinery.Trips.cs). */ +export const actionKeys: Record = { + firstAdvance: 'refinery.trips.firstAdvance', + secondAdvance: 'refinery.trips.secondAdvance', + firstAdvanceReverse: 'refinery.trips.firstAdvanceReverse', + secondAdvanceReverse: 'refinery.trips.secondAdvanceReverse', + exchange: 'refinery.trips.exchange', + exchangeAudit: 'refinery.trips.exchangeAudit', + receipt: 'refinery.trips.receipt', + payment: 'refinery.trips.payment', + activateWalletExchange: 'refinery.trips.activateWalletExchange', + cashPayment: 'refinery.trips.cashPayment', + confirmExchange: 'refinery.trips.confirmExchange', + print: 'refinery.trips.print', +}; + +export function useTripAction(id: number) { + const qc = useQueryClient(); + return useWrite( + (action) => api.post(`${BASE}/${id}/${actionPaths[action]}`), + { + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ['refinery.trip', id] }); + void qc.invalidateQueries({ queryKey: ['refinery.trip.log', id] }); + void qc.invalidateQueries({ queryKey: gridKey(GRID_TRIPS) }); + }, + }, + ); +} + +export function usePrintVoucher(id: number) { + const qc = useQueryClient(); + return useWrite(() => api.post(`${BASE}/${id}/print`), { + toastSuccess: false, + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ['refinery.trip', id] }); + void qc.invalidateQueries({ queryKey: ['refinery.trip.log', id] }); + }, + }); +} diff --git a/web/src/features/refinery/trips/index.ts b/web/src/features/refinery/trips/index.ts new file mode 100644 index 0000000..8ede736 --- /dev/null +++ b/web/src/features/refinery/trips/index.ts @@ -0,0 +1,17 @@ +import { createElement } from 'react'; +import type { RouteObject } from 'react-router-dom'; +import OilBarrelIcon from '@mui/icons-material/OilBarrel'; +import type { MenuItem } from '@/shell/types'; +import { TripPage, TripsPage } from './pages'; +import strings from './strings'; + +/** Refinery trips (legacy REFINERYTRIPGRID / REFINERYTRIP). Buttons inside the pages are gated by the action permission keys. */ +export const routes: RouteObject[] = [ + { path: '/refinery/trips', element: createElement(TripsPage) }, + { path: '/refinery/trips/:id', element: createElement(TripPage), handle: { crumb: strings['trips.crumb'] } }, +]; + +/** Leaf entry only: the lead composes the refinery group. Key = screen key RefineryTrips. */ +export const menuItems: MenuItem[] = [ + { key: 'refinery.trips', title: strings['trips.menu'], icon: OilBarrelIcon, path: '/refinery/trips' }, +]; diff --git a/web/src/features/refinery/trips/meta.tsx b/web/src/features/refinery/trips/meta.tsx new file mode 100644 index 0000000..023f838 --- /dev/null +++ b/web/src/features/refinery/trips/meta.tsx @@ -0,0 +1,111 @@ +import { Stack, Tooltip } from '@mui/material'; +import LocalGasStationIcon from '@mui/icons-material/LocalGasStation'; +import WarningAmberIcon from '@mui/icons-material/WarningAmber'; +import WaterDropIcon from '@mui/icons-material/WaterDrop'; +import UndoIcon from '@mui/icons-material/Undo'; +import type { FilterMeta, GridMeta, OptionItem, StatusMeta } from '@/components/meta/types'; +import { GRID_TRIPS, BASE } from './api'; +import strings from './strings'; +import type { TripGridRow } from './types'; + +const s = strings; + +export const statuses: StatusMeta[] = [ + { value: 'RESD', label: { en: 'Released', ar: 'تم التسريب' }, color: 'info' }, + { value: 'LOADING_FILL', label: { en: 'Filled for loading', ar: 'تم التعبئة للتحميل' }, color: 'info' }, + { value: 'LOADED', label: { en: 'Loaded', ar: 'تم التحميل' }, color: 'primary' }, + { value: 'DISCHARGING_FILL', label: { en: 'Filled for discharge', ar: 'تم التعبئة للتفريغ' }, color: 'primary' }, + { value: 'ARRIVE_LOCATION', label: { en: 'Arrived', ar: 'وصول شويعر' }, color: 'primary' }, + { value: 'DISCHARGING', label: { en: 'Discharging', ar: 'قيد التفريغ' }, color: 'warning' }, + { value: 'DISCHARGED', label: { en: 'Discharged', ar: 'تم التفريغ' }, color: 'warning' }, + { value: 'PENDING_EXCHANGE', label: { en: 'Pending audit', ar: 'قيد التدقيق للصرف' }, color: 'warning' }, + { value: 'READY_TO_PAY', label: { en: 'Ready to pay', ar: 'جاهز للدفع' }, color: 'secondary' }, + { value: 'EXCHANGED', label: { en: 'Paid', ar: 'تم الصرف' }, color: 'success' }, + { value: 'COMPLETE', label: { en: 'Complete', ar: 'مكتمل' }, color: 'success' }, + { value: 'RVKD', label: { en: 'Revoked', ar: 'ملغى' }, color: 'error' }, +]; + +const yesNo: OptionItem[] = [ + { value: 1, label: s['trips.yes'] }, + { value: 0, label: s['trips.no'] }, +]; +const yesNoFlag: OptionItem[] = [ + { value: '1', label: s['trips.yes'] }, + { value: '0', label: s['trips.no'] }, +]; + +/** PAYMENT_METHOD_CODE of the legacy view: 0 none, 1 bank transfer, 2 e-wallet, 3 cash. */ +const paymentMethods: OptionItem[] = [ + { value: 0, label: s['trips.pm.none'] }, + { value: 1, label: s['trips.pm.bank'] }, + { value: 2, label: s['trips.pm.wallet'] }, + { value: 3, label: s['trips.pm.cash'] }, +]; + +const dieselOptions: OptionItem[] = [ + { value: 0, label: s['trips.diesel0'] }, + { value: 1, label: s['trips.diesel1'] }, + { value: 2, label: s['trips.diesel2'] }, +]; + +// legacy search form (REFINERYTRIPpart.html) + the other fields factoryweb.search accepted +const filters: FilterMeta[] = [ + { name: 'dischargeAuthNo', type: 'text', label: s['trips.dischargeNo'], ltr: true }, + { name: 'pn', type: 'text', label: s['trips.pn'], ltr: true }, + { name: 'tn', type: 'text', label: s['trips.tn'], inputKind: 'plate' }, + { name: 'trn', type: 'text', label: s['trips.trn'], inputKind: 'plate' }, + { name: 'nnpn', type: 'text', label: s['trips.nnpn'], ltr: true }, + { name: 'loadingNo', type: 'text', label: s['trips.loadingNo'], ltr: true }, + { name: 'dischargeEntryDate', type: 'date', label: s['trips.dischargeDate'] }, + { name: 'paymentMethodCode', type: 'select', label: s['trips.paymentMethod'], options: paymentMethods }, + { name: 'hasWageClaim', type: 'select', label: s['trips.hasWageClaim'], options: yesNoFlag }, + { name: 'dieselCharge', type: 'select', label: s['trips.dieselCharge'], options: dieselOptions }, + { name: 'wageClaimNo', type: 'text', label: s['trips.wageClaimNo'], ltr: true }, + { name: 'loadingDateFrom', type: 'date', label: s['trips.loadingFrom'] }, + { name: 'loadingDateTo', type: 'date', label: s['trips.loadingTo'] }, + { name: 'bankAccount', type: 'text', label: s['trips.bankAccount'], ltr: true }, + { name: 'waterExist', type: 'select', label: s['trips.water'], options: yesNo }, + { name: 'paymentedDateFrom', type: 'date', label: s['trips.paidFrom'] }, + { name: 'paymentedDateTo', type: 'date', label: s['trips.paidTo'] }, +]; + +const dieselColor = ['#d32f2f', '#ffc107', '#2e7d32']; +const dieselLabel = [s['trips.diesel0'], s['trips.diesel1'], s['trips.diesel2']]; + +/** The legacy action column icons: diesel step (red / yellow / green), no payment method, water, diesel reversed. */ +export function TripIcons({ row, lang }: { row: TripGridRow; lang: 'en' | 'ar' }) { + const step = Math.min(Math.max(row.dieselCharge, 0), 2); + return ( + + + {!row.hasPaymentMethod && } + {row.hasWater && } + {row.reversed && } + + ); +} + +export function tripsGrid(onOpen: (r: TripGridRow) => void): GridMeta { + return { + key: GRID_TRIPS, + endpoint: BASE, + rowKey: (r) => r.id, + status: { param: 'statusCode', options: statuses }, + filters, + onRowClick: onOpen, + visualLtr: true, + columns: [ + { key: 'pn', header: s['trips.pn'], ltr: true }, + { key: 'dispatchDate', header: s['trips.dispatchDate'], ltr: true, hideBelow: 'md' }, + { key: 'loadingNo', header: s['trips.loadingNo'], ltr: true, hideBelow: 'md' }, + { key: 'dischargeAuthNo', header: s['trips.dischargeNo'], ltr: true }, + { key: 'dischargeEntryDate', header: s['trips.dischargeDate'], ltr: true, hideBelow: 'lg' }, + { key: 'tn', header: s['trips.tn'], ltr: true }, + { key: 'trn', header: s['trips.trn'], ltr: true, hideBelow: 'lg' }, + { key: 'nnpn', header: s['trips.nnpn'], ltr: true, hideBelow: 'lg' }, + { key: 'wageClaimNo', header: s['trips.wageClaimNo'], ltr: true, hideBelow: 'lg' }, + { key: 'statusCode', header: s['trips.status'], format: 'status', statuses }, + { key: 'icons', header: { en: '', ar: '' }, render: (r, { lang }) => }, + ], + }; +} diff --git a/web/src/features/refinery/trips/pages.tsx b/web/src/features/refinery/trips/pages.tsx new file mode 100644 index 0000000..f07fe01 --- /dev/null +++ b/web/src/features/refinery/trips/pages.tsx @@ -0,0 +1,349 @@ +import { useState, type ReactNode } from 'react'; +import { Link as RouterLink, useNavigate, useParams } from 'react-router-dom'; +import { + Alert, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, Link, Menu, MenuItem, Stack, Table, TableBody, TableCell, + TableHead, TableRow, TablePagination, Typography, +} from '@mui/material'; +import SummarizeIcon from '@mui/icons-material/Summarize'; +import PrintIcon from '@mui/icons-material/Print'; +import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined'; +import { DataGrid } from '@/components/DataGrid'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { PageHeader } from '@/components/PageHeader'; +import { SectionPaper } from '@/components/SectionPaper'; +import { StatusChip } from '@/components/StatusChip'; +import { ViewItem } from '@/components/ViewItem'; +import { formatNumber } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { downloadFile } from '../../grains-orders/api'; +import { actionKeys, actionPaths, BASE, usePrintVoucher, useTrip, useTripAction, useTripLog } from './api'; +import { statuses, tripsGrid } from './meta'; +import strings, { methodCaptions, propertyCaptions } from './strings'; +import type { TripDetail, TripLogRow, TripVoucher } from './types'; + +const ROOT = '/refinery/trips'; +const MONEY_ACTIONS = new Set(['firstAdvance', 'secondAdvance', 'firstAdvanceReverse', 'secondAdvanceReverse', 'exchange', 'payment', 'cashPayment', 'confirmExchange']); + +// ------------------------------------------------------------------ list +export function TripsPage() { + const { t, tr } = useFeatureUi(strings); + const { can } = useAuth(); + const navigate = useNavigate(); + const toast = useToast(); + const [menu, setMenu] = useState(null); + + const run = async (path: string, params: Record, name: string) => { + setMenu(null); + try { + await downloadFile(`${BASE}/reports/${path}`, params, name); + toast.success(t('trips.report.done')); + } catch (e) { + toast.error(e instanceof Error ? e.message : t('error.generic')); + } + }; + // the report uses the filters of the list (they are in the URL query string) + const current = () => Object.fromEntries([...new URLSearchParams(window.location.search)].filter(([k]) => !['page', 'size', 'f'].includes(k))); + const reports: { key: string; label: string; show: boolean; go: () => void }[] = [ + { key: 'trips', label: t('trips.report.trips'), show: can('refinery.trips.report'), go: () => void run('trips', current(), 'refinery-trips.xlsx') }, + { key: 'diesel', label: t('trips.report.diesel'), show: can('refinery.trips.dieselReport'), go: () => void run('diesel', current(), 'refinery-diesel.xlsx') }, + { key: 'cards', label: t('trips.report.cards'), show: can('refinery.trips.cardsReport'), go: () => void run('cards', { tn: current().tn ?? '' }, 'refinery-cards.xlsx') }, + { + key: 'bank', label: t('trips.report.bank'), show: can('refinery.trips.bankReport'), go: () => { + const account = window.prompt(t('trips.report.bankAsk'), current().bankAccount ?? ''); + if (account) void run('bank', { bankAccount: account, statusCode: current().statusCode ?? '' }, 'refinery-bank.xlsx'); + }, + }, + ].filter((r) => r.show); + + const meta = tripsGrid((r) => navigate(`${ROOT}/${r.id}`)); + return ( + <> + 0 && ( + <> + + setMenu(null)}> + {reports.map((r) => {r.label})} + + + )} + /> + + + ); +} + +// ------------------------------------------------------------------ one trip +function Num({ v }: { v: number | null | undefined }) { + const { lang } = useFeatureUi(strings); + return v === null || v === undefined ? null : {formatNumber(v, lang)}; +} + +function Section({ title, children }: { title: string; children: ReactNode }) { + return ( + + {title} + {children} + + ); +} + +export function TripPage() { + const { id } = useParams(); + const tripId = Number(id); + const q = useTrip(Number.isFinite(tripId) ? tripId : null); + const { t } = useFeatureUi(strings); + if (q.isLoading) return ; + if (q.isError || !q.data) return {q.error?.message ?? t('trips.loadFailed')}; + return ; +} + +function TripView({ trip }: { trip: TripDetail }) { + const { t, tr } = useFeatureUi(strings); + const { can } = useAuth(); + const confirm = useConfirm(); + const action = useTripAction(trip.id); + const printer = usePrintVoucher(trip.id); + const [voucher, setVoucher] = useState(null); + const w = trip.wallet; + const late = ['DISCHARGED', 'PENDING_EXCHANGE', 'READY_TO_PAY', 'EXCHANGED', 'COMPLETE'].includes(trip.statusCode ?? ''); + const loaded = late || ['LOADED', 'DISCHARGING_FILL', 'ARRIVE_LOCATION', 'DISCHARGING'].includes(trip.statusCode ?? ''); + const dischargeSection = late; + + const available = trip.actions.filter((a) => can(actionKeys[a])); + const run = async (a: string) => { + if (a === 'print') { printer.mutate(undefined, { onSuccess: setVoucher }); return; } + const message = MONEY_ACTIONS.has(a) ? t('trips.act.confirmMoney') : t('trips.act.confirm'); + if (await confirm({ title: t(`trips.act.${a}` as 'trips.act.exchange'), message })) action.mutate(a); + }; + + const buttons = ( + <> + {available.filter((a) => a in actionPaths || a === 'print').map((a) => ( + + ))} + + ); + + return ( + + } + actions={buttons} + /> + +
+ {trip.pn} + {trip.dispatchDate} + {trip.tn} + {trip.trn} + {trip.clientName} + {trip.nnpn} + {trip.driverName} + {tr(statuses.find((s) => s.value === trip.statusCode)?.label) || trip.statusCode} + {trip.cardNumber} + + {trip.dieselCharge < 2 && } + {trip.wageClaimId && ( + + {trip.wageClaimNo ?? trip.wageClaimId} + + )} + {dischargeSection && } + {dischargeSection && } + {dischargeSection && ( + + {t('trips.canEdit')} + + )} +
+ + {loaded && ( +
+ {trip.loadingNo} + {trip.actualLoadingDate} + + + +
+ )} + + {dischargeSection && ( +
+ {trip.dischargeAuthNo} + {trip.dischargeEntryDate} + + + + + + + +
+ )} + + {loaded && ( +
+ {w?.epayment === 1 && ( + <> + {w.walletNumber} + {w.ownerNnpn} + {w.ownerName} + + )} + {w?.epayment === 0 && ( + <> + {t('trips.payByBank')} + {w.ownerName} + {w.bankName} + {w.iban} + {w.bankAccount} + + )} + {(!w || w.epayment === null) && {t('trips.noPaymentMethod')}} + {trip.receivedByName} + {trip.receivedDate} + {trip.paymentedDate} + {trip.voucherSerialNumber} + {trip.remarks} +
+ )} + + {dischargeSection && ( +
+ {w?.driverWalletNumber + ? {w.driverWalletNumber} + : {t('trips.driverNoWallet')}} +
+ )} + + + setVoucher(null)} /> +
+ ); +} + +// ------------------------------------------------------------------ history +function TripLog({ tripId }: { tripId: number }) { + const { t } = useFeatureUi(strings); + const [page, setPage] = useState(1); + const [open, setOpen] = useState(false); + const [shown, setShown] = useState(null); + const q = useTripLog(tripId, page, open); + return ( + + + {open && ( + <> + {q.isLoading && } + {q.data && q.data.items.length === 0 && {t('trips.log.none')}} + {q.data && q.data.items.length > 0 && ( + <> + + + + {t('trips.log.method')} + {t('trips.log.date')} + {t('trips.log.user')} + + + + + {q.data.items.map((r) => ( + + {methodCaptions[r.methodName ?? ''] ?? r.methodName} + {r.logDate} + {r.login} + + {r.methodName !== 'CREATE' && (r.oldData || r.newData) && ( + + )} + + + ))} + +
+ setPage(p + 1)} /> + + )} + + )} + setShown(null)} /> +
+ ); +} + +function parse(json: string | null): Record { + try { return json ? (JSON.parse(json) as Record) : {}; } catch { return {}; } +} + +function LogDialog({ row, onClose }: { row: TripLogRow | null; onClose: () => void }) { + const { t } = useFeatureUi(strings); + const oldD = parse(row?.oldData ?? null); + const newD = parse(row?.newData ?? null); + const keys = [...new Set([...Object.keys(oldD), ...Object.keys(newD)])]; + return ( + + {methodCaptions[row?.methodName ?? ''] ?? row?.methodName} + + + + + {t('trips.log.property')} + {t('trips.log.old')} + {t('trips.log.new')} + + + + {keys.map((k) => ( + + {propertyCaptions[k] ?? k} + {String(oldD[k] ?? '')} + {String(newD[k] ?? '')} + + ))} + +
+
+ +
+ ); +} + +// ------------------------------------------------------------------ cash voucher (legacy print: A5 pdf) +function VoucherDialog({ voucher, onClose }: { voucher: TripVoucher | null; onClose: () => void }) { + const { t } = useFeatureUi(strings); + return ( + + + {voucher && ( + + {t('trips.voucher.title')} + + {t('trips.voucher.date')} : {voucher.date} + {t('trips.voucher.no')} : {voucher.serial} + + {t('trips.voucher.body1')} {voucher.amount} {t('trips.voucher.dinar')} + {t('trips.voucher.body2')} {voucher.dischargeAuthNo} + {t('trips.voucher.receiver')}: {voucher.ownerName} + {t('trips.voucher.accountant')} + + )} + + + + + + + ); +} diff --git a/web/src/features/refinery/trips/strings.ts b/web/src/features/refinery/trips/strings.ts new file mode 100644 index 0000000..19b190d --- /dev/null +++ b/web/src/features/refinery/trips/strings.ts @@ -0,0 +1,156 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Strings of the refinery trips screen. Arabic texts are the legacy captions (ntp.lt_caption REFINERYTRIP*, PUBLIC.*) verbatim. */ +export default defineStrings({ + 'trips.menu': { en: 'Trips', ar: 'شاشة الارساليات' }, + 'trips.title': { en: 'Refinery trips', ar: 'شاشة الارساليات' }, + 'trips.crumb': { en: 'Trip details', ar: 'معلومات الارسالية' }, + + // filters / columns + 'trips.pn': { en: 'Trip number', ar: 'رقم الارسالية' }, + 'trips.dispatchDate': { en: 'Trip date', ar: 'تاريخ الارسالية' }, + 'trips.loadingNo': { en: 'Load number', ar: 'رقم الحمولة' }, + 'trips.dischargeNo': { en: 'Form number', ar: 'رقم النموذج' }, + 'trips.dischargeDate': { en: 'Form date', ar: 'تاريخ النموذج' }, + 'trips.tn': { en: 'Truck', ar: 'رقم القاطرة' }, + 'trips.trn': { en: 'Trailer', ar: 'رقم المقطورة' }, + 'trips.nnpn': { en: 'National number', ar: 'الرقم الوطني' }, + 'trips.status': { en: 'Status', ar: 'الحالة' }, + 'trips.wageClaimNo': { en: 'Wage claim number', ar: 'رقم مطالبة اجور النقل' }, + 'trips.hasWageClaim': { en: 'Has a wage claim', ar: 'تحديد مطالبة اجور النقل' }, + 'trips.dieselCharge': { en: 'Diesel charge', ar: 'شحن الديزل' }, + 'trips.paymentMethod': { en: 'Payment method', ar: 'تحديد آلية صرف الاجور' }, + 'trips.bankAccount': { en: 'Account number', ar: 'رقم الحساب' }, + 'trips.water': { en: 'Accompanying water', ar: 'ماء مصاحب' }, + 'trips.loadingFrom': { en: 'Loaded from', ar: 'من تاريخ التحميل' }, + 'trips.loadingTo': { en: 'Loaded to', ar: 'الى تاريخ التحميل' }, + 'trips.paidFrom': { en: 'Paid from', ar: 'من تاريخ الدفع' }, + 'trips.paidTo': { en: 'Paid to', ar: 'الى تاريخ الدفع' }, + 'trips.netWage': { en: 'Net wage paid', ar: 'صافي قيمة الصرف الفعلي' }, + 'trips.yes': { en: 'Yes', ar: 'نعم' }, + 'trips.no': { en: 'No', ar: 'لا' }, + 'trips.pm.none': { en: 'None', ar: 'لا يوجد' }, + 'trips.pm.bank': { en: 'Bank transfer', ar: 'حوالة' }, + 'trips.pm.wallet': { en: 'E-wallet', ar: 'الكتروني' }, + 'trips.pm.cash': { en: 'Cash', ar: 'دفع نقدي' }, + 'trips.diesel0': { en: 'No diesel charged', ar: 'لم يتم شحن الديزل' }, + 'trips.diesel1': { en: 'Charged for loading', ar: 'تم الشحن للتحميل' }, + 'trips.diesel2': { en: 'Charged for discharge', ar: 'تم الشحن للتفريغ' }, + 'trips.noPaymentMethod': { en: 'No payment method', ar: 'لا يوجد طريقة دفع' }, + 'trips.hasWater': { en: 'There is accompanying water', ar: 'يوجد ماء مصاحب' }, + 'trips.reversedIcon': { en: 'Diesel charge cancelled', ar: 'الغاء حركة شحن الديزل' }, + 'trips.view': { en: 'View', ar: 'عرض' }, + 'trips.filterHint': { en: 'Search by trip, truck, form or status.', ar: 'ابحث برقم الارسالية أو القاطرة أو النموذج أو الحالة.' }, + + // reports + 'trips.reports': { en: 'Reports', ar: 'التقارير' }, + 'trips.report.trips': { en: 'Trips (Excel)', ar: 'شاشة الارساليات (Excel)' }, + 'trips.report.diesel': { en: 'Diesel charges (Excel)', ar: 'شحن الديزل (Excel)' }, + 'trips.report.cards': { en: 'Diesel balances (Excel)', ar: 'أرصدة الديزل (Excel)' }, + 'trips.report.bank': { en: 'Bank report (Excel)', ar: 'تقرير البنك (Excel)' }, + 'trips.report.bankAsk': { en: 'Enter the bank account number of the report', ar: 'يجب ادخال رقم الحساب' }, + 'trips.report.done': { en: 'The report was generated', ar: 'تم انشاء التقرير بنجاح' }, + + // form sections + 'trips.sec.basic': { en: 'Basic information', ar: 'المعلومات الأساسية' }, + 'trips.sec.loading': { en: 'Loading information', ar: 'معلومات التحميل' }, + 'trips.sec.discharge': { en: 'Discharge information', ar: 'معلومات التفريغ' }, + 'trips.sec.payment': { en: 'Payment information', ar: 'معلومات الصرف' }, + 'trips.sec.driverWallet': { en: 'Driver wallet information', ar: 'معلومات محفظة السائق' }, + 'trips.sec.history': { en: 'Movement log', ar: 'سجل الحركات' }, + 'trips.client': { en: 'Carrier', ar: 'اسم الناقل' }, + 'trips.driver': { en: 'Driver', ar: 'اسم السائق' }, + 'trips.card': { en: 'Jopetrol card number', ar: 'رقم بطاقة جوبترول' }, + 'trips.currentBalance': { en: 'Current accumulated value', ar: 'القيمة التراكمية الحالية' }, + 'trips.newBalance': { en: 'New accumulated value', ar: 'القيمة التراكمية الجديدة' }, + 'trips.tripNetWage': { en: 'Transport wage', ar: 'قيمة اجور النقل' }, + 'trips.remaining': { en: 'Previous balance', ar: 'قيمة الذمم السابقة' }, + 'trips.canEdit': { en: 'The value can change after the audit', ar: 'القيمة قابلة للتعديل بعد التدقيق' }, + 'trips.grossWeight': { en: 'Gross weight (kg)', ar: 'الوزن القائم (كغ)' }, + 'trips.emptyWeight': { en: 'Empty weight (kg)', ar: 'الوزن الفارغ (كغ)' }, + 'trips.netLoading': { en: 'Net weight (kg)', ar: 'الوزن الصافي(كغ)' }, + 'trips.actualGross': { en: 'Gross weight at discharge (kg)', ar: 'الوزن القائم للتفريغ (كغ)' }, + 'trips.actualEmpty': { en: 'Empty weight at discharge (kg)', ar: 'الوزن الفارغ للتفريغ (كغ)' }, + 'trips.netDischarge': { en: 'Net discharge weight (kg)', ar: 'الوزن الصافي للتفريغ(كغ)' }, + 'trips.liters': { en: 'Liters weight', ar: 'الوزن باللتر' }, + 'trips.waterAmount': { en: 'Water amount', ar: 'كمية الماء' }, + 'trips.difference': { en: 'Weight difference', ar: 'الفرق في الوزن' }, + 'trips.sediment': { en: 'Sediment amount', ar: 'كمية الرواسب' }, + 'trips.walletNumber': { en: 'Wallet number', ar: 'رقم المحفظة للمالك / المفوض' }, + 'trips.ownerNnpn': { en: 'Owner national number', ar: 'الرقم الوطني للمالك' }, + 'trips.ownerName': { en: 'Account holder', ar: 'صاحب الحساب' }, + 'trips.bank': { en: 'Bank', ar: 'البنك' }, + 'trips.iban': { en: 'IBAN', ar: 'IBAN' }, + 'trips.driverWallet': { en: 'Driver wallet number', ar: 'رقم محفظة السائق' }, + 'trips.driverNoWallet': { en: 'The driver has no e-wallet', ar: 'السائق ليس لديه محفظة الكترونية' }, + 'trips.payByBank': { en: 'Payment by bank transfer', ar: 'الصرف بحوالة بنكية' }, + 'trips.receivedBy': { en: 'Received by', ar: 'اسم المستلم' }, + 'trips.receivedDate': { en: 'Received on', ar: 'تاريخ الاستلام' }, + 'trips.paymentedDate': { en: 'Paid on', ar: 'تاريخ الدفع' }, + 'trips.wageClaim': { en: 'Wage claim', ar: 'مطالبة اجور النقل' }, + 'trips.voucher': { en: 'Voucher number', ar: 'رقم السند' }, + 'trips.remarks': { en: 'Remarks', ar: 'ملاحظات' }, + + // actions + 'trips.act.firstAdvance': { en: 'Fill the diesel card for loading', ar: 'تعبئة بطاقة الديزل للتحميل' }, + 'trips.act.secondAdvance': { en: 'Fill the diesel card for discharge', ar: 'تعبئة بطاقة الديزل للتفريغ' }, + 'trips.act.firstAdvanceReverse': { en: 'Cancel loading diesel charge', ar: 'إلغاء شحن الديزل تحميل' }, + 'trips.act.secondAdvanceReverse': { en: 'Cancel discharge diesel charge', ar: 'إلغاء شحن الديزل تفريغ' }, + 'trips.act.exchange': { en: 'Pay (e-wallet)', ar: 'صرف' }, + 'trips.act.exchangeAudit': { en: 'Audit before payment', ar: 'تدقيق صرف' }, + 'trips.act.receipt': { en: 'Receive', ar: 'استلام' }, + 'trips.act.payment': { en: 'Settle', ar: 'تسديد' }, + 'trips.act.activateWalletExchange': { en: 'Activate wallet payment', ar: 'تفعيل صرف المحفظة' }, + 'trips.act.cashPayment': { en: 'Cash payment', ar: 'دفع نقدي' }, + 'trips.act.confirmExchange': { en: 'Confirm payment', ar: 'تأكيد الصرف' }, + 'trips.act.print': { en: 'Print', ar: 'طباعة' }, + 'trips.act.confirm': { en: 'Do you want to run this action on the trip?', ar: 'هل تريد تنفيذ هذا الاجراء على الارسالية؟' }, + 'trips.act.confirmMoney': { en: 'This action pays money or changes the diesel card. Continue?', ar: 'هذا الاجراء يؤثر على المبالغ أو بطاقة الديزل. هل تريد المتابعة؟' }, + + // log + voucher + 'trips.log.method': { en: 'Movement', ar: 'نوع الحركة' }, + 'trips.log.date': { en: 'Date', ar: 'تاريخ التعديل' }, + 'trips.log.user': { en: 'User', ar: 'اسم المستخدم' }, + 'trips.log.property': { en: 'Property', ar: 'اسم الحقل' }, + 'trips.log.old': { en: 'Old data', ar: 'البيانات القديمة' }, + 'trips.log.new': { en: 'New data', ar: 'البيانات الجديدة' }, + 'trips.log.none': { en: 'No movements', ar: 'لا يوجد معلومات' }, + 'trips.voucher.title': { en: 'Cash voucher', ar: 'سند صرف نقدي' }, + 'trips.voucher.date': { en: 'Date', ar: 'التاريخ' }, + 'trips.voucher.no': { en: 'No', ar: 'No' }, + 'trips.voucher.body1': { en: 'Received from Nafith Logistics the amount of', ar: 'وصلني من السادة شركة نافذ للخدمات اللوجستية مبلغ وقدره' }, + 'trips.voucher.dinar': { en: 'dinars', ar: 'دينارا' }, + 'trips.voucher.body2': { en: 'for crude oil transport wages of form number', ar: 'وذلك عن أجور نقل النفط الخام للنموذج رقم' }, + 'trips.voucher.receiver': { en: 'Receiver name and signature', ar: 'اسم وتوقيع المستلم' }, + 'trips.voucher.accountant': { en: 'Accountant signature', ar: 'توقيع المحاسب' }, + 'trips.voucher.print': { en: 'Print', ar: 'طباعة' }, + 'trips.loadFailed': { en: 'Could not load the trip.', ar: 'تعذر تحميل الارسالية.' }, +}); + +/** REFINERYTRIP. captions of the history list. */ +export const methodCaptions: Record = { + FIRST_ADVANCED_PAYMENT: 'تعبئة بطاقة الديزل للتحميل', + SECOND_ADVANCED_PAYMENT: 'تعبئة بطاقة الديزل للتفريغ', + FIRST_ADVANCED_PAYMENT_REVERSE: 'إلغاء شحن الديزل تحميل', + SECOND_ADVANCED_PAYMENT_REVERSE: 'إلغاء شحن الديزل تفريغ', + EXCHANGE: 'صرف', + EXCHANGE_AUDIT: 'تدقيق صرف', + RECEIPT: 'استلام', + PAYMENT: 'تسديد', + TRIP_COMPLETE: 'تسديد', + ACTIVATE_WALLET_EXCHANGE: 'تفعيل صرف المحفظة', + CACH_PAYMENT: 'دفع نقدي', + ORANGE_PAYMENT: 'دفع اورنج', + CONFIRM_EXCHANGE: 'تأكيد الصرف', + PRINT: 'طباعة', + TRANSFER_TO_REFINERY: 'تم إرسال المطالبة إلى المصفاة', +}; + +/** REFINERYTRIP. captions of the old / new data popup. */ +export const propertyCaptions: Record = { + STATUS_CODE: 'الحالة', + REMARKS: 'ملاحظات', + CURRENT_BALANCE: 'القيمة التراكمية الحالية', + DINARAK_REFERENCE_ID: 'رقم مرجع دينارك', + NOTES: 'ملاحظات', +}; diff --git a/web/src/features/refinery/trips/types.ts b/web/src/features/refinery/trips/types.ts new file mode 100644 index 0000000..8bc0a35 --- /dev/null +++ b/web/src/features/refinery/trips/types.ts @@ -0,0 +1,102 @@ +export interface TripGridRow { + id: number; + pn: string | null; + dispatchDate: string | null; + loadingNo: number | null; + dischargeAuthNo: string | null; + dischargeEntryDate: string | null; + tn: string | null; + trn: string | null; + nnpn: string | null; + wageClaimId: number | null; + wageClaimNo: number | null; + statusCode: string | null; + dieselCharge: number; + hasPaymentMethod: boolean; + hasWater: boolean; + reversed: boolean; + netWage: number | null; +} + +export interface TripWallet { + epayment: number | null; + walletNumber: string | null; + ownerNnpn: string | null; + ownerName: string | null; + bankAccount: string | null; + iban: string | null; + bankName: string | null; + driverWalletNumber: string | null; +} + +export interface TripDetail { + id: number; + pn: string | null; + statusCode: string | null; + dispatchDate: string | null; + actualLoadingDate: string | null; + clientName: string | null; + tn: string | null; + trn: string | null; + nnpn: string | null; + driverName: string | null; + loadingNo: number | null; + grossWeight: number | null; + emptyWeight: number | null; + netLoadingWeight: number | null; + litersWeight: number | null; + dischargeAuthNo: string | null; + dischargeEntryDate: string | null; + actualGrossWeight: number | null; + actualEmptyWeight: number | null; + netDischargeWeight: number | null; + waterAmount: number | null; + sedimentAmount: number | null; + weightDifference: number | null; + netWage: number | null; + tripNetWage: number | null; + remainingBalance: number | null; + dieselCharge: number; + reversed: boolean; + cardNumber: string | null; + currentBalance: number | null; + newBalance: number | null; + firstPaymentValue: number | null; + secondPaymentValue: number | null; + wageClaimId: number | null; + wageClaimNo: number | null; + remarks: string | null; + receivedByName: string | null; + receivedDate: string | null; + paymentedDate: string | null; + paymentOptions: string | null; + voucherSerialNumber: number | null; + auditMode: boolean; + wallet: TripWallet | null; + /** Action codes the form offers for this trip (the user also needs the permission key). */ + actions: string[]; +} + +export interface TripLogRow { + id: number; + methodName: string | null; + logDate: string | null; + login: string | null; + oldData: string | null; + newData: string | null; +} + +export interface TripVoucher { + id: number; + pn: string; + serial: string; + date: string; + amount: number; + dischargeAuthNo: string | null; + ownerName: string | null; +} + +export interface TripsResult { + message: string; + id?: number | null; +} diff --git a/web/src/features/refinery/variables/api.ts b/web/src/features/refinery/variables/api.ts new file mode 100644 index 0000000..c94e422 --- /dev/null +++ b/web/src/features/refinery/variables/api.ts @@ -0,0 +1,54 @@ +import { useQuery } from '@tanstack/react-query'; +import { api } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; + +export const BASE = '/refinery/variables'; +export const GRID_VARIABLES = 'refinery.variables'; + +/** One pricing period (REFINERY_VARIABLES rows of a GROUP_ID, pivoted). Dates are ISO strings. */ +export interface VariablesRow { + groupId: number; + startDate: string | null; + endDate: string | null; + dieselLiterPrice: number | null; + tonWage: number | null; + tonPrice: number | null; + driverTip: number | null; + permitDispatch: number | null; + waybillFee: number | null; + commission: number | null; + tolerancePercentage: number | null; + firstAdvancePayment: number | null; + tonPriceCorrection: number | null; + tonPriceCorrectionSet: boolean; +} + +export interface VariablesDetail extends VariablesRow { + canUpdate: boolean; + canSetTonPriceCorrection: boolean; +} + +export interface VariablesResult { + message: string; + id: number | null; +} + +const keys = () => [gridKey(GRID_VARIABLES), ['refinery.variables.one']]; + +export const useVariablesSet = (groupId: number | null) => + useQuery({ queryKey: ['refinery.variables.one', groupId], queryFn: () => api.get(`${BASE}/${groupId}`), enabled: groupId !== null }); + +export const useCreateVariables = () => + useWrite((p: Record) => api.post(BASE, p), { invalidate: keys() }); + +export const useUpdateVariables = () => + useWrite((v: { groupId: number; payload: Record }) => api.put(`${BASE}/${v.groupId}`, v.payload), { + invalidate: keys(), + }); + +export const useSetTonPriceCorrection = () => + useWrite((v: { groupId: number; tonPriceCorrection: number }) => + api.post(`${BASE}/${v.groupId}/ton-price-correction`, { tonPriceCorrection: v.tonPriceCorrection }), { + invalidate: keys(), + }); diff --git a/web/src/features/refinery/variables/index.ts b/web/src/features/refinery/variables/index.ts new file mode 100644 index 0000000..fc2ab2b --- /dev/null +++ b/web/src/features/refinery/variables/index.ts @@ -0,0 +1,24 @@ +import { createElement } from 'react'; +import type { RouteObject } from 'react-router-dom'; +import PriceChangeIcon from '@mui/icons-material/PriceChange'; +import type { MenuItem } from '@/shell/types'; +import { VariablesPage, VariablesRecordPage } from './pages'; +import strings from './strings'; + +/** Refinery pricing periods (تسعير عطاء النفط الخام). The lead composes the refinery group and routes file. */ +export const routes: RouteObject[] = [ + { path: '/refinery/variables', element: createElement(VariablesPage) }, + { path: '/refinery/variables/new', element: createElement(VariablesRecordPage), handle: { crumb: strings['rv.crumb.new'] } }, + { path: '/refinery/variables/:groupId', element: createElement(VariablesRecordPage), handle: { crumb: strings['rv.crumb.details'] } }, +]; + +export const menuItems: MenuItem[] = [ + { + key: 'refinery.variables', + title: strings['rv.menu'], + icon: PriceChangeIcon, + path: '/refinery/variables', + createPath: '/refinery/variables/new', + createKey: 'refinery.variables.create', + }, +]; diff --git a/web/src/features/refinery/variables/meta.ts b/web/src/features/refinery/variables/meta.ts new file mode 100644 index 0000000..0a2f687 --- /dev/null +++ b/web/src/features/refinery/variables/meta.ts @@ -0,0 +1,75 @@ +import type { FieldMeta, FormMeta, GridMeta, L10n } from '@/components/meta/types'; +import strings from './strings'; +import { GRID_VARIABLES, type VariablesRow } from './api'; + +const s = strings; + +/** Legacy REFINERY_VARIABLESGRID: period, then the prices; the filters are the two period dates. */ +export function variablesGrid(h: { onOpen: (r: VariablesRow) => void }): GridMeta { + return { + key: GRID_VARIABLES, + endpoint: '/refinery/variables', + rowKey: (r) => r.groupId, + onRowClick: h.onOpen, + pageSize: 16, + emptyAsGrid: true, + filters: [ + { name: 'startDate', type: 'date', label: s['rv.filter.startDate'] }, + { name: 'endDate', type: 'date', label: s['rv.filter.endDate'] }, + ], + columns: [ + { key: 'startDate', header: s['rv.startDate'], format: 'date', ltr: true }, + { key: 'endDate', header: s['rv.endDate'], format: 'date', ltr: true }, + { key: 'dieselLiterPrice', header: s['rv.dieselLiterPrice'], format: 'number', ltr: true }, + { key: 'tonWage', header: s['rv.tonWage'], format: 'number', ltr: true }, + { key: 'tonPrice', header: s['rv.tonPrice'], format: 'number', ltr: true }, + { key: 'driverTip', header: s['rv.driverTip'], format: 'number', ltr: true, hideBelow: 'sm' }, + { key: 'permitDispatch', header: s['rv.permitDispatch'], format: 'number', ltr: true, hideBelow: 'md' }, + { key: 'waybillFee', header: s['rv.waybillFee'], format: 'number', ltr: true, hideBelow: 'md' }, + { key: 'commission', header: s['rv.commission'], format: 'number', ltr: true, hideBelow: 'lg' }, + { key: 'tolerancePercentage', header: s['rv.tolerancePercentage'], format: 'number', ltr: true, hideBelow: 'lg' }, + ], + }; +} + +const money = (name: string, label: L10n, extra: Partial = {}): FieldMeta => ({ + name, type: 'number', label, required: true, min: 0, max: 9999999, placeholder: { en: '0.000', ar: '0.000' }, ...extra, +}); + +/** Legacy REFINERY_VARIABLESMain.html: every field is required. Diesel price (0, 2) and ton wage (0, 100) are checked by the server too. */ +export function variablesForm(): FormMeta { + return { + key: 'refinery.variables.form', + sections: [ + { + key: 'period', + title: s['rv.basic'], + columns: 2, + fields: [ + { name: 'startDate', type: 'date', label: s['rv.startDate'], required: true }, + { name: 'endDate', type: 'date', label: s['rv.endDate'], required: true }, + money('dieselLiterPrice', s['rv.dieselLiterPrice'], { min: 0.001, max: 1.999 }), + money('firstAdvancePayment', s['rv.firstAdvancePayment']), + money('tonWage', s['rv.tonWage'], { min: 0.001, max: 99.999 }), + money('tonPrice', s['rv.tonPrice']), + money('driverTip', s['rv.driverTip']), + money('permitDispatch', s['rv.permitDispatch']), + money('waybillFee', s['rv.waybillFee']), + money('commission', s['rv.commission']), + money('tolerancePercentage', s['rv.tolerancePercentage']), + ], + }, + ], + }; +} + +export function tonPriceCorrectionForm(): FormMeta { + return { + key: 'refinery.variables.tonPriceCorrection', + sections: [{ + key: 'correction', + columns: 2, + fields: [money('tonPriceCorrection', s['rv.tonPriceCorrection'], { min: 0.001 })], + }], + }; +} diff --git a/web/src/features/refinery/variables/pages.tsx b/web/src/features/refinery/variables/pages.tsx new file mode 100644 index 0000000..f0c7695 --- /dev/null +++ b/web/src/features/refinery/variables/pages.tsx @@ -0,0 +1,159 @@ +import { useMemo, useState } from 'react'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { Alert, Button, Stack } from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import DownloadIcon from '@mui/icons-material/Download'; +import SummarizeIcon from '@mui/icons-material/Summarize'; +import PriceChangeIcon from '@mui/icons-material/PriceChange'; +import type { ApiError } from '@/api/client'; +import { DataGrid, gridReturnUrl } from '@/components/DataGrid'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { MetaForm } from '@/components/MetaForm'; +import { PageHeader } from '@/components/PageHeader'; +import { SectionPaper } from '@/components/SectionPaper'; +import { SectionTitle } from '@/components/SectionTitle'; +import { formatDate } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { downloadFile } from '../../grains-orders/api'; +import { BASE, useCreateVariables, useSetTonPriceCorrection, useUpdateVariables, useVariablesSet } from './api'; +import { tonPriceCorrectionForm, variablesForm, variablesGrid } from './meta'; +import strings from './strings'; + +const ROOT = '/refinery/variables'; +const NUMERIC = ['dieselLiterPrice', 'firstAdvancePayment', 'tonWage', 'tonPrice', 'driverTip', 'permitDispatch', 'waybillFee', 'commission', 'tolerancePercentage']; + +const fieldErrorsOf = (e: ApiError) => ({ ...e.fieldErrors }) as Record; +const isoDay = (v: string | null | undefined) => (v ? v.slice(0, 10) : ''); +const text = (v: number | null | undefined) => (v === null || v === undefined ? '' : String(v)); + +/** Download button of an Excel endpoint: the filters of the page travel in the query string. */ +function DownloadButton({ path, label, icon, permission }: { path: string; label: string; icon: React.ReactNode; permission: string }) { + const { can } = useAuth(); + const toast = useToast(); + const [sp] = useSearchParams(); + const [busy, setBusy] = useState(false); + if (!can(permission)) return null; + const run = async () => { + setBusy(true); + const params: Record = {}; + sp.forEach((v, k) => { if (k !== 'page' && k !== 'pageSize' && k !== 'f') params[k] = v; }); + try { await downloadFile(path, params, 'report.xlsx'); } + catch (e) { toast.error(e instanceof Error ? e.message : String(e)); } + finally { setBusy(false); } + }; + return ; +} + +export function VariablesPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const { can } = useAuth(); + const meta = useMemo(() => variablesGrid({ onOpen: (r) => navigate(`${ROOT}/${r.groupId}`) }), [navigate]); + return ( + <> + + } permission="refinery.variables.report" /> + } permission="refinery.variables.remainingBalanceReport" /> + {can('refinery.variables.create') && ( + + )} + + )} + /> + + + ); +} + +export function VariablesRecordPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const params = useParams(); + const groupId = params.groupId ? Number(params.groupId) : null; + const isNew = groupId === null; + const { can } = useAuth(); + const q = useVariablesSet(groupId); + const create = useCreateVariables(); + const update = useUpdateVariables(); + const correct = useSetTonPriceCorrection(); + const [serverErrors, setServerErrors] = useState>({}); + const d = q.data; + const meta = useMemo(() => variablesForm(), []); + const correctionMeta = useMemo(() => tonPriceCorrectionForm(), []); + + const initial = useMemo(() => (d ? { + startDate: isoDay(d.startDate), endDate: isoDay(d.endDate), dieselLiterPrice: text(d.dieselLiterPrice), + firstAdvancePayment: text(d.firstAdvancePayment), tonWage: text(d.tonWage), tonPrice: text(d.tonPrice), driverTip: text(d.driverTip), + permitDispatch: text(d.permitDispatch), waybillFee: text(d.waybillFee), commission: text(d.commission), + tolerancePercentage: text(d.tolerancePercentage), + } : {}), [d]); + const correctionInitial = useMemo(() => ({ tonPriceCorrection: text(d?.tonPriceCorrection) }), [d?.tonPriceCorrection]); + + if (!isNew && q.isLoading) return ; + if (!isNew && !d) return {q.error?.message ?? t('rv.loadFailed')}; + + const editable = isNew || (!!d?.canUpdate && can('refinery.variables.update')); + const toBody = (payload: Record) => { + const body: Record = { ...payload }; + for (const k of NUMERIC) body[k] = Number(payload[k]); + return body; + }; + + const submit = (payload: Record) => + new Promise((resolve) => { + setServerErrors({}); + const done = { onSuccess: () => { resolve(); navigate(gridReturnUrl(ROOT), { replace: true }); }, onError: (e: ApiError) => { setServerErrors(fieldErrorsOf(e)); resolve(); } }; + if (isNew) create.mutate(toBody(payload), done); + else update.mutate({ groupId: groupId!, payload: toBody(payload) }, done); + }); + + const submitCorrection = (payload: Record) => + new Promise((resolve) => { + correct.mutate({ groupId: groupId!, tonPriceCorrection: Number(payload.tonPriceCorrection) }, { onSuccess: () => resolve(), onError: () => resolve() }); + }); + + return ( + + + {!isNew && !d!.canUpdate && {t('rv.noUpdate')}} + navigate(gridReturnUrl(ROOT))} + onSubmit={submit} + /> + {!isNew && can('refinery.variables.tonPriceCorrection') && ( + + + {d!.tonPriceCorrectionSet + ? {t('rv.tonPriceCorrection.done')} + : ( + + {t('rv.tonPriceCorrection.help')} + + + )} + + )} + + ); +} diff --git a/web/src/features/refinery/variables/strings.ts b/web/src/features/refinery/variables/strings.ts new file mode 100644 index 0000000..86f0ecc --- /dev/null +++ b/web/src/features/refinery/variables/strings.ts @@ -0,0 +1,44 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Strings of the refinery pricing periods screen (legacy captions REFINERY_VARIABLES.* / PUBLIC.*, verbatim in Arabic). */ +export default defineStrings({ + 'rv.menu': { en: 'Crude oil tender pricing', ar: 'تسعير عطاء النفط الخام' }, + 'rv.title': { en: 'Crude oil tender pricing', ar: 'تسعير عطاء النفط الخام' }, + 'rv.subtitle': { en: 'Pricing periods: prices, wages and fees valid between two dates', ar: 'فترات التسعير: الأسعار والأجور والرسوم السارية بين تاريخين' }, + 'rv.new': { en: 'New pricing period', ar: 'فترة تسعير جديدة' }, + 'rv.createTitle': { en: 'New pricing period', ar: 'فترة تسعير جديدة' }, + 'rv.detailTitle': { en: 'Pricing period {from} - {to}', ar: 'فترة التسعير {from} - {to}' }, + 'rv.crumb.new': { en: 'New', ar: 'جديد' }, + 'rv.crumb.details': { en: 'Details', ar: 'التفاصيل' }, + 'rv.loadFailed': { en: 'The pricing period could not be loaded.', ar: 'تعذر تحميل فترة التسعير.' }, + 'rv.return': { en: 'Back', ar: 'عودة' }, + + 'rv.startDate': { en: 'Period start', ar: 'بداية فترة التسعير' }, + 'rv.endDate': { en: 'Period end', ar: 'نهاية فترة التسعير' }, + 'rv.dieselLiterPrice': { en: 'Diesel price per liter', ar: 'سعر لتر الديزل' }, + 'rv.firstAdvancePayment': { en: 'First diesel top-up (loading)', ar: 'قيمة شحن الديزل للتحميل' }, + 'rv.tonWage': { en: 'Ton wage', ar: 'اجور الطن' }, + 'rv.tonPrice': { en: 'Ton price', ar: 'سعر الطن' }, + 'rv.driverTip': { en: 'Driver tip', ar: 'اكرامية السائق' }, + 'rv.permitDispatch': { en: 'Tanker dispatch price', ar: 'سعر تسريب الصهريج' }, + 'rv.waybillFee': { en: 'Waybill fee', ar: 'اصدار وثيقة' }, + 'rv.commission': { en: 'Competitive exchange commission', ar: 'عمولة الصرف التنافسي' }, + 'rv.tolerancePercentage': { en: 'Tolerance percentage', ar: 'نسبة السماح' }, + 'rv.tonPriceCorrection': { en: 'Actual ton price', ar: 'سعر الطن الفعلي' }, + 'rv.basic': { en: 'Basic information', ar: 'المعلومات الأساسية' }, + + 'rv.tonPriceCorrection.title': { en: 'Actual ton price', ar: 'تعديل سعر طن النفط' }, + 'rv.tonPriceCorrection.help': { + en: 'Can be set once per period; the balances of the trucks are then recalculated.', + ar: 'يمكن تعديله مرة واحدة لكل فترة، وبعدها يعاد احتساب الذمم السابقة للشاحنات.', + }, + 'rv.tonPriceCorrection.done': { en: 'The actual ton price was already set for this period.', ar: 'تم تعديل سعر الطن الفعلي سابقا' }, + 'rv.tonPriceCorrection.confirm': { en: 'Set the actual ton price? This cannot be repeated.', ar: 'هل تريد تعديل سعر الطن؟ لا يمكن تكرار هذا الإجراء.' }, + 'rv.tonPriceCorrection.save': { en: 'Update ton price', ar: 'تعديل سعر طن النفط' }, + 'rv.noUpdate': { en: 'Trips were already loaded inside this period: its values can no longer be changed.', ar: 'لا يمكن تعديل القيم بسبب وجود ارساليات مسعره عليها' }, + + 'rv.export': { en: 'Excel', ar: 'تصدير Excel' }, + 'rv.exportBalance': { en: 'Previous balances report', ar: 'تقرير قيمة الذمم السابقة' }, + 'rv.filter.startDate': { en: 'Start date', ar: 'بداية فترة التسعير' }, + 'rv.filter.endDate': { en: 'End date', ar: 'نهاية فترة التسعير' }, +}); diff --git a/web/src/features/refinery/wage-claims/api.ts b/web/src/features/refinery/wage-claims/api.ts new file mode 100644 index 0000000..5cf04da --- /dev/null +++ b/web/src/features/refinery/wage-claims/api.ts @@ -0,0 +1,60 @@ +import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'; +import { api, type PagedResult } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; +import { useLanguage } from '@/providers/LanguageProvider'; +import type { ClaimLogRow, ClaimResult, ClaimTripRow, CreateWageClaimBody, WageClaimRow } from './types'; + +export const BASE = '/refinery/wage-claims'; +export const GRID_WAGE_CLAIMS = 'refinery.wageClaims'; + +export const useWageClaim = (id: number | null) => + useQuery({ queryKey: ['refinery.wageClaim', id], queryFn: () => api.get(`${BASE}/${id}`), enabled: id !== null }); + +export const useClaimTrips = (id: number | null, page: number, pageSize: number) => + useQuery({ + queryKey: ['refinery.wageClaim.trips', id, page, pageSize], + queryFn: () => api.get>(`${BASE}/${id}/trips`, { page, pageSize }, { silent: true }), + enabled: id !== null, + placeholderData: keepPreviousData, + }); + +/** Create dialog preview: trips of the statuses (empty = the three of the dialog) without a wage claim, optionally in a loading date range. */ +export const useCandidateTrips = (f: { statuses: string[]; from: string; to: string }, page: number, pageSize: number, enabled: boolean) => + useQuery({ + queryKey: ['refinery.wageClaim.candidates', f.statuses.join(','), f.from, f.to, page, pageSize], + queryFn: () => api.get>(`${BASE}/candidate-trips`, + { statusCode: f.statuses.join(','), loadingDateFrom: f.from, loadingDateTo: f.to, page, pageSize }, { silent: true }), + enabled, + placeholderData: keepPreviousData, + }); + +/** Log of a claim; `base` is the API base of the screen (wage claims or commission claims, same shape). */ +export function useClaimLog(base: string, id: number, page: number, pageSize: number, enabled: boolean) { + const { langReady } = useLanguage(); + return useQuery({ + queryKey: ['refinery.wageClaim.log', base, id, page, pageSize], + queryFn: () => api.get>(`${base}/${id}/log`, { page, pageSize }, { silent: true }), + enabled: enabled && langReady, + placeholderData: keepPreviousData, + }); +} + +export function useCreateWageClaim() { + return useWrite((body: CreateWageClaimBody) => api.post(BASE, body), { invalidate: [gridKey(GRID_WAGE_CLAIMS), ['refinery.wageClaim.candidates']] }); +} + +/** After close / transfer the claim, its trips and its log change. */ +function useClaimAction(action: 'close' | 'transfer') { + const qc = useQueryClient(); + return useWrite((id: number) => api.post(`${BASE}/${id}/${action}`), { + invalidate: [gridKey(GRID_WAGE_CLAIMS)], + onSuccess: (_res) => { + void qc.invalidateQueries({ queryKey: ['refinery.wageClaim'] }); + void qc.invalidateQueries({ queryKey: ['refinery.wageClaim.trips'] }); + void qc.invalidateQueries({ queryKey: ['refinery.wageClaim.log'] }); + }, + }); +} +export const useCloseWageClaim = () => useClaimAction('close'); +export const useTransferWageClaim = () => useClaimAction('transfer'); diff --git a/web/src/features/refinery/wage-claims/components.tsx b/web/src/features/refinery/wage-claims/components.tsx new file mode 100644 index 0000000..c45d268 --- /dev/null +++ b/web/src/features/refinery/wage-claims/components.tsx @@ -0,0 +1,169 @@ +import { useState, type ReactNode } from 'react'; +import { + Box, Button, Collapse, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Stack, Table, TableBody, TableCell, TableContainer, + TableHead, TablePagination, TableRow, Tooltip, Typography, +} from '@mui/material'; +import HistoryIcon from '@mui/icons-material/History'; +import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined'; +import type { PagedResult } from '@/api/client'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { SectionPaper } from '@/components/SectionPaper'; +import { StatusChip } from '@/components/StatusChip'; +import { formatDate, formatDateTime } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { BASE, useClaimLog } from './api'; +import { tripStatuses } from './meta'; +import strings from './strings'; +import type { ClaimLogRow, ClaimTripRow } from './types'; + +const PAGE_SIZES = [10, 25, 50]; + +/** Framed block with a title (same look as the other record screens). */ +export function Block({ title, actions, children }: { title?: string; actions?: ReactNode; children: ReactNode }) { + return ( + + {(title || actions) && ( + + {title && {title}} + {actions} + + )} + {children} + + ); +} + +/** Trips of a claim (legacy grid searchClaimTrips: 9 columns), paged on the server. A row opens the trip when `onOpen` is given. */ +export function TripsTable(p: { + data: PagedResult | undefined; loading: boolean; page: number; pageSize: number; + onPage: (page: number) => void; onPageSize: (size: number) => void; onOpen?: (row: ClaimTripRow) => void; +}) { + const { t } = useFeatureUi(strings); + if (!p.data && p.loading) return ; + const rows = p.data?.items ?? []; + const ltr = { direction: 'ltr', textAlign: 'start' } as const; + return ( + <> + + + + + {(['wc.trip.pn', 'wc.trip.paymentedDate', 'wc.trip.loadingNo', 'wc.trip.formNo', 'wc.trip.formDate', 'wc.trip.tn', 'wc.trip.trn', 'wc.trip.nnpn', 'wc.trip.status'] as const) + .map((k) => {t(k)})} + + + + {rows.length === 0 && ( + {t('wc.trips.empty')} + )} + {rows.map((r) => ( + p.onOpen!(r) : undefined} sx={{ cursor: p.onOpen ? 'pointer' : undefined }}> + {r.pn} + {formatDate(r.paymentedDate)} + {r.loadingNo} + {r.dischargeAuthoriztionNo} + {formatDate(r.dischargeEntryDate)} + {r.tn} + {r.trn} + {r.nnpn} + + + ))} + +
+
+ p.onPage(v + 1)} onRowsPerPageChange={(e) => { p.onPageSize(Number(e.target.value)); p.onPage(1); }} + sx={{ direction: 'ltr' }} + /> + + ); +} + +/** OLD_DATA / NEW_DATA hold a small JSON object ({"STATUS_CODE":"..."}) or a plain word: show "key: value" lines. */ +function dataLines(text: string | null): string[] { + if (!text) return []; + try { + const v = JSON.parse(text) as unknown; + if (v && typeof v === 'object') return Object.entries(v as Record).map(([k, x]) => `${k}: ${String(x)}`); + } catch { /* not JSON */ } + return [text]; +} + +/** Log popup of a claim (legacy "سجل الحركات"): the history of the record, with a view of the old / new data of each action. */ +export function ClaimLogSection({ id, base = BASE }: { id: number; base?: string }) { + const { t, tr } = useFeatureUi(strings); + const [open, setOpen] = useState(false); + const [page, setPage] = useState(1); + const [size, setSize] = useState(5); + const [detail, setDetail] = useState(null); + const q = useClaimLog(base, id, page, size, open); + const rows = q.data?.items ?? []; + const method = (code: string) => { + const key = `wc.log.${code}` as keyof typeof strings; + return strings[key] ? tr(strings[key]) : code; + }; + return ( + } onClick={() => setOpen((o) => !o)}>{t('wc.log.title')}} + > + + {q.isLoading ? : ( + <> + + + + + {t('wc.log.method')} + {t('wc.log.date')} + {t('wc.log.user')} + + + + + {rows.length === 0 && {t('wc.log.empty')}} + {rows.map((r) => ( + + {method(r.methodName)} + {formatDateTime(r.logDate)} + {r.login} + + {r.methodName !== 'CREATE' && (r.oldData || r.newData) && ( + + setDetail(r)}> + + )} + + + ))} + +
+
+ setPage(v + 1)} onRowsPerPageChange={(e) => { setSize(Number(e.target.value)); setPage(1); }} sx={{ direction: 'ltr' }} + /> + + )} +
+ setDetail(null)} fullWidth maxWidth="xs"> + {detail ? method(detail.methodName) : ''} + + + + {t('wc.log.old')} + {dataLines(detail?.oldData ?? null).map((x, i) => {x})} + + + {t('wc.log.new')} + {dataLines(detail?.newData ?? null).map((x, i) => {x})} + + + + + +
+ ); +} diff --git a/web/src/features/refinery/wage-claims/index.ts b/web/src/features/refinery/wage-claims/index.ts new file mode 100644 index 0000000..d71c25c --- /dev/null +++ b/web/src/features/refinery/wage-claims/index.ts @@ -0,0 +1 @@ +export { routes, menuItems } from './routes'; diff --git a/web/src/features/refinery/wage-claims/meta.ts b/web/src/features/refinery/wage-claims/meta.ts new file mode 100644 index 0000000..bf4be39 --- /dev/null +++ b/web/src/features/refinery/wage-claims/meta.ts @@ -0,0 +1,66 @@ +import type { FilterMeta, GridMeta, StatusMeta } from '@/components/meta/types'; +import strings from './strings'; +import { GRID_WAGE_CLAIMS } from './api'; +import type { WageClaimRow } from './types'; + +const l = (key: keyof typeof strings) => strings[key]; + +/** Claim statuses (REFINERY_WAGE_CLAIM.STATUS.*). */ +export const claimStatuses: StatusMeta[] = [ + { value: 'NEW', label: l('wc.statusNew'), color: 'warning' }, + { value: 'CLOSE', label: l('wc.statusClose'), color: 'info' }, + { value: 'COMPLETE', label: l('wc.statusComplete'), color: 'success' }, +]; + +/** Trip statuses (REFINERYTRIP.STATUS.*), as shown in the trips table of a claim. */ +export const tripStatuses: StatusMeta[] = [ + { value: 'EXCHANGED', label: l('wc.trip.EXCHANGED'), color: 'success' }, + { value: 'READY_TO_PAY', label: l('wc.trip.READY_TO_PAY'), color: 'warning' }, + { value: 'DISCHARGED', label: l('wc.trip.DISCHARGED'), color: 'info' }, + { value: 'COMPLETE', label: l('wc.trip.COMPLETE'), color: 'primary' }, + { value: 'ARRIVE_LOCATION', label: l('wc.trip.ARRIVE_LOCATION'), color: 'default' }, + { value: 'DISCHARGING', label: l('wc.trip.DISCHARGING'), color: 'default' }, + { value: 'DISCHARGING_FILL', label: l('wc.trip.DISCHARGING_FILL'), color: 'default' }, + { value: 'LOADED', label: l('wc.trip.LOADED'), color: 'default' }, + { value: 'LOADING_FILL', label: l('wc.trip.LOADING_FILL'), color: 'default' }, + { value: 'PENDING_EXCHANGE', label: l('wc.trip.PENDING_EXCHANGE'), color: 'default' }, + { value: 'RESD', label: l('wc.trip.RESD'), color: 'default' }, + { value: 'RVKD', label: l('wc.trip.RVKD'), color: 'error' }, +]; + +/** String key of a trip status label (wc.trip.). */ +export const tripStatusLabelKey = (status: string) => `wc.trip.${status}` as keyof typeof strings; + +/** The three trip statuses the create dialog offers (REFINERY_WAGE_CLAIMMain.html). */ +export const claimableTripStatuses = ['EXCHANGED', 'READY_TO_PAY', 'DISCHARGED'] as const; + +const filters: FilterMeta[] = [ + { name: 'wageClaimNo', type: 'text', label: l('wc.no'), inputKind: 'code' }, + { name: 'wageClaimDate', type: 'date', label: l('wc.date') }, + { name: 'commissionClaimNo', type: 'text', label: l('wc.commissionNo'), inputKind: 'code' }, + { + name: 'hasCommissionClaim', type: 'select', label: l('wc.hasCommission'), + options: [{ value: '1', label: l('wc.yes') }, { value: '0', label: l('wc.no.answer') }], + }, +]; + +/** Legacy REFINERY_WAGE_CLAIMGRID: no, date, trips, commission claim no, status; filtered to NEW claims on opening (args STATUS_CODE NEW). */ +export function wageClaimGrid(onOpen: (r: WageClaimRow) => void): GridMeta { + return { + key: GRID_WAGE_CLAIMS, + endpoint: '/refinery/wage-claims', + rowKey: (r) => r.id, + status: { param: 'statusCode', options: claimStatuses }, + defaultFilters: { statusCode: 'NEW' }, + filters, + emptyAsGrid: true, + columns: [ + { key: 'wageClaimNo', header: l('wc.no'), ltr: true }, + { key: 'wageClaimDate', header: l('wc.date'), format: 'date', ltr: true }, + { key: 'tripCnt', header: l('wc.tripCnt'), format: 'number', align: 'center' }, + { key: 'commissionClaimNo', header: l('wc.commissionNo'), ltr: true }, + { key: 'statusCode', header: l('wc.status'), format: 'status', statuses: claimStatuses }, + ], + onRowClick: onOpen, + }; +} diff --git a/web/src/features/refinery/wage-claims/pages.tsx b/web/src/features/refinery/wage-claims/pages.tsx new file mode 100644 index 0000000..4e44b12 --- /dev/null +++ b/web/src/features/refinery/wage-claims/pages.tsx @@ -0,0 +1,202 @@ +import { useMemo, useState } from 'react'; +import { Link as RouterLink, useNavigate, useParams } from 'react-router-dom'; +import { Alert, Button, Checkbox, FormControlLabel, FormGroup, Link, Stack, Typography } from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import DownloadIcon from '@mui/icons-material/Download'; +import PaymentsIcon from '@mui/icons-material/Payments'; +import SearchIcon from '@mui/icons-material/Search'; +import SendIcon from '@mui/icons-material/Send'; +import { DataGrid } from '@/components/DataGrid'; +import { DateField } from '@/components/DateField'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { PageHeader } from '@/components/PageHeader'; +import { StatusChip } from '@/components/StatusChip'; +import { ViewItem } from '@/components/ViewItem'; +import { formatDate, formatNumber } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { downloadFile } from '../../grains-orders/api'; +import { + BASE, useCandidateTrips, useClaimTrips, useCloseWageClaim, useCreateWageClaim, useTransferWageClaim, useWageClaim, +} from './api'; +import { Block, ClaimLogSection, TripsTable } from './components'; +import { claimableTripStatuses, claimStatuses, tripStatusLabelKey, wageClaimGrid } from './meta'; +import strings from './strings'; + +const ROOT = '/refinery/wage-claims'; + +// ================================================================= list (REFINERY_WAGE_CLAIMGRID) +export function WageClaimsPage() { + const { t } = useFeatureUi(strings); + const { can } = useAuth(); + const navigate = useNavigate(); + const meta = useMemo(() => wageClaimGrid((r) => navigate(`${ROOT}/${r.id}`)), [navigate]); + return ( + <> + } onClick={() => navigate(`${ROOT}/new`)}>{t('wc.new')} + : undefined} + /> + + + ); +} + +// ================================================================= create (REFINERY_WAGE_CLAIM dialog with id 0) +export function WageClaimCreatePage() { + const { t, tr } = useFeatureUi(strings); + const navigate = useNavigate(); + const toast = useToast(); + const confirm = useConfirm(); + const create = useCreateWageClaim(); + + // legacy dialog: the three statuses are selected on opening and the grid shows the trips right away (no dates) + const [statuses, setStatuses] = useState([...claimableTripStatuses]); + const [from, setFrom] = useState(''); + const [to, setTo] = useState(''); + const [applied, setApplied] = useState<{ statuses: string[]; from: string; to: string }>({ statuses: [...claimableTripStatuses], from: '', to: '' }); + const [page, setPage] = useState(1); + const [size, setSize] = useState(10); + const trips = useCandidateTrips(applied, page, size, true); + + const allOn = statuses.length === claimableTripStatuses.length; + const toggle = (s: string) => setStatuses((cur) => (cur.includes(s) ? cur.filter((x) => x !== s) : [...cur, s])); + + /** Same checks and order as the server (factory.create); shown as soon as the button is pressed. */ + const problem = (): string | null => { + if (statuses.length === 0) return t('wc.create.statusRequired'); + if (!from || !to) return t('wc.create.dateRequired'); + if (from > to) return t('wc.create.fromAfterTo'); + return null; + }; + + const search = () => { + if (from && to && from > to) { toast.error(t('wc.create.fromAfterTo')); return; } + setApplied({ statuses, from, to }); + setPage(1); + }; + + const save = async () => { + const p = problem(); + if (p) { toast.error(p); return; } + if (!(await confirm({ message: t('wc.create.confirm') }))) return; + create.mutate({ statusCodes: statuses, loadingDateFrom: from, loadingDateTo: to }, { + onSuccess: (r) => navigate(r.id ? `${ROOT}/${r.id}` : ROOT), + }); + }; + + return ( + <> + void save()}>{t('wc.create.save')}} + /> + + + + + 0} + onChange={() => setStatuses(allOn ? [] : [...claimableTripStatuses])} />} + /> + {claimableTripStatuses.map((s) => ( + toggle(s)} />} /> + ))} + + + + + + + + + + + + ); +} + +// ================================================================= view (REFINERY_WAGE_CLAIM dialog with a claim) +export function WageClaimPage() { + const { t } = useFeatureUi(strings); + const { can } = useAuth(); + const navigate = useNavigate(); + const toast = useToast(); + const confirm = useConfirm(); + const { id: idParam } = useParams(); + const id = Number(idParam); + const claim = useWageClaim(Number.isFinite(id) ? id : null); + const [page, setPage] = useState(1); + const [size, setSize] = useState(10); + const trips = useClaimTrips(Number.isFinite(id) ? id : null, page, size); + const close = useCloseWageClaim(); + const transfer = useTransferWageClaim(); + const [exporting, setExporting] = useState(false); + + if (claim.isLoading) return ; + if (claim.isError || !claim.data) return {t('wc.notFound')}; + const c = claim.data; + const isNew = c.statusCode === 'NEW'; // CLOSE / TRANSFER exist only on NEW claims (STATUS_ACTION_MATRIX) + + const runExport = async () => { + setExporting(true); + try { await downloadFile(`${BASE}/${c.id}/export`, {}, `wage_claim_${c.wageClaimNo}.xls`); } + catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + finally { setExporting(false); } + }; + + return ( + <> + } + actions={ + <> + {can('refinery.wageClaims.report') && ( + + )} + {isNew && can('refinery.wageClaims.transfer') && ( + + )} + {isNew && can('refinery.wageClaims.close') && ( + + )} + + } + /> + + + + {c.wageClaimNo} + {formatDate(c.wageClaimDate)} + {formatNumber(c.tripCnt, 'ar')} + + {c.commissionClaimId && can('refinery.commissionClaims') + ? {c.commissionClaimNo} + : c.commissionClaimNo} + + + + + {/* the trip screen is ported by another module: route /refinery/trips/:id */} + navigate(`/refinery/trips/${r.id}`) : undefined} /> + + + + + ); +} diff --git a/web/src/features/refinery/wage-claims/routes.tsx b/web/src/features/refinery/wage-claims/routes.tsx new file mode 100644 index 0000000..1cbe479 --- /dev/null +++ b/web/src/features/refinery/wage-claims/routes.tsx @@ -0,0 +1,20 @@ +import type { RouteObject } from 'react-router-dom'; +import ReceiptLongIcon from '@mui/icons-material/ReceiptLong'; +import type { MenuItem } from '@/shell/types'; +import { WageClaimCreatePage, WageClaimPage, WageClaimsPage } from './pages'; +import strings from './strings'; + +/** Refinery wage claims (مطالبة الأجور). Routes use absolute paths; the trip screen of the trips module links here by /refinery/wage-claims/:id. */ +export const routes: RouteObject[] = [ + { path: '/refinery/wage-claims', element: }, + { path: '/refinery/wage-claims/new', element: , handle: { crumb: strings['wc.crumb.new'] } }, + { path: '/refinery/wage-claims/:id', element: , handle: { crumb: strings['wc.crumb.details'] } }, +]; + +/** Leaf entry only: the lead composes the refinery group. key = the screen key (PermissionKeys.RefineryWageClaims). */ +export const menuItems: MenuItem[] = [ + { + key: 'refinery.wageClaims', title: strings['wc.menu'], icon: ReceiptLongIcon, path: '/refinery/wage-claims', + createPath: '/refinery/wage-claims/new', createKey: 'refinery.wageClaims.create', + }, +]; diff --git a/web/src/features/refinery/wage-claims/strings.ts b/web/src/features/refinery/wage-claims/strings.ts new file mode 100644 index 0000000..8ba2818 --- /dev/null +++ b/web/src/features/refinery/wage-claims/strings.ts @@ -0,0 +1,89 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** + * Strings of the refinery wage claims screen (مطالبات صرف أجور النقل). The Arabic texts are the legacy captions (NTP.LT_CAPTION) verbatim; + * the few texts the legacy screen never had (confirmations, empty states) are marked "new". + */ +export default defineStrings({ + // ---- menu / titles + 'wc.menu': { en: 'Wage claims', ar: 'شاشة مطالبات صرف أجور النقل' }, // MENU.REFINERY_WAGE_CLAIM + 'wc.title': { en: 'Transport wage claims', ar: 'شاشة مطالبات صرف أجور النقل' }, + 'wc.subtitle': { en: 'Claims that group the exchanged trips of the refinery tender', ar: 'مطالبات تجمع الارساليات المصروفة لعطاء المصفاة' }, + 'wc.details': { en: 'Wage claim details', ar: 'معلومات مطالبة صرف اجور النقل' }, // REFINERY_WAGE_CLAIM_DETAILS + 'wc.crumb.new': { en: 'New', ar: 'جديد' }, + 'wc.crumb.details': { en: 'Details', ar: 'التفاصيل' }, + 'wc.new': { en: 'New claim', ar: 'جديد' }, + + // ---- grid columns / filters + 'wc.no': { en: 'Claim number', ar: 'رقم مطالبة اجور النقل' }, // PUBLIC.WAGE_CLAIM_NO + 'wc.date': { en: 'Claim date', ar: 'تاريخ المطالبة' }, // PUBLIC.WAGE_CLAIM_DATE + 'wc.tripCnt': { en: 'Number of trips', ar: 'عدد الارساليات' }, // PUBLIC.TRIP_CNT + 'wc.commissionNo': { en: 'Commission claim number', ar: 'رقم مطالبة عمولات الصرف' }, // PUBLIC.COMMISSION_CLAIM_NO + 'wc.status': { en: 'Status', ar: 'الحالة' }, // PUBLIC.STATUS_CODE + 'wc.hasCommission': { en: 'Has a commission claim', ar: 'تحديد مطالبة عمولة الصرف' }, // REFINERY_WAGE_CLAIM.HAS_COMMISSION_CLAIM + 'wc.yes': { en: 'Yes', ar: 'نعم' }, + 'wc.no.answer': { en: 'No', ar: 'لا' }, + 'wc.statusNew': { en: 'New', ar: 'جديد' }, + 'wc.statusClose': { en: 'Paid', ar: 'تم التسديد' }, + 'wc.statusComplete': { en: 'Complete', ar: 'مكتمل' }, + + // ---- trips table (legacy searchClaimTrips columns) + 'wc.trip.pn': { en: 'Permit number', ar: 'رقم الارسالية' }, + 'wc.trip.paymentedDate': { en: 'Payment date', ar: 'تاريخ الدفع' }, + 'wc.trip.loadingNo': { en: 'Loading number', ar: 'رقم الحمولة' }, + 'wc.trip.formNo': { en: 'Form number', ar: 'رقم النموذج' }, + 'wc.trip.formDate': { en: 'Form date', ar: 'تاريخ النموذج' }, + 'wc.trip.tn': { en: 'Truck number', ar: 'رقم القاطرة' }, + 'wc.trip.trn': { en: 'Trailer number', ar: 'رقم المقطورة' }, + 'wc.trip.nnpn': { en: 'National number', ar: 'الرقم الوطني' }, + 'wc.trip.status': { en: 'Status', ar: 'الحالة' }, + 'wc.trips.title': { en: 'Trips of the claim', ar: 'ارساليات المطالبة' }, // new + 'wc.trips.empty': { en: 'No trips', ar: 'لا يوجد معلومات' }, // PUBLIC.NORECORD + 'wc.trip.EXCHANGED': { en: 'Exchanged', ar: 'تم الصرف' }, + 'wc.trip.READY_TO_PAY': { en: 'Ready to pay', ar: 'جاهز للدفع' }, + 'wc.trip.DISCHARGED': { en: 'Discharged', ar: 'تم التفريغ' }, + 'wc.trip.COMPLETE': { en: 'Complete', ar: 'مكتمل' }, + 'wc.trip.ARRIVE_LOCATION': { en: 'Arrived at Shuwaiyer', ar: 'وصول شويعر' }, + 'wc.trip.DISCHARGING': { en: 'Discharging', ar: 'قيد التفريغ' }, + 'wc.trip.DISCHARGING_FILL': { en: 'Filled for discharge', ar: 'تم التعبئة للتفريغ' }, + 'wc.trip.LOADED': { en: 'Loaded', ar: 'تم التحميل' }, + 'wc.trip.LOADING_FILL': { en: 'Filled for loading', ar: 'تم التعبئة للتحميل' }, + 'wc.trip.PENDING_EXCHANGE': { en: 'Pending audit for exchange', ar: 'قيد التدقيق للصرف' }, + 'wc.trip.RESD': { en: 'Released', ar: 'تم التسريب' }, + 'wc.trip.RVKD': { en: 'Cancelled', ar: 'ملغى' }, + + // ---- create + 'wc.create.title': { en: 'New wage claim', ar: 'إنشاء مطالبة صرف اجور النقل' }, // new + 'wc.create.subtitle': { en: 'Trips of the chosen statuses and policy dates that are not in a claim yet', ar: 'الارساليات بالحالات وتواريخ البوليصة المختارة التي لا تتبع مطالبة بعد' }, + 'wc.create.status': { en: 'Trip status', ar: 'الحالة' }, // PUBLIC.STATUS + 'wc.create.all': { en: 'All', ar: 'الكل' }, + 'wc.create.from': { en: 'From (policy date)', ar: 'من (تاريخ البوليصة)' }, + 'wc.create.to': { en: 'To (policy date)', ar: 'الى (تاريخ البوليصة)' }, + 'wc.create.search': { en: 'Search', ar: 'بحث' }, + 'wc.create.save': { en: 'Create claim', ar: 'إنشاء' }, // PUBLIC.CREATE + 'wc.create.statusRequired': { en: 'Choose the status', ar: 'يجب اختيار الحالة' }, // ERROR.STATUS_REQUIRED + 'wc.create.dateRequired': { en: 'Choose the dates', ar: 'يجب اختيار التاريخ' }, // ERROR.DATE_REQUIRED + 'wc.create.fromAfterTo': { en: 'From date cannot be after To date', ar: 'لا يجوز ان يكون تاريخ من أكبر من تارخ الى' }, + 'wc.create.confirm': { en: 'Create a wage claim with the trips found by the search?', ar: 'هل تريد إنشاء مطالبة تضم الارساليات الظاهرة حسب البحث؟' }, // new + + // ---- actions + 'wc.close': { en: 'Pay', ar: 'تسديد' }, // REFINERY_WAGE_CLAIM.CLAIM_CLOSE + 'wc.closeConfirm': { en: 'Do you want to mark this claim as paid? Its trips become complete.', ar: 'هل تريد تسديد هذه المطالبة؟ ستصبح ارسالياتها مكتملة.' }, // new + 'wc.transfer': { en: 'Transfer', ar: 'ترحيل' }, // REFINERY_WAGE_CLAIM.TRANSFER + 'wc.transferConfirm': { en: 'Send this claim to the refinery (Jopetrol)?', ar: 'هل تريد ترحيل هذه المطالبة إلى المصفاة؟' }, // new + 'wc.report': { en: 'Report', ar: 'تقرير' }, // PUBLIC.REPORT + 'wc.notFound': { en: 'The claim could not be loaded.', ar: 'تعذر تحميل المطالبة.' }, // new + + // ---- log + 'wc.log.title': { en: 'Log', ar: 'سجل الحركات' }, + 'wc.log.method': { en: 'Action', ar: 'نوع الحركة' }, // LOG.METHOD_NAME + 'wc.log.date': { en: 'Date', ar: 'تاريخ التعديل' }, // LOG.LOG_DATE + 'wc.log.user': { en: 'User', ar: 'اسم المستخدم' }, // LOG.USER_ID + 'wc.log.old': { en: 'Old data', ar: 'البيانات القديمة' }, // LOG.OLDDATA + 'wc.log.new': { en: 'New data', ar: 'البيانات الجديدة' }, // LOG.NEWDATA + 'wc.log.CREATE': { en: 'Create', ar: 'إنشاء' }, + 'wc.log.CLAIM_CLOSE': { en: 'Pay', ar: 'تسديد' }, + 'wc.log.COMPLETE': { en: 'Complete', ar: 'مكتمل' }, + 'wc.log.view': { en: 'View data', ar: 'عرض' }, + 'wc.log.empty': { en: 'No records', ar: 'لا يوجد معلومات' }, +}); diff --git a/web/src/features/refinery/wage-claims/types.ts b/web/src/features/refinery/wage-claims/types.ts new file mode 100644 index 0000000..1780071 --- /dev/null +++ b/web/src/features/refinery/wage-claims/types.ts @@ -0,0 +1,39 @@ +/** Wire types of api/v1/refinery/wage-claims (camelCase JSON of the backend DTOs). Dates are ISO strings. */ + +export interface WageClaimRow { + id: number; + wageClaimNo: number | null; + wageClaimDate: string | null; + tripCnt: number; + commissionClaimId: number | null; + commissionClaimNo: number | null; + /** NEW / CLOSE / COMPLETE */ + statusCode: string; +} + +/** A trip inside a claim (legacy searchClaimTrips columns). */ +export interface ClaimTripRow { + id: number; + pn: string | null; + paymentedDate: string | null; + loadingNo: number | null; + dischargeAuthoriztionNo: string | null; + dischargeEntryDate: string | null; + tn: string | null; + trn: string | null; + nnpn: string | null; + statusCode: string; +} + +export interface ClaimLogRow { + id: number; + methodName: string; + logDate: string | null; + login: string | null; + oldData: string | null; + newData: string | null; +} + +export interface ClaimResult { message: string; id?: number | null } + +export interface CreateWageClaimBody { statusCodes: string[]; loadingDateFrom: string; loadingDateTo: string } diff --git a/web/src/features/refinery/wallets/api.ts b/web/src/features/refinery/wallets/api.ts new file mode 100644 index 0000000..67987e7 --- /dev/null +++ b/web/src/features/refinery/wallets/api.ts @@ -0,0 +1,78 @@ +import { useQuery } from '@tanstack/react-query'; +import { api, type PagedResult } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; + +export const BASE = '/refinery/wallets'; +export const GRID_WALLETS = 'refinery.wallets'; + +export interface WalletRow { + id: number; + tn: number | null; + companyCode: number | null; + epayment: number; + ownerNnpn: number | null; + walletNumber: string | null; + ownerName: string | null; + /** The owner's national no. / name, else the driver's (what the legacy grid shows). */ + holderNnpn: number | null; + holderName: string | null; + ownerNameEnglish: string | null; + driverName: string | null; + driverNnpn: number | null; + iban: string | null; + bankAccount: string | null; + bankName: string | null; + bankBranch: string | null; + creationDate: string | null; + createdBy: string | null; + updateDate: string | null; + updatedBy: string | null; + statusCode: string | null; + /** BANK, EWALLET or DRAIVER_WALLET (legacy spelling). */ + paymentMethod: string | null; +} + +export interface WalletDetail extends WalletRow { + canUpdate: boolean; + canDeactivate: boolean; + canActivate: boolean; +} + +export interface WalletLogRow { + id: number; + entityId: number; + methodName: string | null; + login: string | null; + logDate: string | null; + userId: string | null; + userIp: string | null; + oldData: string | null; + newData: string | null; +} + +export interface WalletsResult { + message: string; + id: number | null; +} + +const keys = () => [gridKey(GRID_WALLETS), ['refinery.wallets.one'], ['refinery.wallets.log']]; + +export const useWallet = (id: number | null) => + useQuery({ queryKey: ['refinery.wallets.one', id], queryFn: () => api.get(`${BASE}/${id}`), enabled: id !== null }); + +export const useWalletLog = (id: number | null, page: number, pageSize: number) => + useQuery({ + queryKey: ['refinery.wallets.log', id, page, pageSize], + queryFn: () => api.get>(`${BASE}/${id}/log`, { page, pageSize }, { silent: true }), + enabled: id !== null, + }); + +export const useCreateWallet = () => + useWrite((p: Record) => api.post(BASE, p), { invalidate: keys() }); + +export const useUpdateWallet = () => + useWrite((v: { id: number; payload: Record }) => api.put(`${BASE}/${v.id}`, v.payload), { invalidate: keys() }); + +export const useWalletAction = () => + useWrite((v: { id: number; action: 'activate' | 'deactivate' }) => api.post(`${BASE}/${v.id}/${v.action}`), { invalidate: keys() }); diff --git a/web/src/features/refinery/wallets/index.ts b/web/src/features/refinery/wallets/index.ts new file mode 100644 index 0000000..967a7cd --- /dev/null +++ b/web/src/features/refinery/wallets/index.ts @@ -0,0 +1,24 @@ +import { createElement } from 'react'; +import type { RouteObject } from 'react-router-dom'; +import AccountBalanceWalletIcon from '@mui/icons-material/AccountBalanceWallet'; +import type { MenuItem } from '@/shell/types'; +import { WalletPage, WalletsPage } from './pages'; +import strings from './strings'; + +/** Refinery payment methods (شاشة طرق الدفع). The lead composes the refinery group and routes file. */ +export const routes: RouteObject[] = [ + { path: '/refinery/wallets', element: createElement(WalletsPage) }, + { path: '/refinery/wallets/new', element: createElement(WalletPage), handle: { crumb: strings['rw.crumb.new'] } }, + { path: '/refinery/wallets/:id', element: createElement(WalletPage), handle: { crumb: strings['rw.crumb.details'] } }, +]; + +export const menuItems: MenuItem[] = [ + { + key: 'refinery.wallets', + title: strings['rw.menu'], + icon: AccountBalanceWalletIcon, + path: '/refinery/wallets', + createPath: '/refinery/wallets/new', + createKey: 'refinery.wallets.create', + }, +]; diff --git a/web/src/features/refinery/wallets/meta.ts b/web/src/features/refinery/wallets/meta.ts new file mode 100644 index 0000000..75ad347 --- /dev/null +++ b/web/src/features/refinery/wallets/meta.ts @@ -0,0 +1,109 @@ +import type { FieldMeta, FormMeta, GridMeta, OptionItem, Rule, StatusMeta } from '@/components/meta/types'; +import strings from './strings'; +import { GRID_WALLETS, type WalletRow } from './api'; + +const s = strings; + +export const walletStatuses: StatusMeta[] = [ + { value: 'ACTIVE', label: s['rw.status.ACTIVE'], color: 'success' }, + { value: 'INACTIVE', label: s['rw.status.INACTIVE'], color: 'default' }, +]; + +/** Form codes of the payment method select (legacy PAYMENT_METHOD). */ +const methodOptions: OptionItem[] = [ + { value: 'WALLET', label: s['rw.method.WALLET'] }, + { value: 'BANK', label: s['rw.method.BANK'] }, + { value: 'DRIVER_TIP', label: s['rw.method.DRIVER_TIP'] }, +]; + +/** Filter codes = the legacy view's PAYMENT_METHOD (spelling of DRAIVER_WALLET kept). */ +const kindOptions: OptionItem[] = [ + { value: 'EWALLET', label: s['rw.kind.EWALLET'] }, + { value: 'BANK', label: s['rw.kind.BANK'] }, + { value: 'DRAIVER_WALLET', label: s['rw.kind.DRAIVER_WALLET'] }, +]; + +const kindLabels = Object.fromEntries(kindOptions.map((o) => [String(o.value), o.label])) as Record; + +/** Legacy REFINERY_WALLETGRID: filters TN, wallet number, owner name (contains), bank account, national no., payment method, status. */ +export function walletsGrid(h: { onOpen: (r: WalletRow) => void }): GridMeta { + return { + key: GRID_WALLETS, + endpoint: '/refinery/wallets', + rowKey: (r) => r.id, + onRowClick: h.onOpen, + pageSize: 16, + emptyAsGrid: true, + status: { param: 'statusCode', options: walletStatuses }, + filters: [ + { name: 'tn', type: 'text', label: s['rw.tn'], ltr: true }, + { name: 'walletNumber', type: 'text', label: s['rw.walletNumber'], ltr: true }, + { name: 'ownerName', type: 'text', label: s['rw.ownerName'] }, + { name: 'bankAccount', type: 'text', label: s['rw.bankAccount'], ltr: true }, + { name: 'nnpn', type: 'text', label: s['rw.nnpn'], ltr: true }, + { name: 'paymentMethod', type: 'select', label: s['rw.method'], options: kindOptions }, + ], + columns: [ + { key: 'tn', header: s['rw.tn'], ltr: true }, + { + key: 'paymentMethod', header: s['rw.method'], + render: (r, { lang }) => { const l = kindLabels[r.paymentMethod ?? '']; return l ? (typeof l === 'string' ? l : l[lang]) : (r.paymentMethod ?? ''); }, + }, + { key: 'holderNnpn', header: s['rw.nnpn'], ltr: true, hideBelow: 'sm' }, + { key: 'holderName', header: s['rw.ownerName'] }, + { key: 'walletNumber', header: s['rw.walletNumber'], ltr: true }, + { key: 'iban', header: s['rw.iban'], ltr: true, hideBelow: 'lg' }, + { key: 'bankAccount', header: s['rw.bankAccount'], ltr: true, hideBelow: 'lg' }, + { key: 'bankName', header: s['rw.bankName'], hideBelow: 'md' }, + { key: 'statusCode', header: s['rw.status'], format: 'status', statuses: walletStatuses }, + ], + }; +} + +const is = (m: string): Rule => ({ field: 'paymentMethod', op: 'eq', value: m }); +const isNot = (m: string): Rule => ({ field: 'paymentMethod', op: 'ne', value: m }); +const digits = (max: number): NonNullable => ({ regex: new RegExp(`^\\d{1,${max}}$`), message: s['rw.err.digits'] }); + +/** + * Legacy REFINERY_WALLETMain.html: the payment method decides which fields are shown (the three fieldsets). Required: truck + owner name + * (wallet, bank), wallet number (wallet, driver), IBAN + account (bank), driver name + national no. (driver). + * Wallet number = mobile 07[7-9]xxxxxxx or 7[7-9]xxxxxxx; account = letters, digits, / and space. + */ +export function walletForm(o: { isCreate: boolean }): FormMeta { + return { + key: 'refinery.wallets.form', + sections: [ + { + key: 'method', + columns: 2, + fields: [ + { name: 'paymentMethod', type: 'select', label: s['rw.method'], required: true, options: methodOptions, defaultValue: 'WALLET', readOnly: !o.isCreate }, + ], + }, + { + key: 'info', + title: s['rw.section.info'], + columns: 2, + fields: [ + { name: 'tn', type: 'text', label: s['rw.tn'], required: true, maxLength: 10, inputKind: 'code', pattern: digits(10), hiddenWhen: is('DRIVER_TIP') }, + { + name: 'walletNumber', type: 'text', label: s['rw.walletNumber'], required: true, maxLength: 15, inputKind: 'phone', + pattern: { regex: /^0?7[7-9]\d{7}$/, message: s['rw.err.mobile'] }, hiddenWhen: is('BANK'), + }, + { name: 'ownerNnpn', type: 'text', label: s['rw.ownerNnpn'], maxLength: 15, inputKind: 'code', pattern: digits(15), hiddenWhen: is('DRIVER_TIP') }, + { name: 'ownerName', type: 'text', label: s['rw.ownerName'], required: true, maxLength: 450, hiddenWhen: is('DRIVER_TIP') }, + { name: 'ownerNameEnglish', type: 'text', label: s['rw.ownerNameEnglish'], maxLength: 150, ltr: true, hiddenWhen: isNot('BANK') }, + { name: 'bankName', type: 'text', label: s['rw.bankName'], maxLength: 300, hiddenWhen: isNot('BANK') }, + { name: 'bankBranch', type: 'text', label: s['rw.bankBranch'], maxLength: 50, hiddenWhen: isNot('BANK') }, + { name: 'iban', type: 'text', label: s['rw.iban'], required: true, maxLength: 50, inputKind: 'code', hiddenWhen: isNot('BANK') }, + { + name: 'bankAccount', type: 'text', label: s['rw.bankAccount'], required: true, maxLength: 50, inputKind: 'code', + pattern: { regex: /^[/a-zA-Z 0-9]*$/, message: s['rw.err.account'] }, hiddenWhen: isNot('BANK'), + }, + { name: 'driverName', type: 'text', label: s['rw.driverName'], required: true, maxLength: 450, hiddenWhen: isNot('DRIVER_TIP') }, + { name: 'driverNnpn', type: 'text', label: s['rw.driverNnpn'], required: true, maxLength: 15, inputKind: 'code', pattern: digits(15), hiddenWhen: isNot('DRIVER_TIP') }, + ], + }, + ], + }; +} diff --git a/web/src/features/refinery/wallets/pages.tsx b/web/src/features/refinery/wallets/pages.tsx new file mode 100644 index 0000000..c0f7330 --- /dev/null +++ b/web/src/features/refinery/wallets/pages.tsx @@ -0,0 +1,257 @@ +import { useMemo, useState } from 'react'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { + Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Paper, Stack, Table, TableBody, TableCell, TableContainer, + TableHead, TablePagination, TableRow, Tooltip, Typography, +} from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import BlockIcon from '@mui/icons-material/Block'; +import CheckCircleIcon from '@mui/icons-material/CheckCircle'; +import DownloadIcon from '@mui/icons-material/Download'; +import HistoryIcon from '@mui/icons-material/History'; +import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined'; +import type { ApiError } from '@/api/client'; +import { DataGrid, gridReturnUrl } from '@/components/DataGrid'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { MetaForm } from '@/components/MetaForm'; +import { PageHeader } from '@/components/PageHeader'; +import { SectionPaper } from '@/components/SectionPaper'; +import { SectionTitle } from '@/components/SectionTitle'; +import { StatusChip } from '@/components/StatusChip'; +import { formatDateTime } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { downloadFile } from '../../grains-orders/api'; +import { + BASE, useCreateWallet, useUpdateWallet, useWallet, useWalletAction, useWalletLog, type WalletLogRow, type WalletRow, +} from './api'; +import { walletForm, walletStatuses, walletsGrid } from './meta'; +import strings from './strings'; + +const ROOT = '/refinery/wallets'; +const fieldErrorsOf = (e: ApiError) => ({ ...e.fieldErrors }) as Record; +const text = (v: string | number | null | undefined) => (v === null || v === undefined ? '' : String(v)); + +/** The payment method code of the form for a stored record (mirrors WalletsRules.MethodOf). */ +const methodOf = (w: WalletRow) => (w.epayment === 0 ? 'BANK' : w.tn === null && w.driverNnpn !== null ? 'DRIVER_TIP' : 'WALLET'); + +function ExportButton() { + const { t } = useFeatureUi(strings); + const { can } = useAuth(); + const toast = useToast(); + const [sp] = useSearchParams(); + const [busy, setBusy] = useState(false); + if (!can('refinery.wallets.report')) return null; + const run = async () => { + setBusy(true); + const params: Record = {}; + sp.forEach((v, k) => { if (k !== 'page' && k !== 'pageSize' && k !== 'f') params[k] = v; }); + try { await downloadFile(`${BASE}/export`, params, 'REFINERY_WALLET.xlsx'); } + catch (e) { toast.error(e instanceof Error ? e.message : String(e)); } + finally { setBusy(false); } + }; + return ; +} + +export function WalletsPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const { can } = useAuth(); + const meta = useMemo(() => walletsGrid({ onOpen: (r) => navigate(`${ROOT}/${r.id}`) }), [navigate]); + return ( + <> + + + {can('refinery.wallets.create') && ( + + )} + + )} + /> + + + ); +} + +/** Values of a log JSON column; legacy rows hold one-element arrays as values. */ +function parseLog(raw: string | null): Record { + if (!raw) return {}; + try { + const o = JSON.parse(raw) as Record; + return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, Array.isArray(v) ? String(v[0] ?? '') : String(v ?? '')])); + } catch { return {}; } +} + +function LogDialog({ row, onClose }: { row: WalletLogRow | null; onClose: () => void }) { + const { t } = useFeatureUi(strings); + const oldData = useMemo(() => parseLog(row?.oldData ?? null), [row]); + const newData = useMemo(() => parseLog(row?.newData ?? null), [row]); + const names = Array.from(new Set([...Object.keys(oldData), ...Object.keys(newData)])); + const prop = (k: string) => { const key = `rw.prop.${k}`; return key in strings ? t(key as keyof typeof strings) : k; }; + return ( + + {t('rw.log')} + + + + + + {t('rw.log.property')} + {t('rw.log.old')} + {t('rw.log.new')} + + + + {names.map((k) => ( + + {prop(k)} + {oldData[k]} + {newData[k]} + + ))} + +
+
+
+ +
+ ); +} + +/** Movements of a record (legacy REFINERY_WALLET_logGrid): the old / new values open for everything but CREATE. */ +function WalletLog({ id }: { id: number }) { + const { t } = useFeatureUi(strings); + const [page, setPage] = useState(0); + const [pageSize, setPageSize] = useState(5); + const [open, setOpen] = useState(null); + const q = useWalletLog(id, page + 1, pageSize); + const rows = q.data?.items ?? []; + const method = (m: string | null) => { const key = `rw.logMethod.${m ?? ''}`; return key in strings ? t(key as keyof typeof strings) : (m ?? ''); }; + return ( + + + {q.isLoading ? : rows.length === 0 ? {t('rw.log.empty')} : ( + <> + + + + + {t('rw.log.method')} + {t('rw.log.date')} + {t('rw.log.user')} + + + + + {rows.map((r) => ( + + {method(r.methodName)} + {formatDateTime(r.logDate)} + {r.login} + + {r.methodName !== 'CREATE' && ( + + setOpen(r)}> + + )} + + + ))} + +
+
+ setPage(p)} onRowsPerPageChange={(e) => { setPageSize(Number(e.target.value)); setPage(0); }} + /> + + )} + setOpen(null)} /> +
+ ); +} + +export function WalletPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const params = useParams(); + const id = params.id ? Number(params.id) : null; + const isNew = id === null; + const { can } = useAuth(); + const confirm = useConfirm(); + const q = useWallet(id); + const create = useCreateWallet(); + const update = useUpdateWallet(); + const action = useWalletAction(); + const [serverErrors, setServerErrors] = useState>({}); + const w = q.data; + const meta = useMemo(() => walletForm({ isCreate: isNew }), [isNew]); + const initial = useMemo(() => (w ? { + paymentMethod: methodOf(w), tn: text(w.tn), walletNumber: text(w.walletNumber), ownerNnpn: text(w.ownerNnpn), ownerName: text(w.ownerName), + ownerNameEnglish: text(w.ownerNameEnglish), bankName: w.bankName === '-' ? '' : text(w.bankName), bankBranch: text(w.bankBranch), + iban: w.iban === '-' ? '' : text(w.iban), bankAccount: w.bankAccount === '-' ? '' : text(w.bankAccount), + driverName: text(w.driverName), driverNnpn: text(w.driverNnpn), + } : {}), [w]); + + if (!isNew && q.isLoading) return ; + if (!isNew && !w) return {q.error?.message ?? t('rw.loadFailed')}; + + const editable = isNew || (!!w?.canUpdate && can('refinery.wallets.update')); + + const submit = (payload: Record) => + new Promise((resolve) => { + setServerErrors({}); + const done = { + // an update answers with the id of the NEW record (the old one stays as history) + onSuccess: (res: { id: number | null }) => { resolve(); navigate(res.id ? `${ROOT}/${res.id}` : gridReturnUrl(ROOT), { replace: true }); }, + onError: (e: ApiError) => { setServerErrors(fieldErrorsOf(e)); resolve(); }, + }; + const body = Object.fromEntries(Object.entries(payload).map(([k, v]) => [k, v === null ? null : String(v)])); + if (isNew) create.mutate(body, done); + else update.mutate({ id: id!, payload: body }, done); + }); + + const run = async (kind: 'activate' | 'deactivate') => { + if (await confirm({ message: t(kind === 'activate' ? 'rw.activateConfirm' : 'rw.deactivateConfirm'), danger: kind === 'deactivate' })) { + action.mutate({ id: id!, action: kind }, { onSuccess: () => navigate(gridReturnUrl(ROOT)) }); + } + }; + + return ( + + : undefined} + backTo={ROOT} + actions={!isNew && ( + <> + {w!.canActivate && can('refinery.wallets.activate') && ( + + )} + {w!.canDeactivate && can('refinery.wallets.deactivate') && ( + + )} + + )} + /> + {!isNew && editable && {t('rw.updateNote')}} + navigate(gridReturnUrl(ROOT))} + onSubmit={submit} + /> + {!isNew && } + + ); +} diff --git a/web/src/features/refinery/wallets/strings.ts b/web/src/features/refinery/wallets/strings.ts new file mode 100644 index 0000000..80e25b0 --- /dev/null +++ b/web/src/features/refinery/wallets/strings.ts @@ -0,0 +1,83 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Strings of the refinery payment methods screen (legacy captions REFINERY_WALLET.* / PUBLIC.* / ERROR.*, verbatim in Arabic where they exist). */ +export default defineStrings({ + 'rw.menu': { en: 'Payment methods', ar: 'شاشة طرق الدفع' }, + 'rw.title': { en: 'Payment methods', ar: 'شاشة طرق الدفع' }, + 'rw.subtitle': { en: 'How the truck owners (and the drivers, for the tip) get paid', ar: 'آلية صرف الأجور لأصحاب الشاحنات وإكرامية السائقين' }, + 'rw.new': { en: 'New payment method', ar: 'آلية صرف جديدة' }, + 'rw.createTitle': { en: 'New payment method', ar: 'آلية صرف جديدة' }, + 'rw.detailTitle': { en: 'Payment method {id}', ar: 'آلية الصرف {id}' }, + 'rw.crumb.new': { en: 'New', ar: 'جديد' }, + 'rw.crumb.details': { en: 'Details', ar: 'التفاصيل' }, + 'rw.loadFailed': { en: 'The record could not be loaded.', ar: 'تعذر تحميل السجل.' }, + 'rw.return': { en: 'Back', ar: 'عودة' }, + 'rw.update': { en: 'Update', ar: 'تعديل' }, + 'rw.updateNote': { + en: 'Updating keeps the history: this record is deactivated and a new active record is created.', + ar: 'التعديل يحفظ السجل السابق: يتم ايقاف هذا السجل وانشاء سجل فعال جديد بالبيانات الجديدة.', + }, + + 'rw.method': { en: 'Payment method', ar: 'طريقة الدفع' }, + 'rw.method.WALLET': { en: 'E-wallet', ar: 'محفظة الكترونية' }, + 'rw.method.BANK': { en: 'Bank transfer', ar: 'حوالة' }, + 'rw.method.DRIVER_TIP': { en: 'Driver wallet (tip)', ar: 'محفظة السائق (الإكرامية)' }, + 'rw.kind.EWALLET': { en: 'E-wallet', ar: 'محفظة الالكترونية' }, + 'rw.kind.BANK': { en: 'Bank transfer', ar: 'حوالة بنكية' }, + 'rw.kind.DRAIVER_WALLET': { en: 'Driver wallet', ar: 'محفظة سائق' }, + + 'rw.tn': { en: 'Truck number', ar: 'رقم الشاحنة' }, + 'rw.walletNumber': { en: 'Wallet number', ar: 'رقم المحفظة' }, + 'rw.ownerNnpn': { en: 'Owner national no.', ar: 'الرقم الوطني للمالك' }, + 'rw.ownerName': { en: 'Owner name', ar: 'اسم المالك' }, + 'rw.ownerNameEnglish': { en: 'Owner name (English)', ar: 'اسم المالك باللغة الانجليزية' }, + 'rw.bankName': { en: 'Bank name', ar: 'اسم البنك' }, + 'rw.bankBranch': { en: 'Branch', ar: 'الفرع' }, + 'rw.iban': { en: 'IBAN', ar: 'IBAN' }, + 'rw.bankAccount': { en: 'Account number', ar: 'رقم الحساب' }, + 'rw.driverName': { en: 'Driver name', ar: 'اسم السائق' }, + 'rw.driverNnpn': { en: 'Driver national no.', ar: 'الرقم الوطني' }, + 'rw.nnpn': { en: 'National no.', ar: 'الرقم الوطني' }, + 'rw.status': { en: 'Status', ar: 'الحالة' }, + 'rw.status.ACTIVE': { en: 'Active', ar: 'فعال' }, + 'rw.status.INACTIVE': { en: 'Inactive', ar: 'غير فعال' }, + 'rw.section.info': { en: 'Payment information', ar: 'معلومات آلية الصرف' }, + + 'rw.err.mobile': { en: 'Invalid wallet number', ar: 'رقم المحفظة غير صحيح' }, + 'rw.err.account': { en: 'Letters, digits and / only', ar: 'رقم الحساب غير صحيح مسموح بالارقام والاحرف وال / فقط' }, + 'rw.err.digits': { en: 'Digits only', ar: 'الحقل لا يقبل أحرف' }, + + 'rw.activate': { en: 'Activate', ar: 'تفعيل' }, + 'rw.deactivate': { en: 'Deactivate', ar: 'ايقاف' }, + 'rw.activateConfirm': { en: 'Activate this payment method?', ar: 'هل تريد تفعيل آلية الصرف؟' }, + 'rw.deactivateConfirm': { en: 'Deactivate this payment method?', ar: 'هل تريد ايقاف آلية الصرف؟' }, + 'rw.export': { en: 'Excel', ar: 'تصدير Excel' }, + + 'rw.log': { en: 'Movements log', ar: 'سجل الحركات' }, + 'rw.log.empty': { en: 'No movements', ar: 'لا يوجد معلومات' }, + 'rw.log.method': { en: 'Movement', ar: 'نوع الحركة' }, + 'rw.log.date': { en: 'Date', ar: 'تاريخ التعديل' }, + 'rw.log.user': { en: 'User', ar: 'اسم المستخدم' }, + 'rw.log.view': { en: 'View', ar: 'عرض' }, + 'rw.log.property': { en: 'Property', ar: 'الحقل' }, + 'rw.log.old': { en: 'Old data', ar: 'البيانات القديمة' }, + 'rw.log.new': { en: 'New data', ar: 'البيانات الجديدة' }, + 'rw.log.close': { en: 'Close', ar: 'إغلاق' }, + 'rw.logMethod.CREATE': { en: 'Created', ar: 'إنشاء' }, + 'rw.logMethod.UPDATE': { en: 'Updated', ar: 'تعديل' }, + 'rw.logMethod.ACTIVATE': { en: 'Activated', ar: 'تفعيل' }, + 'rw.logMethod.DEACTIVATE': { en: 'Deactivated', ar: 'إيقاف' }, + 'rw.prop.TN': { en: 'Truck number', ar: 'رقم الشاحنة' }, + 'rw.prop.EPAYMENT': { en: 'E-payment', ar: 'دفع الكتروني' }, + 'rw.prop.OWNER_NNPN': { en: 'Owner national no.', ar: 'الرقم الوطني للمالك' }, + 'rw.prop.WALLET_NUMBER': { en: 'Wallet number', ar: 'رقم المحفظة' }, + 'rw.prop.OWNER_NAME': { en: 'Owner name', ar: 'اسم المالك' }, + 'rw.prop.OWNER_NAME_ENGLISH': { en: 'Owner name (English)', ar: 'اسم المالك باللغة الانجليزية' }, + 'rw.prop.DRIVER_NAME': { en: 'Driver name', ar: 'اسم السائق' }, + 'rw.prop.DRIVER_NNPN': { en: 'Driver national no.', ar: 'الرقم الوطني' }, + 'rw.prop.IBAN': { en: 'IBAN', ar: 'IBAN' }, + 'rw.prop.BANK_ACCOUNT': { en: 'Account number', ar: 'رقم الحساب' }, + 'rw.prop.BANK_NAME': { en: 'Bank name', ar: 'اسم البنك' }, + 'rw.prop.BANK_BRANCH': { en: 'Branch', ar: 'الفرع' }, + 'rw.prop.STATUS_CODE': { en: 'Status', ar: 'الحالة' }, +}); diff --git a/web/src/i18n/ui.ts b/web/src/i18n/ui.ts index cab1035..07ca01e 100644 --- a/web/src/i18n/ui.ts +++ b/web/src/i18n/ui.ts @@ -77,10 +77,10 @@ export const ui = { 'common.delete': { en: 'Delete', ar: 'حذف' }, 'common.create': { en: 'New', ar: 'جديد' }, 'common.search': { en: 'Search', ar: 'بحث' }, - 'common.apply': { en: 'Apply', ar: 'تطبيق' }, + 'common.apply': { en: 'Apply', ar: 'بحث' }, 'common.clear': { en: 'Clear', ar: 'مسح' }, 'common.clearFilters': { en: 'Clear filters', ar: 'مسح التصفية' }, - 'common.filters': { en: 'Filters', ar: 'التصفية' }, + 'common.filters': { en: 'Filters', ar: 'البحث' }, 'common.all': { en: 'All', ar: 'الكل' }, 'common.actions': { en: 'Actions', ar: 'الإجراءات' }, 'common.yes': { en: 'Yes', ar: 'نعم' },