diff --git a/db/disabled-features.sql b/db/disabled-features.sql index 39c1c22..e4dae3e 100644 --- a/db/disabled-features.sql +++ b/db/disabled-features.sql @@ -7,12 +7,16 @@ -- -- grains.permits.absence إيقاف/تفعيل الاستنكاف (stop / activate the absence feature) -- grains.permits.activation تفعيل الطلبية (order activation screen) +-- grains.orders.reportFinance تقارير عطاء التموين المالية (replaced by التأكد من الفواتير, key grains.orders.invoiceCheck) +-- grains.orders.reportOrders تقارير التموين / تقرير الطلبيات INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) SELECT 'DISABLED', v.resource_key FROM ( SELECT 'grains.permits.absence' AS resource_key FROM dual UNION ALL - SELECT 'grains.permits.activation' FROM dual + SELECT 'grains.permits.activation' FROM dual UNION ALL + SELECT 'grains.orders.reportFinance' FROM dual UNION ALL + SELECT 'grains.orders.reportOrders' FROM dual ) v WHERE NOT EXISTS ( SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p @@ -20,7 +24,7 @@ SELECT 'DISABLED', v.resource_key COMMIT; --- Check (expect 2 rows): +-- Check (expect 4 rows): -- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'DISABLED' ORDER BY 2; -- -- Bring one back: diff --git a/db/gnac-finance-screens.sql b/db/gnac-finance-screens.sql new file mode 100644 index 0000000..069d6a3 --- /dev/null +++ b/db/gnac-finance-screens.sql @@ -0,0 +1,20 @@ +-- Screens of the accountant role GNAC (legacy GrainsBilling menu): المطالبات المالية, ادخال المطالبة (same key as the claims +-- list), الغرامات, الأجور, فواتير التموين, التأكد من الفواتير (key grains.orders.invoiceCheck). +-- Run on a database where GRAINS_SCREEN_PERMISSIONS already exists. Safe to re-run. Not executed by the application. +-- Delete a row to take a screen away (the API applies it within about a minute, the browser on the next reload or sign-in). + +INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) +SELECT v.rolecode, v.resource_key + FROM (SELECT 'GNAC' AS rolecode, 'grains.orders.billing' AS resource_key FROM dual UNION ALL + SELECT 'GNAC', 'grains.orders.fines' FROM dual UNION ALL + SELECT 'GNAC', 'grains.orders.wages' FROM dual UNION ALL + SELECT 'GNAC', 'grains.orders.invoices' FROM dual UNION ALL + SELECT 'GNAC', 'grains.orders.invoiceCheck' FROM dual) v + WHERE NOT EXISTS ( + SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p + WHERE p.rolecode = v.rolecode AND p.resource_key = v.resource_key); + +COMMIT; + +-- Check (expect 5 rows): +-- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'GNAC' ORDER BY resource_key; diff --git a/docs/ENVIRONMENTS.md b/docs/ENVIRONMENTS.md index 32fb805..25462c5 100644 --- a/docs/ENVIRONMENTS.md +++ b/docs/ENVIRONMENTS.md @@ -52,6 +52,7 @@ Apply these scripts once per database (not run by the application), in this orde 3. `db/disabled-features.sql` - features switched OFF for everybody, SU included (safe to re-run) 4. `db/permits-create-permission.sql` - right to register a turn (تسجيل دور) from the permits list, granted to GOO (safe to re-run) 5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run) +6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run) **Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU included: the menu entry and buttons disappear and the API answers 403. It overrides every other row. Delete the row to bring the diff --git a/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs b/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs index 54475b5..f1eb306 100644 --- a/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs +++ b/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs @@ -67,7 +67,7 @@ public sealed class OrdersController( public Task DestinationGroups(CancellationToken ct) => lookups.DestinationGroupsAsync(ct); [HttpGet("lookups/companies")] - [RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersReportFinance)] + [RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersInvoiceCheck)] public Task> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct); } @@ -101,9 +101,9 @@ public sealed class OrderBillingController(IBillingService billing) : Controller [HttpGet] [RequirePermission(PermissionKeys.OrdersBilling)] public Task> Search( - [FromQuery] string? tn, [FromQuery] long? pn, [FromQuery] long? scac, + [FromQuery] string? tn, [FromQuery] long? pn, [FromQuery] long? scac, [FromQuery] string? invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => - billing.SearchAsync(new BillingQuery(tn, pn, scac), new PageRequest(page, pageSize), ct); + billing.SearchAsync(new BillingQuery(tn, pn, scac, invoiceNumber), new PageRequest(page, pageSize), ct); /// Prefill of the billing form from a CLOSEd permit (legacy getBillingInfo). [HttpGet("permit/{pn:long}")] @@ -117,6 +117,24 @@ public sealed class OrderBillingController(IBillingService billing) : Controller [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] [RequirePermission(PermissionKeys.OrdersBilling)] public Task Add(AddBillingRequest request, CancellationToken ct) => billing.AddAsync(request, ct); + + /// Data of the reroute dialog (legacy rerouteScreen.cfm). + [HttpGet("{id:long}/reroute")] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersBilling)] + public Task RerouteInfo(long id, CancellationToken ct) => billing.GetRerouteAsync(id, ct); + + [HttpPut("{id:long}/reroute")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersBilling)] + public Task Reroute(long id, RerouteRequest request, CancellationToken ct) => billing.RerouteAsync(id, request, ct); + + [HttpDelete("{id:long}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersBilling)] + public Task Delete(long id, CancellationToken ct) => billing.DeleteAsync(id, ct); } /// Invoices list (legacy InvoiceGrid.cfm, Invoice.cfc getInvoiceGrid). @@ -131,6 +149,38 @@ public sealed class OrderInvoicesController(IInvoiceService invoices) : Controll public Task> Search( [FromQuery] long? invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => invoices.SearchAsync(invoiceNumber, new PageRequest(page, pageSize), ct); + + [HttpPost("{id:long}/archive")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersInvoices)] + public Task Archive(long id, CancellationToken ct) => invoices.ArchiveAsync(id, ct); + + [HttpPost("{id:long}/activate")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersInvoices)] + public Task Activate(long id, CancellationToken ct) => invoices.ActivateAsync(id, ct); +} + +/// الغرامات and الأجور lists (legacy FinesGrid.cfm / WagesGrid.cfm). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/orders")] +[Produces("application/json")] +public sealed class OrderFinanceRatesController(IFinanceRatesService service) : ControllerBase +{ + [HttpGet("fines")] + [RequirePermission(PermissionKeys.OrdersFines)] + public Task> Fines( + [FromQuery] DateTime? startDate, [FromQuery] DateTime? endDate, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + service.FinesAsync(startDate, endDate, new PageRequest(page, pageSize), ct); + + [HttpGet("wages")] + [RequirePermission(PermissionKeys.OrdersWages)] + public Task> Wages( + [FromQuery] DateTime? startDate, [FromQuery] DateTime? endDate, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + service.WagesAsync(startDate, endDate, new PageRequest(page, pageSize), ct); } /// Loading weights entry (legacy addGrainsWeights.cfm). @@ -195,23 +245,23 @@ public sealed class OrderReportsController(IOrderReportService reports) : Contro [HttpGet("financial-billing")] [Produces("application/json")] - [RequirePermission(PermissionKeys.OrdersReportFinance)] + [RequirePermission(PermissionKeys.OrdersInvoiceCheck)] public Task FinancialBilling( [FromQuery] long scac, [FromQuery] long invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => reports.GetFinancialBillingAsync(scac, invoiceNumber, new PageRequest(page, pageSize), ct); - [HttpGet("financial-billing/export")] - [RequirePermission(PermissionKeys.OrdersReportFinance)] - public async Task ExportFinancialBilling( - [FromQuery] long scac, [FromQuery] long invoiceNumber, [FromQuery] string format = "csv", CancellationToken ct = default) + /// The legacy FinancialBilling.cfm Excel of one invoice (print action of an archived invoice). + [HttpGet("financial-billing/excel")] + [RequirePermission(PermissionKeys.OrdersInvoices, PermissionKeys.OrdersInvoiceCheck)] + public async Task ExcelFinancialBilling([FromQuery] long scac, [FromQuery] long invoiceNumber, CancellationToken ct = default) { - var f = await reports.ExportFinancialBillingAsync(scac, invoiceNumber, format, ct); + var f = await reports.ExportFinancialBillingAsync(scac, invoiceNumber, ct); return File(f.Content, f.ContentType, f.FileName); } /// Invoice numbers of a company for the report picker (legacy getInvoiceNo, which does not exist in the CFC). [HttpGet("invoice-numbers")] [Produces("application/json")] - [RequirePermission(PermissionKeys.OrdersReportFinance)] + [RequirePermission(PermissionKeys.OrdersInvoiceCheck)] public Task> InvoiceNumbers([FromQuery] long scac, CancellationToken ct) => reports.GetInvoiceNumbersAsync(scac, ct); } diff --git a/src/NTP.Api/Properties/launchSettings.json b/src/NTP.Api/Properties/launchSettings.json index c2800d2..08c3323 100644 --- a/src/NTP.Api/Properties/launchSettings.json +++ b/src/NTP.Api/Properties/launchSettings.json @@ -5,7 +5,7 @@ "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", - "applicationUrl": "https://localhost:7180;http://localhost:5180", + "applicationUrl": "https://localhost:7180;http://localhost:5181", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/src/NTP.Application/Access/PermissionDefaults.cs b/src/NTP.Application/Access/PermissionDefaults.cs index 498689c..68614e1 100644 --- a/src/NTP.Application/Access/PermissionDefaults.cs +++ b/src/NTP.Application/Access/PermissionDefaults.cs @@ -13,6 +13,11 @@ public static class PermissionKeys public const string OrdersQuotas = "grains.orders.quotas"; public const string OrdersBilling = "grains.orders.billing"; public const string OrdersInvoices = "grains.orders.invoices"; + /// الغرامات and الأجور (GNAC): monthly fine / wage tables read by the billing screens. + /// التأكد من الفواتير (legacy FinancialRpts.cfm): check the billings of one invoice. + public const string OrdersInvoiceCheck = "grains.orders.invoiceCheck"; + public const string OrdersFines = "grains.orders.fines"; + public const string OrdersWages = "grains.orders.wages"; public const string OrdersWeights = "grains.orders.weights"; /// طلبية التموين: distributed permits per destination type (orders menu). public const string OrdersSupply = "grains.orders.supply"; @@ -92,6 +97,9 @@ public static class PermissionDefaults [PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية [PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي [PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف + [PermissionKeys.OrdersInvoiceCheck] = ["GNAC"], // التأكد من الفواتير + [PermissionKeys.OrdersFines] = ["GNAC"], // الغرامات + [PermissionKeys.OrdersWages] = ["GNAC"], // الأجور [PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل [PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ [PermissionKeys.ReportTable("companies-turn")] = ["GTO", "GOO"], // تقرير دور الشركات diff --git a/src/NTP.Application/Grains/Orders/BillingService.cs b/src/NTP.Application/Grains/Orders/BillingService.cs index 4223d12..c46bfc6 100644 --- a/src/NTP.Application/Grains/Orders/BillingService.cs +++ b/src/NTP.Application/Grains/Orders/BillingService.cs @@ -10,12 +10,16 @@ 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, + ICurrentUser user, IValidator validator) : IBillingService { private static string? Date(DateTime? d) => d?.ToString("yyyy-MM-dd"); @@ -69,7 +73,7 @@ public sealed class BillingService( request.LoadDate.Date, request.DischargeDate.Date, info.Dtw, info.Dgw, dnw, info.Ltw, info.Lgw, lnw, request.Scac, request.InvoiceNumber, GrainsOrderConstants.BillingOriginId, - price.Value, finePrice.Value, finalCost, loseFine), token); + price.Value, finePrice.Value, finalCost, loseFine, user.UserId), token); return new OrdersResult(OrdersErrors.Success, id); }, ct); @@ -83,26 +87,76 @@ public sealed class BillingService( 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)).ToList(); + 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) : IInvoiceService +public sealed class InvoiceService(IInvoiceRepository repository, IUnitOfWork unitOfWork) : IInvoiceService { public async Task> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct) { - // Legacy returned an empty grid when no invoice number was given. - if (!invoiceNumber.HasValue) return new PagedResult([], page.SafePage, page.SafePageSize, 0); - 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); + } } diff --git a/src/NTP.Application/Grains/Orders/FinanceRatesService.cs b/src/NTP.Application/Grains/Orders/FinanceRatesService.cs new file mode 100644 index 0000000..ee91ad0 --- /dev/null +++ b/src/NTP.Application/Grains/Orders/FinanceRatesService.cs @@ -0,0 +1,58 @@ +using NTP.Application.Common; + +namespace NTP.Application.Grains.Orders; + +/// Monthly fine / wage tables the billing screens read (legacy GRAINS_FINE, GRAINS_WAGE). +public sealed class FineRow +{ + public long Id { get; set; } + public string? CargoType { get; set; } + public string? StartDate { get; set; } + public string? EndDate { get; set; } + public decimal? Fine { get; set; } + public decimal? Allowance { get; set; } +} + +public sealed class WageRow +{ + public long Id { get; set; } + public string? Location { get; set; } + public string? StartDate { get; set; } + public string? EndDate { get; set; } + public decimal? Wage { get; set; } +} + +public sealed record FineDto(long Id, string? CargoType, string? StartDate, string? EndDate, decimal? Fine, decimal? Allowance); +public sealed record WageDto(long Id, string? Location, string? StartDate, string? EndDate, decimal? Wage); + +public interface IFinanceRatesRepository +{ + Task> SearchFinesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct = default); + Task> SearchWagesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct = default); +} + +public interface IFinanceRatesService +{ + Task> FinesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct); + Task> WagesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct); +} + +/// Port of fines.cfc getFinesGrid and wages.cfc getWagesGrid (read only; the Excel upload screen is not ported). +public sealed class FinanceRatesService(IFinanceRatesRepository repository) : IFinanceRatesService +{ + public async Task> FinesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct) + { + var r = await repository.SearchFinesAsync(startDate, endDate, page, ct); + return new PagedResult( + r.Items.Select(x => new FineDto(x.Id, x.CargoType, x.StartDate, x.EndDate, x.Fine, x.Allowance)).ToList(), + r.Page, r.PageSize, r.TotalCount); + } + + public async Task> WagesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct) + { + var r = await repository.SearchWagesAsync(startDate, endDate, page, ct); + return new PagedResult( + r.Items.Select(x => new WageDto(x.Id, x.Location, x.StartDate, x.EndDate, x.Wage)).ToList(), + r.Page, r.PageSize, r.TotalCount); + } +} diff --git a/src/NTP.Application/Grains/Orders/OrderReportService.cs b/src/NTP.Application/Grains/Orders/OrderReportService.cs index 0bc64ba..685396d 100644 --- a/src/NTP.Application/Grains/Orders/OrderReportService.cs +++ b/src/NTP.Application/Grains/Orders/OrderReportService.cs @@ -10,7 +10,8 @@ public interface IOrderReportService Task ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct); Task GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct); - Task ExportFinancialBillingAsync(long scac, long invoiceNumber, string format, CancellationToken ct); + /// The legacy FinancialBilling.cfm Excel (an HTML table opened by Excel), byte for byte the same layout. + Task ExportFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct); Task> GetInvoiceNumbersAsync(long scac, CancellationToken ct); } @@ -111,41 +112,62 @@ public sealed class OrderReportService(IOrderReportRepository repository, ICurre return new FinancialBillingPage(paged.Items.Select(Map).ToList(), paged.Page, paged.PageSize, paged.TotalCount, Totals(all)); } - public async Task ExportFinancialBillingAsync(long scac, long invoiceNumber, string format, CancellationToken ct) + public async Task ExportFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct) { var rows = await repository.GetFinancialBillingAsync(scac, invoiceNumber, ct); var first = rows.FirstOrDefault(); var totals = Totals(rows); + static string E(object? v) => System.Net.WebUtility.HtmlEncode(Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty); - var title = new List + var h = new System.Text.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(""); + foreach (var c in new[] { "التسلسل", " رقم الارسالية", " رقم المستند", "تاريخ التحميل", "من", "الى", "نوع المادة", "رقم السيارة", "الوزن المرسل", "تاريخ التفريغ", "الوزن المستلم", "الفرق ", "السعر", "سعر التغريم", "غرامة النقص ", "غرامة التاخير", "غرامات آخرى", "القيمة النهائية" }) + h.Append($""); + h.Append(""); + + decimal priceTotal = 0, finePriceTotal = 0; + var n = 0; + foreach (var x in rows) { - L("شركة نافذ للخدمات اللوجستية", "Nafith Logistics Services"), - L("قائمة بنماذج المعدة لصرف أجور النقل حسب رقم المطالبة", "Transport wages forms by invoice number"), - $"{L("إسم الشركة", "Company")}: {first?.CompanyName}", - $"{L("رقم المطالبة", "Invoice number")}: {invoiceNumber}", - $"{L("رقم العطاء", "Tender number")}: {GrainsOrderConstants.BillingTenderNumber}", - $"{L("التاريخ", "Date")}: {Date(first?.LoadDate)}", - }; - var headers = new[] + n++; + priceTotal += x.Price; finePriceTotal += x.FinePrice; + h.Append(""); + foreach (var v in new object?[] { n, x.Pn, x.SerialNo, Date(x.LoadDate), "عقبة", x.Name, x.CargoType, x.Tn, x.Lnw, Date(x.DischargeDate), x.Dnw, x.Dnw - x.Lnw, x.Price, x.FinePrice, x.LoseFine, x.DemurrageFine, x.OtherFine, x.FinalCost }) + h.Append($""); + h.Append(""); + } + + if (rows.Count != 0) { - L("التسلسل", "#"), L("رقم الارسالية", "Permit no."), L("رقم المستند", "Document no."), L("تاريخ التحميل", "Load date"), - L("من", "From"), L("الى", "To"), L("نوع المادة", "Cargo"), L("رقم السيارة", "Truck"), L("الوزن المرسل", "Sent weight"), - L("تاريخ التفريغ", "Discharge date"), L("الوزن المستلم", "Received weight"), L("الفرق", "Difference"), L("السعر", "Price"), - L("سعر التغريم", "Fine price"), L("غرامة النقص", "Shortage fine"), L("غرامة التاخير", "Demurrage fine"), - L("غرامات آخرى", "Other fines"), L("القيمة النهائية", "Final value"), - }; - var origin = L("عقبة", "Aqaba"); - var data = rows.Select((x, i) => (IReadOnlyList)new object?[] - { - i + 1, x.Pn, x.SerialNo, Date(x.LoadDate), origin, x.Name, x.CargoType, x.Tn, x.Lnw, Date(x.DischargeDate), x.Dnw, - x.Dnw - x.Lnw, x.Price, x.FinePrice, x.LoseFine, x.DemurrageFine, x.OtherFine, x.FinalCost - }).ToList(); - IReadOnlyList? totalRow = rows.Count == 0 ? null : new object?[] - { - L("المجموع", "Total"), null, null, null, null, null, null, null, totals.Lnw, null, totals.Dnw, null, null, null, - totals.LoseFine, totals.DemurrageFine, totals.OtherFine, totals.FinalCost - }; - return Build([new ExportTable(title, headers, data, totalRow)], format, $"FinancialReport_{scac}_{invoiceNumber}"); + h.Append(""); + foreach (var v in new object?[] { "المجموع", null, null, null, null, null, null, null, totals.Lnw, null, totals.Dnw, null, null, null, totals.LoseFine, totals.DemurrageFine, totals.OtherFine, totals.FinalCost }) + h.Append($""); + h.Append(""); + } + else h.Append(""); + + h.Append(""); + h.Append($""); + h.Append(""); + h.Append($""); + h.Append($""); + h.Append("
شركة نافذ للخدمات اللوجستية
قائمة بنماذج المعدة لصرف أجور النقل حسب رقم المطالبة
إسم الشركة : {E(first?.CompanyName)} رقم المطالبة : {E(first?.InvoiceNumber)}رقم العطاء : {GrainsOrderConstants.BillingTenderNumber}التاريخ : {E(Date(first?.LoadDate))}
{c}
{E(v)}
{E(v)}
لايوجد معلومات
بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm}جميع الحقوق محفوظة لشركة نافذ للخدمات اللوجستيةعدد النتائج : {rows.Count}طبع التقرير بواسطة : {E(user.UserId)}
"); + + var bytes = new System.Text.UTF8Encoding(true).GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(h.ToString())).ToArray(); + return new ExportFile(bytes, "application/vnd.ms-excel", "FinancialReport.xls"); } public Task> GetInvoiceNumbersAsync(long scac, CancellationToken ct) => diff --git a/src/NTP.Application/Grains/Orders/OrdersContracts.cs b/src/NTP.Application/Grains/Orders/OrdersContracts.cs index d8149ff..6392f21 100644 --- a/src/NTP.Application/Grains/Orders/OrdersContracts.cs +++ b/src/NTP.Application/Grains/Orders/OrdersContracts.cs @@ -119,9 +119,9 @@ public sealed record AddBillingRequest( public sealed record WageRate(decimal Wage); public sealed record FineRate(decimal Allowance, decimal Fine); -public sealed record BillingQuery(string? Tn, long? Pn, long? Scac) +public sealed record BillingQuery(string? Tn, long? Pn, long? Scac, string? InvoiceNumber = null) { - public bool HasFilter => !string.IsNullOrWhiteSpace(Tn) || Pn.HasValue || Scac.HasValue; + public bool HasFilter => !string.IsNullOrWhiteSpace(Tn) || Pn.HasValue || Scac.HasValue || !string.IsNullOrWhiteSpace(InvoiceNumber); } public sealed class BillingRow @@ -138,11 +138,44 @@ public sealed class BillingRow public decimal? Dnw { get; set; } public decimal? Price { get; set; } public decimal? FinePrice { get; set; } + public string? InvoiceNumber { get; set; } + public string? CreateUserId { get; set; } } public sealed record BillingDto( long Id, string? CargoType, string? Scac, long Pn, string? Tn, string? LoadDate, string? Destination, - string? DischargeDate, decimal? Lnw, decimal? Dnw, decimal? Price, decimal? FinePrice); + string? DischargeDate, decimal? Lnw, decimal? Dnw, decimal? Price, decimal? FinePrice, string? InvoiceNumber, string? CreateUserId); + +/// Billing row as the delete / reroute screens need it (legacy deleteInvoice, getBillingInfoForReroute). +public sealed class BillingDetailRow +{ + public long Id { get; set; } + public long Pn { get; set; } + public string? Tn { get; set; } + public string? CompanyName { get; set; } + public string? SerialNo { get; set; } + public string? CargoType { get; set; } + public string? Destination { get; set; } + public DateTime? LoadDate { get; set; } + public DateTime? DischargeDate { get; set; } + public decimal? Lnw { get; set; } + public decimal? Dnw { get; set; } + public decimal? Price { get; set; } + public string? InvoiceNumber { get; set; } + public string? Scac { get; set; } + public decimal? DemurrageFine { get; set; } + public decimal? OtherFine { get; set; } + public decimal? ReroutePrice { get; set; } + public string? RerouteName { get; set; } + public string? CreateUserId { get; set; } +} + +public sealed record BillingRerouteDto( + long Id, long Pn, string? Tn, string? CompanyName, string? SerialNo, string? CargoType, string? Destination, + string? LoadDate, string? DischargeDate, decimal? Lnw, decimal? Dnw, decimal? Price, string? InvoiceNumber, + decimal? DemurrageFine, decimal? OtherFine, decimal? ReroutePrice, string? RerouteName); + +public sealed record RerouteRequest(decimal? ReroutePrice, string? RerouteName); // ---------------------------------------------------------------- invoices public sealed class InvoiceRow diff --git a/src/NTP.Application/Grains/Orders/OrdersRepositories.cs b/src/NTP.Application/Grains/Orders/OrdersRepositories.cs index d5106e5..7da14c2 100644 --- a/src/NTP.Application/Grains/Orders/OrdersRepositories.cs +++ b/src/NTP.Application/Grains/Orders/OrdersRepositories.cs @@ -63,11 +63,20 @@ public interface IBillingRepository Task GetFineRateAsync(DateTime loadDate, CancellationToken ct = default); Task InsertAsync(NewGrainsBilling billing, CancellationToken ct = default); Task> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default); + Task GetDetailAsync(long id, CancellationToken ct = default); + /// INVOICE.STATUSCODE of the invoice a billing belongs to (null when there is no INVOICE row). + Task GetInvoiceStatusAsync(string scac, string invoiceNumber, CancellationToken ct = default); + Task MarkDeletedAsync(long id, CancellationToken ct = default); + Task UpdateRerouteAsync(long id, decimal? price, string? name, CancellationToken ct = default); } public interface IInvoiceRepository { Task> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct = default); + Task ExistsAsync(long id, CancellationToken ct = default); + /// Recomputes FINALCOST of every billing of the invoice, then sets the invoice ARCHIVED. + Task ArchiveAsync(long id, CancellationToken ct = default); + Task ActivateAsync(long id, CancellationToken ct = default); } public interface IGrainsWeightRepository diff --git a/src/NTP.Application/Grains/Orders/OrdersRules.cs b/src/NTP.Application/Grains/Orders/OrdersRules.cs index 9f7744f..4c3e57f 100644 --- a/src/NTP.Application/Grains/Orders/OrdersRules.cs +++ b/src/NTP.Application/Grains/Orders/OrdersRules.cs @@ -54,7 +54,26 @@ public static class OrdersErrors public static BusinessException InvalidDestination() => new("COMPANY_DESTINATION_INVALID", "وجهة غير صحيحة"); + public static BusinessException BillingNotFound() => + new("BILLING_NOT_FOUND", "المطالبة غير موجودة"); + + public static BusinessException InvoiceNotFound() => + new("INVOICE_NOT_FOUND", "الفاتورة غير موجودة"); + + public static BusinessException DeleteFromArchivedInvoice() => + new("BILLING_INVOICE_ARCHIVED", "لا تسطيع حذف مطالبة من فاتورة مؤرشفة"); + + public static BusinessException DeleteNotOwner(string? creator) => + new("BILLING_NOT_OWNER", $"لا تستطيع حذف مطالبة لم تقم بإدخالها - مدخل الإرسالية {creator}"); + + public static BusinessException ReroutePriceRange() => + new("BILLING_REROUTE_PRICE", "السعر الجديد يجب ان يكون اعلى من السعر الحالي واقل من 35"); + public const string Success = "تمت العملية بنجاح"; + public const string Archived = "تمت عملية الأرشفة بنجاح"; + public const string Activated = "تمت عملية التفعيل بنجاح"; + public const string Deleted = "تم الحذف بنجاح"; + public const string Rerouted = "تمت عملية اعادة التوجيه بنجاح"; } /// Pure business rules of tender orders (ported from createNewTenderOrder.cfm / tenderOrder.cfc). diff --git a/src/NTP.Domain/Grains/Orders/OrdersDomain.cs b/src/NTP.Domain/Grains/Orders/OrdersDomain.cs index 8a1bd64..3f8b444 100644 --- a/src/NTP.Domain/Grains/Orders/OrdersDomain.cs +++ b/src/NTP.Domain/Grains/Orders/OrdersDomain.cs @@ -59,4 +59,4 @@ public sealed record NewTenderOrder( public sealed record NewGrainsBilling( long Pn, string SerialNo, string Tn, long CargoType, long Destination, DateTime LoadDate, DateTime DischargeDate, decimal Dtw, decimal Dgw, decimal Dnw, decimal Ltw, decimal Lgw, decimal Lnw, long Scac, long InvoiceNumber, - long Origin, decimal Price, decimal FinePrice, decimal FinalCost, decimal LoseFine); + long Origin, decimal Price, decimal FinePrice, decimal FinalCost, decimal LoseFine, string CreateUserId = ""); diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/BillingRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/BillingRepository.cs index 475c7c6..59572cd 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/BillingRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/BillingRepository.cs @@ -80,17 +80,18 @@ internal sealed class BillingRepository(IDbSession session, ILogger("NewId")); @@ -110,17 +111,21 @@ internal sealed class BillingRepository(IDbSession session, ILogger 'DELETED' """); var p = new DynamicParameters(); if (!string.IsNullOrWhiteSpace(query.Tn)) { sql.Append(" AND t.tn = :Tn"); p.Add("Tn", query.Tn.Trim()); } if (query.Pn.HasValue) { sql.Append(" AND t.pn = :Pn"); p.Add("Pn", query.Pn.Value.ToString()); } if (query.Scac.HasValue) { sql.Append(" AND t.scac = :Scac"); p.Add("Scac", query.Scac.Value.ToString()); } + if (!string.IsNullOrWhiteSpace(query.InvoiceNumber)) { sql.Append(" AND t.invoicenumber = :InvoiceNumber"); p.Add("InvoiceNumber", query.InvoiceNumber.Trim()); } var baseSql = sql.ToString(); var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); @@ -131,6 +136,32 @@ internal sealed class BillingRepository(IDbSession session, ILogger(OracleSql.Paginate(baseSql + " ORDER BY t.pn, t.id"), p, ct); return new PagedResult(items, page.SafePage, page.SafePageSize, total); } + + public Task GetDetailAsync(long id, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT g.id AS Id, g.pn AS Pn, g.tn AS Tn, g.companyname AS CompanyName, g.serialno AS SerialNo, + t.name AS CargoType, l.name AS Destination, g.loaddate AS LoadDate, g.dischargedate AS DischargeDate, + g.lnw AS Lnw, g.dnw AS Dnw, g.price AS Price, g.invoicenumber AS InvoiceNumber, g.scac AS Scac, + g.demurragefine AS DemurrageFine, g.otherfine AS OtherFine, g.rerouteprice AS ReroutePrice, + g.reroutename AS RerouteName, g.createuserid AS CreateUserId + FROM GRAINS_BILLING g, CARGOTYPE t, LOCATIONS l + WHERE g.id = :Id AND t.id = g.cargotype AND l.id = g.destination + """, new { Id = id }, ct); + + public async Task GetInvoiceStatusAsync(string scac, string invoiceNumber, CancellationToken ct = default) + { + var rows = await QueryAsync( + "SELECT i.statuscode FROM INVOICE i WHERE i.invoicenumber = :Inv AND i.scac = :Scac AND i.domain = 'GN'", + new { Inv = invoiceNumber, Scac = scac }, ct); + return rows.FirstOrDefault(); + } + + public Task MarkDeletedAsync(long id, CancellationToken ct = default) => + ExecuteAsync("UPDATE GRAINS_BILLING SET statuscode = 'DELETED' WHERE id = :Id", new { Id = id }, ct); + + public Task UpdateRerouteAsync(long id, decimal? price, string? name, CancellationToken ct = default) => + ExecuteAsync("UPDATE GRAINS_BILLING SET rerouteprice = :Price, reroutename = :Name WHERE id = :Id", + new { Price = price, Name = name, Id = id }, ct); } /// Port of Invoice.cfc getInvoiceGrid (legacy datasource GNB, assumed to be the same schema). @@ -144,21 +175,21 @@ internal sealed class InvoiceRepository(IDbSession session, ILogger TO_DATE('1/1/' || (EXTRACT(YEAR FROM SYSDATE) - 1), 'dd/mm/yyyy') """); var p = new DynamicParameters(); if (invoiceNumber.HasValue) { sql.Append(" AND i.invoicenumber = :InvoiceNumber"); p.Add("InvoiceNumber", invoiceNumber.Value.ToString()); } sql.Append(""" - GROUP BY i.invoicenumber, i.id, i.statuscode, ntc.name, i.scac, TO_CHAR(i.invoicedate, 'yyyy/mm/dd') + GROUP BY i.invoicenumber, i.id, i.statuscode, TRIM(gb.companyname), i.scac, TO_CHAR(i.invoicedate, 'yyyy/mm/dd') """); var baseSql = sql.ToString(); @@ -168,7 +199,38 @@ internal sealed class InvoiceRepository(IDbSession session, ILogger( - OracleSql.Paginate(baseSql + " ORDER BY TO_CHAR(i.invoicedate, 'yyyy/mm/dd'), i.invoicenumber, i.id"), p, ct); + OracleSql.Paginate(baseSql + " ORDER BY TO_CHAR(i.invoicedate, 'yyyy/mm/dd') DESC, i.invoicenumber, i.id"), p, ct); return new PagedResult(items, page.SafePage, page.SafePageSize, total); } + + public async Task ExistsAsync(long id, CancellationToken ct = default) => + await ExecuteScalarAsync("SELECT COUNT(*) FROM INVOICE WHERE id = :Id AND domain = 'GN'", new { Id = id }, ct) > 0; + + // Legacy archiveInvoice merged on GRAINS_BILLING.ID = (a bug: it touched an unrelated billing row); + // here every billing of the invoice gets its final cost recomputed, including the reroute price. + public async Task ArchiveAsync(long id, CancellationToken ct = default) + { + await ExecuteAsync(""" + MERGE INTO GRAINS_BILLING d + USING (SELECT t.id AS sid, + ROUND((NVL(t.rerouteprice, t.price) * t.lnw) / 1000, 3) + - NVL((SELECT MAX(CASE WHEN (t.lnw - t.dnw) > f.allowance * t.lnw + THEN ROUND(((t.lnw - t.dnw) - f.allowance * t.lnw) * f.fine / 1000, 3) + ELSE 0 END) + FROM grains_fine f + WHERE f.cargotype = t.cargotype + AND t.loaddate BETWEEN f.startdate AND f.enddate), 0) + - NVL(t.demurragefine, 0) - NVL(t.otherfine, 0) AS sfinalcost + FROM GRAINS_BILLING t, INVOICE i + WHERE i.id = :Id AND i.domain = 'GN' + AND t.scac = i.scac AND t.invoicenumber = i.invoicenumber + AND NVL(t.statuscode, 'ACTIVE') <> 'DELETED') s + ON (d.id = s.sid) + WHEN MATCHED THEN UPDATE SET d.finalcost = s.sfinalcost + """, new { Id = id }, ct); + await ExecuteAsync("UPDATE INVOICE SET statuscode = 'ARCHIVED' WHERE id = :Id AND domain = 'GN'", new { Id = id }, ct); + } + + public Task ActivateAsync(long id, CancellationToken ct = default) => + ExecuteAsync("UPDATE INVOICE SET statuscode = 'ACTIVE' WHERE id = :Id AND domain = 'GN'", new { Id = id }, ct); } diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/FinanceRatesRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/FinanceRatesRepository.cs new file mode 100644 index 0000000..72febac --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/FinanceRatesRepository.cs @@ -0,0 +1,45 @@ +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Orders; + +/// Port of fines.cfc getFinesGrid and wages.cfc getWagesGrid (GRAINS_FINE, GRAINS_WAGE). +internal sealed class FinanceRatesRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IFinanceRatesRepository +{ + public Task> SearchFinesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct = default) => + SearchAsync(""" + SELECT t.id AS Id, c.name AS CargoType, + TO_CHAR(t.startdate, 'yyyy-mm-dd') AS StartDate, TO_CHAR(t.enddate, 'yyyy-mm-dd') AS EndDate, + t.fine AS Fine, t.allowance AS Allowance + FROM GRAINS_FINE t, cargotype c + WHERE t.cargotype = c.id + """, startDate, endDate, page, ct); + + public Task> SearchWagesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct = default) => + SearchAsync(""" + SELECT t.id AS Id, l.name AS Location, + TO_CHAR(t.startdate, 'yyyy-mm-dd') AS StartDate, TO_CHAR(t.enddate, 'yyyy-mm-dd') AS EndDate, + t.wage AS Wage + FROM GRAINS_WAGE t, locations l + WHERE t.locationid = l.id AND l.domain = 'GN' + """, startDate, endDate, page, ct); + + private async Task> SearchAsync(string select, DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct) + { + var sql = select; + var p = new DynamicParameters(); + if (startDate.HasValue) { sql += " AND t.startdate = TRUNC(:StartDate)"; p.Add("StartDate", startDate.Value.Date); } + if (endDate.HasValue) { sql += " AND t.enddate = TRUNC(:EndDate)"; p.Add("EndDate", endDate.Value.Date); } + + 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 t.id DESC"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/WeightsAndReportsRepositories.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/WeightsAndReportsRepositories.cs index 3389e85..14ac4c6 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/WeightsAndReportsRepositories.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/WeightsAndReportsRepositories.cs @@ -134,6 +134,6 @@ internal sealed class OrderReportRepository(IDbSession session, ILogger> GetInvoiceNumbersAsync(long scac, CancellationToken ct = default) => await QueryAsync( - "SELECT DISTINCT invoicenumber FROM GRAINS_BILLING WHERE scac = :Scac AND invoicenumber IS NOT NULL ORDER BY invoicenumber DESC", + "SELECT t.invoicenumber FROM GRAINS_BILLING t WHERE t.scac = :Scac AND t.invoicenumber IS NOT NULL AND NVL(t.statuscode, 'ACTIVE') <> 'DELETED' AND t.createtimestamp > SYSDATE - 365 GROUP BY t.invoicenumber ORDER BY t.invoicenumber DESC", new { Scac = scac.ToString() }, ct); } diff --git a/web/index.html b/web/index.html index 82a408b..9e97c53 100644 --- a/web/index.html +++ b/web/index.html @@ -3,7 +3,7 @@ - + Nafith diff --git a/web/public/brand/favicon.ico b/web/public/brand/favicon.ico new file mode 100644 index 0000000..d14e783 Binary files /dev/null and b/web/public/brand/favicon.ico differ diff --git a/web/src/features/grains-orders/api.ts b/web/src/features/grains-orders/api.ts index 4ba50e6..00d781c 100644 --- a/web/src/features/grains-orders/api.ts +++ b/web/src/features/grains-orders/api.ts @@ -4,7 +4,7 @@ import { useWrite } from '@/api/hooks'; import { gridKey } from '@/components/DataGrid'; import type { OptionItem, OptionsLoader } from '@/components/meta/types'; import { useLanguage } from '@/providers/LanguageProvider'; -import type { +import type { BillingReroute, BillingPermit, CompanyDestinations, CompanyOption, DestinationGroupsData, FinancialBillingPage, LookupOption, OrdersResult, PermitWeights, TenderOrderReport, } from './types'; @@ -49,6 +49,15 @@ export function useCompanies() { }); } +export function useInvoiceNumbers(scac: string) { + return useQuery({ + queryKey: ['grains.orders.invoiceNumbers.list', scac], + queryFn: () => api.get(`${BASE}/reports/invoice-numbers`, { scac }, { silent: true }), + enabled: !!scac, + staleTime: 30_000, + }); +} + export function useDestinationGroups() { const { lang, langReady } = useLanguage(); return useQuery({ @@ -116,6 +125,33 @@ export function useAddBilling() { }); } +export function useDeleteBilling() { + return useWrite((id: number) => api.delete(`${BASE}/billing/${id}`), { + invalidate: [gridKey('grains.orders.billing')], + }); +} + +export const fetchBillingReroute = (id: number) => api.get(`${BASE}/billing/${id}/reroute`); + +export function useReroute(id: number, onDone: () => void) { + return useWrite( + (v: { reroutePrice: number | null; rerouteName: string }) => api.put(`${BASE}/billing/${id}/reroute`, v), + { invalidate: [gridKey('grains.orders.billing')], onSuccess: onDone }, + ); +} + +export function useArchiveInvoice() { + return useWrite((id: number) => api.post(`${BASE}/invoices/${id}/archive`, {}), { + invalidate: [gridKey('grains.orders.invoices')], + }); +} + +export function useActivateInvoice() { + return useWrite((id: number) => api.post(`${BASE}/invoices/${id}/activate`, {}), { + invalidate: [gridKey('grains.orders.invoices')], + }); +} + export function useSaveWeights() { return useWrite((payload: Record) => api.post(`${BASE}/weights`, payload)); } diff --git a/web/src/features/grains-orders/meta/billing.tsx b/web/src/features/grains-orders/meta/billing.tsx index 9d67c93..c71d07d 100644 --- a/web/src/features/grains-orders/meta/billing.tsx +++ b/web/src/features/grains-orders/meta/billing.tsx @@ -1,25 +1,29 @@ +import AltRouteIcon from '@mui/icons-material/AltRoute'; +import ArchiveIcon from '@mui/icons-material/Archive'; +import DeleteOutlineIcon from '@mui/icons-material/DeleteOutlined'; +import DownloadIcon from '@mui/icons-material/Download'; +import UnarchiveIcon from '@mui/icons-material/Unarchive'; import type { FormMeta, GridMeta, StatusMeta } from '@/components/meta/types'; -import { - billingDestinationOptions, cargoTypeOptions, companyOptions, fetchFinancialBilling, invoiceNumberOptions, -} from '../api'; -import type { BillingRow, FinancialBillingRow, FinancialBillingTotals, InvoiceRow } from '../types'; +import { billingDestinationOptions, cargoTypeOptions, companyOptions } from '../api'; +import type { BillingRow, FineRow, InvoiceRow, WageRow } from '../types'; -/** Declarative tables for billing, invoices, loading weights and the financial report. */ +/** Declarative tables for billing, invoices, loading weights, fines and wages. */ // ---------------------------------------------------------------- billing list (BillingGrid.cfm) -export const billingGrid = (): GridMeta => ({ +export const billingGrid = (h: { onDelete: (r: BillingRow) => void; onReroute: (r: BillingRow) => void }): GridMeta => ({ key: 'grains.orders.billing', endpoint: '/grains/orders/billing', rowKey: (r) => r.id, requireFilter: true, // legacy returned an empty grid without a filter filters: [ { name: 'pn', type: 'text', label: { en: 'Permit number', ar: 'رقم الارسالية' }, inputKind: 'code' }, - { name: 'tn', type: 'text', label: { en: 'Trailer number', ar: 'رقم المقطورة' }, inputKind: 'code' }, + { name: 'tn', type: 'text', label: { en: 'Truck number', ar: 'رقم القاطرة' }, inputKind: 'code' }, + { name: 'invoiceNumber', type: 'text', label: { en: 'Invoice (claim) number', ar: 'رقم الفاتورة(المطالبة)' }, inputKind: 'code' }, { name: 'scac', type: 'autocomplete', label: { en: 'Company', ar: 'اسم الشركة' }, options: companyOptions }, ], columns: [ { key: 'pn', header: { en: 'Permit no.', ar: 'رقم الارسالية' }, ltr: true }, - { key: 'tn', header: { en: 'Trailer no.', ar: 'رقم المقطورة' }, ltr: true }, + { key: 'tn', header: { en: 'Truck no.', ar: 'رقم القاطرة' }, ltr: true }, { key: 'scac', header: { en: 'Company', ar: 'اسم الشركة' }, hideBelow: 'sm' }, { key: 'cargoType', header: { en: 'Cargo', ar: 'نوع المادة' }, hideBelow: 'md' }, { key: 'destination', header: { en: 'Destination', ar: 'الوجهة' } }, @@ -27,6 +31,12 @@ export const billingGrid = (): GridMeta => ({ { key: 'dischargeDate', header: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, format: 'date', ltr: true, hideBelow: 'md' }, { key: 'lnw', header: { en: 'Sent weight', ar: 'الوزن المرسل' }, format: 'number', align: 'end' }, { key: 'dnw', header: { en: 'Received weight', ar: 'الوزن المستلم' }, format: 'number', align: 'end' }, + { key: 'invoiceNumber', header: { en: 'Invoice', ar: 'الفاتورة' }, ltr: true }, + { key: 'createUserId', header: { en: 'By', ar: 'بواسطة' }, ltr: true, hideBelow: 'lg' }, + ], + rowActions: [ + { key: 'reroute', label: { en: 'Reroute', ar: 'اعادة توجيه' }, icon: , onClick: h.onReroute }, + { key: 'delete', label: { en: 'Delete', ar: 'حذف' }, icon: , danger: true, onClick: h.onDelete }, ], }); @@ -58,6 +68,7 @@ export const billingForm: FormMeta = { // ---------------------------------------------------------------- invoices (InvoiceGrid.cfm) export const invoiceStatuses: StatusMeta[] = [ + { value: 'ACTIVE', label: { en: 'Active', ar: 'فعال' }, color: 'success' }, { value: 'ARCHIVED', label: { en: 'Archived', ar: 'مؤرشف' }, color: 'default' }, ]; @@ -66,11 +77,14 @@ const slashDate = (s: string | null) => { return m ? `${m[3]}/${m[2]}/${m[1]}` : (s ?? ''); }; -export const invoiceGrid = (h: { onExport: (r: InvoiceRow, format: 'csv' | 'xlsx') => void }): GridMeta => ({ +export const invoiceGrid = (h: { + onExport: (r: InvoiceRow) => void; + onArchive: (r: InvoiceRow) => void; + onActivate: (r: InvoiceRow) => void; +}): GridMeta => ({ key: 'grains.orders.invoices', endpoint: '/grains/orders/invoices', rowKey: (r) => r.id, - requireFilter: true, filters: [{ name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم الفاتورة' }, inputKind: 'code' }], columns: [ { key: 'invoiceNumber', header: { en: 'Invoice number', ar: 'رقم الفاتورة' }, ltr: true }, @@ -80,8 +94,10 @@ export const invoiceGrid = (h: { onExport: (r: InvoiceRow, format: 'csv' | 'xlsx { key: 'statusCode', header: { en: 'Status', ar: 'الحالة' }, format: 'status', statuses: invoiceStatuses }, ], rowActions: [ - { key: 'xlsx', label: { en: 'Print Excel', ar: 'طباعة XLS' }, onClick: (r) => h.onExport(r, 'xlsx') }, - { key: 'csv', label: { en: 'Export CSV', ar: 'تصدير CSV' }, onClick: (r) => h.onExport(r, 'csv') }, + // ARCHIVED: export to Excel + activate; ACTIVE: archive (legacy getInvoiceGrid) + { key: 'excel', label: { en: 'Export to Excel', ar: 'تصدير Excel' }, icon: , hidden: (r) => r.statusCode !== 'ARCHIVED', onClick: h.onExport }, + { key: 'activate', label: { en: 'Activate', ar: 'تفعيل' }, icon: , hidden: (r) => r.statusCode !== 'ARCHIVED', onClick: h.onActivate }, + { key: 'archive', label: { en: 'Archive', ar: 'أرشفة' }, icon: , hidden: (r) => r.statusCode !== 'ACTIVE', onClick: h.onArchive }, ], }); @@ -115,44 +131,35 @@ export const weightsForm: FormMeta = { ], }; -// ---------------------------------------------------------------- financial billing report (FinancialBilling.cfm) -export const financialGrid = (h: { onTotals: (t: FinancialBillingTotals | null) => void }): GridMeta => ({ - key: 'grains.orders.financial', +// ---------------------------------------------------------------- fines and wages (FinesGrid.cfm / WagesGrid.cfm) +const periodFilters: GridMeta['filters'] = [ + { name: 'startDate', type: 'date', label: { en: 'Start date', ar: 'تاريخ البداية' } }, + { name: 'endDate', type: 'date', label: { en: 'End date', ar: 'تاريخ الإنتهاء' } }, +]; + +export const finesGrid = (): GridMeta => ({ + key: 'grains.orders.fines', + endpoint: '/grains/orders/fines', rowKey: (r) => r.id, - requireFilter: true, - pageSize: 50, - pageSizeOptions: [25, 50, 100, 200], - filters: [ - { name: 'scac', type: 'autocomplete', label: { en: 'Company', ar: 'اسم الشركة' }, options: companyOptions }, - { name: 'invoiceNumber', type: 'select', label: { en: 'Invoice number', ar: 'رقم المطالبة' }, options: invoiceNumberOptions, dependsOn: 'scac' }, - ], - // both filters are needed; one request per action, totals come back with the page - fetcher: async (q) => { - const { scac, invoiceNumber } = q.filters; - if (!scac || !invoiceNumber) { - h.onTotals(null); - return { items: [], page: q.page, pageSize: q.pageSize, totalCount: 0 }; - } - const r = await fetchFinancialBilling({ scac, invoiceNumber, page: q.page, pageSize: q.pageSize }); - h.onTotals(r.totals); - return r; - }, + filters: periodFilters, columns: [ - { key: 'pn', header: { en: 'Permit no.', ar: 'رقم الارسالية' }, ltr: true }, - { key: 'serialNo', header: { en: 'Document no.', ar: 'رقم المستند' }, ltr: true, hideBelow: 'md' }, - { key: 'loadDate', header: { en: 'Load date', ar: 'تاريخ التحميل' }, ltr: true, hideBelow: 'md' }, - { key: 'destination', header: { en: 'To', ar: 'الى' } }, - { key: 'cargoType', header: { en: 'Cargo', ar: 'نوع المادة' }, hideBelow: 'lg' }, - { key: 'tn', header: { en: 'Truck', ar: 'رقم السيارة' }, ltr: true, hideBelow: 'sm' }, - { key: 'lnw', header: { en: 'Sent weight', ar: 'الوزن المرسل' }, format: 'number', align: 'end' }, - { key: 'dischargeDate', header: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, ltr: true, hideBelow: 'lg' }, - { key: 'dnw', header: { en: 'Received weight', ar: 'الوزن المستلم' }, format: 'number', align: 'end' }, - { key: 'difference', header: { en: 'Difference', ar: 'الفرق' }, format: 'number', align: 'end', hideBelow: 'md' }, - { key: 'price', header: { en: 'Price', ar: 'السعر' }, format: 'number', align: 'end', hideBelow: 'lg' }, - { key: 'finePrice', header: { en: 'Fine price', ar: 'سعر التغريم' }, format: 'number', align: 'end', hideBelow: 'lg' }, - { key: 'loseFine', header: { en: 'Shortage fine', ar: 'غرامة النقص' }, format: 'number', align: 'end', hideBelow: 'md' }, - { key: 'demurrageFine', header: { en: 'Demurrage fine', ar: 'غرامة التاخير' }, format: 'number', align: 'end', hideBelow: 'lg' }, - { key: 'otherFine', header: { en: 'Other fines', ar: 'غرامات آخرى' }, format: 'number', align: 'end', hideBelow: 'lg' }, - { key: 'finalCost', header: { en: 'Final value', ar: 'القيمة النهائية' }, format: 'number', align: 'end' }, + { key: 'cargoType', header: { en: 'Cargo type', ar: 'نوع الحمولة' } }, + { key: 'startDate', header: { en: 'Start date', ar: 'تاريخ البداية' }, format: 'date', ltr: true, align: 'center' }, + { key: 'endDate', header: { en: 'End date', ar: 'تاريخ الإنتهاء' }, format: 'date', ltr: true, align: 'center' }, + { key: 'fine', header: { en: 'Fine', ar: 'الغرامة' }, format: 'number', align: 'center' }, + { key: 'allowance', header: { en: 'Allowance', ar: 'نسبة السماح' }, format: 'number', align: 'center' }, + ], +}); + +export const wagesGrid = (): GridMeta => ({ + key: 'grains.orders.wages', + endpoint: '/grains/orders/wages', + rowKey: (r) => r.id, + filters: periodFilters as unknown as GridMeta['filters'], + columns: [ + { key: 'location', header: { en: 'Location', ar: 'الموقع' } }, + { key: 'startDate', header: { en: 'Start date', ar: 'تاريخ البداية' }, format: 'date', ltr: true, align: 'center' }, + { key: 'endDate', header: { en: 'End date', ar: 'تاريخ الإنتهاء' }, format: 'date', ltr: true, align: 'center' }, + { key: 'wage', header: { en: 'Wage', ar: 'الأجر' }, format: 'number', align: 'center' }, ], }); diff --git a/web/src/features/grains-orders/pages.tsx b/web/src/features/grains-orders/pages.tsx index 10fa70e..f1d2cd4 100644 --- a/web/src/features/grains-orders/pages.tsx +++ b/web/src/features/grains-orders/pages.tsx @@ -1,5 +1,5 @@ import { useEffect, useMemo, useState, type KeyboardEvent } from 'react'; -import { useNavigate, useSearchParams } from 'react-router-dom'; +import { useNavigate } from 'react-router-dom'; import { Alert, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, Paper, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, @@ -7,6 +7,7 @@ import { import AddIcon from '@mui/icons-material/Add'; import AssessmentIcon from '@mui/icons-material/Assessment'; import DownloadIcon from '@mui/icons-material/Download'; +import FactCheckIcon from '@mui/icons-material/FactCheck'; import GrainIcon from '@mui/icons-material/Grain'; import Inventory2Icon from '@mui/icons-material/Inventory2'; import LocalShippingIcon from '@mui/icons-material/LocalShipping'; @@ -17,22 +18,23 @@ import { DestinationGroups } from '@/components/DestinationGroups'; import { LoadingBanner } from '@/components/LoadingBanner'; import { MetaForm } from '@/components/MetaForm'; import { PageHeader } from '@/components/PageHeader'; +import { FormCard } from '@/components/FormCard'; 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 { - downloadExport, fetchBillingPermit, fetchPermitWeights, useAddBilling, useCompanies, useCompanyDestinations, - useCreateOrder, useDeleteOrder, useDestinationGroups, usePublishOrder, useSaveCompanyDestinations, useSaveWeights, - useSetQuota, useTenderOrderReport, + downloadExport, fetchBillingPermit, fetchBillingReroute, fetchFinancialBilling, fetchPermitWeights, useActivateInvoice, useAddBilling, + useArchiveInvoice, useCompanies, useCompanyDestinations, useCreateOrder, useDeleteBilling, useDeleteOrder, useDestinationGroups, + useInvoiceNumbers, usePublishOrder, useReroute, useSaveCompanyDestinations, useSaveWeights, useSetQuota, useTenderOrderReport, } from './api'; -import { billingForm, billingGrid, financialGrid, invoiceGrid, weightsForm } from './meta/billing'; +import { billingForm, billingGrid, finesGrid, invoiceGrid, wagesGrid, weightsForm } from './meta/billing'; import { quotaGrid, tenderOrderForm, tenderOrderGrid, todayIso, } from './meta/orders'; import strings from './strings'; -import type { BillingPermit, FinancialBillingTotals, InvoiceRow, PermitWeights, Quota } from './types'; +import type { BillingPermit, BillingRow, BillingReroute, FinancialBillingRow, InvoiceRow, PermitWeights, Quota } from './types'; const INDIVIDUALS_SCAC = 327; @@ -184,10 +186,94 @@ export function QuotasPage() { } // ================================================================= billing +/** Legacy rerouteScreen.cfm: the claim is shown read only; only the new price and the reroute destination can be typed. */ +function RerouteDialog({ id, onClose }: { id: number; onClose: () => void }) { + const { t, lang } = useFeatureUi(strings); + const [info, setInfo] = useState(null); + const [price, setPrice] = useState(''); + const [name, setName] = useState(''); + const [err, setErr] = useState(null); + const save = useReroute(id, onClose); + + useEffect(() => { + let live = true; + fetchBillingReroute(id).then((r) => { + if (!live) return; + setInfo(r); + setPrice(r.reroutePrice == null ? '' : String(r.reroutePrice)); + setName(r.rerouteName ?? ''); + }).catch(() => { if (live) onClose(); }); + return () => { live = false; }; + }, [id, onClose]); + + const submit = () => { + const p = price.trim() === '' ? null : Number(price); + if (p !== null && (Number.isNaN(p) || p < (info?.price ?? 0) || p > 35)) { setErr(t('ord.billing.reroute.range')); return; } + setErr(null); + save.mutate({ reroutePrice: p, rerouteName: name }); + }; + + const ro = (label: string, v: unknown) => ( + + ); + const d = (v: string | null) => (v ? v.split('-').reverse().join('/') : ''); + + return ( + + {t('ord.billing.reroute.title')} + + {!info ? : ( + + {ro(lang === 'ar' ? 'رقم الارسالية' : 'Permit no.', info.pn)} + {ro(lang === 'ar' ? 'رقم القاطرة' : 'Truck no.', info.tn)} + {ro(lang === 'ar' ? 'اسم الشركة' : 'Company', info.companyName)} + {ro(lang === 'ar' ? 'رقم المطالبة' : 'Claim no.', info.serialNo)} + {ro(lang === 'ar' ? 'نوع المادة' : 'Cargo', info.cargoType)} + {ro(lang === 'ar' ? 'الوجهه' : 'Destination', info.destination)} + {ro(lang === 'ar' ? 'تاريخ التحميل' : 'Load date', d(info.loadDate))} + {ro(lang === 'ar' ? 'تاريخ التفريغ' : 'Discharge date', d(info.dischargeDate))} + {ro(lang === 'ar' ? 'الوزن المرسل' : 'Sent weight', info.lnw)} + {ro(lang === 'ar' ? 'الوزن المستلم' : 'Received weight', info.dnw)} + {ro(t('ord.billing.reroute.current'), info.price)} + {ro(lang === 'ar' ? 'الفاتورة' : 'Invoice', info.invoiceNumber)} + {ro(lang === 'ar' ? 'غرامة التأخير' : 'Demurrage fine', info.demurrageFine)} + {ro(lang === 'ar' ? 'غرامات اخرى' : 'Other fines', info.otherFine)} + setPrice(e.target.value.replace(/[^\d.]/g, ''))} + slotProps={{ htmlInput: { inputMode: 'decimal', dir: 'ltr', style: { textAlign: 'start' } } }} + /> + setName(e.target.value)} slotProps={{ htmlInput: { maxLength: 50 } }} + /> + {err && {err}} + + )} + + + + + + + ); +} + export function BillingListPage() { const { t } = useFeatureUi(strings); const navigate = useNavigate(); - const meta = useMemo(() => billingGrid(), []); + const confirm = useConfirm(); + const del = useDeleteBilling(); + const [rerouteId, setRerouteId] = useState(null); + const meta = useMemo( + () => billingGrid({ + onDelete: async (r: BillingRow) => { + if (await confirm({ message: t('ord.billing.deleteConfirm', { n: r.pn }), danger: true })) del.mutate(r.id); + }, + onReroute: (r: BillingRow) => setRerouteId(r.id), + }), + [confirm, del, t], + ); return ( <> } onClick={() => navigate('/grains/orders/billing/new')}>{t('ord.billing.new')}} /> + {rerouteId !== null && setRerouteId(null)} />} ); } @@ -319,14 +406,23 @@ export function BillingEntryPage() { export function InvoicesPage() { const { t } = useFeatureUi(strings); const toast = useToast(); + const confirm = useConfirm(); + const archive = useArchiveInvoice(); + const activate = useActivateInvoice(); const meta = useMemo( () => invoiceGrid({ - onExport: (r: InvoiceRow, format) => - downloadExport('/reports/financial-billing/export', { scac: r.scac, invoiceNumber: r.invoiceNumber, format }, `FinancialReport_${r.scac}_${r.invoiceNumber}.${format}`) + onExport: (r: InvoiceRow) => + downloadExport('/reports/financial-billing/excel', { scac: r.scac, invoiceNumber: r.invoiceNumber }, 'FinancialReport.xls') .catch((e) => toast.error(errText(e, t('ord.export.failed')))), + onArchive: async (r: InvoiceRow) => { + if (await confirm({ message: t('ord.invoices.archiveConfirm', { n: r.invoiceNumber }) })) archive.mutate(r.id); + }, + onActivate: async (r: InvoiceRow) => { + if (await confirm({ message: t('ord.invoices.activateConfirm', { n: r.invoiceNumber }) })) activate.mutate(r.id); + }, }), - [toast, t], + [toast, confirm, archive, activate, t], ); return ( <> @@ -336,6 +432,29 @@ export function InvoicesPage() { ); } +// ================================================================= fines and wages +export function FinesPage() { + const { t } = useFeatureUi(strings); + const meta = useMemo(() => finesGrid(), []); + return ( + <> + + + + ); +} + +export function WagesPage() { + const { t } = useFeatureUi(strings); + const meta = useMemo(() => wagesGrid(), []); + return ( + <> + + + + ); +} + // ================================================================= loading weights export function WeightsPage() { const { t } = useFeatureUi(strings); @@ -566,46 +685,114 @@ export function TenderOrderReportPage() { ); } -export function FinancialReportPage() { - const { t, lang } = useFeatureUi(strings); - const toast = useToast(); - const [sp] = useSearchParams(); - const [totals, setTotals] = useState(null); - const meta = useMemo(() => financialGrid({ onTotals: setTotals }), []); - const scac = sp.get('scac') ?? ''; - const invoiceNumber = sp.get('invoiceNumber') ?? ''; - const n = (v: number) => formatNumber(v, lang); +// ================================================================= invoice check (legacy FinancialRpts.cfm + billingValidation.cfm) +const pad = (v: number, int: number) => v.toFixed(3).padStart(int + 4, '0'); - const exportAs = (format: 'csv' | 'xlsx') => - downloadExport('/reports/financial-billing/export', { scac, invoiceNumber, format }, `FinancialReport_${scac}_${invoiceNumber}.${format}`) - .catch((e) => toast.error(errText(e, t('ord.export.failed')))); +export function InvoiceCheckPage() { + const { t } = useFeatureUi(strings); + const toast = useToast(); + const companies = useCompanies(); + const [scac, setScac] = useState(''); + const [inv, setInv] = useState(''); + const invoices = useInvoiceNumbers(scac); + const [rows, setRows] = useState(null); + const [busy, setBusy] = useState(false); + + const search = async () => { + if (!scac || !inv) return; + setBusy(true); + try { + let page = 1; + const all: FinancialBillingRow[] = []; + for (;;) { + const r = await fetchFinancialBilling({ scac, invoiceNumber: inv, page, pageSize: 200 }); + all.push(...r.items); + if (all.length >= r.totalCount || r.items.length === 0) break; + page++; + } + setRows(all); + } catch (e) { + toast.error(errText(e, t('ord.export.failed'))); + } finally { + setBusy(false); + } + }; + + const sum = (f: (r: FinancialBillingRow) => number) => (rows ?? []).reduce((a, r) => a + f(r), 0); + const net = sum((r) => Number(pad(r.finalCost, 3))); + const fines = sum((r) => Number(pad(r.loseFine, 2))); return ( <> - - - - - } - /> - {totals && scac && invoiceNumber && ( - - - {t('ord.fin.totals')} - {lang === 'ar' ? 'الوزن المرسل' : 'Sent'}: {n(totals.lnw)} - {lang === 'ar' ? 'الوزن المستلم' : 'Received'}: {n(totals.dnw)} - {lang === 'ar' ? 'غرامة النقص' : 'Shortage fine'}: {n(totals.loseFine)} - {lang === 'ar' ? 'غرامة التاخير' : 'Demurrage'}: {n(totals.demurrageFine)} - {lang === 'ar' ? 'غرامات آخرى' : 'Other fines'}: {n(totals.otherFine)} - {lang === 'ar' ? 'القيمة النهائية' : 'Final value'}: {n(totals.finalCost)} + + + } disabled={!scac || !inv || busy} onClick={() => void search()}>{t('common.search')}} + > + + { setScac(e.target.value); setInv(''); setRows(null); }} + slotProps={{ select: { native: true }, inputLabel: { shrink: true } }} + > + + {(companies.data ?? []).map((c) => )} + + { setInv(e.target.value); setRows(null); }} + slotProps={{ select: { native: true }, inputLabel: { shrink: true } }} + > + + {(invoices.data ?? []).map((n) => )} + - - )} - + + + {busy && } + {rows && !busy && ( + + + + + + {(['no', 'total', 'fine', 'lnw', 'dnw', 'price', 'center', 'doc', 'truck'] as const).map((k) => ( + {t(`ord.check.${k}`)} + ))} + + + + {rows.length === 0 && {t('ord.check.none')}} + {rows.map((r, i) => ( + + {i + 1} + {pad(r.finalCost, 3)} + {`${r.cargoType ?? ''} / ${pad(r.loseFine, 2)}`} + {r.lnw} + {r.dnw} + {pad(r.price, 3)} + {r.destination} + {r.serialNo} + {r.tn} + + ))} + +
+
+ {rows.length > 0 && ( + + {([ + ['ord.check.net', net], ['ord.check.fineTotal', fines], ['ord.check.weights', sum((r) => r.lnw)], + ['ord.check.count', rows.length], ['ord.check.grand', net + fines], + ] as const).map(([k, v]) => ( + {t(k)}{': '}{Number.isInteger(v) ? v : Number(v.toFixed(3))} + ))} + + )} +
+ )} + ); } diff --git a/web/src/features/grains-orders/routes.tsx b/web/src/features/grains-orders/routes.tsx index a72501a..3f9134a 100644 --- a/web/src/features/grains-orders/routes.tsx +++ b/web/src/features/grains-orders/routes.tsx @@ -1,6 +1,9 @@ import type { RouteObject } from 'react-router-dom'; import AccountBalanceIcon from '@mui/icons-material/AccountBalance'; import BusinessIcon from '@mui/icons-material/Business'; +import FactCheckIcon from '@mui/icons-material/FactCheck'; +import GavelIcon from '@mui/icons-material/Gavel'; +import PaymentsIcon from '@mui/icons-material/Payments'; import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import ListAltIcon from '@mui/icons-material/ListAlt'; import PercentIcon from '@mui/icons-material/Percent'; @@ -10,8 +13,8 @@ import RequestQuoteIcon from '@mui/icons-material/RequestQuote'; import ScaleIcon from '@mui/icons-material/Scale'; import type { MenuItem } from '@/shell/types'; import { - BillingEntryPage, BillingListPage, CompanyDestinationsPage, FinancialReportPage, InvoicesPage, QuotasPage, - TenderOrderCreatePage, TenderOrderReportPage, TenderOrdersPage, WeightsPage, + BillingEntryPage, BillingListPage, CompanyDestinationsPage, FinesPage, InvoiceCheckPage, InvoicesPage, QuotasPage, + TenderOrderCreatePage, TenderOrderReportPage, TenderOrdersPage, WagesPage, WeightsPage, } from './pages'; import strings from './strings'; import permitStrings from '../grains-permits/strings'; @@ -27,10 +30,12 @@ export const routes: RouteObject[] = [ { path: '/grains/orders/billing', element: }, { path: '/grains/orders/billing/new', element: , handle: { crumb: strings['ord.crumb.new'] } }, { path: '/grains/orders/invoices', element: }, + { path: '/grains/orders/fines', element: }, + { path: '/grains/orders/wages', element: }, { path: '/grains/orders/weights', element: }, { path: '/grains/orders/company-destinations', element: }, { path: '/grains/orders/reports/tender-orders', element: }, - { path: '/grains/orders/reports/financial-billing', element: }, + { path: '/grains/orders/invoice-check', element: }, ]; export const menu: MenuItem[] = [ @@ -52,6 +57,9 @@ export const menu: MenuItem[] = [ icon: AccountBalanceIcon, children: [ { key: 'grains.orders.billing', title: strings['ord.menu.billing'], icon: RequestQuoteIcon, path: '/grains/orders/billing', createPath: '/grains/orders/billing/new' }, + { key: 'grains.orders.fines', title: strings['ord.menu.fines'], icon: GavelIcon, path: '/grains/orders/fines' }, + { key: 'grains.orders.wages', title: strings['ord.menu.wages'], icon: PaymentsIcon, path: '/grains/orders/wages' }, + { key: 'grains.orders.invoiceCheck', title: strings['ord.menu.invoiceCheck'], icon: FactCheckIcon, path: '/grains/orders/invoice-check' }, { key: 'grains.orders.invoices', title: strings['ord.menu.invoices'], icon: ReceiptIcon, path: '/grains/orders/invoices' }, ], }, diff --git a/web/src/features/grains-orders/strings.ts b/web/src/features/grains-orders/strings.ts index 499826c..f172e59 100644 --- a/web/src/features/grains-orders/strings.ts +++ b/web/src/features/grains-orders/strings.ts @@ -9,6 +9,9 @@ export default defineStrings({ 'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' }, 'ord.menu.billing': { en: 'Billing claims', ar: 'المطالبات المالية' }, 'ord.menu.invoices': { en: 'Invoices', ar: 'فواتير التموين' }, + 'ord.menu.invoiceCheck': { en: 'Invoice check', ar: 'التأكد من الفواتير' }, + 'ord.menu.fines': { en: 'Fines', ar: 'الغرامات' }, + 'ord.menu.wages': { en: 'Wages', ar: 'الأجور' }, 'ord.menu.weights': { en: 'Loading weights', ar: 'تثبيت أوزان التحميل' }, 'ord.menu.companyDest': { en: 'Company destinations', ar: 'وجهات الشركات' }, 'ord.menu.reportOrders': { en: 'Orders report', ar: 'تقرير الطلبيات' }, @@ -70,6 +73,44 @@ export default defineStrings({ 'ord.billing.notLoaded': { en: 'Load a permit first.', ar: 'الرجاء تحميل الارسالية أولاً.' }, 'ord.billing.saveConfirm': { en: 'Save this billing claim?', ar: 'حفظ هذه المطالبة؟' }, + // ---- invoice actions + 'ord.invoices.archiveConfirm': { en: 'Archive invoice {n}?', ar: 'هل انت متأكد من أرشفة الفاتورة رقم {n}؟' }, + 'ord.invoices.activateConfirm': { en: 'Activate invoice {n}?', ar: 'هل انت متأكد من تفعيل الفاتورة رقم {n}؟' }, + + // ---- billing actions + 'ord.billing.deleteConfirm': { en: 'Delete claim {n}?', ar: 'هل انت متأكد من حذف المطالبة رقم {n}' }, + 'ord.billing.reroute.title': { en: 'Reroute', ar: 'شاشة اعادة التوجيه' }, + 'ord.billing.reroute.price': { en: 'New price', ar: 'السعر' }, + 'ord.billing.reroute.name': { en: 'Reroute destination', ar: 'وجهة التحويل' }, + 'ord.billing.reroute.range': { en: 'The new price must be at least the current price and at most 35', ar: 'السعر الجديد يجب ان يكون اعلى من السعر الحالي واقل من 35' }, + 'ord.billing.reroute.current': { en: 'Current price', ar: 'السعر الحالي' }, + + // ---- invoice check (FinancialRpts.cfm) + 'ord.check.title': { en: 'Invoice check', ar: 'التأكد من الفواتير' }, + 'ord.check.subtitle': { en: 'Billings of one invoice with its totals', ar: 'مطالبات الفاتورة مع المجاميع' }, + 'ord.check.invoice': { en: 'Invoice (claim) number', ar: 'رقم المطالبة' }, + 'ord.check.no': { en: 'No.', ar: 'رقم' }, + 'ord.check.total': { en: 'Total', ar: 'الإجمالي' }, + 'ord.check.fine': { en: 'Fine', ar: 'التغريم' }, + 'ord.check.lnw': { en: 'Sent weight', ar: 'الوزن المرسل' }, + 'ord.check.dnw': { en: 'Received weight', ar: 'الوزن المستلم' }, + 'ord.check.price': { en: 'Price', ar: 'السعر' }, + 'ord.check.center': { en: 'Loading centre', ar: 'مركز التحميل' }, + 'ord.check.doc': { en: 'Voucher no.', ar: 'رقم البون' }, + 'ord.check.truck': { en: 'Truck no.', ar: 'رقم السيارة' }, + 'ord.check.net': { en: 'Net', ar: 'الصافي' }, + 'ord.check.fineTotal': { en: 'Total fines', ar: 'أجمالي التغريم' }, + 'ord.check.weights': { en: 'Weights', ar: 'الأوزان' }, + 'ord.check.count': { en: 'Vouchers', ar: 'عدد البونات' }, + 'ord.check.grand': { en: 'Grand total', ar: 'الإجمالي' }, + 'ord.check.none': { en: 'No information', ar: 'لايوجد معلومات' }, + + // ---- fines and wages + 'ord.fines.title': { en: 'Fines', ar: 'شاشة الغرامات' }, + 'ord.fines.subtitle': { en: 'Fine and allowance per cargo type and period', ar: 'الغرامة ونسبة السماح لكل نوع حمولة وفترة' }, + 'ord.wages.title': { en: 'Wages', ar: 'شاشة الأجور' }, + 'ord.wages.subtitle': { en: 'Transport wage per location and period', ar: 'أجر النقل لكل موقع وفترة' }, + // ---- invoices 'ord.invoices.title': { en: 'Supply invoices', ar: 'شاشة فواتير التموين' }, 'ord.invoices.subtitle': { en: 'Invoices grouped by company and invoice number', ar: 'الفواتير حسب الشركة ورقم الفاتورة' }, diff --git a/web/src/features/grains-orders/types.ts b/web/src/features/grains-orders/types.ts index 46cdfd5..23869f1 100644 --- a/web/src/features/grains-orders/types.ts +++ b/web/src/features/grains-orders/types.ts @@ -55,6 +55,28 @@ export interface BillingPermit { lastInvoice: number | null; price: number | null; finePrice: number | null; + invoiceNumber: string | null; + createUserId: string | null; +} + +export interface BillingReroute { + id: number; + pn: number; + tn: string | null; + companyName: string | null; + serialNo: string | null; + cargoType: string | null; + destination: string | null; + loadDate: string | null; + dischargeDate: string | null; + lnw: number | null; + dnw: number | null; + price: number | null; + invoiceNumber: string | null; + demurrageFine: number | null; + otherFine: number | null; + reroutePrice: number | null; + rerouteName: string | null; } export interface BillingRow { @@ -157,3 +179,20 @@ export interface FinancialBillingPage { totalCount: number; totals: FinancialBillingTotals; } + +export interface FineRow { + id: number; + cargoType: string | null; + startDate: string | null; + endDate: string | null; + fine: number | null; + allowance: number | null; +} + +export interface WageRow { + id: number; + location: string | null; + startDate: string | null; + endDate: string | null; + wage: number | null; +} diff --git a/web/src/features/grains-reports/pages.tsx b/web/src/features/grains-reports/pages.tsx index 429ab00..94a82a6 100644 --- a/web/src/features/grains-reports/pages.tsx +++ b/web/src/features/grains-reports/pages.tsx @@ -510,7 +510,6 @@ function TableReportBody({ meta }: { meta: TableReportMeta }) { } /> - {meta.inferred && {t('rpt.t.inferredNote')}} {meta.defaults === 'yesterday' && {t('rpt.f.yesterdayNote')}} {missing.length > 0 && ( diff --git a/web/src/features/grains-reports/routes.tsx b/web/src/features/grains-reports/routes.tsx index 2f86f88..18be5a4 100644 --- a/web/src/features/grains-reports/routes.tsx +++ b/web/src/features/grains-reports/routes.tsx @@ -13,7 +13,6 @@ import { } from './pages'; import { tableReports } from './meta'; import strings from './strings'; -import orderStrings from '../grains-orders/strings'; const B = '/grains/reports'; @@ -51,8 +50,6 @@ export const menu: MenuItem[] = [ table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'), table('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'), table('companies-turn'), table('owners-turn'), - { key: 'grains.orders.reportOrders', title: orderStrings['ord.menu.reportOrders'], icon: AssessmentIcon, path: '/grains/orders/reports/tender-orders' }, - { key: 'grains.orders.reportFinance', title: orderStrings['ord.menu.reportFinance'], icon: AssessmentIcon, path: '/grains/orders/reports/financial-billing' }, table('drivers'), table('trucks'), { key: 'grains.reports.motMulti', title: strings['rpt.menu.motMulti'], icon: BarChartIcon, path: `${B}/mot/multi-trips` }, table('mot-grain-cube'), table('mot-grain-frequency'), diff --git a/web/src/features/grains-reports/strings.ts b/web/src/features/grains-reports/strings.ts index 32e5af4..1255a55 100644 --- a/web/src/features/grains-reports/strings.ts +++ b/web/src/features/grains-reports/strings.ts @@ -127,7 +127,6 @@ export default defineStrings({ 'rpt.t.trucks': { en: 'Registered trucks', ar: 'تقرير القاطرات المسجلة' }, 'rpt.t.mot-grain-cube': { en: 'Grain cube (MOT)', ar: 'مكعب الحبوب (وزارة النقل)' }, 'rpt.t.mot-grain-frequency': { en: 'Grain trip frequency (MOT)', ar: 'تكرار رحلات الحبوب (وزارة النقل)' }, - 'rpt.t.inferredNote': { en: 'Columns of this report were reconstructed from the legacy request parameters (the original template is not readable). Please confirm the layout.', ar: 'أعمدة هذا التقرير أُعيد بناؤها من معاملات الطلب في النظام القديم (قالب التقرير الأصلي غير قابل للقراءة). يرجى تأكيد التصميم.' }, 'rpt.t.shortageTotal': { en: 'Total shortage', ar: 'إجمالي العجز' }, 'rpt.t.individuals': { en: 'Individuals', ar: 'أفراد' }, 'rpt.t.companies': { en: 'Companies', ar: 'شركات' },