From 21328b7d1a2c18fcf925c7971914168b1f73a896 Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Thu, 12 Nov 2026 11:18:04 +0300 Subject: [PATCH] Grains: menu reorganisation, DB-driven permissions, form/grid polish - Create-permit and register-turn become DB authorities (grains.permits.create, grains.orders.supply) - Reorganise menus (permits, orders, finance, flat reports) and fix sidebar expand/collapse - Company destinations grouped by cargo type; weighbridge screen reduced to manual weighing - Hide absence toggle; remove PDF actions from reports; loading-weights uses literal dates - FormCard/SectionTitle components, framed DataGrid with row hover - DB scripts: menu-reorganisation, permits-create-permission, disabled-features, events perf notes Co-Authored-By: Claude Sonnet 5.5 --- db/disabled-features.sql | 28 + db/events-report-performance.sql | 22 + db/grains-screen-permissions.sql | 7 +- db/menu-reorganisation.sql | 31 + db/permits-create-permission.sql | 16 + docs/ENVIRONMENTS.md | 8 + .../Controllers/V1/Grains/OrdersController.cs | 4 + .../V1/Grains/PermitsController.cs | 34 +- .../V1/Grains/RegistryController.cs | 20 +- .../Access/PermissionDefaults.cs | 9 +- .../Access/PermissionService.cs | 31 +- .../Grains/Orders/OrdersContracts.cs | 3 + .../Grains/Orders/OrdersRepositories.cs | 3 + .../Grains/Orders/TenderOrderService.cs | 5 + .../Orders/WeightsAndDestinationsService.cs | 6 +- .../Grains/Permits/PermitService.cs | 4 +- .../Grains/Permits/PermitSupport.cs | 3 + .../Grains/Orders/OrderLookupRepository.cs | 7 + .../Grains/Reports/ReportsRepository.cs | 12 +- tests/NTP.Tests/OracleCredentialGuardTests.cs | 4 +- tests/NTP.Tests/PermissionTests.cs | 56 +- tests/NTP.Tests/PermitsRulesTests.cs | 14 + web/src/api/auth.ts | 4 +- web/src/api/mock.ts | 2 +- web/src/components/DataGrid/DataGrid.tsx | 7 +- web/src/components/DestinationGroups.tsx | 65 +++ web/src/components/FormCard.tsx | 40 ++ web/src/components/SectionTitle.tsx | 15 + web/src/features/grains-orders/api.ts | 8 +- web/src/features/grains-orders/pages.tsx | 39 +- web/src/features/grains-orders/routes.tsx | 18 +- web/src/features/grains-orders/strings.ts | 12 +- web/src/features/grains-orders/types.ts | 2 + .../features/grains-permits/meta/permits.tsx | 21 +- web/src/features/grains-permits/pages.tsx | 549 +++++++++++------- web/src/features/grains-permits/routes.tsx | 17 +- web/src/features/grains-permits/strings.ts | 56 +- web/src/features/grains-registry/routes.tsx | 2 - web/src/features/grains-reports/pages.tsx | 10 +- web/src/features/grains-reports/routes.tsx | 63 +- web/src/providers/AuthProvider.tsx | 2 +- web/src/shell/Sidebar.tsx | 55 +- web/src/shell/menuUtils.ts | 2 +- 43 files changed, 885 insertions(+), 431 deletions(-) create mode 100644 db/disabled-features.sql create mode 100644 db/events-report-performance.sql create mode 100644 db/menu-reorganisation.sql create mode 100644 db/permits-create-permission.sql create mode 100644 web/src/components/DestinationGroups.tsx create mode 100644 web/src/components/FormCard.tsx create mode 100644 web/src/components/SectionTitle.tsx diff --git a/db/disabled-features.sql b/db/disabled-features.sql new file mode 100644 index 0000000..39c1c22 --- /dev/null +++ b/db/disabled-features.sql @@ -0,0 +1,28 @@ +-- Features switched OFF for EVERYBODY, SU included (NAFITHTCS schema). Run once on a database where GRAINS_SCREEN_PERMISSIONS exists. +-- Safe to re-run: a row is only inserted when it is not there yet. Not executed by the application. +-- +-- A row with ROLECODE = 'DISABLED' takes the resource out of the system for all users: its menu entry and buttons disappear and +-- the API answers 403 for it. It overrides every other row and the SU rule. To bring a feature back, DELETE its row; the change +-- reaches the API within about a minute and a user's browser on the next page reload or sign-in. +-- +-- grains.permits.absence إيقاف/تفعيل الاستنكاف (stop / activate the absence feature) +-- grains.permits.activation تفعيل الطلبية (order activation screen) + +INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) +SELECT 'DISABLED', v.resource_key + FROM ( + SELECT 'grains.permits.absence' AS resource_key FROM dual UNION ALL + SELECT 'grains.permits.activation' FROM dual + ) v + WHERE NOT EXISTS ( + SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p + WHERE p.rolecode = 'DISABLED' AND p.resource_key = v.resource_key); + +COMMIT; + +-- Check (expect 2 rows): +-- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'DISABLED' ORDER BY 2; +-- +-- Bring one back: +-- DELETE FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'DISABLED' AND resource_key = 'grains.permits.absence'; +-- COMMIT; diff --git a/db/events-report-performance.sql b/db/events-report-performance.sql new file mode 100644 index 0000000..80389ed --- /dev/null +++ b/db/events-report-performance.sql @@ -0,0 +1,22 @@ +-- تقرير أوزان التحميل (loading-weights) and the other reports that filter EVENTS by type and date time out on QA: +-- a ONE-DAY range already exceeds the 30 s command timeout, so the cost does not depend on the date range. That points to +-- a full scan of EVENTS because no index serves "EVENTTYPE IN (...) AND EVENTDATE >= :from AND EVENTDATE < :to + 1". +-- NOT executed by the application and NOT verified: the DBA decides after looking at the existing indexes and the plan. +-- +-- Step 1 - what indexes EVENTS already has, and how big it is +-- SELECT index_name, column_position, column_name FROM all_ind_columns WHERE table_name = 'EVENTS' ORDER BY index_name, column_position; +-- SELECT num_rows, last_analyzed FROM all_tables WHERE table_name = 'EVENTS'; +-- +-- Step 2 - plan of the report query (replace the dates) +-- EXPLAIN PLAN FOR +-- select p.pn, max(decode(e.eventtype, 'LTW', to_number(e.weight))), min(e.eventdate) +-- from permits p, events e +-- where p.domain = 'GN' and e.permitid = p.id and e.eventtype in ('LTW', 'LGW', 'LNW') +-- and e.eventdate >= DATE '2026-11-10' and e.eventdate < DATE '2026-11-10' + 1 +-- group by p.id, p.pn; +-- SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY); +-- +-- Step 3 - if EVENTS has no index starting with EVENTDATE / EVENTTYPE, this one is the candidate +-- (EVENTDATE second keeps date-range scans cheap for each of the few event types): +-- CREATE INDEX EVENTS_TYPE_DATE_IX ON EVENTS (EVENTTYPE, EVENTDATE); +-- EXEC DBMS_STATS.GATHER_INDEX_STATS(USER, 'EVENTS_TYPE_DATE_IX'); diff --git a/db/grains-screen-permissions.sql b/db/grains-screen-permissions.sql index 7eee46b..bed04d1 100644 --- a/db/grains-screen-permissions.sql +++ b/db/grains-screen-permissions.sql @@ -63,15 +63,14 @@ INSERT ALL INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.manualEntry') -- إيقاف\تفعيل الاستنكاف INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.absence') + -- طلبية التموين (orders menu) + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.orders.supply') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.orders.supply') -- تثبيت أوزان التحميل INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.orders.weights') -- تقارير حركات قبان التحميل والتفريغ INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.weighbridge-events') INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.weighbridge-events') - INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.waybridge-summary') - INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.waybridge-summary') - INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.waybridge-details') - INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.waybridge-details') -- تقرير دور الشركات INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.companies-turn') INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.companies-turn') diff --git a/db/menu-reorganisation.sql b/db/menu-reorganisation.sql new file mode 100644 index 0000000..11862ce --- /dev/null +++ b/db/menu-reorganisation.sql @@ -0,0 +1,31 @@ +-- Menu reorganisation (run on a database where GRAINS_SCREEN_PERMISSIONS already exists; safe to re-run; not run by the app). +-- 1. New screen "طلبية التموين" (grains.orders.supply, orders menu): granted to GTO and GOO (it replaces the old pivot table +-- that lived inside توزيع الطلبيات, which used grains.permits.distribution). +-- 2. GOO loses the weighbridge control screen (ضبط الميزان, grains.registry.weighbridge) if it was ever granted. +-- 3. GOO keeps only two reports: حركات قبان التحميل والتفريغ (weighbridge-events) and دور الشركات (companies-turn). +-- GOO rows of the two other weighbridge reports (waybridge-summary, waybridge-details) are removed. +-- 4. GTO keeps only five reports: weighbridge-events, companies-turn, owners-turn, loading-weights, closed-permits +-- (its waybridge-summary / waybridge-details rows are removed; GTO keeps the القبّان screen). +-- Take any right away by deleting its row; the API applies it within about a minute, the browser on the next reload / sign-in. + +INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) +SELECT v.rolecode, v.resource_key + FROM (SELECT 'GTO' AS rolecode, 'grains.orders.supply' AS resource_key FROM dual UNION ALL + SELECT 'GOO', 'grains.orders.supply' FROM dual UNION ALL + SELECT 'GOO', 'grains.reports.t.weighbridge-events' FROM dual UNION ALL + SELECT 'GOO', 'grains.reports.t.companies-turn' 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); + +DELETE FROM GRAINS_SCREEN_PERMISSIONS + WHERE rolecode = 'GOO' + AND resource_key IN ('grains.registry.weighbridge', 'grains.permits.weighbridge', + 'grains.reports.t.waybridge-summary', 'grains.reports.t.waybridge-details'); + +DELETE FROM GRAINS_SCREEN_PERMISSIONS + WHERE rolecode = 'GTO' + AND resource_key IN ('grains.reports.t.waybridge-summary', 'grains.reports.t.waybridge-details'); + +COMMIT; + +-- Check: GOO should have these report rows only +-- SELECT resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'GOO' AND resource_key LIKE 'grains.reports.%' ORDER BY 1; diff --git a/db/permits-create-permission.sql b/db/permits-create-permission.sql new file mode 100644 index 0000000..bac520c --- /dev/null +++ b/db/permits-create-permission.sql @@ -0,0 +1,16 @@ +-- Right to REGISTER A TURN (تسجيل دور) from the permits list (ارساليات التموين): action key grains.permits.create. +-- Run on a database where GRAINS_SCREEN_PERMISSIONS already exists. Safe to re-run. Not executed by the application. +-- SU is never stored: it always has every right. Granted here: GOO. Add a row per role to grant it to more roles; delete the +-- row to take it away (the API applies it within about a minute, the user's browser on the next reload or sign-in). + +INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) +SELECT v.rolecode, v.resource_key + FROM (SELECT 'GOO' AS rolecode, 'grains.permits.create' AS resource_key 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 1 row): +-- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE resource_key = 'grains.permits.create'; diff --git a/docs/ENVIRONMENTS.md b/docs/ENVIRONMENTS.md index 158e99d..32fb805 100644 --- a/docs/ENVIRONMENTS.md +++ b/docs/ENVIRONMENTS.md @@ -49,6 +49,14 @@ Apply these scripts once per database (not run by the application), in this orde 1. `db/grains-screen-permissions.sql` - role to screen/action permissions (`GRAINS_SCREEN_PERMISSIONS`) 2. `db/registry-create-permissions.sql` - add / edit rights of trucks, trailers and drivers (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) +5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run) + +**Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU +included: the menu entry and buttons disappear and the API answers 403. It overrides every other row. Delete the row to bring the +feature back. Currently disabled by `db/disabled-features.sql`: `grains.permits.absence` (إيقاف/تفعيل الاستنكاف) and +`grains.permits.activation` (تفعيل الطلبية). Roles and their rights live in that table (SU always has everything). Changing a row takes effect within about a minute on the API and on the user's next page reload or sign-in. diff --git a/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs b/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs index d5ce3cc..54475b5 100644 --- a/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs +++ b/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs @@ -62,6 +62,10 @@ public sealed class OrdersController( [RequirePermission(PermissionKeys.OrdersCompanyDest)] public Task> PackedDestinations(CancellationToken ct) => lookups.PackedDestinationsAsync(ct); + [HttpGet("lookups/destination-groups")] + [RequirePermission(PermissionKeys.OrdersCompanyDest)] + public Task DestinationGroups(CancellationToken ct) => lookups.DestinationGroupsAsync(ct); + [HttpGet("lookups/companies")] [RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersReportFinance)] public Task> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct); diff --git a/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs b/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs index de9fdff..67f234d 100644 --- a/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs +++ b/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs @@ -144,59 +144,59 @@ public sealed class PermitQueueController(IQueueService queue) : ControllerBase { /// getGNQueueList (queueGrid.cfm). [HttpGet] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task> List([FromQuery] string? tn, [FromQuery] string? pn, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => queue.ListAsync(new QueueSearchQuery(tn, pn), new PageRequest(page, pageSize), ct); /// AddToQueue (CreateQueue.cfm). [HttpPost] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task Add(AddToQueueRequest request, CancellationToken ct) => queue.AddToQueueAsync(request, ct); [HttpGet("trailer-of/{tn}")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public async Task> TrailerOf(string tn, CancellationToken ct) => new { trailer = await queue.GetTrailerNumberAsync(tn, ct) }; /// checkTrucks. [HttpPost("check-trucks")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task CheckTrucks([FromQuery] long tn, [FromQuery] long scac, CancellationToken ct) => queue.CheckTrucksAsync(tn, scac, ct); /// parseGrainsPermits job, on demand: create OPEN permits for the given companies. [HttpPost("seed")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task Seed(SeedPermitsRequest request, CancellationToken ct) => queue.SeedPermitsAsync(request, ct); // ---- TCS permit form (createPermit.cfm) [HttpGet("{id:long}/tcs-form")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task TcsForm(long id, CancellationToken ct) => queue.GetTcsFormDataAsync(id, ct); [HttpGet("tcs/routing-templates")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task> RoutingTemplates([FromQuery] long origin, [FromQuery] long destination, [FromQuery] string shipmentMode, [FromQuery] string firms, CancellationToken ct) => queue.GetRoutingTemplatesAsync(origin, destination, shipmentMode, firms, ct); [HttpGet("tcs/origins")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task> Origins([FromQuery] long routing, CancellationToken ct) => queue.GetOriginAddressesAsync(routing, ct); [HttpGet("tcs/ph-routes")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task> PhRoutes(CancellationToken ct) => queue.GetPhRoutesAsync(ct); [HttpGet("tcs/clearing-agent/{can:long}")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public async Task> ClearingAgent(long can, CancellationToken ct) => new { name = await queue.GetClearingAgentNameAsync(can, ct) }; [HttpGet("tcs/fop/{fop}")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task Fop(string fop, CancellationToken ct) => queue.GetFopDetailAsync(fop, ct); [HttpPost("{id:long}/tcs-permit")] - [RequirePermission(PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsCreate)] public Task CreateTcsPermit(long id, CreateTcsPermitRequest request, CancellationToken ct) => queue.CreateTcsPermitAsync(id, request, ct); } @@ -209,7 +209,7 @@ public sealed class PermitQueueController(IQueueService queue) : ControllerBase public sealed class PermitDestinationsController(IDestinationService destinations) : ControllerBase { [HttpGet("lookups/locations")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsCreate)] public Task> Locations(CancellationToken ct) => destinations.GetGrainsLocationsAsync(ct); /// Destination filter of the permit list (GNPermits.cfm): every GN exit location by name, active or not. @@ -218,11 +218,11 @@ public sealed class PermitDestinationsController(IDestinationService destination public Task> FilterDestinations(CancellationToken ct) => destinations.GetPermitFilterDestinationsAsync(ct); [HttpGet("lookups/exit-locations")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsCreate)] public Task> ExitLocations(CancellationToken ct) => destinations.GetExitLocationsAsync(ct); [HttpGet("lookups/cargo-types")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsCreate)] public Task> CargoTypes(CancellationToken ct) => destinations.GetCargoTypesAsync(ct); [HttpGet("lookups/location-groups")] @@ -230,7 +230,7 @@ public sealed class PermitDestinationsController(IDestinationService destination public Task LocationGroups(CancellationToken ct) => destinations.GetLocationGroupsAsync(ct); [HttpGet("lookups/companies")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsCreate)] public Task> Companies(CancellationToken ct) => destinations.GetCompaniesAsync(ct); [HttpGet("companies/{scac:long}")] @@ -328,7 +328,7 @@ public sealed class PermitDistributionController(IDistributionService distributi public Task> Summary(CancellationToken ct) => distribution.GetSummaryAsync(ct); [HttpGet("pivot")] - [RequirePermission(PermissionKeys.PermitsDistribution)] + [RequirePermission(PermissionKeys.PermitsDistribution, PermissionKeys.OrdersSupply)] public Task> Pivot(CancellationToken ct) => distribution.GetPivotAsync(ct); [HttpGet("search-truck")] diff --git a/src/NTP.Api/Controllers/V1/Grains/RegistryController.cs b/src/NTP.Api/Controllers/V1/Grains/RegistryController.cs index 96c30dd..bd931f9 100644 --- a/src/NTP.Api/Controllers/V1/Grains/RegistryController.cs +++ b/src/NTP.Api/Controllers/V1/Grains/RegistryController.cs @@ -194,57 +194,57 @@ public sealed class RegistryController( /// checkTrucks: every company must use its whole fleet before reusing a truck. [HttpPost("fleet-check")] - [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.PermitsQueue)] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.PermitsCreate)] public Task FleetCheck(FleetCheckRequest request, CancellationToken ct) => ops.CheckTrucksAsync(request, ct); /// validateNtpTrucks. [HttpGet("validate-truck")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public async Task ValidateTruck([FromQuery] string tn, CancellationToken ct) => new { validTn = await ops.ValidateNtpTruckAsync(tn ?? string.Empty, ct) }; // ------------------------------------------------------------------------------------------ permit-screen lookups (grains.cfc) /// grains.cfc getDriverInfo: latest permit of the driver (active status). [HttpGet("permit-lookups/driver")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public Task DriverFromPermits([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverFromPermitsAsync(nnpn ?? string.Empty, ct); /// grains.cfc getTruckInfo: latest finished permit of the truck. [HttpGet("permit-lookups/truck")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public Task TruckFromPermits([FromQuery] string tn, CancellationToken ct) => lookups.TruckFromPermitsAsync(tn ?? string.Empty, ct); /// grains.cfc isTrailerInUse. [HttpGet("permit-lookups/trailer-in-use")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public Task> TrailerInUse([FromQuery] string trn, [FromQuery] long? permitId, CancellationToken ct) => lookups.TrailerInUseAsync(trn ?? string.Empty, permitId, ct); /// grains.cfc getTruckInfoFromTN. [HttpGet("permit-lookups/permit-by-truck")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public Task PermitByTruck([FromQuery] string tn, [FromQuery] string status, CancellationToken ct) => lookups.PermitByTruckAsync(tn ?? string.Empty, status ?? string.Empty, ct); /// grains.cfc getTrailerNumber: the trailer of a truck. [HttpGet("permit-lookups/truck-trailer")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public Task TruckTrailer([FromQuery] string tn, CancellationToken ct) => lookups.TrailerNumberOfTruckAsync(tn ?? string.Empty, ct); /// grains.cfc getTNinfo (validate = ownership + MOT checks). [HttpGet("permit-lookups/truck-info")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public Task TruckInfo([FromQuery] string tn, [FromQuery] bool validate = true, CancellationToken ct = default) => lookups.TruckInfoAsync(tn ?? string.Empty, validate, ct); /// grains.cfc getTRNinfo. [HttpGet("permit-lookups/trailer-info")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public Task TrailerInfo([FromQuery] string trn, CancellationToken ct) => lookups.TrailerInfoAsync(trn ?? string.Empty, ct); /// grains.cfc getDRVRinfo. [HttpGet("permit-lookups/driver-info")] - [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsCreate, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] public Task DriverInfo([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverInfoAsync(nnpn ?? string.Empty, ct); // ------------------------------------------------------------------------------------------ MOT (register.cfc validate*) diff --git a/src/NTP.Application/Access/PermissionDefaults.cs b/src/NTP.Application/Access/PermissionDefaults.cs index 8df346d..498689c 100644 --- a/src/NTP.Application/Access/PermissionDefaults.cs +++ b/src/NTP.Application/Access/PermissionDefaults.cs @@ -14,12 +14,14 @@ public static class PermissionKeys public const string OrdersBilling = "grains.orders.billing"; public const string OrdersInvoices = "grains.orders.invoices"; public const string OrdersWeights = "grains.orders.weights"; + /// طلبية التموين: distributed permits per destination type (orders menu). + public const string OrdersSupply = "grains.orders.supply"; public const string OrdersCompanyDest = "grains.orders.companyDest"; public const string OrdersReportOrders = "grains.orders.reportOrders"; public const string OrdersReportFinance = "grains.orders.reportFinance"; public const string PermitsList = "grains.permits.list"; - public const string PermitsQueue = "grains.permits.queue"; + public const string PermitsCreate = "grains.permits.create"; public const string PermitsDestinations = "grains.permits.destinations"; public const string PermitsDistribution = "grains.permits.distribution"; public const string PermitsWeighbridge = "grains.permits.weighbridge"; @@ -85,15 +87,14 @@ public static class PermissionDefaults [PermissionKeys.PermitsTruckOrder] = ["GTO"], // طلبية لسيارة [PermissionKeys.RegistryBlacklist] = ["GTO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار [PermissionKeys.PermitsDistribution] = ["GTO", "GOO"], // طلبية التموين + [PermissionKeys.OrdersSupply] = ["GTO", "GOO"], // طلبية التموين (orders menu) [PermissionKeys.PermitsTruckStatus] = ["GTO", "GOO"], // استعلام عن حالة التوزيع لسيارة [PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية [PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي [PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف [PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل [PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ - [PermissionKeys.ReportTable("waybridge-summary")] = ["GTO", "GOO"], - [PermissionKeys.ReportTable("waybridge-details")] = ["GTO", "GOO"], - [PermissionKeys.ReportTable("companies-turn")] = ["GTO", "GOO"], // تقرير دور الشركات + [PermissionKeys.ReportTable("companies-turn")] = ["GTO", "GOO"], // تقرير دور الشركات [PermissionKeys.ReportTable("owners-turn")] = ["GTO"], // تقرير دور الأفراد [PermissionKeys.ReportTable("loading-weights")] = ["GTO"], // تقرير أوزان التحميل [PermissionKeys.ReportTable("closed-permits")] = ["GTO"], // الارساليات المكتملة diff --git a/src/NTP.Application/Access/PermissionService.cs b/src/NTP.Application/Access/PermissionService.cs index 0e75e0b..56767c5 100644 --- a/src/NTP.Application/Access/PermissionService.cs +++ b/src/NTP.Application/Access/PermissionService.cs @@ -7,7 +7,8 @@ namespace NTP.Application.Access; /// Caller's role code. /// True for SU: everything is allowed, is then empty. /// Allowed resource keys (see ), e.g. grains.orders.list. -public sealed record PermissionsDto(string RoleCode, bool All, IReadOnlyList Allowed); +/// Resources switched OFF for everybody (rows with role code DISABLED), SU included. Overrides . +public sealed record PermissionsDto(string RoleCode, bool All, IReadOnlyList Allowed, IReadOnlyList Denied); public interface IPermissionRepository { @@ -27,9 +28,15 @@ public interface IPermissionService Task IsAllowedAsync(string resourceKey, CancellationToken ct = default); } -/// Role -> allowed resource keys. SU is always allowed everything; any other role is allow-listed. +/// +/// Role -> allowed resource keys. SU is allowed everything; any other role is allow-listed. A resource that has a row with the +/// role code is switched off for EVERYBODY, SU included (a feature taken out of the system from the +/// database without a deployment). +/// public sealed class PermissionService(IPermissionRepository repository, ICurrentUser user) : IPermissionService { + /// Pseudo role code in GRAINS_SCREEN_PERMISSIONS: its rows are resources disabled for all users. + public const string DisabledRole = "DISABLED"; private const string SuperUser = "SU"; private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(60); private static readonly ConcurrentDictionary Keys)> Cache = new(StringComparer.OrdinalIgnoreCase); @@ -37,19 +44,35 @@ public sealed class PermissionService(IPermissionRepository repository, ICurrent public async Task GetForCurrentUserAsync(CancellationToken ct = default) { var role = user.RoleCode ?? string.Empty; - if (IsSuper(role)) return new PermissionsDto(role, true, []); + var denied = await DeniedAsync(ct); + var deniedList = denied.OrderBy(k => k, StringComparer.Ordinal).ToList(); + if (IsSuper(role)) return new PermissionsDto(role, true, [], deniedList); var keys = await KeysAsync(role, ct); - return new PermissionsDto(role, false, keys.OrderBy(k => k, StringComparer.Ordinal).ToList()); + return new PermissionsDto(role, false, keys.Where(k => !denied.Contains(k)).OrderBy(k => k, StringComparer.Ordinal).ToList(), deniedList); } public async Task IsAllowedAsync(string resourceKey, CancellationToken ct = default) { var role = user.RoleCode ?? string.Empty; + if ((await DeniedAsync(ct)).Contains(resourceKey)) return false; // switched off for everybody, SU included if (IsSuper(role)) return true; if (!user.IsAuthenticated) return false; return (await KeysAsync(role, ct)).Contains(resourceKey); } + /// Resources disabled for all users. No built-in defaults: while the table is missing nothing is disabled. + private async Task> DeniedAsync(CancellationToken ct) + { + if (Cache.TryGetValue(DisabledRole, out var hit) && hit.ExpiresUtc > DateTime.UtcNow) return hit.Keys; + var fromDb = await repository.GetAllowedAsync(DisabledRole, ct); + var keys = new HashSet(fromDb ?? [], StringComparer.OrdinalIgnoreCase); + Cache[DisabledRole] = (DateTime.UtcNow + CacheTtl, keys); + return keys; + } + + /// For tests: forget every cached role (the cache is static, shared by all requests). + public static void ResetCache() => Cache.Clear(); + private static bool IsSuper(string role) => string.Equals(role, SuperUser, StringComparison.OrdinalIgnoreCase); private async Task> KeysAsync(string role, CancellationToken ct) diff --git a/src/NTP.Application/Grains/Orders/OrdersContracts.cs b/src/NTP.Application/Grains/Orders/OrdersContracts.cs index 4dd6108..d8149ff 100644 --- a/src/NTP.Application/Grains/Orders/OrdersContracts.cs +++ b/src/NTP.Application/Grains/Orders/OrdersContracts.cs @@ -183,6 +183,9 @@ public sealed record PermitWeightsDto( public sealed record SaveWeightsRequest(long Pn, string EmptyWeight, string GrossWeight, string DocumentNumber); // ---------------------------------------------------------------- company destinations (compdest.cfm) +/// Destinations a company can be linked to, by kind: packed (مشول), bulk (سائب) and bulk tipper (سائب قلاب). +public sealed record DestinationGroupsDto(IReadOnlyList Packed, IReadOnlyList Bulk, IReadOnlyList BulkGallab); + public sealed record CompanyDestinationsDto(long Scac, IReadOnlyList LocationIds); public sealed record SaveCompanyDestinationsRequest(IReadOnlyList LocationIds); diff --git a/src/NTP.Application/Grains/Orders/OrdersRepositories.cs b/src/NTP.Application/Grains/Orders/OrdersRepositories.cs index c38772f..d5106e5 100644 --- a/src/NTP.Application/Grains/Orders/OrdersRepositories.cs +++ b/src/NTP.Application/Grains/Orders/OrdersRepositories.cs @@ -35,6 +35,9 @@ public interface IOrderLookupRepository /// register.getDistination: GN exit locations of GN_TYPE 'PCKD', ordered by SORTORDER. Task> GetPackedDestinationsAsync(CancellationToken ct = default); + /// GN exit locations of one GN_TYPE ('PCKD', 'BULK', 'BULK_GALLAB'), ordered by SORTORDER. + Task> GetDestinationsByGnTypeAsync(string gnType, CancellationToken ct = default); + /// NTP_TENDERS_COMPANIES with STATUSCODE='ACTIVE' (grains.cfc getCompanies). Task> GetCompaniesAsync(CancellationToken ct = default); } diff --git a/src/NTP.Application/Grains/Orders/TenderOrderService.cs b/src/NTP.Application/Grains/Orders/TenderOrderService.cs index 1de93f4..0ab2ce3 100644 --- a/src/NTP.Application/Grains/Orders/TenderOrderService.cs +++ b/src/NTP.Application/Grains/Orders/TenderOrderService.cs @@ -106,6 +106,7 @@ public interface IOrderLookupService Task> DestinationsAsync(CancellationToken ct); Task> BillingDestinationsAsync(CancellationToken ct); Task> PackedDestinationsAsync(CancellationToken ct); + Task DestinationGroupsAsync(CancellationToken ct); Task> CompaniesAsync(CancellationToken ct); } @@ -116,5 +117,9 @@ public sealed class OrderLookupService(IOrderLookupRepository repository) : IOrd public Task> DestinationsAsync(CancellationToken ct) => repository.GetLocationsAsync("EX", ct); public Task> BillingDestinationsAsync(CancellationToken ct) => repository.GetBillingDestinationsAsync(ct); public Task> PackedDestinationsAsync(CancellationToken ct) => repository.GetPackedDestinationsAsync(ct); + public async Task DestinationGroupsAsync(CancellationToken ct) => new( + await repository.GetDestinationsByGnTypeAsync("PCKD", ct), + await repository.GetDestinationsByGnTypeAsync("BULK", ct), + await repository.GetDestinationsByGnTypeAsync("BULK_GALLAB", ct)); public Task> CompaniesAsync(CancellationToken ct) => repository.GetCompaniesAsync(ct); } diff --git a/src/NTP.Application/Grains/Orders/WeightsAndDestinationsService.cs b/src/NTP.Application/Grains/Orders/WeightsAndDestinationsService.cs index f35c37d..b0b470d 100644 --- a/src/NTP.Application/Grains/Orders/WeightsAndDestinationsService.cs +++ b/src/NTP.Application/Grains/Orders/WeightsAndDestinationsService.cs @@ -76,11 +76,13 @@ public sealed class CompanyDestinationService( if (!(await lookups.GetCompaniesAsync(ct)).Any(c => c.Scac == scac)) throw OrdersErrors.CompanyNotFound(); - var packed = (await lookups.GetPackedDestinationsAsync(ct)).Select(x => x.Id).ToHashSet(); + var packed = new HashSet(); // every destination the screen can show: packed, bulk and bulk tipper + foreach (var gnType in new[] { "PCKD", "BULK", "BULK_GALLAB" }) + foreach (var d in await lookups.GetDestinationsByGnTypeAsync(gnType, ct)) packed.Add(d.Id); var chosen = request.LocationIds.Distinct().ToList(); if (chosen.Any(id => !packed.Contains(id))) throw OrdersErrors.InvalidDestination(); - // Only the destinations the screen can show (packed ones) are replaced; other rows of the company are kept. + // Only the destinations the screen can show (packed, bulk and bulk tipper) are replaced; other rows of the company are kept. await unitOfWork.ExecuteInTransactionAsync(async token => { await repository.ReplaceAsync(scac, packed, chosen, user.UserId, token); diff --git a/src/NTP.Application/Grains/Permits/PermitService.cs b/src/NTP.Application/Grains/Permits/PermitService.cs index 8579b2a..5fbfe7c 100644 --- a/src/NTP.Application/Grains/Permits/PermitService.cs +++ b/src/NTP.Application/Grains/Permits/PermitService.cs @@ -228,8 +228,8 @@ public sealed class PermitService( var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); - // Deviation: legacy did not check the status; the UI only offers "edit" for REQST / PLND, so the API enforces it. - if (permit.ShipmentStatusCode is not (PermitStatus.Requested or PermitStatus.Planned)) + // Deviation: legacy did not check the status; the UI only offers "edit" for REQST / PLND / OPEN (on the turn), so the API enforces it. + if (permit.ShipmentStatusCode is not (PermitStatus.Requested or PermitStatus.Planned or PermitStatus.Open)) throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus); await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: false, ct); diff --git a/src/NTP.Application/Grains/Permits/PermitSupport.cs b/src/NTP.Application/Grains/Permits/PermitSupport.cs index 16842d5..549f464 100644 --- a/src/NTP.Application/Grains/Permits/PermitSupport.cs +++ b/src/NTP.Application/Grains/Permits/PermitSupport.cs @@ -73,6 +73,9 @@ public static class PermitActionRules case PermitStatus.Planned: a.Add(Accept); a.Add(Reject); a.Add(Edit); break; + case PermitStatus.Open: + a.Add(Edit); // on the turn: the truck / trailer / driver can still be corrected, as for a confirmed (PLND) permit + break; case PermitStatus.Accepted: case PermitStatus.Released: a.Add(RevokeAccepted); a.Add(Print); diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/OrderLookupRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/OrderLookupRepository.cs index ba2caad..1640432 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/OrderLookupRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/OrderLookupRepository.cs @@ -43,6 +43,13 @@ internal sealed class OrderLookupRepository(IDbSession session, ILogger> GetDestinationsByGnTypeAsync(string gnType, CancellationToken ct = default) => + OptionsAsync(""" + SELECT t.id AS Id, t.name AS Name FROM LOCATIONS t + WHERE t.domain = 'GN' AND t.status = '1' AND t.gn_type = :GnType AND t.type = 'EX' + ORDER BY t.sortorder, t.id + """, new { GnType = gnType }, ct); + public async Task> GetCompaniesAsync(CancellationToken ct = default) => (await QueryAsync(""" SELECT t.scac AS Scac, diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/ReportsRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/ReportsRepository.cs index f3f1027..25fce01 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/ReportsRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/ReportsRepository.cs @@ -212,9 +212,14 @@ internal sealed class ReportsRepository(IDbSession session, ILoggerINFERRED from weightsReport.cfr (page grainsReports i=7: date range only): loading weights per permit. private Task>> LoadingWeights(ReportFilter f, ReportScope s, CancellationToken ct) { - var p = Range(f); + // The date range is written into the SQL as DATE literals (values come from a validated DateOnly, never from text). + // With bind variables Oracle picked a full scan of EVENTS (even a one-day range timed out); with literals it uses + // IDX_EVENTS_EVENTDATE (plan confirmed by the DBA, runs in well under a second). + var p = new DynamicParameters(); var visitor = ""; if (IsDestVisitor(s)) { visitor = " and loc.id = :LocId"; p.Add("LocId", s.LocationId ?? -1); } + var from = DateLiteral(f.From!.Value); + var toExclusive = DateLiteral(f.To!.Value) + " + 1"; return RowsAsync($""" select p.pn as pn, p.tn as tn, getcompanynamefromscac(p.companycode, 62) as company, {CargoDecode} as cargoType, loc2.name as origin, loc.name as destination, @@ -226,12 +231,15 @@ internal sealed class ReportsRepository(IDbSession session, ILogger= :FromDate and e.eventdate < :ToDate + 1{visitor} + and e.eventdate >= {from} and e.eventdate < {toExclusive}{visitor} group by p.id, p.pn, p.tn, p.companycode, ct.code, loc2.name, loc.name order by min(e.eventdate), p.id """, p, ct); } + /// SQL DATE literal of a day (yyyy-mm-dd from a DateOnly: no user text reaches the statement). + private static string DateLiteral(DateOnly d) => $"to_date('{d:yyyy-MM-dd}', 'yyyy-mm-dd')"; + /// INFERRED from GRINS_INCAPABILITY.cfr (page grainsReports i=6: order-date range): permits with their load/discharge weights. private Task>> Incapability(ReportFilter f, ReportScope s, CancellationToken ct) { diff --git a/tests/NTP.Tests/OracleCredentialGuardTests.cs b/tests/NTP.Tests/OracleCredentialGuardTests.cs index 05ad9c3..83d828f 100644 --- a/tests/NTP.Tests/OracleCredentialGuardTests.cs +++ b/tests/NTP.Tests/OracleCredentialGuardTests.cs @@ -64,8 +64,8 @@ public class OracleCredentialGuardTests [Fact] public void Key_is_user_at_datasource_without_the_password() { - var key = OracleCredentialGuard.KeyOf("User Id=NTP;Password=secret123;Data Source=db-host:1521/service;Min Pool Size=1"); + var key = OracleCredentialGuard.KeyOf("User Id=NTP;Password=123456;Data Source=db-host:1521/service;Min Pool Size=1"); Assert.Equal("NTP@db-host:1521/service", key); - Assert.DoesNotContain("secret123", key); + Assert.DoesNotContain("123456", key); } } diff --git a/tests/NTP.Tests/PermissionTests.cs b/tests/NTP.Tests/PermissionTests.cs index 740b52f..613f70a 100644 --- a/tests/NTP.Tests/PermissionTests.cs +++ b/tests/NTP.Tests/PermissionTests.cs @@ -5,6 +5,9 @@ namespace NTP.Tests; public class PermissionTests { + // the permission cache is static (shared by all requests): every test starts from an empty one + public PermissionTests() => PermissionService.ResetCache(); + private sealed class FakeUser(string role, bool authenticated = true) : ICurrentUser { public bool IsAuthenticated => authenticated; @@ -28,11 +31,15 @@ public class PermissionTests public bool IsInAnyRole(params string[] roleCodes) => roleCodes.Any(IsInRole); } - private sealed class FakeRepo(Func?> answer) : IPermissionRepository + /// Rows of a role. The DISABLED pseudo role is answered by instead. + private sealed class FakeRepo(Func?> answer, IReadOnlyList? disabled = null) : IPermissionRepository { - public int Calls; + public int Calls; // lookups of real roles only + public readonly List Asked = []; public Task?> GetAllowedAsync(string roleCode, CancellationToken ct = default) { + Asked.Add(roleCode); + if (roleCode == PermissionService.DisabledRole) return Task.FromResult(disabled); Calls++; return Task.FromResult(answer(roleCode)); } @@ -42,7 +49,7 @@ public class PermissionTests private static PermissionService Svc(string role, FakeRepo repo, bool authenticated = true) => new(repo, new FakeUser(role, authenticated)); [Fact] - public async Task Super_user_gets_everything_without_touching_the_database() + public async Task Super_user_gets_everything_without_a_role_lookup() { var repo = new FakeRepo(_ => throw new InvalidOperationException("must not be called")); var svc = Svc("SU", repo); @@ -50,7 +57,8 @@ public class PermissionTests Assert.True(dto.All); Assert.Empty(dto.Allowed); Assert.True(await svc.IsAllowedAsync("grains.anything.at.all")); - Assert.Equal(0, repo.Calls); + Assert.Equal(0, repo.Calls); // no role rows read for SU + Assert.Equal([PermissionService.DisabledRole], repo.Asked.Distinct()); // only the disabled list is consulted } [Fact] @@ -93,6 +101,46 @@ public class PermissionTests Assert.True(await Svc("SU", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.RegistryDriversCreate)); } + [Fact] + public async Task Registering_a_turn_is_granted_by_database_rows_only() + { + foreach (var role in new[] { "GTO", "GOO", "GPO", "GGO" }) + Assert.False(await Svc(role, new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.PermitsCreate)); + Assert.True(await Svc("GOO-TURN", new FakeRepo(_ => new[] { PermissionKeys.PermitsCreate })).IsAllowedAsync(PermissionKeys.PermitsCreate)); + Assert.True(await Svc("SU", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.PermitsCreate)); + } + + [Fact] + public async Task A_resource_with_a_DISABLED_row_is_off_for_everybody_including_su() + { + IReadOnlyList? Rows(string role) => new[] { PermissionKeys.PermitsAbsence, PermissionKeys.PermitsList }; + var off = new[] { PermissionKeys.PermitsAbsence, PermissionKeys.PermitsActivation }; + + var su = Svc("SU", new FakeRepo(Rows, off)); + Assert.False(await su.IsAllowedAsync(PermissionKeys.PermitsAbsence)); // even SU + Assert.False(await su.IsAllowedAsync(PermissionKeys.PermitsActivation)); + Assert.True(await su.IsAllowedAsync(PermissionKeys.OrdersList)); // everything else stays open for SU + var dto = await su.GetForCurrentUserAsync(); + Assert.True(dto.All); + Assert.Contains(PermissionKeys.PermitsAbsence, dto.Denied); + Assert.Contains(PermissionKeys.PermitsActivation, dto.Denied); + + var gto = Svc("GTO-DISABLED-TEST", new FakeRepo(Rows, off)); + Assert.False(await gto.IsAllowedAsync(PermissionKeys.PermitsAbsence)); // granted by its own row, still disabled + Assert.True(await gto.IsAllowedAsync(PermissionKeys.PermitsList)); + var gtoDto = await gto.GetForCurrentUserAsync(); + Assert.DoesNotContain(PermissionKeys.PermitsAbsence, gtoDto.Allowed); + Assert.Contains(PermissionKeys.PermitsList, gtoDto.Allowed); + } + + [Fact] + public async Task Nothing_is_disabled_while_the_permission_table_is_missing() + { + var su = Svc("SU", new FakeRepo(_ => null)); + Assert.True(await su.IsAllowedAsync(PermissionKeys.PermitsAbsence)); + Assert.Empty((await su.GetForCurrentUserAsync()).Denied); + } + [Fact] public async Task Screens_not_in_the_sheet_are_hidden_from_non_super_roles() { diff --git a/tests/NTP.Tests/PermitsRulesTests.cs b/tests/NTP.Tests/PermitsRulesTests.cs index c4f78fa..7cfe7af 100644 --- a/tests/NTP.Tests/PermitsRulesTests.cs +++ b/tests/NTP.Tests/PermitsRulesTests.cs @@ -144,6 +144,20 @@ public class PermitActionRuleTests Assert.Contains(PermitActionRules.PhoneAccept, staff); } + [Fact] + public void A_permit_on_the_turn_can_be_edited_like_a_confirmed_one() + { + var planned = PermitActionRules.For(PermitStatus.Planned, 12, isCompany: false, isOperator: true, isConvertRole: false, isReactivator: false, 327); + var open = PermitActionRules.For(PermitStatus.Open, 12, isCompany: false, isOperator: true, isConvertRole: false, isReactivator: false, 327); + Assert.Contains(PermitActionRules.Edit, planned); + Assert.Contains(PermitActionRules.Edit, open); // على الدور + Assert.DoesNotContain(PermitActionRules.Accept, open); // confirming the turn is still only for PLND + Assert.Contains(PermitActionRules.RevokePermit, open); // staff keep the revoke button + var company = PermitActionRules.For(PermitStatus.Open, 12, isCompany: true, isOperator: true, isConvertRole: false, isReactivator: false, 327); + Assert.Contains(PermitActionRules.Edit, company); // the owning company can correct its own permit + Assert.DoesNotContain(PermitActionRules.RevokePermit, company); + } + [Fact] public void Accepted_permit_offers_convert_to_resd_only_to_su_gpo() { diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts index 4d824c0..7536773 100644 --- a/web/src/api/auth.ts +++ b/web/src/api/auth.ts @@ -53,12 +53,14 @@ export interface Permissions { roleCode: string; all: boolean; allowed: string[]; + /** Resources switched off for everybody (SU included), from the database. */ + denied: string[]; } export const authApi = { async permissions(): Promise { const r = await api.get('/auth/permissions', undefined, { silent: true }); - return { roleCode: String(r.roleCode ?? ''), all: Boolean(r.all), allowed: Array.isArray(r.allowed) ? (r.allowed as unknown[]).map(String) : [] }; + return { roleCode: String(r.roleCode ?? ''), all: Boolean(r.all), allowed: Array.isArray(r.allowed) ? (r.allowed as unknown[]).map(String) : [], denied: Array.isArray(r.denied) ? (r.denied as unknown[]).map(String) : [] }; }, async login(username: string, password: string): Promise { const r = await api.post('/auth/login', { userName: username, password }, { noAuthRedirect: true }); diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts index 3778563..cea7cbf 100644 --- a/web/src/api/mock.ts +++ b/web/src/api/mock.ts @@ -77,7 +77,7 @@ registerMock('GET', /^\/auth\/me$/, () => ({ userId: 1001, name: 'demo', roleCode: 'SU', roleName: 'Super user', domain: 'NTP', locationId: 5, locationName: 'Sohar', stkId: 77, compId: 12, companyCode: 'NAF', lang: 'AR', isStaff: true, })); -registerMock('GET', /^\/auth\/permissions$/, () => ({ roleCode: 'SU', all: true, allowed: [] })); +registerMock('GET', /^\/auth\/permissions$/, () => ({ roleCode: 'SU', all: true, allowed: [], denied: [] })); registerMock('PUT', /^\/auth\/language$/, () => ({})); registerMock('POST', /^\/auth\/change-password$/, () => ({ message: 'تم تغيير كلمة المرور' })); registerMock('POST', /^\/files\/temp$/, () => ({ id: `tmp-${Date.now()}` })); diff --git a/web/src/components/DataGrid/DataGrid.tsx b/web/src/components/DataGrid/DataGrid.tsx index 57429e2..086f34f 100644 --- a/web/src/components/DataGrid/DataGrid.tsx +++ b/web/src/components/DataGrid/DataGrid.tsx @@ -12,6 +12,7 @@ import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined'; import { api, ApiError, type PagedResult } from '@/api/client'; import { EmptyState } from '@/components/EmptyState'; import { LoadingBanner } from '@/components/LoadingBanner'; +import { SectionPaper } from '@/components/SectionPaper'; import { StatusChip } from '@/components/StatusChip'; import { formatDate, formatDateTime, formatNumber, getPath } from '@/components/meta/format'; import type { ColumnMeta, FilterMeta, GridMeta, RowAction } from '@/components/meta/types'; @@ -214,7 +215,7 @@ export function DataGrid({ meta }: DataGridProps) { {updating && } {(blankGrid || (canLoad && !firstLoad && !q.isError)) && ( - + {items.length === 0 && !blankGrid && !meta.emptyAsGrid ? ( ({ meta }: DataGridProps) { key={meta.rowKey(row)} hover onClick={meta.onRowClick ? () => meta.onRowClick!(row) : undefined} - sx={{ cursor: meta.onRowClick ? 'pointer' : 'default', '&:nth-of-type(even)': { bgcolor: (t) => alpha(t.palette.primary.main, t.palette.mode === 'dark' ? 0.09 : 0.05) } }} + sx={{ cursor: meta.onRowClick ? 'pointer' : 'default', '&:hover': { bgcolor: (t) => alpha(t.palette.primary.main, t.palette.mode === 'dark' ? 0.16 : 0.09) }, '&:nth-of-type(even)': { bgcolor: (t) => alpha(t.palette.primary.main, t.palette.mode === 'dark' ? 0.09 : 0.05) } }} > {hasActions && actionsBefore && actionsCell(row)} {columns.map((c) => ( @@ -278,7 +279,7 @@ export function DataGrid({ meta }: DataGridProps) { /> )} - + )} ; + onChange: (next: Set) => void; + labels: { all: string; clear: string }; + disabled?: boolean; +}) { + const { groups, selected, onChange, labels, disabled } = props; + const toggle = (id: number, on: boolean) => { const n = new Set(selected); if (on) n.add(id); else n.delete(id); onChange(n); }; + const setGroup = (ids: number[], on: boolean) => { const n = new Set(selected); ids.forEach((i) => (on ? n.add(i) : n.delete(i))); onChange(n); }; + + return ( + + {groups.map((g) => { + if (g.options.length === 0) return null; + const ids = g.options.map((o) => o.id); + const count = ids.filter((i) => selected.has(i)).length; + return ( + + ({ alignItems: 'center', px: 1.5, py: 0.75, bgcolor: alpha(th.palette.primary.main, 0.08), borderBottom: 1, borderColor: 'divider' })} + > + {g.icon} + {g.title} + {`${count} / ${g.options.length}`}} sx={{ height: 20, fontSize: 11.5 }} /> + + {!disabled && ( + <> + + + + )} + + + {g.options.map((o) => ( + toggle(o.id, e.target.checked)} />} + /> + ))} + + + ); + })} + + ); +} diff --git a/web/src/components/FormCard.tsx b/web/src/components/FormCard.tsx new file mode 100644 index 0000000..bc1b3bb --- /dev/null +++ b/web/src/components/FormCard.tsx @@ -0,0 +1,40 @@ +import type { ElementType, ReactNode } from 'react'; +import { Box, Stack } from '@mui/material'; +import { alpha } from '@mui/material/styles'; +import { SectionPaper } from './SectionPaper'; +import { SectionTitle } from './SectionTitle'; + +/** + * A framed card for the small data-entry screens (assign destination, manual input, close a permit, truck inquiry...): + * icon + title, the fields, and a footer strip with the buttons. Same frame as every record section. + */ +export function FormCard({ icon, title, children, actions, maxWidth = 760 }: { + icon: ElementType; + title: string; + children: ReactNode; + /** Buttons shown in a tinted footer strip. */ + actions?: ReactNode; + maxWidth?: number | string; +}) { + return ( + + + + {children} + + {actions && ( + ({ flexWrap: 'wrap', px: { xs: 2, sm: 2.5 }, py: 1.5, borderTop: 1, borderColor: 'divider', bgcolor: alpha(t.palette.primary.main, t.palette.mode === 'dark' ? 0.08 : 0.04) })} + > + {actions} + + )} + + ); +} + +/** Two columns of fields on wide screens, one on phones. */ +export function FormGrid({ children }: { children: ReactNode }) { + return {children}; +} diff --git a/web/src/components/SectionTitle.tsx b/web/src/components/SectionTitle.tsx new file mode 100644 index 0000000..29485e0 --- /dev/null +++ b/web/src/components/SectionTitle.tsx @@ -0,0 +1,15 @@ +import type { ElementType } from 'react'; +import { Typography } from '@mui/material'; + +/** Title of a section of a record page: icon, bold title and a thin rule (same look as the MetaForm sections). */ +export function SectionTitle({ icon: Icon, title }: { icon: ElementType; title: string }) { + return ( + + + {title} + + ); +} diff --git a/web/src/features/grains-orders/api.ts b/web/src/features/grains-orders/api.ts index 6aef2e8..4ba50e6 100644 --- a/web/src/features/grains-orders/api.ts +++ b/web/src/features/grains-orders/api.ts @@ -5,7 +5,7 @@ import { gridKey } from '@/components/DataGrid'; import type { OptionItem, OptionsLoader } from '@/components/meta/types'; import { useLanguage } from '@/providers/LanguageProvider'; import type { - BillingPermit, CompanyDestinations, CompanyOption, FinancialBillingPage, LookupOption, OrdersResult, + BillingPermit, CompanyDestinations, CompanyOption, DestinationGroupsData, FinancialBillingPage, LookupOption, OrdersResult, PermitWeights, TenderOrderReport, } from './types'; @@ -49,11 +49,11 @@ export function useCompanies() { }); } -export function usePackedDestinations() { +export function useDestinationGroups() { const { lang, langReady } = useLanguage(); return useQuery({ - queryKey: ['grains.orders.packedDest', lang], - queryFn: () => api.get(`${BASE}/lookups/packed-destinations`, undefined, { silent: true }), + queryKey: ['grains.orders.destGroups', lang], + queryFn: () => api.get(`${BASE}/lookups/destination-groups`, undefined, { silent: true }), enabled: langReady, staleTime: 5 * 60_000, }); diff --git a/web/src/features/grains-orders/pages.tsx b/web/src/features/grains-orders/pages.tsx index 4b7227e..10fa70e 100644 --- a/web/src/features/grains-orders/pages.tsx +++ b/web/src/features/grains-orders/pages.tsx @@ -1,15 +1,19 @@ import { useEffect, useMemo, useState, type KeyboardEvent } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { - Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Paper, Stack, + Alert, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, Paper, Stack, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, } from '@mui/material'; import AddIcon from '@mui/icons-material/Add'; import AssessmentIcon from '@mui/icons-material/Assessment'; import DownloadIcon from '@mui/icons-material/Download'; +import GrainIcon from '@mui/icons-material/Grain'; +import Inventory2Icon from '@mui/icons-material/Inventory2'; +import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import SearchIcon from '@mui/icons-material/Search'; import { ApiError } from '@/api/client'; import { DataGrid } from '@/components/DataGrid'; +import { DestinationGroups } from '@/components/DestinationGroups'; import { LoadingBanner } from '@/components/LoadingBanner'; import { MetaForm } from '@/components/MetaForm'; import { PageHeader } from '@/components/PageHeader'; @@ -20,7 +24,7 @@ import { useConfirm } from '@/providers/ConfirmProvider'; import { useToast } from '@/providers/ToastProvider'; import { downloadExport, fetchBillingPermit, fetchPermitWeights, useAddBilling, useCompanies, useCompanyDestinations, - useCreateOrder, useDeleteOrder, usePackedDestinations, usePublishOrder, useSaveCompanyDestinations, useSaveWeights, + useCreateOrder, useDeleteOrder, useDestinationGroups, usePublishOrder, useSaveCompanyDestinations, useSaveWeights, useSetQuota, useTenderOrderReport, } from './api'; import { billingForm, billingGrid, financialGrid, invoiceGrid, weightsForm } from './meta/billing'; @@ -397,7 +401,7 @@ export function CompanyDestinationsPage() { const { t } = useFeatureUi(strings); const confirm = useConfirm(); const companies = useCompanies(); - const packed = usePackedDestinations(); + const groupsData = useDestinationGroups(); const [scac, setScac] = useState(null); const current = useCompanyDestinations(scac); const save = useSaveCompanyDestinations(scac); @@ -407,13 +411,17 @@ export function CompanyDestinationsPage() { setChecked(new Set(current.data?.locationIds ?? [])); }, [current.data]); - const list = packed.data ?? []; - const toggle = (id: number) => setChecked((s) => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n; }); + const groups = [ + { key: 'packed', title: t('ord.compDest.packed'), icon: , options: groupsData.data?.packed ?? [] }, + { key: 'bulk', title: t('ord.compDest.bulk'), icon: , options: groupsData.data?.bulk ?? [] }, + { key: 'bulkGallab', title: t('ord.compDest.bulkGallab'), icon: , options: groupsData.data?.bulkGallab ?? [] }, + ]; + const all = groups.flatMap((g) => g.options); async function onSave() { if (scac === null) return; if (!(await confirm({ message: t('ord.compDest.saveConfirm') }))) return; - save.mutate([...checked].filter((id) => list.some((d) => d.id === id))); + save.mutate([...checked].filter((id) => all.some((d) => d.id === id))); } return ( @@ -431,26 +439,13 @@ export function CompanyDestinationsPage() { {scac === null && {t('ord.compDest.pick')}} - {scac !== null && (current.isPending || packed.isPending) && } + {scac !== null && (current.isPending || groupsData.isPending) && } {current.isError && {errText(current.error, t('error.generic'))}} {scac !== null && current.data && ( <> - - {t('ord.compDest.packed')} - - - - {list.length === 0 && {t('ord.compDest.empty')}} - - {list.map((d) => ( - toggle(d.id)} />} - label={<>{d.id} - {d.name}} - /> - ))} - + {all.length === 0 && {t('ord.compDest.empty')}} + diff --git a/web/src/features/grains-orders/routes.tsx b/web/src/features/grains-orders/routes.tsx index 787f5ab..a72501a 100644 --- a/web/src/features/grains-orders/routes.tsx +++ b/web/src/features/grains-orders/routes.tsx @@ -1,6 +1,7 @@ import type { RouteObject } from 'react-router-dom'; -import AssessmentIcon from '@mui/icons-material/Assessment'; +import AccountBalanceIcon from '@mui/icons-material/AccountBalance'; import BusinessIcon from '@mui/icons-material/Business'; +import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import ListAltIcon from '@mui/icons-material/ListAlt'; import PercentIcon from '@mui/icons-material/Percent'; import ReceiptIcon from '@mui/icons-material/Receipt'; @@ -13,6 +14,7 @@ import { TenderOrderCreatePage, TenderOrderReportPage, TenderOrdersPage, WeightsPage, } from './pages'; import strings from './strings'; +import permitStrings from '../grains-permits/strings'; /** * Grains "orders" slice: tender orders, daily quota, billing, invoices, loading weights, company destinations and reports. @@ -38,13 +40,19 @@ export const menu: MenuItem[] = [ icon: ReceiptLongIcon, children: [ { key: 'grains.orders.list', title: strings['ord.menu.orders'], icon: ListAltIcon, path: '/grains/orders', createPath: '/grains/orders/new', createKey: 'grains.orders.create' }, + { key: 'grains.orders.supply', title: permitStrings['pm.menu.supply'], icon: LocalShippingIcon, path: '/grains/orders/supply' }, { key: 'grains.orders.quotas', title: strings['ord.menu.quotas'], icon: PercentIcon, path: '/grains/orders/quotas' }, - { key: 'grains.orders.billing', title: strings['ord.menu.billing'], icon: RequestQuoteIcon, path: '/grains/orders/billing', createPath: '/grains/orders/billing/new' }, - { key: 'grains.orders.invoices', title: strings['ord.menu.invoices'], icon: ReceiptIcon, path: '/grains/orders/invoices' }, { key: 'grains.orders.weights', title: strings['ord.menu.weights'], icon: ScaleIcon, path: '/grains/orders/weights' }, { key: 'grains.orders.companyDest', title: strings['ord.menu.companyDest'], icon: BusinessIcon, path: '/grains/orders/company-destinations' }, - { key: 'grains.orders.reportOrders', title: strings['ord.menu.reportOrders'], icon: AssessmentIcon, path: '/grains/orders/reports/tender-orders' }, - { key: 'grains.orders.reportFinance', title: strings['ord.menu.reportFinance'], icon: AssessmentIcon, path: '/grains/orders/reports/financial-billing' }, + ], + }, + { + key: 'grains.finance', + title: strings['ord.menu.finance'], + icon: AccountBalanceIcon, + children: [ + { key: 'grains.orders.billing', title: strings['ord.menu.billing'], icon: RequestQuoteIcon, path: '/grains/orders/billing', createPath: '/grains/orders/billing/new' }, + { key: 'grains.orders.invoices', title: strings['ord.menu.invoices'], icon: ReceiptIcon, path: '/grains/orders/invoices' }, ], }, ]; diff --git a/web/src/features/grains-orders/strings.ts b/web/src/features/grains-orders/strings.ts index 144736d..499826c 100644 --- a/web/src/features/grains-orders/strings.ts +++ b/web/src/features/grains-orders/strings.ts @@ -3,6 +3,7 @@ import { defineStrings } from '@/i18n/useUi'; /** Feature strings of the Grains "orders" slice (tender orders, quotas, billing, invoices, reports). */ export default defineStrings({ // ---- menu + 'ord.menu.finance': { en: 'Finance', ar: 'المالية' }, 'ord.menu.group': { en: 'Orders and billing', ar: 'الطلبيات والمطالبات' }, 'ord.menu.orders': { en: 'Tender orders', ar: 'الطلبيات' }, 'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' }, @@ -11,7 +12,7 @@ export default defineStrings({ 'ord.menu.weights': { en: 'Loading weights', ar: 'تثبيت أوزان التحميل' }, 'ord.menu.companyDest': { en: 'Company destinations', ar: 'وجهات الشركات' }, 'ord.menu.reportOrders': { en: 'Orders report', ar: 'تقرير الطلبيات' }, - 'ord.menu.reportFinance': { en: 'Financial report', ar: 'التقرير المالي' }, + 'ord.menu.reportFinance': { en: 'Tender financial reports', ar: 'تقارير عطاء التموين المالية' }, 'ord.crumb.new': { en: 'New', ar: 'جديد' }, // ---- shared @@ -82,13 +83,16 @@ export default defineStrings({ // ---- company destinations 'ord.compDest.title': { en: 'Company destinations', ar: 'وجهات الشركات' }, - 'ord.compDest.subtitle': { en: 'Packed-cargo destinations each company may receive', ar: 'وجهات المشوّل المسموحة لكل شركة' }, - 'ord.compDest.packed': { en: 'Packed destinations', ar: 'مشوّل' }, + 'ord.compDest.subtitle': { en: 'Packed, bulk and bulk-tipper destinations each company may receive', ar: 'وجهات المشول والسائب والسائب (قلاب) المسموحة لكل شركة' }, + 'ord.compDest.packed': { en: 'Packed', ar: 'مشول' }, + 'ord.compDest.bulk': { en: 'Bulk', ar: 'سائب' }, + 'ord.compDest.bulkGallab': { en: 'Bulk (tipper)', ar: 'سائب (قلاب)' }, + 'ord.compDest.clear': { en: 'Clear', ar: 'إلغاء' }, 'ord.compDest.all': { en: 'Select all', ar: 'تحديد الكل' }, 'ord.compDest.none': { en: 'Clear all', ar: 'إلغاء التحديد' }, 'ord.compDest.saveConfirm': { en: 'Save the destinations of this company?', ar: 'حفظ وجهات هذه الشركة؟' }, 'ord.compDest.pick': { en: 'Select a company to view and edit its destinations.', ar: 'اختر شركة لعرض وجهاتها وتعديلها.' }, - 'ord.compDest.empty': { en: 'No packed destinations are defined.', ar: 'لا توجد وجهات مشوّل معرّفة.' }, + 'ord.compDest.empty': { en: 'No destinations are defined.', ar: 'لا توجد وجهات معرّفة.' }, // ---- financial report 'ord.fin.title': { en: 'Financial billing report', ar: 'تقارير عطاء التموين المالية' }, diff --git a/web/src/features/grains-orders/types.ts b/web/src/features/grains-orders/types.ts index 40f0c28..46cdfd5 100644 --- a/web/src/features/grains-orders/types.ts +++ b/web/src/features/grains-orders/types.ts @@ -92,6 +92,8 @@ export interface PermitWeights { documentNumber: string | null; } +export interface DestinationGroupsData { packed: LookupOption[]; bulk: LookupOption[]; bulkGallab: LookupOption[] } + export interface CompanyDestinations { scac: number; locationIds: number[]; diff --git a/web/src/features/grains-permits/meta/permits.tsx b/web/src/features/grains-permits/meta/permits.tsx index 894fb9f..084f8b5 100644 --- a/web/src/features/grains-permits/meta/permits.tsx +++ b/web/src/features/grains-permits/meta/permits.tsx @@ -1,6 +1,6 @@ import type { FilterMeta, GridMeta, L10n, OptionItem, StatusMeta } from '@/components/meta/types'; import { cargoOptions, companyFilterOptions, exitLocationOptions, tenderOrderDateOptions } from '../api'; -import type { PermitListItem, QueueItem } from '../types'; +import type { PermitListItem } from '../types'; /** Declarative tables for the permit list (legacy GNPermits.cfm / getGNPermits) and the queue grid (queueGrid.cfm). */ @@ -42,7 +42,7 @@ export interface PermitGridHandlers { const actionLabels: Record = { view: { en: 'View', ar: 'مشاهدة' }, submit: { en: 'Submit order', ar: 'تقديم الطلب' }, - edit: { en: 'Edit order', ar: 'تعديل الطلب' }, + edit: { en: 'Edit information', ar: 'تعديل المعلومات' }, accept: { en: 'Confirm turn', ar: 'تثبيت الدور' }, reject: { en: 'Revoke confirmation', ar: 'الغاء التثبيت' }, revokeAccepted: { en: 'Cancel confirmation', ar: 'الغاء التثبيت (جاهز للتسريب)' }, @@ -104,7 +104,7 @@ export const permitGrid = (h: PermitGridHandlers, o: PermitGridOptions = {}): Gr /** Row actions are computed by the server (`actions`): only the allowed buttons are shown. */ export const permitRowActions = (h: PermitGridHandlers): NonNullable['rowActions']> => - Object.keys(actionLabels).map((a) => ({ + Object.keys(actionLabels).filter((a) => a !== 'edit').map((a) => ({ key: a, label: actionLabels[a]!, danger: danger.has(a), @@ -112,19 +112,4 @@ export const permitRowActions = (h: PermitGridHandlers): NonNullable h.onAction(a, r), })); -export const queueGrid = (): GridMeta => ({ - key: 'grains.permits.queue', - endpoint: '/grains/permit-queue', - rowKey: (r) => r.id, - filters: [ - { name: 'tn', type: 'text', label: { en: 'Truck no.', ar: 'رقم القاطرة' }, inputKind: 'plate' }, - { name: 'pn', type: 'text', label: { en: 'Permit no.', ar: 'رقم الارسالية' }, inputKind: 'code' }, - ], - columns: [ - { key: 'pn', header: { en: 'Permit no.', ar: 'رقم الارسالية' }, ltr: true }, - { key: 'tn', header: { en: 'Truck', ar: 'القاطرة' }, ltr: true }, - { key: 'creationDate', header: { en: 'Created', ar: 'تاريخ الانشاء' }, format: 'datetime', ltr: true }, - ], -}); - export { cargoOptions }; diff --git a/web/src/features/grains-permits/pages.tsx b/web/src/features/grains-permits/pages.tsx index 425bbdb..8341fe4 100644 --- a/web/src/features/grains-permits/pages.tsx +++ b/web/src/features/grains-permits/pages.tsx @@ -5,17 +5,40 @@ import { Stack, Tab, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tabs, TextField, Typography, } from '@mui/material'; import AddIcon from '@mui/icons-material/Add'; +import AssignmentIcon from '@mui/icons-material/Assignment'; +import BadgeIcon from '@mui/icons-material/Badge'; +import BlockIcon from '@mui/icons-material/Block'; +import CancelOutlinedIcon from '@mui/icons-material/CancelOutlined'; +import CheckCircleOutlinedIcon from '@mui/icons-material/CheckCircleOutlined'; +import CloseIcon from '@mui/icons-material/Close'; +import EditIcon from '@mui/icons-material/Edit'; +import HistoryIcon from '@mui/icons-material/History'; +import LocalShippingIcon from '@mui/icons-material/LocalShipping'; +import PhoneCallbackIcon from '@mui/icons-material/PhoneCallback'; +import PhoneDisabledIcon from '@mui/icons-material/PhoneDisabled'; import PrintIcon from '@mui/icons-material/Print'; +import RestoreIcon from '@mui/icons-material/Restore'; +import RvHookupIcon from '@mui/icons-material/RvHookup'; +import SwapHorizIcon from '@mui/icons-material/SwapHoriz'; +import UndoIcon from '@mui/icons-material/Undo'; import SearchIcon from '@mui/icons-material/Search'; +import SaveIcon from '@mui/icons-material/Save'; +import AltRouteIcon from '@mui/icons-material/AltRoute'; +import EditNoteIcon from '@mui/icons-material/EditNote'; +import LockIcon from '@mui/icons-material/Lock'; +import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck'; +import ScaleIcon from '@mui/icons-material/Scale'; import { DataGrid } from '@/components/DataGrid'; +import { FormCard, FormGrid } from '@/components/FormCard'; // the shared framed section look (see components/SectionPaper): every Paper on the permit screens uses it import { SectionPaper as Paper } from '@/components/SectionPaper'; import { ViewItem } from '@/components/ViewItem'; import { EmptyState } from '@/components/EmptyState'; import { LoadingBanner } from '@/components/LoadingBanner'; import { PageHeader } from '@/components/PageHeader'; +import { SectionTitle } from '@/components/SectionTitle'; import { StatusChip } from '@/components/StatusChip'; -import { formatNumber } from '@/components/meta/format'; +import { formatDate, formatNumber } from '@/components/meta/format'; import { elementToPdfUrl, type PdfOrientation } from '@/lib/pdf'; import { useFeatureUi } from '@/i18n/useUi'; import { useAuth } from '@/providers/AuthProvider'; @@ -23,13 +46,12 @@ import { useConfirm } from '@/providers/ConfirmProvider'; import { useToast } from '@/providers/ToastProvider'; import { fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, fetchTruck, searchDestination, searchTruckDistribution, - useAbsenceFeature, useActivateOrders, useActivation, useAddToQueue, useAssignByPn, useClosePermit, useDistribute, - useDistributionPivot, useDistributionSummary, useLocationCounts, useLocationGroups, useManualInput, useOrderDates, + useActivateOrders, useActivation, useAddToQueue, useAssignByPn, useClosePermit, useDistribute, + useDistributionPivot, useDistributionSummary, useLocationGroups, useManualInput, useOrderDates, usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination, - useRevokeAllRequested, useSingleTruck, useSubmitOrder, useToggleAbsence, useUpdateOrder, useWeighbridgeManual, - useWeighbridgeReading, useWeights, + useRevokeAllRequested, useSingleTruck, useSubmitOrder, useUpdateOrder, useWeighbridgeManual, } from './api'; -import { actionLabel, permitGrid, permitRowActions, permitStatuses, queueGrid, shipmentModeOptions } from './meta/permits'; +import { actionLabel, permitGrid, permitRowActions, permitStatuses, shipmentModeOptions } from './meta/permits'; import strings from './strings'; import { AcceptSlip, InSlip, OutSlip } from './slips'; import type { PermitListItem, TruckDistribution } from './types'; @@ -57,7 +79,7 @@ function useRoles() { // Backend-driven (GET /auth/permissions): the role code decides on the server, not here. const { hasRole, can } = useAuth(); return { - canQueueAdd: can('grains.permits.queue'), + canCreate: can('grains.permits.create'), canAbsence: can('grains.permits.absence'), canClose: can('grains.permits.close'), canTruckOrder: can('grains.permits.truckOrder'), @@ -187,7 +209,7 @@ function usePermitActions() { // ================================================================= permit list (GNPermits.cfm) export function PermitsPage() { - const { t } = useFeatureUi(strings); + const { t, lang } = useFeatureUi(strings); const { user } = useAuth(); const { run, element } = usePermitActions(); const companyUser = Number(user?.stkId) === 62; // legacy session.stkid = 62 @@ -197,11 +219,40 @@ export function PermitsPage() { return { ...permitGrid(h, { companyUser, showRevoked }), rowActions: permitRowActions(h) }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [companyUser, showRevoked]); + const { canCreate } = useRoles(); + const add = useAddToQueue(); + const confirm = useConfirm(); + const [open, setOpen] = useState(false); + const [tn, setTn] = useState(''); + const [tt, setTt] = useState('BULK'); + + async function save() { + if (!tn.trim() || !(await confirm({ message: t('pm.queue.confirm') }))) return; + add.mutate({ tn: tn.trim(), tt, checkStatuses: false }, { onSuccess: (r) => { if (r.success) { setOpen(false); setTn(''); } } }); + } return ( <> - + } onClick={() => setOpen(true)}>{t('pm.queue.add')}} + /> {element} + setOpen(false)} fullWidth maxWidth="xs"> + {t('pm.queue.add')} + + + void save()} /> + setTt(e.target.value)}> + {shipmentModeOptions.map((o) => {typeof o.label === 'string' ? o.label : o.label[lang]})} + + + + + + + + ); } @@ -224,6 +275,7 @@ export function PermitDetailPage() { const [v, setV] = useState(emptyOrder); const [info, setInfo] = useState<{ truck?: string; trailer?: string }>({}); const [loaded, setLoaded] = useState(false); + const [editing, setEditing] = useState(false); // the edit / submit form opens from the header button const d = detail.data; if (d && !loaded) { @@ -268,45 +320,91 @@ export function PermitDetailPage() { async function save() { if (!complete || !(await confirm({ message: t(canSubmit ? 'pm.confirm.submit' : 'pm.confirm.update') }))) return; const body = { tn: v.tn.trim(), trn: v.trn.trim(), nnpn: v.nnpn.trim(), dln: v.dln.trim(), dled: v.dled || null, name: v.name.trim() }; - if (canSubmit) submit.mutate({ id, body: { ...body, opType: v.opType } }); - else update.mutate({ id, body }); + const done = { onSuccess: () => setEditing(false) }; + if (canSubmit) submit.mutate({ id, body: { ...body, opType: v.opType } }, done); + else update.mutate({ id, body }, done); } const others = d.actions.filter((a) => !['view', 'submit', 'edit'].includes(a)); + const fd = (x: string | null | undefined) => (x ? formatDate(x, lang) || x : null); + const when = (x: string | null) => { + if (!x) return ''; + const dt = new Date(x); + const p2 = (n: number) => String(n).padStart(2, '0'); + return Number.isNaN(dt.getTime()) ? x : `${dt.getFullYear()}/${p2(dt.getMonth() + 1)}/${p2(dt.getDate())} ${p2(dt.getHours())}:${p2(dt.getMinutes())}`; + }; + const cols = { display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))', lg: 'repeat(4, minmax(0, 1fr))' } } as const; + + // header buttons (top end side like the other record pages): the edit / submit toggle first, then the other actions + const headerActions = ( + <> + {editable && ( + + )} + {others.map((a) => ( + + ))} + + ); + return ( <> } + actions={headerActions} backTo="/grains/permits" /> - - + + + {d.pn} {d.queueNo} - {d.cargoType} {d.shift} - {d.operationType} - {[d.truck?.tn, d.truck?.chasesNumber, d.truck?.axials].filter(Boolean).join(' / ')} - {[d.trailer?.tn, d.trailer?.chasesNumber, d.trailer?.axials].filter(Boolean).join(' / ')} - {[d.driver?.name, d.driver?.dln].filter(Boolean).join(' / ')} + {d.cargoType} - {others.length > 0 && ( - - {others.map((a) => ( - - ))} - - )} - {editable && ( + + + + {d.truck?.tn} + {d.truck?.chasesNumber} + {d.truck?.axials} + {fd(d.truck?.regDate)} + + + + + + + {d.trailer?.tn} + {d.trailer?.chasesNumber} + {d.operationType} + {d.trailer?.axials} + {fd(d.trailer?.regDate)} + + + + + + + {d.driver?.nnpn} + {d.driver?.name} + {d.driver?.dln} + {fd(d.driver?.dled)} + + + + {editable && editing && ( - {t(canSubmit ? 'pm.order.submitTitle' : 'pm.order.editTitle')} + void lookupTruck()} helperText={info.truck} slotProps={ltr} /> @@ -326,20 +424,21 @@ export function PermitDetailPage() { + )} - {t('pm.events.title')} + - {t('pm.events.date')} {t('pm.events.type')} {t('pm.events.by')} {t('pm.events.status')} + {t('pm.events.date')} {t('pm.events.weight')} {t('pm.events.remarks')} @@ -347,15 +446,15 @@ export function PermitDetailPage() { {d.events.map((e, i) => ( - {e.eventDate ? new Date(e.eventDate).toLocaleString('en-GB') : ''} {e.eventCaption ?? e.eventType} {e.doneBy} {e.currentStatus} + {when(e.eventDate)} {e.weight === null ? '' : fmt(e.weight)} {e.remarks} ))} - {d.events.length === 0 && {tr({ en: 'No events', ar: 'لا توجد احداث' })}} + {d.events.length === 0 && {tr({ en: 'No movements', ar: 'لا توجد حركات' })}}
@@ -366,6 +465,14 @@ export function PermitDetailPage() { ); } +/** Header buttons of the permit page: icon per action; the destructive ones are red. */ +const ACTION_ICONS: Record = { + print: , accept: , reject: , revokeAccepted: , convertToResd: , + phoneAccept: , phoneReject: , cancelOrder: , revokePermit: , + reactivate: , +}; +const DANGER_ACTIONS = new Set(['reject', 'revokeAccepted', 'phoneReject', 'cancelOrder', 'revokePermit']); + function Info({ label, children, ltr: isLtr }: { label: string; children?: ReactNode; ltr?: boolean }) { return ( @@ -374,47 +481,6 @@ function Info({ label, children, ltr: isLtr }: { label: string; children?: React ); } -// ================================================================= queue (CreateQueue.cfm / queueGrid.cfm) -export function QueuePage() { - const { t, lang } = useFeatureUi(strings); - const { canQueueAdd } = useRoles(); - const add = useAddToQueue(); - const confirm = useConfirm(); - const meta = useMemo(() => queueGrid(), []); - const [open, setOpen] = useState(false); - const [tn, setTn] = useState(''); - const [tt, setTt] = useState('BULK'); - - async function save() { - if (!tn.trim() || !(await confirm({ message: t('pm.queue.confirm') }))) return; - add.mutate({ tn: tn.trim(), tt, checkStatuses: false }, { onSuccess: (r) => { if (r.success) { setOpen(false); setTn(''); } } }); - } - return ( - <> - } onClick={() => setOpen(true)}>{t('pm.queue.add')}} - /> - - setOpen(false)} fullWidth maxWidth="xs"> - {t('pm.queue.add')} - - - void save()} /> - setTt(e.target.value)}> - {shipmentModeOptions.map((o) => {typeof o.label === 'string' ? o.label : o.label[lang]})} - - - - - - - - - - ); -} - // ================================================================= destinations (assginggdest / ManualInput / activateOrders) function AssignByPn() { const { t, lang } = useFeatureUi(strings); @@ -431,16 +497,32 @@ function AssignByPn() { assign.mutate({ pn, destId: Number(dest), shipmentMode: Number(mode) }); } return ( - - - setDest(e.target.value)}> - {locations.map((l) => {l.name})} - - setMode(e.target.value)}> - {cargo.map((c) => {lang === 'ar' ? c.ar : c.en})} - - - + } disabled={!pn || !dest || !mode} onClick={() => void save()}>{t('common.save')}} + > + + + setMode(e.target.value)}> + {cargo.map((c) => {lang === 'ar' ? c.ar : c.en})} + + + setDest(e.target.value)}> + {locations.map((l) => {l.name})} + + + + + ); +} + +/** Label beside its field (legacy manual-input screen). */ +function MiRow({ label, children }: { label: string; children: ReactNode }) { + return ( + + {label} + {children} + ); } @@ -475,22 +557,33 @@ function ManualInput() { manual.mutate({ pn, orderId: Number(orderId), orderDate: date, ltw: Number(ltw), lgw: Number(lgw) }); } return ( - - - void loadOrders(e.target.value)}> - {(dates.data ?? []).map((d) => {d.split('-').reverse().join('/')})} - - setOrderId(e.target.value)} - helperText={orders.length === 0 && date ? t('pm.manual.noOrders') : undefined}> - {orders.map((o) => {o.name})} - - - - - - - - + + + + + )} + > + + + void loadOrders(e.target.value)}> + {(dates.data ?? []).map((d) => {d.split('-').reverse().join('/')})} + + + + + + setOrderId(e.target.value)} + helperText={orders.length === 0 && date ? t('pm.manual.noOrders') : undefined}> + {orders.map((o) => {o.name})} + + + + + + ); } @@ -507,16 +600,21 @@ function Activation() { const toggle = (k: string) => { const n = new Set(sel); if (n.has(k)) n.delete(k); else n.add(k); setChecked(n); }; async function save() { if (await confirm({ message: t('pm.activate.confirm') })) activate.mutate([...sel], { onSuccess: () => setChecked(null) }); } return ( - - + } onClick={() => void save()}>{t('common.save')}} + > + - {t('pm.activate.loc')}{t('pm.activate.cargo')} - {t('pm.activate.total')}{t('pm.activate.used')} + + {t('pm.activate.loc')}{t('pm.activate.cargo')} + {t('pm.activate.total')}{t('pm.activate.used')} + {rows.map((r) => { const k = `${r.locId}-${r.ctId}`; return ( - + toggle(k)} /> {r.loc}{r.ct} {fmt(r.total)}{fmt(r.used)} @@ -526,8 +624,7 @@ function Activation() {
- -
+ ); } @@ -562,6 +659,61 @@ export function ActivationPage() { ); } +// ================================================================= separate screens moved out of the tabs +/** طلبية التموين (orders menu): distributed permits per destination type. */ +export function SupplyOrderPage() { + const { t } = useFeatureUi(strings); + const pivot = useDistributionPivot(); + return ( + <> + + + + {t('pm.dist.company')}{t('pm.dist.silos')} + {t('pm.dist.direct')}{t('pm.dist.packed')} + {(pivot.data ?? []).map((r) => ( + {r.company}{r.silos} + {r.direct}{r.packed} + ))} +
+
+ + ); +} + +/** اغلاق إرسالية (permits menu): close a permit manually. */ +export function ClosePermitPage() { + const { t } = useFeatureUi(strings); + const closeP = useClosePermit(); + const confirm = useConfirm(); + const [pn, setPn] = useState(''); + return ( + <> + + } disabled={!pn} + onClick={async () => { if (await confirm({ message: t('pm.wb.closeConfirm'), danger: true })) closeP.mutate(pn); }}>{t('pm.wb.close')} + )} + > + + + + ); +} + +/** استعلام عن سيارة (permits menu). */ +export function TruckInquiryPage() { + const { t } = useFeatureUi(strings); + return ( + <> + + + + ); +} + // ================================================================= distribution function DistributeTab() { const fmt = useFmt(); @@ -575,7 +727,6 @@ function DistributeTab() { ]; const [cat, setCat] = useState('PCKD'); const summary = useDistributionSummary(); - const pivot = useDistributionPivot(); async function go() { if (await confirm({ message: t('pm.dist.confirm') })) distribute.mutate(cat); } return ( @@ -585,7 +736,7 @@ function DistributeTab() { - + {t('pm.dist.summary')} @@ -593,17 +744,6 @@ function DistributeTab() { {(summary.data ?? []).map((r) => {r.comp}{fmt(r.cnt)})}
- - {t('pm.dist.pivot')} - - {t('pm.dist.company')}{t('pm.dist.silos')} - {t('pm.dist.direct')}{t('pm.dist.packed')} - {(pivot.data ?? []).map((r) => ( - {r.company}{r.silos} - {r.direct}{r.packed} - ))} -
-
); @@ -668,13 +808,15 @@ function SearchTruckTab() { try { setR(await searchTruckDistribution(tn)); } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } } return ( - - + + } disabled={!tn} onClick={() => void go()}>{t('common.search')}} + > void go()} /> - - + {r && ( - + {r.status} {r.companyLocations} @@ -682,7 +824,7 @@ function SearchTruckTab() { {`${r.trucksTotalQuantity} / ${r.tenderTotalQuantity}`} {r.errorMsg && {r.errorMsg}} - + )} ); @@ -690,142 +832,97 @@ function SearchTruckTab() { export function DistributionPage() { const { t } = useFeatureUi(strings); - const [tab, setTab] = useState<'distribute' | 'process' | 'search'>('distribute'); - const absence = useAbsenceFeature(); - const toggle = useToggleAbsence(); - const confirm = useConfirm(); - const { canAbsence, canTruckOrder, canTruckStatus } = useRoles(); + const [tab, setTab] = useState<'distribute' | 'process'>('distribute'); + const { canTruckOrder } = useRoles(); return ( <> { if (await confirm({ message: t('pm.absence.confirm') })) toggle.mutate(undefined as never); }}> - {absence.data?.enabled ? t('pm.absence.disable') : t('pm.absence.enable')} - - )} /> setTab(v)} variant="scrollable" sx={{ mb: 2 }}> {canTruckOrder && } - {canTruckStatus && } {tab === 'distribute' && } {tab === 'process' && canTruckOrder && } - {tab === 'search' && canTruckStatus && } ); } // ================================================================= weighbridges -function ReadingTab({ kind }: { kind: 'enter' | 'exit' }) { - const { t } = useFeatureUi(strings); - const call = useWeighbridgeReading(kind); - const toast = useToast(); - const [tn, setTn] = useState(''); - const [w, setW] = useState(''); - async function go() { - if (!tn || !w) return; - call.mutate({ tn, weight: Number(w) }, { onSuccess: (r) => { if (r.success) { toast.success(r.message); setW(''); } } }); - } - return ( - - - void go()} /> - - - ); -} - -function WeightsTab({ kind }: { kind: 'loading-weights' | 'discharge-weights' }) { - const { t } = useFeatureUi(strings); - const save = useWeights(kind); - const [tn, setTn] = useState(''); - const [tare, setTare] = useState(''); - const [gross, setGross] = useState(''); - return ( - - - - - - - ); -} - function ManualTab() { const { t } = useFeatureUi(strings); const save = useWeighbridgeManual(); const toast = useToast(); const { user } = useAuth(); const [tn, setTn] = useState(''); - const [loc, setLoc] = useState(user?.locationId ? String(user.locationId) : ''); + const loc = user?.locationId ? String(user.locationId) : ''; + const [locInput, setLocInput] = useState(''); const [wi, setWi] = useState(''); const [wo, setWo] = useState(''); - const [dest, setDest] = useState(''); + const [found, setFound] = useState<{ destination: string | null; message: string | null } | null>(null); + const location = loc || locInput; async function find() { if (!tn) return; - try { const r = await searchDestination(tn); setDest(r.destination ? `${r.destination}${r.message ? ` - ${r.message}` : ''}` : r.message ?? ''); } - catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + try { const r = await searchDestination(tn); setFound({ destination: r.destination, message: r.message }); } + catch (e) { setFound(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } } + const row = { display: 'grid', gridTemplateColumns: { xs: '1fr', sm: '140px minmax(0, 280px)' }, alignItems: 'center', gap: 1 } as const; return ( - - void find()} /> - {dest && {dest}} - - - - - - - - - ); -} + + + + + + {t('pm.wb.truckNo')} + { setTn(v); setFound(null); }} onEnter={() => void find()} /> + + + + + {t('pm.wb.dest')} + + {found ? (found.destination ?? '-') : ''} + {found?.message && {found.message}} + + + + -function CountsTab() { - const fmt = useFmt(); - const { t } = useFeatureUi(strings); - const q = useLocationCounts(); - if (q.isLoading) return ; - return ( - - - {t('pm.wb.loc')}{t('pm.wb.trucks')} - {(q.data ?? []).map((r, i) => {r.loc}{fmt(r.cnt)})} -
-
+ } disabled={!tn || !location || !wi || !wo} + onClick={() => save.mutate({ tn, locationId: Number(location), weightIn: Number(wi), weightOut: Number(wo) })}>{t('common.save')} + )} + > + + {!loc && ( + + {t('pm.wb.location')} + + + )} + + {t('pm.wb.first')} + + + + {t('pm.wb.second')} + + + + +
); } export function WeighbridgePage() { const { t } = useFeatureUi(strings); - const { canClose } = useRoles(); - const [tab, setTab] = useState(0); - const closeP = useClosePermit(); - const confirm = useConfirm(); - const [pn, setPn] = useState(''); return ( <> - setTab(v)} variant="scrollable" sx={{ mb: 2 }}> - - {canClose && } - - {tab === 0 && } - {tab === 1 && } - {tab === 2 && } - {tab === 3 && } - {tab === 4 && } - {tab === 5 && } - {tab === 6 && canClose && ( - - - - - )} + ); } diff --git a/web/src/features/grains-permits/routes.tsx b/web/src/features/grains-permits/routes.tsx index a7cd966..33dfc9c 100644 --- a/web/src/features/grains-permits/routes.tsx +++ b/web/src/features/grains-permits/routes.tsx @@ -4,24 +4,29 @@ import EditNoteIcon from '@mui/icons-material/EditNote'; import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck'; import AssignmentIcon from '@mui/icons-material/Assignment'; import LocalShippingIcon from '@mui/icons-material/LocalShipping'; +import BlockIcon from '@mui/icons-material/Block'; +import LockIcon from '@mui/icons-material/Lock'; +import SearchIcon from '@mui/icons-material/Search'; import ScaleIcon from '@mui/icons-material/Scale'; -import SortIcon from '@mui/icons-material/Sort'; import TuneIcon from '@mui/icons-material/Tune'; import type { MenuItem } from '@/shell/types'; import { - ActivationPage, DestinationsPage, DistributionPage, ManualInputPage, PermitDetailPage, PermitsPage, PrintAcceptPage, PrintInPage, PrintOutPage, QueuePage, WeighbridgePage, + ActivationPage, DestinationsPage, DistributionPage, ManualInputPage, ClosePermitPage, PermitDetailPage, PermitsPage, SupplyOrderPage, TruckInquiryPage, PrintAcceptPage, PrintInPage, PrintOutPage, WeighbridgePage, } from './pages'; import strings from './strings'; +import registryStrings from '../grains-registry/strings'; /** Grains "permits" slice: permit list / order form / queue / destinations / distribution / weighbridges / print pages. */ export const routes: RouteObject[] = [ { path: '/grains/permits', element: }, - { path: '/grains/permits/queue', element: }, { path: '/grains/permits/destinations', element: }, { path: '/grains/permits/manual-input', element: }, { path: '/grains/permits/activation', element: }, { path: '/grains/permits/distribution', element: }, { path: '/grains/permits/weighbridge', element: }, + { path: '/grains/permits/close', element: }, + { path: '/grains/permits/truck-inquiry', element: }, + { path: '/grains/orders/supply', element: }, { path: '/grains/permits/:id', element: , handle: { crumb: strings['pm.crumb.view'] } }, { path: '/grains/permits/:id/print/accept', element: , handle: { crumb: strings['pm.crumb.print'] } }, { path: '/grains/permits/:id/print/in', element: , handle: { crumb: strings['pm.crumb.print'] } }, @@ -35,11 +40,13 @@ export const menu: MenuItem[] = [ icon: AssignmentIcon, children: [ { key: 'grains.permits.list', title: strings['pm.menu.permits'], icon: LocalShippingIcon, path: '/grains/permits' }, - { key: 'grains.permits.queue', title: strings['pm.menu.queue'], icon: SortIcon, path: '/grains/permits/queue' }, + { key: 'grains.permits.distribution', title: strings['pm.menu.distribution'], icon: TuneIcon, path: '/grains/permits/distribution' }, { key: 'grains.permits.destinations', title: strings['pm.menu.destinations'], icon: AltRouteIcon, path: '/grains/permits/destinations' }, { key: 'grains.permits.manualEntry', title: strings['pm.menu.manualInput'], icon: EditNoteIcon, path: '/grains/permits/manual-input' }, { key: 'grains.permits.activation', title: strings['pm.menu.activation'], icon: PlaylistAddCheckIcon, path: '/grains/permits/activation' }, - { key: 'grains.permits.distribution', title: strings['pm.menu.distribution'], icon: TuneIcon, path: '/grains/permits/distribution' }, + { key: 'grains.permits.close', title: strings['pm.menu.close'], icon: LockIcon, path: '/grains/permits/close' }, + { key: 'grains.permits.truckStatus', title: strings['pm.menu.inquiry'], icon: SearchIcon, path: '/grains/permits/truck-inquiry' }, + { key: 'grains.registry.blacklist', title: registryStrings['reg.menu.blacklist'], icon: BlockIcon, path: '/grains/registry/blacklist', createPath: '/grains/registry/blacklist/new' }, { key: 'grains.permits.weighbridge', title: strings['pm.menu.weighbridge'], icon: ScaleIcon, path: '/grains/permits/weighbridge' }, ], }, diff --git a/web/src/features/grains-permits/strings.ts b/web/src/features/grains-permits/strings.ts index 4605af9..45ac12d 100644 --- a/web/src/features/grains-permits/strings.ts +++ b/web/src/features/grains-permits/strings.ts @@ -37,15 +37,29 @@ export default defineStrings({ // ---- detail / order form 'pm.detail.title': { en: 'Permit {pn}', ar: 'الارسالية {pn}' }, 'pm.detail.status': { en: 'Status', ar: 'الحالة' }, + 'pm.detail.sectionPermit': { en: 'Permit information', ar: 'معلومات الارسالية' }, + 'pm.detail.sectionTruck': { en: 'Truck information', ar: 'معلومات القاطرة' }, + 'pm.detail.sectionTrailer': { en: 'Trailer information', ar: 'معلومات المقطورة' }, + 'pm.detail.sectionDriver': { en: 'Driver information', ar: 'معلومات السائق' }, + 'pm.detail.pn': { en: 'Permit no.', ar: 'رقم الارسالية' }, + 'pm.detail.truckNo': { en: 'Truck no.', ar: 'رقم القاطرة' }, + 'pm.detail.trailerNo': { en: 'Trailer no.', ar: 'رقم المقطورة' }, + 'pm.detail.chassis': { en: 'Chassis no.', ar: 'رقم الشصي' }, + 'pm.detail.axles': { en: 'Axle loads', ar: 'الأحمال المحورية' }, + 'pm.detail.licenseDate': { en: 'License date', ar: 'تاريخ الترخيص' }, + 'pm.detail.nnpn': { en: 'National no.', ar: 'الرقم الوطني' }, + 'pm.detail.driverName': { en: 'Driver name', ar: 'اسم السائق' }, + 'pm.detail.licenseNo': { en: 'License no.', ar: 'رقم الرخصة' }, + 'pm.detail.licenseExpiry': { en: 'License expiry date', ar: 'تاريخ انتهاء الترخيص' }, 'pm.detail.queueNo': { en: 'Queue no.', ar: 'رقم الدور' }, - 'pm.detail.cargo': { en: 'Cargo', ar: 'الحمولة' }, - 'pm.detail.shift': { en: 'Shift', ar: 'الفترة' }, + 'pm.detail.cargo': { en: 'Cargo type', ar: 'نوع المادة' }, + 'pm.detail.shift': { en: 'Shift', ar: 'الشفت' }, 'pm.detail.operation': { en: 'Operation', ar: 'نوع العملية' }, 'pm.detail.truck': { en: 'Truck', ar: 'القاطرة' }, 'pm.detail.trailer': { en: 'Trailer', ar: 'المقطورة' }, 'pm.detail.driver': { en: 'Driver', ar: 'السائق' }, 'pm.order.submitTitle': { en: 'Submit the order', ar: 'تقديم الطلب' }, - 'pm.order.editTitle': { en: 'Edit the order', ar: 'تعديل الطلب' }, + 'pm.order.editTitle': { en: 'Edit information', ar: 'تعديل المعلومات' }, 'pm.order.pn': { en: 'Permit no.', ar: 'رقم الارسالية' }, 'pm.order.tn': { en: 'Truck no.', ar: 'رقم القاطرة' }, 'pm.order.trn': { en: 'Trailer no.', ar: 'رقم المقطورة' }, @@ -58,9 +72,9 @@ export default defineStrings({ 'pm.order.update': { en: 'Save changes', ar: 'حفظ التعديلات' }, 'pm.order.notRegistered': { en: 'Not registered', ar: 'غير مسجلة' }, 'pm.order.driverMissing': { en: 'The driver must be registered in the drivers screen', ar: 'السائق يجب ان يكون مسجل في شاشة السائقين' }, - 'pm.events.title': { en: 'Permit events', ar: 'احداث الارسالية' }, - 'pm.events.date': { en: 'Date', ar: 'التاريخ' }, - 'pm.events.type': { en: 'Event', ar: 'الحدث' }, + 'pm.events.title': { en: 'Movement log', ar: 'سجل الحركات' }, + 'pm.events.date': { en: 'Movement date', ar: 'تاريخ الحركة' }, + 'pm.events.type': { en: 'Movement', ar: 'الحركة' }, 'pm.events.by': { en: 'Done by', ar: 'بواسطة' }, 'pm.events.status': { en: 'Status', ar: 'الحالة' }, 'pm.events.weight': { en: 'Weight', ar: 'الوزن' }, @@ -78,7 +92,7 @@ export default defineStrings({ 'pm.dest.subtitle': { en: 'Assign a destination to a supply permit', ar: 'تحديد وجهة ارسالية تموين' }, 'pm.menu.manualInput': { en: 'Manual input', ar: 'الادخال اليدوي' }, 'pm.menu.activation': { en: 'Activate orders', ar: 'تفعيل الطلبيات' }, - 'pm.manual.title': { en: 'Manual input', ar: 'الادخال اليدوي' }, + 'pm.manual.title': { en: 'Manual input', ar: 'شاشة الادخال اليدوي' }, 'pm.manual.subtitle': { en: 'Enter a truck by hand against an order date and destination', ar: 'ادخال شاحنة يدوياً على طلبية ووجهة' }, 'pm.activation.title': { en: 'Activate orders', ar: 'تفعيل الطلبيات' }, 'pm.activation.subtitle': { en: 'Activate or deactivate the orders of the day', ar: 'تفعيل وإلغاء تفعيل طلبيات اليوم' }, @@ -86,10 +100,10 @@ export default defineStrings({ 'pm.dest.cargo': { en: 'Cargo', ar: 'الحمولة' }, 'pm.dest.confirm': { en: 'Assign this destination to the permit?', ar: 'هل تريد تحديد هذه الوجهة للارسالية؟' }, 'pm.manual.orderDate': { en: 'Order date', ar: 'تاريخ الطلبية' }, - 'pm.manual.order': { en: 'Order', ar: 'الطلبية' }, + 'pm.manual.order': { en: 'Destination', ar: 'وجهة' }, 'pm.manual.noOrders': { en: 'No orders available', ar: 'لا توجد طلبيات متاحة' }, - 'pm.manual.ltw': { en: 'First weight (tare)', ar: 'الوزن الأول' }, - 'pm.manual.lgw': { en: 'Second weight (gross)', ar: 'الوزن الثاني' }, + 'pm.manual.ltw': { en: 'Tare weight', ar: 'وزن فارغ' }, + 'pm.manual.lgw': { en: 'Gross weight', ar: 'وزن قائم' }, 'pm.manual.altList': { en: 'List orders of the permit type', ar: 'طلبيات حسب نوع الارسالية' }, 'pm.manual.confirm': { en: 'Assign the destination manually and record the weights?', ar: 'هل تريد تحديد الوجهة يدويا وتسجيل الأوزان؟' }, 'pm.activate.loc': { en: 'Loading site', ar: 'الموقع' }, @@ -133,24 +147,40 @@ export default defineStrings({ // ---- weighbridges 'pm.wb.title': { en: 'Weighbridges', ar: 'القبّان' }, - 'pm.wb.subtitle': { en: 'Entry / exit weighings, manual weighing and manual closing', ar: 'الوزن عند الدخول والخروج والوزن اليدوي واغلاق التصريح' }, + 'pm.wb.subtitle': { en: 'Manual weighing', ar: 'الوزن اليدوي' }, 'pm.wb.tabEnter': { en: 'Entry weighing', ar: 'وزن الدخول' }, 'pm.wb.tabExit': { en: 'Exit weighing', ar: 'وزن الخروج' }, 'pm.wb.tabManual': { en: 'Manual weighing', ar: 'وزن يدوي' }, 'pm.wb.tabLoading': { en: 'Loading weights', ar: 'أوزان التحميل' }, 'pm.wb.tabDischarge': { en: 'Discharge weights', ar: 'أوزان التفريغ' }, 'pm.wb.tabCounts': { en: 'Trucks per site', ar: 'السيارات حسب الموقع' }, - 'pm.wb.tabClose': { en: 'Close a permit', ar: 'اغلاق تصريح' }, + 'pm.wb.tabClose': { en: 'Close a permit', ar: 'اغلاق إرسالية' }, + 'pm.menu.close': { en: 'Close a permit', ar: 'اغلاق إرسالية' }, + 'pm.menu.inquiry': { en: 'Truck inquiry', ar: 'استعلام عن سيارة' }, + 'pm.menu.supply': { en: 'Supply order', ar: 'طلبية التموين' }, + 'pm.close.title': { en: 'Close a permit', ar: 'اغلاق إرسالية' }, + 'pm.close.subtitle': { en: 'Close a permit manually by its number', ar: 'اغلاق الإرسالية يدويا برقمها' }, + 'pm.inquiry.subtitle': { en: 'Distribution status of a truck', ar: 'حالة توزيع السيارة' }, + 'pm.supply.title': { en: 'Supply order', ar: 'طلبية التموين' }, + 'pm.supply.subtitle': { en: 'Distributed permits per destination type', ar: 'الارساليات الموزعة حسب نوع الوجهة' }, 'pm.wb.weight': { en: 'Weight (kg)', ar: 'الوزن (كغم)' }, 'pm.wb.tare': { en: 'Tare weight', ar: 'الوزن الفارغ' }, 'pm.wb.gross': { en: 'Gross weight', ar: 'الوزن القائم' }, 'pm.wb.first': { en: 'First weight (tare)', ar: 'الوزن الأول' }, 'pm.wb.second': { en: 'Second weight (gross)', ar: 'الوزن الثاني' }, 'pm.wb.location': { en: 'Weighbridge location no.', ar: 'رقم موقع القبان' }, + 'pm.form.permitData': { en: 'Permit data', ar: 'بيانات الارسالية' }, + 'pm.form.manualData': { en: 'Manual entry data', ar: 'بيانات الادخال اليدوي' }, + 'pm.form.truckData': { en: 'Truck', ar: 'بيانات السيارة' }, + 'pm.form.result': { en: 'Result', ar: 'النتيجة' }, + 'pm.wb.truckNo': { en: 'Truck no.', ar: 'رقم السيارة' }, + 'pm.wb.dest': { en: 'Destination', ar: 'الوجهة' }, + 'pm.wb.search': { en: 'Search', ar: 'بحث' }, + 'pm.wb.card': { en: 'Weighbridge card', ar: 'كرت القبان' }, 'pm.wb.findDest': { en: 'Find destination', ar: 'البحث عن الوجهة' }, 'pm.wb.loc': { en: 'Site', ar: 'الموقع' }, 'pm.wb.trucks': { en: 'Trucks', ar: 'عدد السيارات' }, - 'pm.wb.close': { en: 'Close the permit', ar: 'اغلاق التصريح' }, + 'pm.wb.close': { en: 'Close the permit', ar: 'اغلاق الإرسالية' }, 'pm.wb.closeConfirm': { en: 'Close this permit manually?', ar: 'هل تريد اغلاق التصريح يدويا؟' }, // ---- print diff --git a/web/src/features/grains-registry/routes.tsx b/web/src/features/grains-registry/routes.tsx index 3bc0ce6..c76a85d 100644 --- a/web/src/features/grains-registry/routes.tsx +++ b/web/src/features/grains-registry/routes.tsx @@ -1,7 +1,6 @@ import type { RouteObject } from 'react-router-dom'; import BadgeIcon from '@mui/icons-material/Badge'; import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings'; -import BlockIcon from '@mui/icons-material/Block'; import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import PinDropIcon from '@mui/icons-material/PinDrop'; import RvHookupIcon from '@mui/icons-material/RvHookup'; @@ -51,7 +50,6 @@ export const menu: MenuItem[] = [ title: strings['reg.menu.controlGroup'], icon: AdminPanelSettingsIcon, children: [ - { key: 'grains.registry.blacklist', title: strings['reg.menu.blacklist'], icon: BlockIcon, path: '/grains/registry/blacklist', createPath: '/grains/registry/blacklist/new' }, { key: 'grains.registry.weighbridge', title: strings['reg.menu.weighbridge'], icon: ScaleIcon, path: '/grains/registry/weighbridge-control' }, ], }, diff --git a/web/src/features/grains-reports/pages.tsx b/web/src/features/grains-reports/pages.tsx index 1ab04dd..429ab00 100644 --- a/web/src/features/grains-reports/pages.tsx +++ b/web/src/features/grains-reports/pages.tsx @@ -6,7 +6,6 @@ import { } from '@mui/material'; import DownloadIcon from '@mui/icons-material/Download'; import PlayArrowIcon from '@mui/icons-material/PlayArrow'; -import PrintIcon from '@mui/icons-material/Print'; import UploadFileIcon from '@mui/icons-material/UploadFile'; import { ApiError, type PagedResult } from '@/api/client'; import { DataGrid } from '@/components/DataGrid'; @@ -96,10 +95,6 @@ function useRange(opts: { company?: boolean; cargo?: boolean }) { return { bar, params, lang, t }; } -const PrintButton = ({ label }: { label: string }) => ( - -); - function ReportShell({ title, subtitle, bar, params, query, print = true, children }: { title: string; subtitle?: string; bar: ReactNode; params: RangeParams | null; query: { isPending: boolean; isError: boolean; error: unknown; isFetching: boolean; data: unknown }; @@ -109,7 +104,7 @@ function ReportShell({ title, subtitle, bar, params, query, print = true, childr const { user } = useAuth(); return ( - : undefined} /> + {bar} {!params && } {params && query.isPending && } @@ -420,7 +415,7 @@ export function MotMultiTripsPage() { const names = [t('rpt.mot.companies'), t('rpt.mot.individuals')]; return ( - : undefined} /> + {q.isPending && } {q.isError && {t('rpt.loadError')}: {errText(q.error, '')}} {r && ( @@ -511,7 +506,6 @@ function TableReportBody({ meta }: { meta: TableReportMeta }) { actions={ - } /> diff --git a/web/src/features/grains-reports/routes.tsx b/web/src/features/grains-reports/routes.tsx index 0ba5eec..2f86f88 100644 --- a/web/src/features/grains-reports/routes.tsx +++ b/web/src/features/grains-reports/routes.tsx @@ -2,7 +2,6 @@ import type { RouteObject } from 'react-router-dom'; import AssessmentIcon from '@mui/icons-material/Assessment'; import BarChartIcon from '@mui/icons-material/BarChart'; import DashboardIcon from '@mui/icons-material/Dashboard'; -import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import PieChartIcon from '@mui/icons-material/PieChart'; import ScaleIcon from '@mui/icons-material/Scale'; import TableChartIcon from '@mui/icons-material/TableChart'; @@ -14,6 +13,7 @@ import { } from './pages'; import { tableReports } from './meta'; import strings from './strings'; +import orderStrings from '../grains-orders/strings'; const B = '/grains/reports'; @@ -36,53 +36,28 @@ const table = (key: string, icon: MenuItem['icon'] = TableChartIcon): MenuItem = export const menu: MenuItem[] = [ { + // One flat group: every report is a direct entry (no sub menus). Each entry is shown by its own permission key. key: 'grains.reports', title: strings['rpt.menu.group'], icon: AssessmentIcon, children: [ - { - key: 'grains.reports.trips', title: strings['rpt.menu.trips'], icon: BarChartIcon, - children: [ - { key: 'grains.reports.dashboard', title: strings['rpt.menu.dashboard'], icon: DashboardIcon, path: `${B}/dashboard` }, - { key: 'grains.reports.numOfTrips', title: strings['rpt.menu.numOfTrips'], icon: BarChartIcon, path: `${B}/trips/num-of-trips` }, - { key: 'grains.reports.quota', title: strings['rpt.menu.quota'], icon: PieChartIcon, path: `${B}/trips/quota` }, - { key: 'grains.reports.frequency', title: strings['rpt.menu.frequency'], icon: BarChartIcon, path: `${B}/trips/frequency` }, - { key: 'grains.reports.distribution', title: strings['rpt.menu.distribution'], icon: PieChartIcon, path: `${B}/trips/distribution` }, - { key: 'grains.reports.details', title: strings['rpt.menu.details'], icon: TableChartIcon, path: `${B}/trips/details` }, - ], - }, - { - key: 'grains.reports.ops', title: strings['rpt.menu.ops'], icon: ScaleIcon, - children: [ - table('weighbridge-events', ScaleIcon), table('waybridge-summary', ScaleIcon), table('waybridge-details', ScaleIcon), - table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'), - ], - }, - { - key: 'grains.reports.orders', title: strings['rpt.menu.orders'], icon: TableChartIcon, - children: [ - table('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'), - table('companies-turn'), table('owners-turn'), - ], - }, - { - key: 'grains.reports.registry', title: strings['rpt.menu.registry'], icon: LocalShippingIcon, - children: [table('drivers'), table('trucks')], - }, - { - key: 'grains.reports.mot', title: strings['rpt.menu.mot'], icon: BarChartIcon, - children: [ - { key: 'grains.reports.motMulti', title: strings['rpt.menu.motMulti'], icon: BarChartIcon, path: `${B}/mot/multi-trips` }, - table('mot-grain-cube'), table('mot-grain-frequency'), - ], - }, - { - key: 'grains.reports.imports', title: strings['rpt.menu.imports'], icon: UploadFileIcon, - children: [ - { key: 'grains.reports.phoneApprovals', title: strings['rpt.menu.phoneApprovals'], icon: UploadFileIcon, path: `${B}/imports/phone-approvals` }, - { key: 'grains.reports.wbFiles', title: strings['rpt.menu.wbFiles'], icon: UploadFileIcon, path: `${B}/imports/weighbridge-files`, roles: ['SU'] }, - ], - }, + { key: 'grains.reports.dashboard', title: strings['rpt.menu.dashboard'], icon: DashboardIcon, path: `${B}/dashboard` }, + { key: 'grains.reports.numOfTrips', title: strings['rpt.menu.numOfTrips'], icon: BarChartIcon, path: `${B}/trips/num-of-trips` }, + { key: 'grains.reports.quota', title: strings['rpt.menu.quota'], icon: PieChartIcon, path: `${B}/trips/quota` }, + { key: 'grains.reports.frequency', title: strings['rpt.menu.frequency'], icon: BarChartIcon, path: `${B}/trips/frequency` }, + { key: 'grains.reports.distribution', title: strings['rpt.menu.distribution'], icon: PieChartIcon, path: `${B}/trips/distribution` }, + { key: 'grains.reports.details', title: strings['rpt.menu.details'], icon: TableChartIcon, path: `${B}/trips/details` }, + table('weighbridge-events', ScaleIcon), table('waybridge-summary', ScaleIcon), table('waybridge-details', ScaleIcon), + table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'), + table('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'), + table('companies-turn'), table('owners-turn'), + { key: 'grains.orders.reportOrders', title: orderStrings['ord.menu.reportOrders'], icon: AssessmentIcon, path: '/grains/orders/reports/tender-orders' }, + { key: 'grains.orders.reportFinance', title: orderStrings['ord.menu.reportFinance'], icon: AssessmentIcon, path: '/grains/orders/reports/financial-billing' }, + table('drivers'), table('trucks'), + { key: 'grains.reports.motMulti', title: strings['rpt.menu.motMulti'], icon: BarChartIcon, path: `${B}/mot/multi-trips` }, + table('mot-grain-cube'), table('mot-grain-frequency'), + { key: 'grains.reports.phoneApprovals', title: strings['rpt.menu.phoneApprovals'], icon: UploadFileIcon, path: `${B}/imports/phone-approvals` }, + { key: 'grains.reports.wbFiles', title: strings['rpt.menu.wbFiles'], icon: UploadFileIcon, path: `${B}/imports/weighbridge-files`, roles: ['SU'] }, ], }, ]; diff --git a/web/src/providers/AuthProvider.tsx b/web/src/providers/AuthProvider.tsx index 46571b5..b7ca788 100644 --- a/web/src/providers/AuthProvider.tsx +++ b/web/src/providers/AuthProvider.tsx @@ -92,7 +92,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { // No permissions answer (request failed) = nothing is allowed except for the role checks above; SU gets all=true. const can = useCallback( - (key: string) => !!perms && (perms.all || perms.allowed.includes(key)), + (key: string) => !!perms && !perms.denied.includes(key) && (perms.all || perms.allowed.includes(key)), [perms], ); diff --git a/web/src/shell/Sidebar.tsx b/web/src/shell/Sidebar.tsx index 8e391c3..0b2aed7 100644 --- a/web/src/shell/Sidebar.tsx +++ b/web/src/shell/Sidebar.tsx @@ -1,4 +1,4 @@ -import { Fragment, useEffect, useState, type MouseEvent } from 'react'; +import { Fragment, useEffect, useMemo, useState, type MouseEvent } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import { Box, Collapse, Divider, Drawer, IconButton, List, ListItemButton, ListItemText, Menu, MenuItem, Tooltip, Typography, @@ -13,7 +13,7 @@ import HomeIcon from '@mui/icons-material/Home'; import { Logo } from '@/components/Logo'; import { useUi } from '@/i18n/useUi'; import { badgeColors } from '@/theme/tokens'; -import { pathMatches } from './menuUtils'; +import { findOwner } from './menuUtils'; import type { MenuItem as Item } from './types'; export const DRAWER_FULL = 272; @@ -64,22 +64,17 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob const [open, setOpen] = useState>({}); const [pop, setPop] = useState<{ anchor: HTMLElement; item: Item } | null>(null); - // open the group that owns the current page + // The entry that owns the current page = longest matching path (so /grains/orders/billing belongs to billing, + // not to the orders list whose path is only a prefix of it). + const owner = useMemo(() => findOwner(items, pathname), [items, pathname]); + const activeKeys = useMemo(() => new Set(owner ? [owner.item.key, ...owner.trail.map((g) => g.key)] : []), [owner]); + const ownerTrail = owner ? owner.trail.map((g) => g.key).join('|') : ''; + + // open the groups that own the page when the page changes (not on every re-render, so a group can be collapsed by hand) useEffect(() => { - const next: Record = {}; - const walk = (list: Item[]): boolean => { - let any = false; - for (const it of list) { - const own = pathMatches(pathname, it.path) || pathMatches(pathname, it.createPath); - const kid = it.children ? walk(it.children) : false; - if (kid) next[it.key] = true; - any = any || own || kid; - } - return any; - }; - walk(items); - setOpen((o) => ({ ...o, ...next })); - }, [pathname, items]); + if (!ownerTrail) return; + setOpen((o) => ({ ...o, ...Object.fromEntries(ownerTrail.split('|').map((k) => [k, true])) })); + }, [ownerTrail, pathname]); const go = (path: string) => { navigate(path); @@ -87,12 +82,13 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob setPop(null); }; - const isActive = (it: Item): boolean => - (it.path === '/' ? pathname === '/' : pathMatches(pathname, it.path)) || pathMatches(pathname, it.createPath) || !!it.children?.some(isActive); + const isActive = (it: Item): boolean => (it.key === 'home' ? pathname === '/' : activeKeys.has(it.key)); const renderRow = (it: Item, depth: number) => { const isGroup = !!it.children?.length; + const hasPage = isGroup && !!it.path; // an entry with its own page AND sub entries const active = isActive(it); + const ownActive = hasPage && owner?.item.key === it.key; const title = tr(it.title); if (mini) { @@ -113,8 +109,12 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob <> (isGroup ? setOpen((o) => ({ ...o, [it.key]: !o[it.key] })) : it.path && go(it.path))} + selected={(active && !isGroup) || ownActive} + onClick={() => { + if (hasPage) { setOpen((o) => ({ ...o, [it.key]: true })); go(it.path!); } + else if (isGroup) setOpen((o) => ({ ...o, [it.key]: !o[it.key] })); + else if (it.path) go(it.path); + }} sx={{ borderRadius: 1.5, gap: 1.25, paddingInlineStart: 1 + depth * 2, py: 0.75, minWidth: 0, flex: 1 }} > @@ -122,8 +122,13 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob primary={title} slotProps={{ primary: { noWrap: true, sx: { fontWeight: active ? 700 : 500, fontSize: depth ? 14 : 15 } } }} /> - {isGroup && (open[it.key] ? : )} + {isGroup && !hasPage && (open[it.key] ? : )} + {hasPage && ( + setOpen((o) => ({ ...o, [it.key]: !o[it.key] }))} sx={{ marginInlineStart: 0.25 }}> + {open[it.key] ? : } + + )} {it.createPath && ( go(it.createPath!)} sx={{ marginInlineStart: 0.5, color: colorOf(it) }}> @@ -165,6 +170,12 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob )} setPop(null)} anchorOrigin={{ vertical: 'top', horizontal: dir === 'rtl' ? 'left' : 'right' }} transformOrigin={{ vertical: 'top', horizontal: dir === 'rtl' ? 'right' : 'left' }}> {pop && {tr(pop.item.title)}} + {pop?.item.path && ( + go(pop.item.path!)} sx={{ gap: 1.5 }}> + + {tr(pop.item.title)} + + )} {pop?.item.children?.map((c) => ( c.path && go(c.path)} sx={{ gap: 1.5, paddingInlineEnd: c.createPath ? 0.5 : 2 }}> diff --git a/web/src/shell/menuUtils.ts b/web/src/shell/menuUtils.ts index b9bf1aa..b8f281e 100644 --- a/web/src/shell/menuUtils.ts +++ b/web/src/shell/menuUtils.ts @@ -5,7 +5,7 @@ import type { MenuItem } from './types'; * SU = everything). Groups (children) are visible when the roles allow and at least one child is (see filterMenu). */ export function itemAllowed(hasRole: (roles?: string[]) => boolean, can: (key: string) => boolean) { - return (it: MenuItem): boolean => hasRole(it.roles) && (it.children ? true : can(it.key)); + return (it: MenuItem): boolean => hasRole(it.roles) && (it.children && !it.path ? true : can(it.key)); } /** Recursively keep only items the role may see; drop groups left empty. */