Grains finance: GNAC screens, invoice archive/activate, legacy Excel, invoice check

- New fines (الغرامات) and wages (الأجور) lists; GNAC finance screens seed script
- Invoices: archive/activate actions, legacy-format Excel export, active invoices listed
- Billing grid: truck-number label, invoice filter, invoice/by columns, reroute and delete actions
- التأكد من الفواتير page (port of FinancialRpts); hide financial and orders reports (DISABLED rows)
- Browser tab icon, remove "reconstructed columns" note, move API http port to 5181

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-12 16:41:53 +03:00
parent 21328b7d1a
commit b88ced45c4
27 changed files with 866 additions and 168 deletions

View File

@ -7,12 +7,16 @@
-- --
-- grains.permits.absence إيقاف/تفعيل الاستنكاف (stop / activate the absence feature) -- grains.permits.absence إيقاف/تفعيل الاستنكاف (stop / activate the absence feature)
-- grains.permits.activation تفعيل الطلبية (order activation screen) -- 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) INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
SELECT 'DISABLED', v.resource_key SELECT 'DISABLED', v.resource_key
FROM ( FROM (
SELECT 'grains.permits.absence' AS resource_key FROM dual UNION ALL 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 ) v
WHERE NOT EXISTS ( WHERE NOT EXISTS (
SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p
@ -20,7 +24,7 @@ SELECT 'DISABLED', v.resource_key
COMMIT; COMMIT;
-- Check (expect 2 rows): -- Check (expect 4 rows):
-- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'DISABLED' ORDER BY 2; -- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'DISABLED' ORDER BY 2;
-- --
-- Bring one back: -- Bring one back:

View File

@ -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;

View File

@ -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) 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) 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) 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 **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 included: the menu entry and buttons disappear and the API answers 403. It overrides every other row. Delete the row to bring the

View File

@ -67,7 +67,7 @@ public sealed class OrdersController(
public Task<DestinationGroupsDto> DestinationGroups(CancellationToken ct) => lookups.DestinationGroupsAsync(ct); public Task<DestinationGroupsDto> DestinationGroups(CancellationToken ct) => lookups.DestinationGroupsAsync(ct);
[HttpGet("lookups/companies")] [HttpGet("lookups/companies")]
[RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersReportFinance)] [RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersInvoiceCheck)]
public Task<IReadOnlyList<CompanyOptionDto>> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct); public Task<IReadOnlyList<CompanyOptionDto>> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct);
} }
@ -101,9 +101,9 @@ public sealed class OrderBillingController(IBillingService billing) : Controller
[HttpGet] [HttpGet]
[RequirePermission(PermissionKeys.OrdersBilling)] [RequirePermission(PermissionKeys.OrdersBilling)]
public Task<PagedResult<BillingDto>> Search( public Task<PagedResult<BillingDto>> 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) => [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);
/// <summary>Prefill of the billing form from a CLOSEd permit (legacy getBillingInfo).</summary> /// <summary>Prefill of the billing form from a CLOSEd permit (legacy getBillingInfo).</summary>
[HttpGet("permit/{pn:long}")] [HttpGet("permit/{pn:long}")]
@ -117,6 +117,24 @@ public sealed class OrderBillingController(IBillingService billing) : Controller
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)] [ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
[RequirePermission(PermissionKeys.OrdersBilling)] [RequirePermission(PermissionKeys.OrdersBilling)]
public Task<OrdersResult> Add(AddBillingRequest request, CancellationToken ct) => billing.AddAsync(request, ct); public Task<OrdersResult> Add(AddBillingRequest request, CancellationToken ct) => billing.AddAsync(request, ct);
/// <summary>Data of the reroute dialog (legacy rerouteScreen.cfm).</summary>
[HttpGet("{id:long}/reroute")]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
[RequirePermission(PermissionKeys.OrdersBilling)]
public Task<BillingRerouteDto> RerouteInfo(long id, CancellationToken ct) => billing.GetRerouteAsync(id, ct);
[HttpPut("{id:long}/reroute")]
[ProducesResponseType<OrdersResult>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
[RequirePermission(PermissionKeys.OrdersBilling)]
public Task<OrdersResult> Reroute(long id, RerouteRequest request, CancellationToken ct) => billing.RerouteAsync(id, request, ct);
[HttpDelete("{id:long}")]
[ProducesResponseType<OrdersResult>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
[RequirePermission(PermissionKeys.OrdersBilling)]
public Task<OrdersResult> Delete(long id, CancellationToken ct) => billing.DeleteAsync(id, ct);
} }
/// <summary>Invoices list (legacy InvoiceGrid.cfm, Invoice.cfc getInvoiceGrid).</summary> /// <summary>Invoices list (legacy InvoiceGrid.cfm, Invoice.cfc getInvoiceGrid).</summary>
@ -131,6 +149,38 @@ public sealed class OrderInvoicesController(IInvoiceService invoices) : Controll
public Task<PagedResult<InvoiceDto>> Search( public Task<PagedResult<InvoiceDto>> Search(
[FromQuery] long? invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => [FromQuery] long? invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) =>
invoices.SearchAsync(invoiceNumber, new PageRequest(page, pageSize), ct); invoices.SearchAsync(invoiceNumber, new PageRequest(page, pageSize), ct);
[HttpPost("{id:long}/archive")]
[ProducesResponseType<OrdersResult>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
[RequirePermission(PermissionKeys.OrdersInvoices)]
public Task<OrdersResult> Archive(long id, CancellationToken ct) => invoices.ArchiveAsync(id, ct);
[HttpPost("{id:long}/activate")]
[ProducesResponseType<OrdersResult>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
[RequirePermission(PermissionKeys.OrdersInvoices)]
public Task<OrdersResult> Activate(long id, CancellationToken ct) => invoices.ActivateAsync(id, ct);
}
/// <summary>الغرامات and الأجور lists (legacy FinesGrid.cfm / WagesGrid.cfm).</summary>
[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<PagedResult<FineDto>> 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<PagedResult<WageDto>> 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);
} }
/// <summary>Loading weights entry (legacy addGrainsWeights.cfm).</summary> /// <summary>Loading weights entry (legacy addGrainsWeights.cfm).</summary>
@ -195,23 +245,23 @@ public sealed class OrderReportsController(IOrderReportService reports) : Contro
[HttpGet("financial-billing")] [HttpGet("financial-billing")]
[Produces("application/json")] [Produces("application/json")]
[RequirePermission(PermissionKeys.OrdersReportFinance)] [RequirePermission(PermissionKeys.OrdersInvoiceCheck)]
public Task<FinancialBillingPage> FinancialBilling( public Task<FinancialBillingPage> FinancialBilling(
[FromQuery] long scac, [FromQuery] long invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => [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); reports.GetFinancialBillingAsync(scac, invoiceNumber, new PageRequest(page, pageSize), ct);
[HttpGet("financial-billing/export")] /// <summary>The legacy FinancialBilling.cfm Excel of one invoice (print action of an archived invoice).</summary>
[RequirePermission(PermissionKeys.OrdersReportFinance)] [HttpGet("financial-billing/excel")]
public async Task<IActionResult> ExportFinancialBilling( [RequirePermission(PermissionKeys.OrdersInvoices, PermissionKeys.OrdersInvoiceCheck)]
[FromQuery] long scac, [FromQuery] long invoiceNumber, [FromQuery] string format = "csv", CancellationToken ct = default) public async Task<IActionResult> 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); return File(f.Content, f.ContentType, f.FileName);
} }
/// <summary>Invoice numbers of a company for the report picker (legacy getInvoiceNo, which does not exist in the CFC).</summary> /// <summary>Invoice numbers of a company for the report picker (legacy getInvoiceNo, which does not exist in the CFC).</summary>
[HttpGet("invoice-numbers")] [HttpGet("invoice-numbers")]
[Produces("application/json")] [Produces("application/json")]
[RequirePermission(PermissionKeys.OrdersReportFinance)] [RequirePermission(PermissionKeys.OrdersInvoiceCheck)]
public Task<IReadOnlyList<long>> InvoiceNumbers([FromQuery] long scac, CancellationToken ct) => reports.GetInvoiceNumbersAsync(scac, ct); public Task<IReadOnlyList<long>> InvoiceNumbers([FromQuery] long scac, CancellationToken ct) => reports.GetInvoiceNumbersAsync(scac, ct);
} }

View File

@ -5,7 +5,7 @@
"commandName": "Project", "commandName": "Project",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "swagger", "launchUrl": "swagger",
"applicationUrl": "https://localhost:7180;http://localhost:5180", "applicationUrl": "https://localhost:7180;http://localhost:5181",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }

View File

@ -13,6 +13,11 @@ public static class PermissionKeys
public const string OrdersQuotas = "grains.orders.quotas"; public const string OrdersQuotas = "grains.orders.quotas";
public const string OrdersBilling = "grains.orders.billing"; public const string OrdersBilling = "grains.orders.billing";
public const string OrdersInvoices = "grains.orders.invoices"; public const string OrdersInvoices = "grains.orders.invoices";
/// <summary>الغرامات and الأجور (GNAC): monthly fine / wage tables read by the billing screens.</summary>
/// <summary>التأكد من الفواتير (legacy FinancialRpts.cfm): check the billings of one invoice.</summary>
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"; public const string OrdersWeights = "grains.orders.weights";
/// <summary>طلبية التموين: distributed permits per destination type (orders menu).</summary> /// <summary>طلبية التموين: distributed permits per destination type (orders menu).</summary>
public const string OrdersSupply = "grains.orders.supply"; public const string OrdersSupply = "grains.orders.supply";
@ -92,6 +97,9 @@ public static class PermissionDefaults
[PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية [PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية
[PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي [PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي
[PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف [PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف
[PermissionKeys.OrdersInvoiceCheck] = ["GNAC"], // التأكد من الفواتير
[PermissionKeys.OrdersFines] = ["GNAC"], // الغرامات
[PermissionKeys.OrdersWages] = ["GNAC"], // الأجور
[PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل [PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل
[PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ [PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ
[PermissionKeys.ReportTable("companies-turn")] = ["GTO", "GOO"], // تقرير دور الشركات [PermissionKeys.ReportTable("companies-turn")] = ["GTO", "GOO"], // تقرير دور الشركات

View File

@ -10,12 +10,16 @@ public interface IBillingService
Task<BillingPermitDto> GetPermitAsync(long pn, long? scac, CancellationToken ct); Task<BillingPermitDto> GetPermitAsync(long pn, long? scac, CancellationToken ct);
Task<OrdersResult> AddAsync(AddBillingRequest request, CancellationToken ct); Task<OrdersResult> AddAsync(AddBillingRequest request, CancellationToken ct);
Task<PagedResult<BillingDto>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct); Task<PagedResult<BillingDto>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct);
Task<BillingRerouteDto> GetRerouteAsync(long id, CancellationToken ct);
Task<OrdersResult> RerouteAsync(long id, RerouteRequest request, CancellationToken ct);
Task<OrdersResult> DeleteAsync(long id, CancellationToken ct);
} }
/// <summary>Port of Invoice.cfc getBillingInfo / addBillingInfo / getBillingGrid (BillingScreen.cfm, BillingGrid.cfm).</summary> /// <summary>Port of Invoice.cfc getBillingInfo / addBillingInfo / getBillingGrid (BillingScreen.cfm, BillingGrid.cfm).</summary>
public sealed class BillingService( public sealed class BillingService(
IBillingRepository repository, IBillingRepository repository,
IUnitOfWork unitOfWork, IUnitOfWork unitOfWork,
ICurrentUser user,
IValidator<AddBillingRequest> validator) : IBillingService IValidator<AddBillingRequest> validator) : IBillingService
{ {
private static string? Date(DateTime? d) => d?.ToString("yyyy-MM-dd"); 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, request.LoadDate.Date, request.DischargeDate.Date,
info.Dtw, info.Dgw, dnw, info.Ltw, info.Lgw, lnw, info.Dtw, info.Dgw, dnw, info.Ltw, info.Lgw, lnw,
request.Scac, request.InvoiceNumber, GrainsOrderConstants.BillingOriginId, 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); return new OrdersResult(OrdersErrors.Success, id);
}, ct); }, ct);
@ -83,26 +87,76 @@ public sealed class BillingService(
var r = await repository.SearchAsync(query, page, ct); var r = await repository.SearchAsync(query, page, ct);
var items = r.Items.Select(x => new BillingDto( 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.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<BillingDto>(items, r.Page, r.PageSize, r.TotalCount); return new PagedResult<BillingDto>(items, r.Page, r.PageSize, r.TotalCount);
} }
/// <summary>Port of getBillingInfoForReroute (rerouteScreen.cfm).</summary>
public async Task<BillingRerouteDto> 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);
}
/// <summary>Port of addRerouteInfo; the page JS rule: a new price must be at least the current price and at most 35.</summary>
public async Task<OrdersResult> 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);
}
/// <summary>Port of deleteInvoice: soft delete; not from an archived invoice; only the entering user unless GNAC.</summary>
public async Task<OrdersResult> 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 public interface IInvoiceService
{ {
Task<PagedResult<InvoiceDto>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct); Task<PagedResult<InvoiceDto>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct);
Task<OrdersResult> ArchiveAsync(long id, CancellationToken ct);
Task<OrdersResult> ActivateAsync(long id, CancellationToken ct);
} }
/// <summary>Port of Invoice.cfc getInvoiceGrid (InvoiceGrid.cfm).</summary> /// <summary>Port of Invoice.cfc getInvoiceGrid (InvoiceGrid.cfm).</summary>
public sealed class InvoiceService(IInvoiceRepository repository) : IInvoiceService public sealed class InvoiceService(IInvoiceRepository repository, IUnitOfWork unitOfWork) : IInvoiceService
{ {
public async Task<PagedResult<InvoiceDto>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct) public async Task<PagedResult<InvoiceDto>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct)
{ {
// Legacy returned an empty grid when no invoice number was given.
if (!invoiceNumber.HasValue) return new PagedResult<InvoiceDto>([], page.SafePage, page.SafePageSize, 0);
var r = await repository.SearchAsync(invoiceNumber, page, 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(); 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<InvoiceDto>(items, r.Page, r.PageSize, r.TotalCount); return new PagedResult<InvoiceDto>(items, r.Page, r.PageSize, r.TotalCount);
} }
public async Task<OrdersResult> 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<OrdersResult> 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);
}
} }

View File

@ -0,0 +1,58 @@
using NTP.Application.Common;
namespace NTP.Application.Grains.Orders;
/// <summary>Monthly fine / wage tables the billing screens read (legacy GRAINS_FINE, GRAINS_WAGE).</summary>
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<PagedResult<FineRow>> SearchFinesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct = default);
Task<PagedResult<WageRow>> SearchWagesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct = default);
}
public interface IFinanceRatesService
{
Task<PagedResult<FineDto>> FinesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct);
Task<PagedResult<WageDto>> WagesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct);
}
/// <summary>Port of fines.cfc getFinesGrid and wages.cfc getWagesGrid (read only; the Excel upload screen is not ported).</summary>
public sealed class FinanceRatesService(IFinanceRatesRepository repository) : IFinanceRatesService
{
public async Task<PagedResult<FineDto>> FinesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct)
{
var r = await repository.SearchFinesAsync(startDate, endDate, page, ct);
return new PagedResult<FineDto>(
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<PagedResult<WageDto>> WagesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct)
{
var r = await repository.SearchWagesAsync(startDate, endDate, page, ct);
return new PagedResult<WageDto>(
r.Items.Select(x => new WageDto(x.Id, x.Location, x.StartDate, x.EndDate, x.Wage)).ToList(),
r.Page, r.PageSize, r.TotalCount);
}
}

View File

@ -10,7 +10,8 @@ public interface IOrderReportService
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct); Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct);
Task<FinancialBillingPage> GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct); Task<FinancialBillingPage> GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct);
Task<ExportFile> ExportFinancialBillingAsync(long scac, long invoiceNumber, string format, CancellationToken ct); /// <summary>The legacy FinancialBilling.cfm Excel (an HTML table opened by Excel), byte for byte the same layout.</summary>
Task<ExportFile> ExportFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct);
Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct); Task<IReadOnlyList<long>> 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)); return new FinancialBillingPage(paged.Items.Select(Map).ToList(), paged.Page, paged.PageSize, paged.TotalCount, Totals(all));
} }
public async Task<ExportFile> ExportFinancialBillingAsync(long scac, long invoiceNumber, string format, CancellationToken ct) public async Task<ExportFile> ExportFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct)
{ {
var rows = await repository.GetFinancialBillingAsync(scac, invoiceNumber, ct); var rows = await repository.GetFinancialBillingAsync(scac, invoiceNumber, ct);
var first = rows.FirstOrDefault(); var first = rows.FirstOrDefault();
var totals = Totals(rows); 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<string> var h = new System.Text.StringBuilder();
h.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
h.Append("<style>.header{font-weight:bold;font-size:28px;}");
h.Append(".sub_header{font-weight:bold;font-size:14px;text-align:right;width:80px;background-color:#034878;color:#FFFFFF;text-align:center;}");
h.Append(".footer{background-color:#034878;color:#FFFFFF;font-weight:bold;}</style>");
h.Append("<table border=\"2\" bordercolor=\"#034878\"><tr><td><table align=\"center\" dir=\"rtl\" border=\"1\">");
h.Append("<tr align=\"center\" dir=\"rtl\"><td colspan=\"18\" align=\"center\" class=\"header\">شركة نافذ للخدمات اللوجستية</td></tr>");
h.Append("<tr align=\"center\" dir=\"rtl\"><td colspan=\"18\" align=\"center\" class=\"header\">قائمة بنماذج المعدة لصرف أجور النقل حسب رقم المطالبة</td></tr>");
h.Append("<tr dir=\"rtl\">");
h.Append($"<td colspan=\"6\" class=\"sub_header\">إسم الشركة : {E(first?.CompanyName)} </td>");
h.Append($"<td colspan=\"4\" class=\"sub_header\">رقم المطالبة : {E(first?.InvoiceNumber)}</td>");
h.Append($"<td colspan=\"3\" class=\"sub_header\">رقم العطاء : {GrainsOrderConstants.BillingTenderNumber}</td>");
h.Append($"<td colspan=\"3\" class=\"sub_header\">التاريخ : {E(Date(first?.LoadDate))}</td>");
h.Append("<td colspan=\"2\" class=\"sub_header\"></td></tr>");
h.Append("<tr align=\"center\" dir=\"rtl\">");
foreach (var c in new[] { "التسلسل", " رقم الارسالية", " رقم المستند", "تاريخ التحميل", "من", "الى", "نوع المادة", "رقم السيارة", "الوزن المرسل", "تاريخ التفريغ", "الوزن المستلم", "الفرق ", "السعر", "سعر التغريم", "غرامة النقص ", "غرامة التاخير", "غرامات آخرى", "القيمة النهائية" })
h.Append($"<td class=\"sub_header\">{c}</td>");
h.Append("</tr>");
decimal priceTotal = 0, finePriceTotal = 0;
var n = 0;
foreach (var x in rows)
{ {
L("شركة نافذ للخدمات اللوجستية", "Nafith Logistics Services"), n++;
L("قائمة بنماذج المعدة لصرف أجور النقل حسب رقم المطالبة", "Transport wages forms by invoice number"), priceTotal += x.Price; finePriceTotal += x.FinePrice;
$"{L("إسم الشركة", "Company")}: {first?.CompanyName}", h.Append("<tr align=\"center\" dir=\"rtl\">");
$"{L("رقم المطالبة", "Invoice number")}: {invoiceNumber}", 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 })
$"{L("رقم العطاء", "Tender number")}: {GrainsOrderConstants.BillingTenderNumber}", h.Append($"<td>{E(v)}</td>");
$"{L("التاريخ", "Date")}: {Date(first?.LoadDate)}", h.Append("</tr>");
}; }
var headers = new[]
if (rows.Count != 0)
{ {
L("التسلسل", "#"), L("رقم الارسالية", "Permit no."), L("رقم المستند", "Document no."), L("تاريخ التحميل", "Load date"), h.Append("<tr align=\"center\" dir=\"rtl\">");
L("من", "From"), L("الى", "To"), L("نوع المادة", "Cargo"), L("رقم السيارة", "Truck"), L("الوزن المرسل", "Sent weight"), 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 })
L("تاريخ التفريغ", "Discharge date"), L("الوزن المستلم", "Received weight"), L("الفرق", "Difference"), L("السعر", "Price"), h.Append($"<td class=\"footer\">{E(v)}</td>");
L("سعر التغريم", "Fine price"), L("غرامة النقص", "Shortage fine"), L("غرامة التاخير", "Demurrage fine"), h.Append("</tr>");
L("غرامات آخرى", "Other fines"), L("القيمة النهائية", "Final value"), }
}; else h.Append("<tr><td colspan=\"18\">لايوجد معلومات</td></tr>");
var origin = L("عقبة", "Aqaba");
var data = rows.Select((x, i) => (IReadOnlyList<object?>)new object?[] h.Append("<tr>");
{ h.Append($"<td colspan=\"5\">بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm}</td>");
i + 1, x.Pn, x.SerialNo, Date(x.LoadDate), origin, x.Name, x.CargoType, x.Tn, x.Lnw, Date(x.DischargeDate), x.Dnw, h.Append("<td colspan=\"5\">جميع الحقوق محفوظة لشركة نافذ للخدمات اللوجستية</td>");
x.Dnw - x.Lnw, x.Price, x.FinePrice, x.LoseFine, x.DemurrageFine, x.OtherFine, x.FinalCost h.Append($"<td colspan=\"3\">عدد النتائج : {rows.Count}</td>");
}).ToList(); h.Append($"<td colspan=\"5\" align=\"left\">طبع التقرير بواسطة : {E(user.UserId)}</td>");
IReadOnlyList<object?>? totalRow = rows.Count == 0 ? null : new object?[] h.Append("</tr></table></td></tr></table></body></html>");
{
L("المجموع", "Total"), null, null, null, null, null, null, null, totals.Lnw, null, totals.Dnw, null, null, null, var bytes = new System.Text.UTF8Encoding(true).GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(h.ToString())).ToArray();
totals.LoseFine, totals.DemurrageFine, totals.OtherFine, totals.FinalCost return new ExportFile(bytes, "application/vnd.ms-excel", "FinancialReport.xls");
};
return Build([new ExportTable(title, headers, data, totalRow)], format, $"FinancialReport_{scac}_{invoiceNumber}");
} }
public Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct) => public Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct) =>

View File

@ -119,9 +119,9 @@ public sealed record AddBillingRequest(
public sealed record WageRate(decimal Wage); public sealed record WageRate(decimal Wage);
public sealed record FineRate(decimal Allowance, decimal Fine); 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 public sealed class BillingRow
@ -138,11 +138,44 @@ public sealed class BillingRow
public decimal? Dnw { get; set; } public decimal? Dnw { get; set; }
public decimal? Price { get; set; } public decimal? Price { get; set; }
public decimal? FinePrice { get; set; } public decimal? FinePrice { get; set; }
public string? InvoiceNumber { get; set; }
public string? CreateUserId { get; set; }
} }
public sealed record BillingDto( public sealed record BillingDto(
long Id, string? CargoType, string? Scac, long Pn, string? Tn, string? LoadDate, string? Destination, 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);
/// <summary>Billing row as the delete / reroute screens need it (legacy deleteInvoice, getBillingInfoForReroute).</summary>
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 // ---------------------------------------------------------------- invoices
public sealed class InvoiceRow public sealed class InvoiceRow

View File

@ -63,11 +63,20 @@ public interface IBillingRepository
Task<FineRate?> GetFineRateAsync(DateTime loadDate, CancellationToken ct = default); Task<FineRate?> GetFineRateAsync(DateTime loadDate, CancellationToken ct = default);
Task<long> InsertAsync(NewGrainsBilling billing, CancellationToken ct = default); Task<long> InsertAsync(NewGrainsBilling billing, CancellationToken ct = default);
Task<PagedResult<BillingRow>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default); Task<PagedResult<BillingRow>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default);
Task<BillingDetailRow?> GetDetailAsync(long id, CancellationToken ct = default);
/// <summary>INVOICE.STATUSCODE of the invoice a billing belongs to (null when there is no INVOICE row).</summary>
Task<string?> 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 public interface IInvoiceRepository
{ {
Task<PagedResult<InvoiceRow>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct = default); Task<PagedResult<InvoiceRow>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct = default);
Task<bool> ExistsAsync(long id, CancellationToken ct = default);
/// <summary>Recomputes FINALCOST of every billing of the invoice, then sets the invoice ARCHIVED.</summary>
Task ArchiveAsync(long id, CancellationToken ct = default);
Task ActivateAsync(long id, CancellationToken ct = default);
} }
public interface IGrainsWeightRepository public interface IGrainsWeightRepository

View File

@ -54,7 +54,26 @@ public static class OrdersErrors
public static BusinessException InvalidDestination() => public static BusinessException InvalidDestination() =>
new("COMPANY_DESTINATION_INVALID", "وجهة غير صحيحة"); 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 Success = "تمت العملية بنجاح";
public const string Archived = "تمت عملية الأرشفة بنجاح";
public const string Activated = "تمت عملية التفعيل بنجاح";
public const string Deleted = "تم الحذف بنجاح";
public const string Rerouted = "تمت عملية اعادة التوجيه بنجاح";
} }
/// <summary>Pure business rules of tender orders (ported from createNewTenderOrder.cfm / tenderOrder.cfc).</summary> /// <summary>Pure business rules of tender orders (ported from createNewTenderOrder.cfm / tenderOrder.cfc).</summary>

View File

@ -59,4 +59,4 @@ public sealed record NewTenderOrder(
public sealed record NewGrainsBilling( public sealed record NewGrainsBilling(
long Pn, string SerialNo, string Tn, long CargoType, long Destination, DateTime LoadDate, DateTime DischargeDate, 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, 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 = "");

View File

@ -80,17 +80,18 @@ internal sealed class BillingRepository(IDbSession session, ILogger<BillingRepos
b.Price, b.Price,
b.FinePrice, b.FinePrice,
b.FinalCost, b.FinalCost,
b.LoseFine b.LoseFine,
b.CreateUserId
}); });
p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output);
await ExecuteAsync(""" await ExecuteAsync("""
INSERT INTO GRAINS_BILLING INSERT INTO GRAINS_BILLING
(ID, PN, SERIALNO, TN, CARGOTYPE, DESTINATION, LOADDATE, DISCHARGEDATE, DTW, DGW, DNW, LTW, LGW, LNW, (ID, PN, SERIALNO, TN, CARGOTYPE, DESTINATION, LOADDATE, DISCHARGEDATE, DTW, DGW, DNW, LTW, LGW, LNW,
SCAC, INVOICENUMBER, ORIGIN, PRICE, FINEPRICE, FINALCOST, LOSEFINE) SCAC, INVOICENUMBER, ORIGIN, PRICE, FINEPRICE, FINALCOST, LOSEFINE, CREATEUSERID)
VALUES VALUES
(seq_GRAINS_BILLING.NEXTVAL, :Pn, :SerialNo, :Tn, :CargoType, :Destination, :LoadDate, :DischargeDate, :Dtw, :Dgw, :Dnw, :Ltw, :Lgw, :Lnw, (seq_GRAINS_BILLING.NEXTVAL, :Pn, :SerialNo, :Tn, :CargoType, :Destination, :LoadDate, :DischargeDate, :Dtw, :Dgw, :Dnw, :Ltw, :Lgw, :Lnw,
:Scac, :InvoiceNumber, :Origin, :Price, :FinePrice, :FinalCost, :LoseFine) :Scac, :InvoiceNumber, :Origin, :Price, :FinePrice, :FinalCost, :LoseFine, :CreateUserId)
RETURNING ID INTO :NewId RETURNING ID INTO :NewId
""", p, ct); """, p, ct);
return OracleSql.ToInt64(p.Get<object>("NewId")); return OracleSql.ToInt64(p.Get<object>("NewId"));
@ -110,17 +111,21 @@ internal sealed class BillingRepository(IDbSession session, ILogger<BillingRepos
t.lnw AS Lnw, t.lnw AS Lnw,
t.dnw AS Dnw, t.dnw AS Dnw,
t.price AS Price, t.price AS Price,
t.fineprice AS FinePrice t.fineprice AS FinePrice,
t.invoicenumber AS InvoiceNumber,
t.createuserid AS CreateUserId
FROM GRAINS_BILLING t, FROM GRAINS_BILLING t,
(SELECT * FROM CARGOTYPE WHERE domain = 'GN') ctp, (SELECT * FROM CARGOTYPE WHERE domain = 'GN') ctp,
(SELECT * FROM LOCATIONS l WHERE l.domain = 'GN' AND l.type = 'EX' AND l.area IS NULL AND l.status = '1') loc (SELECT * FROM LOCATIONS l WHERE l.domain = 'GN' AND l.type = 'EX' AND l.area IS NULL AND l.status = '1') loc
WHERE t.cargotype = ctp.id WHERE t.cargotype = ctp.id
AND t.destination = loc.id AND t.destination = loc.id
AND NVL(t.statuscode, 'ACTIVE') <> 'DELETED'
"""); """);
var p = new DynamicParameters(); var p = new DynamicParameters();
if (!string.IsNullOrWhiteSpace(query.Tn)) { sql.Append(" AND t.tn = :Tn"); p.Add("Tn", query.Tn.Trim()); } 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.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 (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 baseSql = sql.ToString();
var total = await ExecuteScalarAsync<long>(OracleSql.Count(baseSql), p, ct); var total = await ExecuteScalarAsync<long>(OracleSql.Count(baseSql), p, ct);
@ -131,6 +136,32 @@ internal sealed class BillingRepository(IDbSession session, ILogger<BillingRepos
var items = await QueryAsync<BillingRow>(OracleSql.Paginate(baseSql + " ORDER BY t.pn, t.id"), p, ct); var items = await QueryAsync<BillingRow>(OracleSql.Paginate(baseSql + " ORDER BY t.pn, t.id"), p, ct);
return new PagedResult<BillingRow>(items, page.SafePage, page.SafePageSize, total); return new PagedResult<BillingRow>(items, page.SafePage, page.SafePageSize, total);
} }
public Task<BillingDetailRow?> GetDetailAsync(long id, CancellationToken ct = default) =>
QueryFirstAsync<BillingDetailRow>("""
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<string?> GetInvoiceStatusAsync(string scac, string invoiceNumber, CancellationToken ct = default)
{
var rows = await QueryAsync<string>(
"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);
} }
/// <summary>Port of Invoice.cfc getInvoiceGrid (legacy datasource GNB, assumed to be the same schema).</summary> /// <summary>Port of Invoice.cfc getInvoiceGrid (legacy datasource GNB, assumed to be the same schema).</summary>
@ -144,21 +175,21 @@ internal sealed class InvoiceRepository(IDbSession session, ILogger<InvoiceRepos
i.id AS Id, i.id AS Id,
i.statuscode AS StatusCode, i.statuscode AS StatusCode,
COUNT(*) AS Cnt, COUNT(*) AS Cnt,
ntc.name AS CompanyName, TRIM(gb.companyname) AS CompanyName,
i.scac AS Scac, i.scac AS Scac,
TO_CHAR(i.invoicedate, 'yyyy/mm/dd') AS InvoiceDate TO_CHAR(i.invoicedate, 'yyyy/mm/dd') AS InvoiceDate
FROM INVOICE i, ntp_tenders_companies ntc, GRAINS_BILLING gb FROM INVOICE i, GRAINS_BILLING gb
WHERE i.scac = ntc.scac WHERE gb.scac = i.scac
AND gb.scac = i.scac
AND gb.invoicenumber = i.invoicenumber AND gb.invoicenumber = i.invoicenumber
AND i.statuscode NOT IN ('DELETED', 'ACTIVE') AND i.statuscode NOT IN ('DELETED')
AND i.domain = 'GN' AND i.domain = 'GN'
AND i.invoicedate > TO_DATE('1/1/' || (EXTRACT(YEAR FROM SYSDATE) - 1), 'dd/mm/yyyy')
"""); """);
var p = new DynamicParameters(); var p = new DynamicParameters();
if (invoiceNumber.HasValue) { sql.Append(" AND i.invoicenumber = :InvoiceNumber"); p.Add("InvoiceNumber", invoiceNumber.Value.ToString()); } if (invoiceNumber.HasValue) { sql.Append(" AND i.invoicenumber = :InvoiceNumber"); p.Add("InvoiceNumber", invoiceNumber.Value.ToString()); }
sql.Append(""" 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(); var baseSql = sql.ToString();
@ -168,7 +199,38 @@ internal sealed class InvoiceRepository(IDbSession session, ILogger<InvoiceRepos
p.Add("MinRow", page.MinRow); p.Add("MinRow", page.MinRow);
p.Add("MaxRow", page.MaxRow); p.Add("MaxRow", page.MaxRow);
var items = await QueryAsync<InvoiceRow>( var items = await QueryAsync<InvoiceRow>(
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<InvoiceRow>(items, page.SafePage, page.SafePageSize, total); return new PagedResult<InvoiceRow>(items, page.SafePage, page.SafePageSize, total);
} }
public async Task<bool> ExistsAsync(long id, CancellationToken ct = default) =>
await ExecuteScalarAsync<long>("SELECT COUNT(*) FROM INVOICE WHERE id = :Id AND domain = 'GN'", new { Id = id }, ct) > 0;
// Legacy archiveInvoice merged on GRAINS_BILLING.ID = <invoice 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);
} }

View File

@ -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;
/// <summary>Port of fines.cfc getFinesGrid and wages.cfc getWagesGrid (GRAINS_FINE, GRAINS_WAGE).</summary>
internal sealed class FinanceRatesRepository(IDbSession session, ILogger<FinanceRatesRepository> logger)
: OracleRepositoryBase(session, logger), IFinanceRatesRepository
{
public Task<PagedResult<FineRow>> SearchFinesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct = default) =>
SearchAsync<FineRow>("""
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<PagedResult<WageRow>> SearchWagesAsync(DateTime? startDate, DateTime? endDate, PageRequest page, CancellationToken ct = default) =>
SearchAsync<WageRow>("""
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<PagedResult<T>> SearchAsync<T>(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<long>(OracleSql.Count(sql), p, ct);
if (total == 0) return new PagedResult<T>([], page.SafePage, page.SafePageSize, 0);
p.Add("MinRow", page.MinRow);
p.Add("MaxRow", page.MaxRow);
var items = await QueryAsync<T>(OracleSql.Paginate(sql + " ORDER BY t.id DESC"), p, ct);
return new PagedResult<T>(items, page.SafePage, page.SafePageSize, total);
}
}

View File

@ -134,6 +134,6 @@ internal sealed class OrderReportRepository(IDbSession session, ILogger<OrderRep
public async Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct = default) => public async Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct = default) =>
await QueryAsync<long>( await QueryAsync<long>(
"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); new { Scac = scac.ToString() }, ct);
} }

View File

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="data:," /> <link rel="icon" href="/brand/favicon.ico" sizes="any" />
<title>Nafith</title> <title>Nafith</title>
<link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@ -4,7 +4,7 @@ import { useWrite } from '@/api/hooks';
import { gridKey } from '@/components/DataGrid'; import { gridKey } from '@/components/DataGrid';
import type { OptionItem, OptionsLoader } from '@/components/meta/types'; import type { OptionItem, OptionsLoader } from '@/components/meta/types';
import { useLanguage } from '@/providers/LanguageProvider'; import { useLanguage } from '@/providers/LanguageProvider';
import type { import type { BillingReroute,
BillingPermit, CompanyDestinations, CompanyOption, DestinationGroupsData, FinancialBillingPage, LookupOption, OrdersResult, BillingPermit, CompanyDestinations, CompanyOption, DestinationGroupsData, FinancialBillingPage, LookupOption, OrdersResult,
PermitWeights, TenderOrderReport, PermitWeights, TenderOrderReport,
} from './types'; } 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<number[]>(`${BASE}/reports/invoice-numbers`, { scac }, { silent: true }),
enabled: !!scac,
staleTime: 30_000,
});
}
export function useDestinationGroups() { export function useDestinationGroups() {
const { lang, langReady } = useLanguage(); const { lang, langReady } = useLanguage();
return useQuery({ return useQuery({
@ -116,6 +125,33 @@ export function useAddBilling() {
}); });
} }
export function useDeleteBilling() {
return useWrite((id: number) => api.delete<OrdersResult>(`${BASE}/billing/${id}`), {
invalidate: [gridKey('grains.orders.billing')],
});
}
export const fetchBillingReroute = (id: number) => api.get<BillingReroute>(`${BASE}/billing/${id}/reroute`);
export function useReroute(id: number, onDone: () => void) {
return useWrite(
(v: { reroutePrice: number | null; rerouteName: string }) => api.put<OrdersResult>(`${BASE}/billing/${id}/reroute`, v),
{ invalidate: [gridKey('grains.orders.billing')], onSuccess: onDone },
);
}
export function useArchiveInvoice() {
return useWrite((id: number) => api.post<OrdersResult>(`${BASE}/invoices/${id}/archive`, {}), {
invalidate: [gridKey('grains.orders.invoices')],
});
}
export function useActivateInvoice() {
return useWrite((id: number) => api.post<OrdersResult>(`${BASE}/invoices/${id}/activate`, {}), {
invalidate: [gridKey('grains.orders.invoices')],
});
}
export function useSaveWeights() { export function useSaveWeights() {
return useWrite((payload: Record<string, unknown>) => api.post<OrdersResult>(`${BASE}/weights`, payload)); return useWrite((payload: Record<string, unknown>) => api.post<OrdersResult>(`${BASE}/weights`, payload));
} }

View File

@ -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 type { FormMeta, GridMeta, StatusMeta } from '@/components/meta/types';
import { import { billingDestinationOptions, cargoTypeOptions, companyOptions } from '../api';
billingDestinationOptions, cargoTypeOptions, companyOptions, fetchFinancialBilling, invoiceNumberOptions, import type { BillingRow, FineRow, InvoiceRow, WageRow } from '../types';
} from '../api';
import type { BillingRow, FinancialBillingRow, FinancialBillingTotals, InvoiceRow } 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) // ---------------------------------------------------------------- billing list (BillingGrid.cfm)
export const billingGrid = (): GridMeta<BillingRow> => ({ export const billingGrid = (h: { onDelete: (r: BillingRow) => void; onReroute: (r: BillingRow) => void }): GridMeta<BillingRow> => ({
key: 'grains.orders.billing', key: 'grains.orders.billing',
endpoint: '/grains/orders/billing', endpoint: '/grains/orders/billing',
rowKey: (r) => r.id, rowKey: (r) => r.id,
requireFilter: true, // legacy returned an empty grid without a filter requireFilter: true, // legacy returned an empty grid without a filter
filters: [ filters: [
{ name: 'pn', type: 'text', label: { en: 'Permit number', ar: 'رقم الارسالية' }, inputKind: 'code' }, { 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 }, { name: 'scac', type: 'autocomplete', label: { en: 'Company', ar: 'اسم الشركة' }, options: companyOptions },
], ],
columns: [ columns: [
{ key: 'pn', header: { en: 'Permit no.', ar: 'رقم الارسالية' }, ltr: true }, { 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: 'scac', header: { en: 'Company', ar: 'اسم الشركة' }, hideBelow: 'sm' },
{ key: 'cargoType', header: { en: 'Cargo', ar: 'نوع المادة' }, hideBelow: 'md' }, { key: 'cargoType', header: { en: 'Cargo', ar: 'نوع المادة' }, hideBelow: 'md' },
{ key: 'destination', header: { en: 'Destination', ar: 'الوجهة' } }, { key: 'destination', header: { en: 'Destination', ar: 'الوجهة' } },
@ -27,6 +31,12 @@ export const billingGrid = (): GridMeta<BillingRow> => ({
{ key: 'dischargeDate', header: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, format: 'date', ltr: true, hideBelow: 'md' }, { 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: 'lnw', header: { en: 'Sent weight', ar: 'الوزن المرسل' }, format: 'number', align: 'end' },
{ key: 'dnw', header: { en: 'Received 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: <AltRouteIcon fontSize="small" />, onClick: h.onReroute },
{ key: 'delete', label: { en: 'Delete', ar: 'حذف' }, icon: <DeleteOutlineIcon fontSize="small" />, danger: true, onClick: h.onDelete },
], ],
}); });
@ -58,6 +68,7 @@ export const billingForm: FormMeta = {
// ---------------------------------------------------------------- invoices (InvoiceGrid.cfm) // ---------------------------------------------------------------- invoices (InvoiceGrid.cfm)
export const invoiceStatuses: StatusMeta[] = [ export const invoiceStatuses: StatusMeta[] = [
{ value: 'ACTIVE', label: { en: 'Active', ar: 'فعال' }, color: 'success' },
{ value: 'ARCHIVED', label: { en: 'Archived', ar: 'مؤرشف' }, color: 'default' }, { 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 ?? ''); return m ? `${m[3]}/${m[2]}/${m[1]}` : (s ?? '');
}; };
export const invoiceGrid = (h: { onExport: (r: InvoiceRow, format: 'csv' | 'xlsx') => void }): GridMeta<InvoiceRow> => ({ export const invoiceGrid = (h: {
onExport: (r: InvoiceRow) => void;
onArchive: (r: InvoiceRow) => void;
onActivate: (r: InvoiceRow) => void;
}): GridMeta<InvoiceRow> => ({
key: 'grains.orders.invoices', key: 'grains.orders.invoices',
endpoint: '/grains/orders/invoices', endpoint: '/grains/orders/invoices',
rowKey: (r) => r.id, rowKey: (r) => r.id,
requireFilter: true,
filters: [{ name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم الفاتورة' }, inputKind: 'code' }], filters: [{ name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم الفاتورة' }, inputKind: 'code' }],
columns: [ columns: [
{ key: 'invoiceNumber', header: { en: 'Invoice number', ar: 'رقم الفاتورة' }, ltr: true }, { 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 }, { key: 'statusCode', header: { en: 'Status', ar: 'الحالة' }, format: 'status', statuses: invoiceStatuses },
], ],
rowActions: [ rowActions: [
{ key: 'xlsx', label: { en: 'Print Excel', ar: 'طباعة XLS' }, onClick: (r) => h.onExport(r, 'xlsx') }, // ARCHIVED: export to Excel + activate; ACTIVE: archive (legacy getInvoiceGrid)
{ key: 'csv', label: { en: 'Export CSV', ar: 'تصدير CSV' }, onClick: (r) => h.onExport(r, 'csv') }, { key: 'excel', label: { en: 'Export to Excel', ar: 'تصدير Excel' }, icon: <DownloadIcon fontSize="small" />, hidden: (r) => r.statusCode !== 'ARCHIVED', onClick: h.onExport },
{ key: 'activate', label: { en: 'Activate', ar: 'تفعيل' }, icon: <UnarchiveIcon fontSize="small" />, hidden: (r) => r.statusCode !== 'ARCHIVED', onClick: h.onActivate },
{ key: 'archive', label: { en: 'Archive', ar: 'أرشفة' }, icon: <ArchiveIcon fontSize="small" />, hidden: (r) => r.statusCode !== 'ACTIVE', onClick: h.onArchive },
], ],
}); });
@ -115,44 +131,35 @@ export const weightsForm: FormMeta = {
], ],
}; };
// ---------------------------------------------------------------- financial billing report (FinancialBilling.cfm) // ---------------------------------------------------------------- fines and wages (FinesGrid.cfm / WagesGrid.cfm)
export const financialGrid = (h: { onTotals: (t: FinancialBillingTotals | null) => void }): GridMeta<FinancialBillingRow> => ({ const periodFilters: GridMeta<FineRow>['filters'] = [
key: 'grains.orders.financial', { name: 'startDate', type: 'date', label: { en: 'Start date', ar: 'تاريخ البداية' } },
{ name: 'endDate', type: 'date', label: { en: 'End date', ar: 'تاريخ الإنتهاء' } },
];
export const finesGrid = (): GridMeta<FineRow> => ({
key: 'grains.orders.fines',
endpoint: '/grains/orders/fines',
rowKey: (r) => r.id, rowKey: (r) => r.id,
requireFilter: true, filters: periodFilters,
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;
},
columns: [ columns: [
{ key: 'pn', header: { en: 'Permit no.', ar: 'رقم الارسالية' }, ltr: true }, { key: 'cargoType', header: { en: 'Cargo type', ar: 'نوع الحمولة' } },
{ key: 'serialNo', header: { en: 'Document no.', ar: 'رقم المستند' }, ltr: true, hideBelow: 'md' }, { key: 'startDate', header: { en: 'Start date', ar: 'تاريخ البداية' }, format: 'date', ltr: true, align: 'center' },
{ key: 'loadDate', header: { en: 'Load date', ar: 'تاريخ التحميل' }, ltr: true, hideBelow: 'md' }, { key: 'endDate', header: { en: 'End date', ar: 'تاريخ الإنتهاء' }, format: 'date', ltr: true, align: 'center' },
{ key: 'destination', header: { en: 'To', ar: 'الى' } }, { key: 'fine', header: { en: 'Fine', ar: 'الغرامة' }, format: 'number', align: 'center' },
{ key: 'cargoType', header: { en: 'Cargo', ar: 'نوع المادة' }, hideBelow: 'lg' }, { key: 'allowance', header: { en: 'Allowance', ar: 'نسبة السماح' }, format: 'number', align: 'center' },
{ 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' }, export const wagesGrid = (): GridMeta<WageRow> => ({
{ key: 'difference', header: { en: 'Difference', ar: 'الفرق' }, format: 'number', align: 'end', hideBelow: 'md' }, key: 'grains.orders.wages',
{ key: 'price', header: { en: 'Price', ar: 'السعر' }, format: 'number', align: 'end', hideBelow: 'lg' }, endpoint: '/grains/orders/wages',
{ key: 'finePrice', header: { en: 'Fine price', ar: 'سعر التغريم' }, format: 'number', align: 'end', hideBelow: 'lg' }, rowKey: (r) => r.id,
{ key: 'loseFine', header: { en: 'Shortage fine', ar: 'غرامة النقص' }, format: 'number', align: 'end', hideBelow: 'md' }, filters: periodFilters as unknown as GridMeta<WageRow>['filters'],
{ key: 'demurrageFine', header: { en: 'Demurrage fine', ar: 'غرامة التاخير' }, format: 'number', align: 'end', hideBelow: 'lg' }, columns: [
{ key: 'otherFine', header: { en: 'Other fines', ar: 'غرامات آخرى' }, format: 'number', align: 'end', hideBelow: 'lg' }, { key: 'location', header: { en: 'Location', ar: 'الموقع' } },
{ key: 'finalCost', header: { en: 'Final value', ar: 'القيمة النهائية' }, format: 'number', align: 'end' }, { 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' },
], ],
}); });

View File

@ -1,5 +1,5 @@
import { useEffect, useMemo, useState, type KeyboardEvent } from 'react'; import { useEffect, useMemo, useState, type KeyboardEvent } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { import {
Alert, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, Paper, Stack, Alert, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, Paper, Stack,
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography,
@ -7,6 +7,7 @@ import {
import AddIcon from '@mui/icons-material/Add'; import AddIcon from '@mui/icons-material/Add';
import AssessmentIcon from '@mui/icons-material/Assessment'; import AssessmentIcon from '@mui/icons-material/Assessment';
import DownloadIcon from '@mui/icons-material/Download'; import DownloadIcon from '@mui/icons-material/Download';
import FactCheckIcon from '@mui/icons-material/FactCheck';
import GrainIcon from '@mui/icons-material/Grain'; import GrainIcon from '@mui/icons-material/Grain';
import Inventory2Icon from '@mui/icons-material/Inventory2'; import Inventory2Icon from '@mui/icons-material/Inventory2';
import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import LocalShippingIcon from '@mui/icons-material/LocalShipping';
@ -17,22 +18,23 @@ import { DestinationGroups } from '@/components/DestinationGroups';
import { LoadingBanner } from '@/components/LoadingBanner'; import { LoadingBanner } from '@/components/LoadingBanner';
import { MetaForm } from '@/components/MetaForm'; import { MetaForm } from '@/components/MetaForm';
import { PageHeader } from '@/components/PageHeader'; import { PageHeader } from '@/components/PageHeader';
import { FormCard } from '@/components/FormCard';
import { formatNumber } from '@/components/meta/format'; import { formatNumber } from '@/components/meta/format';
import { useFeatureUi } from '@/i18n/useUi'; import { useFeatureUi } from '@/i18n/useUi';
import { useAuth } from '@/providers/AuthProvider'; import { useAuth } from '@/providers/AuthProvider';
import { useConfirm } from '@/providers/ConfirmProvider'; import { useConfirm } from '@/providers/ConfirmProvider';
import { useToast } from '@/providers/ToastProvider'; import { useToast } from '@/providers/ToastProvider';
import { import {
downloadExport, fetchBillingPermit, fetchPermitWeights, useAddBilling, useCompanies, useCompanyDestinations, downloadExport, fetchBillingPermit, fetchBillingReroute, fetchFinancialBilling, fetchPermitWeights, useActivateInvoice, useAddBilling,
useCreateOrder, useDeleteOrder, useDestinationGroups, usePublishOrder, useSaveCompanyDestinations, useSaveWeights, useArchiveInvoice, useCompanies, useCompanyDestinations, useCreateOrder, useDeleteBilling, useDeleteOrder, useDestinationGroups,
useSetQuota, useTenderOrderReport, useInvoiceNumbers, usePublishOrder, useReroute, useSaveCompanyDestinations, useSaveWeights, useSetQuota, useTenderOrderReport,
} from './api'; } from './api';
import { billingForm, billingGrid, financialGrid, invoiceGrid, weightsForm } from './meta/billing'; import { billingForm, billingGrid, finesGrid, invoiceGrid, wagesGrid, weightsForm } from './meta/billing';
import { import {
quotaGrid, tenderOrderForm, tenderOrderGrid, todayIso, quotaGrid, tenderOrderForm, tenderOrderGrid, todayIso,
} from './meta/orders'; } from './meta/orders';
import strings from './strings'; 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; const INDIVIDUALS_SCAC = 327;
@ -184,10 +186,94 @@ export function QuotasPage() {
} }
// ================================================================= billing // ================================================================= 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<BillingReroute | null>(null);
const [price, setPrice] = useState('');
const [name, setName] = useState('');
const [err, setErr] = useState<string | null>(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) => (
<TextField size="small" label={label} value={v == null ? '' : String(v)} slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }} />
);
const d = (v: string | null) => (v ? v.split('-').reverse().join('/') : '');
return (
<Dialog open onClose={onClose} fullWidth maxWidth="md">
<DialogTitle>{t('ord.billing.reroute.title')}</DialogTitle>
<DialogContent>
{!info ? <LoadingBanner variant="first" /> : (
<Box sx={{ display: 'grid', gap: 2, pt: 1, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))' } }}>
{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)}
<TextField
size="small" label={t('ord.billing.reroute.price')} value={price} autoFocus
onChange={(e) => setPrice(e.target.value.replace(/[^\d.]/g, ''))}
slotProps={{ htmlInput: { inputMode: 'decimal', dir: 'ltr', style: { textAlign: 'start' } } }}
/>
<TextField
size="small" label={t('ord.billing.reroute.name')} value={name}
onChange={(e) => setName(e.target.value)} slotProps={{ htmlInput: { maxLength: 50 } }}
/>
{err && <Alert severity="warning" sx={{ gridColumn: '1 / -1' }}>{err}</Alert>}
</Box>
)}
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t('common.cancel')}</Button>
<Button variant="contained" disabled={!info || save.isPending} onClick={submit}>{t('common.save')}</Button>
</DialogActions>
</Dialog>
);
}
export function BillingListPage() { export function BillingListPage() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
const navigate = useNavigate(); const navigate = useNavigate();
const meta = useMemo(() => billingGrid(), []); const confirm = useConfirm();
const del = useDeleteBilling();
const [rerouteId, setRerouteId] = useState<number | null>(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 ( return (
<> <>
<PageHeader <PageHeader
@ -196,6 +282,7 @@ export function BillingListPage() {
actions={<Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate('/grains/orders/billing/new')}>{t('ord.billing.new')}</Button>} actions={<Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate('/grains/orders/billing/new')}>{t('ord.billing.new')}</Button>}
/> />
<DataGrid meta={meta} /> <DataGrid meta={meta} />
{rerouteId !== null && <RerouteDialog id={rerouteId} onClose={() => setRerouteId(null)} />}
</> </>
); );
} }
@ -319,14 +406,23 @@ export function BillingEntryPage() {
export function InvoicesPage() { export function InvoicesPage() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
const toast = useToast(); const toast = useToast();
const confirm = useConfirm();
const archive = useArchiveInvoice();
const activate = useActivateInvoice();
const meta = useMemo( const meta = useMemo(
() => () =>
invoiceGrid({ invoiceGrid({
onExport: (r: InvoiceRow, format) => onExport: (r: InvoiceRow) =>
downloadExport('/reports/financial-billing/export', { scac: r.scac, invoiceNumber: r.invoiceNumber, format }, `FinancialReport_${r.scac}_${r.invoiceNumber}.${format}`) downloadExport('/reports/financial-billing/excel', { scac: r.scac, invoiceNumber: r.invoiceNumber }, 'FinancialReport.xls')
.catch((e) => toast.error(errText(e, t('ord.export.failed')))), .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 ( return (
<> <>
@ -336,6 +432,29 @@ export function InvoicesPage() {
); );
} }
// ================================================================= fines and wages
export function FinesPage() {
const { t } = useFeatureUi(strings);
const meta = useMemo(() => finesGrid(), []);
return (
<>
<PageHeader title={t('ord.fines.title')} subtitle={t('ord.fines.subtitle')} />
<DataGrid meta={meta} />
</>
);
}
export function WagesPage() {
const { t } = useFeatureUi(strings);
const meta = useMemo(() => wagesGrid(), []);
return (
<>
<PageHeader title={t('ord.wages.title')} subtitle={t('ord.wages.subtitle')} />
<DataGrid meta={meta} />
</>
);
}
// ================================================================= loading weights // ================================================================= loading weights
export function WeightsPage() { export function WeightsPage() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
@ -566,46 +685,114 @@ export function TenderOrderReportPage() {
); );
} }
export function FinancialReportPage() { // ================================================================= invoice check (legacy FinancialRpts.cfm + billingValidation.cfm)
const { t, lang } = useFeatureUi(strings); const pad = (v: number, int: number) => v.toFixed(3).padStart(int + 4, '0');
const toast = useToast();
const [sp] = useSearchParams();
const [totals, setTotals] = useState<FinancialBillingTotals | null>(null);
const meta = useMemo(() => financialGrid({ onTotals: setTotals }), []);
const scac = sp.get('scac') ?? '';
const invoiceNumber = sp.get('invoiceNumber') ?? '';
const n = (v: number) => formatNumber(v, lang);
const exportAs = (format: 'csv' | 'xlsx') => export function InvoiceCheckPage() {
downloadExport('/reports/financial-billing/export', { scac, invoiceNumber, format }, `FinancialReport_${scac}_${invoiceNumber}.${format}`) const { t } = useFeatureUi(strings);
.catch((e) => toast.error(errText(e, t('ord.export.failed')))); const toast = useToast();
const companies = useCompanies();
const [scac, setScac] = useState('');
const [inv, setInv] = useState('');
const invoices = useInvoiceNumbers(scac);
const [rows, setRows] = useState<FinancialBillingRow[] | null>(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 ( return (
<> <>
<PageHeader <PageHeader title={t('ord.check.title')} subtitle={t('ord.check.subtitle')} />
title={t('ord.fin.title')} <Stack spacing={2}>
subtitle={t('ord.fin.subtitle')} <FormCard
actions={ icon={FactCheckIcon} title={t('ord.check.title')} maxWidth={760}
<> actions={<Button variant="contained" startIcon={<SearchIcon />} disabled={!scac || !inv || busy} onClick={() => void search()}>{t('common.search')}</Button>}
<Button variant="outlined" startIcon={<DownloadIcon />} disabled={!scac || !invoiceNumber} onClick={() => void exportAs('csv')}>{t('ord.export.csv')}</Button> >
<Button variant="outlined" startIcon={<DownloadIcon />} disabled={!scac || !invoiceNumber} onClick={() => void exportAs('xlsx')}>{t('ord.export.xlsx')}</Button> <Stack spacing={2}>
</> <TextField
} select fullWidth size="small" label={t('ord.company')} value={scac}
/> onChange={(e) => { setScac(e.target.value); setInv(''); setRows(null); }}
{totals && scac && invoiceNumber && ( slotProps={{ select: { native: true }, inputLabel: { shrink: true } }}
<Paper variant="outlined" sx={{ p: 1.5, mb: 1.5 }}> >
<Stack direction="row" spacing={3} useFlexGap sx={{ flexWrap: 'wrap' }}> <option value="">{companies.isPending ? '...' : t('ord.selectCompany')}</option>
<Typography variant="subtitle2">{t('ord.fin.totals')}</Typography> {(companies.data ?? []).map((c) => <option key={c.scac} value={String(c.scac)}>{c.label}</option>)}
<Typography variant="body2">{lang === 'ar' ? 'الوزن المرسل' : 'Sent'}: <bdi dir="ltr">{n(totals.lnw)}</bdi></Typography> </TextField>
<Typography variant="body2">{lang === 'ar' ? 'الوزن المستلم' : 'Received'}: <bdi dir="ltr">{n(totals.dnw)}</bdi></Typography> <TextField
<Typography variant="body2">{lang === 'ar' ? 'غرامة النقص' : 'Shortage fine'}: <bdi dir="ltr">{n(totals.loseFine)}</bdi></Typography> select fullWidth size="small" label={t('ord.check.invoice')} value={inv} disabled={!scac}
<Typography variant="body2">{lang === 'ar' ? 'غرامة التاخير' : 'Demurrage'}: <bdi dir="ltr">{n(totals.demurrageFine)}</bdi></Typography> onChange={(e) => { setInv(e.target.value); setRows(null); }}
<Typography variant="body2">{lang === 'ar' ? 'غرامات آخرى' : 'Other fines'}: <bdi dir="ltr">{n(totals.otherFine)}</bdi></Typography> slotProps={{ select: { native: true }, inputLabel: { shrink: true } }}
<Typography variant="body2" sx={{ fontWeight: 700 }}>{lang === 'ar' ? 'القيمة النهائية' : 'Final value'}: <bdi dir="ltr">{n(totals.finalCost)}</bdi></Typography> >
<option value="">-----------------</option>
{(invoices.data ?? []).map((n) => <option key={n} value={String(n)}>{n}</option>)}
</TextField>
</Stack> </Stack>
</FormCard>
{busy && <LoadingBanner variant="first" />}
{rows && !busy && (
<Paper variant="outlined" sx={{ overflow: 'hidden' }}>
<TableContainer>
<Table size="small">
<TableHead sx={{ bgcolor: 'action.hover' }}>
<TableRow>
{(['no', 'total', 'fine', 'lnw', 'dnw', 'price', 'center', 'doc', 'truck'] as const).map((k) => (
<TableCell key={k} align="center">{t(`ord.check.${k}`)}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows.length === 0 && <TableRow><TableCell colSpan={9} align="center" sx={{ py: 3, color: 'text.secondary' }}>{t('ord.check.none')}</TableCell></TableRow>}
{rows.map((r, i) => (
<TableRow key={r.id} hover>
<TableCell align="center">{i + 1}</TableCell>
<TableCell align="center" dir="ltr">{pad(r.finalCost, 3)}</TableCell>
<TableCell align="center" dir="ltr">{`${r.cargoType ?? ''} / ${pad(r.loseFine, 2)}`}</TableCell>
<TableCell align="center" dir="ltr">{r.lnw}</TableCell>
<TableCell align="center" dir="ltr">{r.dnw}</TableCell>
<TableCell align="center" dir="ltr">{pad(r.price, 3)}</TableCell>
<TableCell align="center">{r.destination}</TableCell>
<TableCell align="center" dir="ltr">{r.serialNo}</TableCell>
<TableCell align="center" dir="ltr">{r.tn}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
{rows.length > 0 && (
<Stack direction="row" useFlexGap spacing={3} sx={{ flexWrap: 'wrap', p: 2, borderTop: 1, borderColor: 'divider', bgcolor: 'action.hover' }}>
{([
['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]) => (
<Typography key={k} variant="body2"><b>{t(k)}</b>{': '}<bdi dir="ltr">{Number.isInteger(v) ? v : Number(v.toFixed(3))}</bdi></Typography>
))}
</Stack>
)}
</Paper> </Paper>
)} )}
<DataGrid meta={meta} /> </Stack>
</> </>
); );
} }

View File

@ -1,6 +1,9 @@
import type { RouteObject } from 'react-router-dom'; import type { RouteObject } from 'react-router-dom';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance'; import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import BusinessIcon from '@mui/icons-material/Business'; 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 LocalShippingIcon from '@mui/icons-material/LocalShipping';
import ListAltIcon from '@mui/icons-material/ListAlt'; import ListAltIcon from '@mui/icons-material/ListAlt';
import PercentIcon from '@mui/icons-material/Percent'; 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 ScaleIcon from '@mui/icons-material/Scale';
import type { MenuItem } from '@/shell/types'; import type { MenuItem } from '@/shell/types';
import { import {
BillingEntryPage, BillingListPage, CompanyDestinationsPage, FinancialReportPage, InvoicesPage, QuotasPage, BillingEntryPage, BillingListPage, CompanyDestinationsPage, FinesPage, InvoiceCheckPage, InvoicesPage, QuotasPage,
TenderOrderCreatePage, TenderOrderReportPage, TenderOrdersPage, WeightsPage, TenderOrderCreatePage, TenderOrderReportPage, TenderOrdersPage, WagesPage, WeightsPage,
} from './pages'; } from './pages';
import strings from './strings'; import strings from './strings';
import permitStrings from '../grains-permits/strings'; import permitStrings from '../grains-permits/strings';
@ -27,10 +30,12 @@ export const routes: RouteObject[] = [
{ path: '/grains/orders/billing', element: <BillingListPage /> }, { path: '/grains/orders/billing', element: <BillingListPage /> },
{ path: '/grains/orders/billing/new', element: <BillingEntryPage />, handle: { crumb: strings['ord.crumb.new'] } }, { path: '/grains/orders/billing/new', element: <BillingEntryPage />, handle: { crumb: strings['ord.crumb.new'] } },
{ path: '/grains/orders/invoices', element: <InvoicesPage /> }, { path: '/grains/orders/invoices', element: <InvoicesPage /> },
{ path: '/grains/orders/fines', element: <FinesPage /> },
{ path: '/grains/orders/wages', element: <WagesPage /> },
{ path: '/grains/orders/weights', element: <WeightsPage /> }, { path: '/grains/orders/weights', element: <WeightsPage /> },
{ path: '/grains/orders/company-destinations', element: <CompanyDestinationsPage /> }, { path: '/grains/orders/company-destinations', element: <CompanyDestinationsPage /> },
{ path: '/grains/orders/reports/tender-orders', element: <TenderOrderReportPage /> }, { path: '/grains/orders/reports/tender-orders', element: <TenderOrderReportPage /> },
{ path: '/grains/orders/reports/financial-billing', element: <FinancialReportPage /> }, { path: '/grains/orders/invoice-check', element: <InvoiceCheckPage /> },
]; ];
export const menu: MenuItem[] = [ export const menu: MenuItem[] = [
@ -52,6 +57,9 @@ export const menu: MenuItem[] = [
icon: AccountBalanceIcon, icon: AccountBalanceIcon,
children: [ children: [
{ key: 'grains.orders.billing', title: strings['ord.menu.billing'], icon: RequestQuoteIcon, path: '/grains/orders/billing', createPath: '/grains/orders/billing/new' }, { 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' }, { key: 'grains.orders.invoices', title: strings['ord.menu.invoices'], icon: ReceiptIcon, path: '/grains/orders/invoices' },
], ],
}, },

View File

@ -9,6 +9,9 @@ export default defineStrings({
'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' }, 'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' },
'ord.menu.billing': { en: 'Billing claims', ar: 'المطالبات المالية' }, 'ord.menu.billing': { en: 'Billing claims', ar: 'المطالبات المالية' },
'ord.menu.invoices': { en: 'Invoices', 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.weights': { en: 'Loading weights', ar: 'تثبيت أوزان التحميل' },
'ord.menu.companyDest': { en: 'Company destinations', ar: 'وجهات الشركات' }, 'ord.menu.companyDest': { en: 'Company destinations', ar: 'وجهات الشركات' },
'ord.menu.reportOrders': { en: 'Orders report', 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.notLoaded': { en: 'Load a permit first.', ar: 'الرجاء تحميل الارسالية أولاً.' },
'ord.billing.saveConfirm': { en: 'Save this billing claim?', 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 // ---- invoices
'ord.invoices.title': { en: 'Supply invoices', ar: 'شاشة فواتير التموين' }, 'ord.invoices.title': { en: 'Supply invoices', ar: 'شاشة فواتير التموين' },
'ord.invoices.subtitle': { en: 'Invoices grouped by company and invoice number', ar: 'الفواتير حسب الشركة ورقم الفاتورة' }, 'ord.invoices.subtitle': { en: 'Invoices grouped by company and invoice number', ar: 'الفواتير حسب الشركة ورقم الفاتورة' },

View File

@ -55,6 +55,28 @@ export interface BillingPermit {
lastInvoice: number | null; lastInvoice: number | null;
price: number | null; price: number | null;
finePrice: 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 { export interface BillingRow {
@ -157,3 +179,20 @@ export interface FinancialBillingPage {
totalCount: number; totalCount: number;
totals: FinancialBillingTotals; 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;
}

View File

@ -510,7 +510,6 @@ function TableReportBody({ meta }: { meta: TableReportMeta }) {
} }
/> />
<Stack spacing={1.5} sx={{ mb: 1.5 }}> <Stack spacing={1.5} sx={{ mb: 1.5 }}>
{meta.inferred && <Alert severity="info">{t('rpt.t.inferredNote')}</Alert>}
{meta.defaults === 'yesterday' && <Alert severity="info">{t('rpt.f.yesterdayNote')}</Alert>} {meta.defaults === 'yesterday' && <Alert severity="info">{t('rpt.f.yesterdayNote')}</Alert>}
{missing.length > 0 && ( {missing.length > 0 && (
<Alert severity="warning"> <Alert severity="warning">

View File

@ -13,7 +13,6 @@ import {
} from './pages'; } from './pages';
import { tableReports } from './meta'; import { tableReports } from './meta';
import strings from './strings'; import strings from './strings';
import orderStrings from '../grains-orders/strings';
const B = '/grains/reports'; const B = '/grains/reports';
@ -51,8 +50,6 @@ export const menu: MenuItem[] = [
table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'), table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'),
table('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'), table('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'),
table('companies-turn'), table('owners-turn'), 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'), table('drivers'), table('trucks'),
{ key: 'grains.reports.motMulti', title: strings['rpt.menu.motMulti'], icon: BarChartIcon, path: `${B}/mot/multi-trips` }, { key: 'grains.reports.motMulti', title: strings['rpt.menu.motMulti'], icon: BarChartIcon, path: `${B}/mot/multi-trips` },
table('mot-grain-cube'), table('mot-grain-frequency'), table('mot-grain-cube'), table('mot-grain-frequency'),

View File

@ -127,7 +127,6 @@ export default defineStrings({
'rpt.t.trucks': { en: 'Registered trucks', ar: 'تقرير القاطرات المسجلة' }, 'rpt.t.trucks': { en: 'Registered trucks', ar: 'تقرير القاطرات المسجلة' },
'rpt.t.mot-grain-cube': { en: 'Grain cube (MOT)', ar: 'مكعب الحبوب (وزارة النقل)' }, 'rpt.t.mot-grain-cube': { en: 'Grain cube (MOT)', ar: 'مكعب الحبوب (وزارة النقل)' },
'rpt.t.mot-grain-frequency': { en: 'Grain trip frequency (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.shortageTotal': { en: 'Total shortage', ar: 'إجمالي العجز' },
'rpt.t.individuals': { en: 'Individuals', ar: 'أفراد' }, 'rpt.t.individuals': { en: 'Individuals', ar: 'أفراد' },
'rpt.t.companies': { en: 'Companies', ar: 'شركات' }, 'rpt.t.companies': { en: 'Companies', ar: 'شركات' },