using FluentValidation; using NTP.Application.Abstractions; using NTP.Application.Common; using NTP.Domain.Grains.Orders; namespace NTP.Application.Grains.Orders; public interface IBillingService { Task GetPermitAsync(long pn, long? scac, CancellationToken ct); Task AddAsync(AddBillingRequest request, CancellationToken ct); Task> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct); Task GetRerouteAsync(long id, CancellationToken ct); Task RerouteAsync(long id, RerouteRequest request, CancellationToken ct); Task DeleteAsync(long id, CancellationToken ct); } /// Port of Invoice.cfc getBillingInfo / addBillingInfo / getBillingGrid (BillingScreen.cfm, BillingGrid.cfm). public sealed class BillingService( IBillingRepository repository, IUnitOfWork unitOfWork, IEventLogger events, ICurrentUser user, IValidator validator) : IBillingService { private static string? Date(DateTime? d) => d?.ToString("yyyy-MM-dd"); /// Port of getBillingInfo (2023 version): empty PN, billing already entered, permit not found. public async Task GetPermitAsync(long pn, long? scac, CancellationToken ct) { if (await repository.PnExistsAsync(pn, ct)) throw OrdersErrors.BillingExists(); var info = await repository.GetPermitBillingInfoAsync(pn, user.UserId, ct) ?? throw OrdersErrors.InvalidPn(); if (scac.HasValue && scac.Value != info.Scac) throw OrdersErrors.PnNotOfCompany(); var lnw = BillingCalculator.NetWeight(info.Lgw, info.Ltw); var dnw = BillingCalculator.NetWeight(info.Dgw, info.Dtw); // Prices shown on the screen are the ones addBillingInfo will store: the destination's wage rate and the // cargo type's fine rate, both valid on the loading date. decimal? price = null, finePrice = null; if (info.LoadDate.HasValue) { if (info.Destination.HasValue) price = (await repository.GetWageRateAsync(info.Destination.Value, info.LoadDate.Value.Date, ct))?.Wage; if (info.CargoType.HasValue) finePrice = (await repository.GetFineRateAsync(info.CargoType.Value, info.LoadDate.Value.Date, ct))?.Fine; } return new BillingPermitDto( info.Pn, info.Scac, info.CompanyName, info.CargoType, info.Tn, info.Destination, Date(info.LoadDate), Date(info.DischargeDate), lnw, dnw == 0 ? null : dnw, // the legacy page left the received-weight box empty when it was 0 info.LastInvoice, price, finePrice); } /// /// Port of addBillingInfo (Invoice.cfc, 2023) with the field mapping corrected on request: "رقم المطالبة" is the invoice /// number (INVOICE / GRAINS_BILLING.INVOICENUMBER) and "رقم المستند" is stored in GRAINS_BILLING.SERIALNO. /// (The legacy CFC had the two swapped.) /// public async Task AddAsync(AddBillingRequest request, CancellationToken ct) { await validator.ValidateAndThrowAsync(request, ct); var invoiceNumber = request.InvoiceNumber; var serialNo = long.Parse(request.SerialNo.Trim()); // 1. an invoice keeps one family of cargo types (38 / 74 / 39+41) var invoiceCargo = await repository.GetInvoiceCargoTypeAsync(request.Scac, invoiceNumber, ct); if (invoiceCargo.HasValue && !BillingCalculator.IsCargoAllowedOnInvoice(invoiceCargo.Value, request.CargoType)) throw OrdersErrors.InvoiceCargoMismatch(); // 2. archived invoices take no new billing var invoiceStatus = await repository.GetInvoiceStatusAsync(request.Scac.ToString(), invoiceNumber.ToString(), ct); if (string.Equals(invoiceStatus, "ARCHIVED", StringComparison.OrdinalIgnoreCase)) throw OrdersErrors.InvoiceArchived(); // 3. one billing per permit if (await repository.PnExistsAsync(request.Pn, ct)) throw OrdersErrors.BillingExists(); // page JS rules kept as server checks if (!BillingCalculator.IsDischargeAfterLoad(request.LoadDate, request.DischargeDate)) throw OrdersErrors.DischargeBeforeLoad(); var lnw = request.Lnw; var dnw = request.Dnw; if (dnw <= 0) throw OrdersErrors.ReceivedWeightMissing(); if (!BillingCalculator.IsSentWeightInRange(lnw)) throw OrdersErrors.SentWeightRange(); // 4. PRICE = wage rate of the destination on the loading date, FINEPRICE = fine rate of the cargo type on that // date; if either is missing the billing cannot be added. var wage = await repository.GetWageRateAsync(request.Destination, request.LoadDate.Date, ct); var fine = await repository.GetFineRateAsync(request.CargoType, request.LoadDate.Date, ct); if (wage is null || fine is null) throw OrdersErrors.PriceNotDefined(); var wageAmount = BillingCalculator.Wage(wage.Wage, lnw); var loseFine = BillingCalculator.ShortageFine(lnw, dnw, fine.Allowance, fine.Fine); var finalCost = wageAmount - loseFine; var companyName = await repository.GetTenderCompanyNameAsync(request.Scac, ct); var permit = await repository.GetPermitRefAsync(request.Pn, ct) ?? throw OrdersErrors.InvalidPn(); return await unitOfWork.ExecuteInTransactionAsync(async token => { // first billing of the invoice creates it if (invoiceStatus is null) await repository.InsertInvoiceAsync(invoiceNumber, request.Scac, token); // a permit that is not CLOSE yet is closed by the system when it is billed if (!string.Equals(permit.ShipmentStatusCode, "CLOSE", StringComparison.OrdinalIgnoreCase)) { await repository.ClosePermitAsync(permit.Id, token); await events.AddAsync(new EventEntry( "PERMITID", permit.Id, permit.ShipmentStatusCode, "CLOSE", "SYSTEM", "OVRD", "GN", null, "NTP", null, new Dictionary { ["REMARKS"] = "Billing Close." }), token); } var id = await repository.InsertAsync(new NewGrainsBilling( request.Pn, serialNo, request.Tn.Trim(), request.CargoType, request.Destination, request.LoadDate.Date, request.DischargeDate.Date, dnw, lnw, request.Scac, companyName, invoiceNumber, GrainsOrderConstants.BillingOriginId, wage.Wage, fine.Fine, finalCost, loseFine, user.UserId, request.DemurrageFine, request.OtherFine), token); return new OrdersResult(OrdersErrors.Success, id); }, ct); } /// Legacy returned an empty grid when no filter was supplied. public async Task> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct) { if (!query.HasFilter) return new PagedResult([], page.SafePage, page.SafePageSize, 0); var r = await repository.SearchAsync(query, page, ct); var items = r.Items.Select(x => new BillingDto( x.Id, x.CargoType, x.Scac, x.Pn, x.Tn, Date(x.LoadDate), x.Destination, Date(x.DischargeDate), x.Lnw, x.Dnw, x.Price, x.FinePrice, x.InvoiceNumber, x.CreateUserId)).ToList(); return new PagedResult(items, r.Page, r.PageSize, r.TotalCount); } /// Port of getBillingInfoForReroute (rerouteScreen.cfm). public async Task GetRerouteAsync(long id, CancellationToken ct) { var b = await repository.GetDetailAsync(id, ct) ?? throw OrdersErrors.BillingNotFound(); return new BillingRerouteDto(b.Id, b.Pn, b.Tn, b.CompanyName, b.SerialNo, b.CargoType, b.Destination, Date(b.LoadDate), Date(b.DischargeDate), b.Lnw, b.Dnw, b.Price, b.InvoiceNumber, b.DemurrageFine, b.OtherFine, b.ReroutePrice, b.RerouteName); } /// Port of addRerouteInfo; the page JS rule: a new price must be at least the current price and at most 35. public async Task RerouteAsync(long id, RerouteRequest request, CancellationToken ct) { var b = await repository.GetDetailAsync(id, ct) ?? throw OrdersErrors.BillingNotFound(); if (request.ReroutePrice.HasValue && (request.ReroutePrice.Value < (b.Price ?? 0) || request.ReroutePrice.Value > 35)) throw OrdersErrors.ReroutePriceRange(); var name = string.IsNullOrWhiteSpace(request.RerouteName) ? null : request.RerouteName.Trim(); if (name is { Length: > 50 }) name = name[..50]; await repository.UpdateRerouteAsync(id, request.ReroutePrice, name, ct); return new OrdersResult(OrdersErrors.Rerouted, id); } /// Port of deleteInvoice: soft delete; not from an archived invoice; only the entering user unless GNAC. public async Task DeleteAsync(long id, CancellationToken ct) { var b = await repository.GetDetailAsync(id, ct) ?? throw OrdersErrors.BillingNotFound(); if (b.Scac is not null && b.InvoiceNumber is not null && string.Equals(await repository.GetInvoiceStatusAsync(b.Scac, b.InvoiceNumber, ct), "ARCHIVED", StringComparison.OrdinalIgnoreCase)) throw OrdersErrors.DeleteFromArchivedInvoice(); if (!user.IsInRole("GNAC") && !string.Equals(b.CreateUserId, user.UserId, StringComparison.OrdinalIgnoreCase)) throw OrdersErrors.DeleteNotOwner(b.CreateUserId); await repository.MarkDeletedAsync(id, ct); return new OrdersResult(OrdersErrors.Deleted, id); } } public interface IInvoiceService { Task> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct); Task ArchiveAsync(long id, CancellationToken ct); Task ActivateAsync(long id, CancellationToken ct); } /// Port of Invoice.cfc getInvoiceGrid (InvoiceGrid.cfm). public sealed class InvoiceService(IInvoiceRepository repository, IUnitOfWork unitOfWork) : IInvoiceService { public async Task> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct) { var r = await repository.SearchAsync(invoiceNumber, page, ct); var items = r.Items.Select(x => new InvoiceDto(x.Id, x.InvoiceNumber, x.StatusCode, x.Cnt, x.CompanyName, x.Scac, x.InvoiceDate)).ToList(); return new PagedResult(items, r.Page, r.PageSize, r.TotalCount); } public async Task ArchiveAsync(long id, CancellationToken ct) { if (!await repository.ExistsAsync(id, ct)) throw OrdersErrors.InvoiceNotFound(); return await unitOfWork.ExecuteInTransactionAsync(async token => { await repository.ArchiveAsync(id, token); return new OrdersResult(OrdersErrors.Archived, id); }, ct); } public async Task ActivateAsync(long id, CancellationToken ct) { if (!await repository.ExistsAsync(id, ct)) throw OrdersErrors.InvoiceNotFound(); await repository.ActivateAsync(id, ct); return new OrdersResult(OrdersErrors.Activated, id); } }