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 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-12 11:18:04 +03:00
parent 0c0b64239c
commit 21328b7d1a
43 changed files with 885 additions and 431 deletions

28
db/disabled-features.sql Normal file
View File

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

View File

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

View File

@ -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.manualEntry')
-- إيقاف\تفعيل الاستنكاف -- إيقاف\تفعيل الاستنكاف
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.absence') 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.orders.weights')
-- تقارير حركات قبان التحميل والتفريغ -- تقارير حركات قبان التحميل والتفريغ
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.weighbridge-events') 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 ('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 ('GTO', 'grains.reports.t.companies-turn')
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.companies-turn') INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.companies-turn')

View File

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

View File

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

View File

@ -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`) 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) 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 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. API and on the user's next page reload or sign-in.

View File

@ -62,6 +62,10 @@ public sealed class OrdersController(
[RequirePermission(PermissionKeys.OrdersCompanyDest)] [RequirePermission(PermissionKeys.OrdersCompanyDest)]
public Task<IReadOnlyList<LookupOptionDto>> PackedDestinations(CancellationToken ct) => lookups.PackedDestinationsAsync(ct); public Task<IReadOnlyList<LookupOptionDto>> PackedDestinations(CancellationToken ct) => lookups.PackedDestinationsAsync(ct);
[HttpGet("lookups/destination-groups")]
[RequirePermission(PermissionKeys.OrdersCompanyDest)]
public Task<DestinationGroupsDto> DestinationGroups(CancellationToken ct) => lookups.DestinationGroupsAsync(ct);
[HttpGet("lookups/companies")] [HttpGet("lookups/companies")]
[RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersReportFinance)] [RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersReportFinance)]
public Task<IReadOnlyList<CompanyOptionDto>> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct); public Task<IReadOnlyList<CompanyOptionDto>> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct);

View File

@ -144,59 +144,59 @@ public sealed class PermitQueueController(IQueueService queue) : ControllerBase
{ {
/// <summary>getGNQueueList (queueGrid.cfm).</summary> /// <summary>getGNQueueList (queueGrid.cfm).</summary>
[HttpGet] [HttpGet]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<PagedResult<QueueItem>> List([FromQuery] string? tn, [FromQuery] string? pn, public Task<PagedResult<QueueItem>> List([FromQuery] string? tn, [FromQuery] string? pn,
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) =>
queue.ListAsync(new QueueSearchQuery(tn, pn), new PageRequest(page, pageSize), ct); queue.ListAsync(new QueueSearchQuery(tn, pn), new PageRequest(page, pageSize), ct);
/// <summary>AddToQueue (CreateQueue.cfm).</summary> /// <summary>AddToQueue (CreateQueue.cfm).</summary>
[HttpPost] [HttpPost]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<PermitOperationResult> Add(AddToQueueRequest request, CancellationToken ct) => queue.AddToQueueAsync(request, ct); public Task<PermitOperationResult> Add(AddToQueueRequest request, CancellationToken ct) => queue.AddToQueueAsync(request, ct);
[HttpGet("trailer-of/{tn}")] [HttpGet("trailer-of/{tn}")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public async Task<ActionResult<object>> TrailerOf(string tn, CancellationToken ct) => new { trailer = await queue.GetTrailerNumberAsync(tn, ct) }; public async Task<ActionResult<object>> TrailerOf(string tn, CancellationToken ct) => new { trailer = await queue.GetTrailerNumberAsync(tn, ct) };
/// <summary>checkTrucks.</summary> /// <summary>checkTrucks.</summary>
[HttpPost("check-trucks")] [HttpPost("check-trucks")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<PermitOperationResult> CheckTrucks([FromQuery] long tn, [FromQuery] long scac, CancellationToken ct) => queue.CheckTrucksAsync(tn, scac, ct); public Task<PermitOperationResult> CheckTrucks([FromQuery] long tn, [FromQuery] long scac, CancellationToken ct) => queue.CheckTrucksAsync(tn, scac, ct);
/// <summary>parseGrainsPermits job, on demand: create OPEN permits for the given companies.</summary> /// <summary>parseGrainsPermits job, on demand: create OPEN permits for the given companies.</summary>
[HttpPost("seed")] [HttpPost("seed")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<PermitOperationResult> Seed(SeedPermitsRequest request, CancellationToken ct) => queue.SeedPermitsAsync(request, ct); public Task<PermitOperationResult> Seed(SeedPermitsRequest request, CancellationToken ct) => queue.SeedPermitsAsync(request, ct);
// ---- TCS permit form (createPermit.cfm) // ---- TCS permit form (createPermit.cfm)
[HttpGet("{id:long}/tcs-form")] [HttpGet("{id:long}/tcs-form")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<TcsFormDataDto?> TcsForm(long id, CancellationToken ct) => queue.GetTcsFormDataAsync(id, ct); public Task<TcsFormDataDto?> TcsForm(long id, CancellationToken ct) => queue.GetTcsFormDataAsync(id, ct);
[HttpGet("tcs/routing-templates")] [HttpGet("tcs/routing-templates")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<IReadOnlyList<RoutingTemplateDto>> RoutingTemplates([FromQuery] long origin, [FromQuery] long destination, public Task<IReadOnlyList<RoutingTemplateDto>> RoutingTemplates([FromQuery] long origin, [FromQuery] long destination,
[FromQuery] string shipmentMode, [FromQuery] string firms, CancellationToken ct) => [FromQuery] string shipmentMode, [FromQuery] string firms, CancellationToken ct) =>
queue.GetRoutingTemplatesAsync(origin, destination, shipmentMode, firms, ct); queue.GetRoutingTemplatesAsync(origin, destination, shipmentMode, firms, ct);
[HttpGet("tcs/origins")] [HttpGet("tcs/origins")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<IReadOnlyList<LookupItem>> Origins([FromQuery] long routing, CancellationToken ct) => queue.GetOriginAddressesAsync(routing, ct); public Task<IReadOnlyList<LookupItem>> Origins([FromQuery] long routing, CancellationToken ct) => queue.GetOriginAddressesAsync(routing, ct);
[HttpGet("tcs/ph-routes")] [HttpGet("tcs/ph-routes")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<IReadOnlyList<RoutingTemplateDto>> PhRoutes(CancellationToken ct) => queue.GetPhRoutesAsync(ct); public Task<IReadOnlyList<RoutingTemplateDto>> PhRoutes(CancellationToken ct) => queue.GetPhRoutesAsync(ct);
[HttpGet("tcs/clearing-agent/{can:long}")] [HttpGet("tcs/clearing-agent/{can:long}")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public async Task<ActionResult<object>> ClearingAgent(long can, CancellationToken ct) => new { name = await queue.GetClearingAgentNameAsync(can, ct) }; public async Task<ActionResult<object>> ClearingAgent(long can, CancellationToken ct) => new { name = await queue.GetClearingAgentNameAsync(can, ct) };
[HttpGet("tcs/fop/{fop}")] [HttpGet("tcs/fop/{fop}")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<TcsFopDetail> Fop(string fop, CancellationToken ct) => queue.GetFopDetailAsync(fop, ct); public Task<TcsFopDetail> Fop(string fop, CancellationToken ct) => queue.GetFopDetailAsync(fop, ct);
[HttpPost("{id:long}/tcs-permit")] [HttpPost("{id:long}/tcs-permit")]
[RequirePermission(PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.PermitsCreate)]
public Task<PermitOperationResult> CreateTcsPermit(long id, CreateTcsPermitRequest request, CancellationToken ct) => public Task<PermitOperationResult> CreateTcsPermit(long id, CreateTcsPermitRequest request, CancellationToken ct) =>
queue.CreateTcsPermitAsync(id, request, ct); queue.CreateTcsPermitAsync(id, request, ct);
} }
@ -209,7 +209,7 @@ public sealed class PermitQueueController(IQueueService queue) : ControllerBase
public sealed class PermitDestinationsController(IDestinationService destinations) : ControllerBase public sealed class PermitDestinationsController(IDestinationService destinations) : ControllerBase
{ {
[HttpGet("lookups/locations")] [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<IReadOnlyList<LookupItem>> Locations(CancellationToken ct) => destinations.GetGrainsLocationsAsync(ct); public Task<IReadOnlyList<LookupItem>> Locations(CancellationToken ct) => destinations.GetGrainsLocationsAsync(ct);
/// <summary>Destination filter of the permit list (GNPermits.cfm): every GN exit location by name, active or not.</summary> /// <summary>Destination filter of the permit list (GNPermits.cfm): every GN exit location by name, active or not.</summary>
@ -218,11 +218,11 @@ public sealed class PermitDestinationsController(IDestinationService destination
public Task<IReadOnlyList<LookupItem>> FilterDestinations(CancellationToken ct) => destinations.GetPermitFilterDestinationsAsync(ct); public Task<IReadOnlyList<LookupItem>> FilterDestinations(CancellationToken ct) => destinations.GetPermitFilterDestinationsAsync(ct);
[HttpGet("lookups/exit-locations")] [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<IReadOnlyList<LookupItem>> ExitLocations(CancellationToken ct) => destinations.GetExitLocationsAsync(ct); public Task<IReadOnlyList<LookupItem>> ExitLocations(CancellationToken ct) => destinations.GetExitLocationsAsync(ct);
[HttpGet("lookups/cargo-types")] [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<IReadOnlyList<LookupItem>> CargoTypes(CancellationToken ct) => destinations.GetCargoTypesAsync(ct); public Task<IReadOnlyList<LookupItem>> CargoTypes(CancellationToken ct) => destinations.GetCargoTypesAsync(ct);
[HttpGet("lookups/location-groups")] [HttpGet("lookups/location-groups")]
@ -230,7 +230,7 @@ public sealed class PermitDestinationsController(IDestinationService destination
public Task<LocationGroupsDto> LocationGroups(CancellationToken ct) => destinations.GetLocationGroupsAsync(ct); public Task<LocationGroupsDto> LocationGroups(CancellationToken ct) => destinations.GetLocationGroupsAsync(ct);
[HttpGet("lookups/companies")] [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<IReadOnlyList<CompanyOption>> Companies(CancellationToken ct) => destinations.GetCompaniesAsync(ct); public Task<IReadOnlyList<CompanyOption>> Companies(CancellationToken ct) => destinations.GetCompaniesAsync(ct);
[HttpGet("companies/{scac:long}")] [HttpGet("companies/{scac:long}")]
@ -328,7 +328,7 @@ public sealed class PermitDistributionController(IDistributionService distributi
public Task<IReadOnlyList<DistributionSummaryRow>> Summary(CancellationToken ct) => distribution.GetSummaryAsync(ct); public Task<IReadOnlyList<DistributionSummaryRow>> Summary(CancellationToken ct) => distribution.GetSummaryAsync(ct);
[HttpGet("pivot")] [HttpGet("pivot")]
[RequirePermission(PermissionKeys.PermitsDistribution)] [RequirePermission(PermissionKeys.PermitsDistribution, PermissionKeys.OrdersSupply)]
public Task<IReadOnlyList<DistributionPivotRow>> Pivot(CancellationToken ct) => distribution.GetPivotAsync(ct); public Task<IReadOnlyList<DistributionPivotRow>> Pivot(CancellationToken ct) => distribution.GetPivotAsync(ct);
[HttpGet("search-truck")] [HttpGet("search-truck")]

View File

@ -194,57 +194,57 @@ public sealed class RegistryController(
/// <summary>checkTrucks: every company must use its whole fleet before reusing a truck.</summary> /// <summary>checkTrucks: every company must use its whole fleet before reusing a truck.</summary>
[HttpPost("fleet-check")] [HttpPost("fleet-check")]
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.PermitsQueue)] [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.PermitsCreate)]
public Task<FleetCheckResult> FleetCheck(FleetCheckRequest request, CancellationToken ct) => ops.CheckTrucksAsync(request, ct); public Task<FleetCheckResult> FleetCheck(FleetCheckRequest request, CancellationToken ct) => ops.CheckTrucksAsync(request, ct);
/// <summary>validateNtpTrucks.</summary> /// <summary>validateNtpTrucks.</summary>
[HttpGet("validate-truck")] [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<object> ValidateTruck([FromQuery] string tn, CancellationToken ct) => new { validTn = await ops.ValidateNtpTruckAsync(tn ?? string.Empty, ct) }; public async Task<object> ValidateTruck([FromQuery] string tn, CancellationToken ct) => new { validTn = await ops.ValidateNtpTruckAsync(tn ?? string.Empty, ct) };
// ------------------------------------------------------------------------------------------ permit-screen lookups (grains.cfc) // ------------------------------------------------------------------------------------------ permit-screen lookups (grains.cfc)
/// <summary>grains.cfc getDriverInfo: latest permit of the driver (active status).</summary> /// <summary>grains.cfc getDriverInfo: latest permit of the driver (active status).</summary>
[HttpGet("permit-lookups/driver")] [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<DriverFromPermitDto?> DriverFromPermits([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverFromPermitsAsync(nnpn ?? string.Empty, ct); public Task<DriverFromPermitDto?> DriverFromPermits([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverFromPermitsAsync(nnpn ?? string.Empty, ct);
/// <summary>grains.cfc getTruckInfo: latest finished permit of the truck.</summary> /// <summary>grains.cfc getTruckInfo: latest finished permit of the truck.</summary>
[HttpGet("permit-lookups/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<TruckFromPermitDto?> TruckFromPermits([FromQuery] string tn, CancellationToken ct) => lookups.TruckFromPermitsAsync(tn ?? string.Empty, ct); public Task<TruckFromPermitDto?> TruckFromPermits([FromQuery] string tn, CancellationToken ct) => lookups.TruckFromPermitsAsync(tn ?? string.Empty, ct);
/// <summary>grains.cfc isTrailerInUse.</summary> /// <summary>grains.cfc isTrailerInUse.</summary>
[HttpGet("permit-lookups/trailer-in-use")] [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<IReadOnlyList<TrailerInUseDto>> TrailerInUse([FromQuery] string trn, [FromQuery] long? permitId, CancellationToken ct) => public Task<IReadOnlyList<TrailerInUseDto>> TrailerInUse([FromQuery] string trn, [FromQuery] long? permitId, CancellationToken ct) =>
lookups.TrailerInUseAsync(trn ?? string.Empty, permitId, ct); lookups.TrailerInUseAsync(trn ?? string.Empty, permitId, ct);
/// <summary>grains.cfc getTruckInfoFromTN.</summary> /// <summary>grains.cfc getTruckInfoFromTN.</summary>
[HttpGet("permit-lookups/permit-by-truck")] [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<PermitByTruckDto?> PermitByTruck([FromQuery] string tn, [FromQuery] string status, CancellationToken ct) => public Task<PermitByTruckDto?> PermitByTruck([FromQuery] string tn, [FromQuery] string status, CancellationToken ct) =>
lookups.PermitByTruckAsync(tn ?? string.Empty, status ?? string.Empty, ct); lookups.PermitByTruckAsync(tn ?? string.Empty, status ?? string.Empty, ct);
/// <summary>grains.cfc getTrailerNumber: the trailer of a truck.</summary> /// <summary>grains.cfc getTrailerNumber: the trailer of a truck.</summary>
[HttpGet("permit-lookups/truck-trailer")] [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<TrailerOfTruckDto> TruckTrailer([FromQuery] string tn, CancellationToken ct) => lookups.TrailerNumberOfTruckAsync(tn ?? string.Empty, ct); public Task<TrailerOfTruckDto> TruckTrailer([FromQuery] string tn, CancellationToken ct) => lookups.TrailerNumberOfTruckAsync(tn ?? string.Empty, ct);
/// <summary>grains.cfc getTNinfo (validate = ownership + MOT checks).</summary> /// <summary>grains.cfc getTNinfo (validate = ownership + MOT checks).</summary>
[HttpGet("permit-lookups/truck-info")] [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<TruckInfoForPermitDto> TruckInfo([FromQuery] string tn, [FromQuery] bool validate = true, CancellationToken ct = default) => public Task<TruckInfoForPermitDto> TruckInfo([FromQuery] string tn, [FromQuery] bool validate = true, CancellationToken ct = default) =>
lookups.TruckInfoAsync(tn ?? string.Empty, validate, ct); lookups.TruckInfoAsync(tn ?? string.Empty, validate, ct);
/// <summary>grains.cfc getTRNinfo.</summary> /// <summary>grains.cfc getTRNinfo.</summary>
[HttpGet("permit-lookups/trailer-info")] [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<TrailerInfoForPermitDto> TrailerInfo([FromQuery] string trn, CancellationToken ct) => lookups.TrailerInfoAsync(trn ?? string.Empty, ct); public Task<TrailerInfoForPermitDto> TrailerInfo([FromQuery] string trn, CancellationToken ct) => lookups.TrailerInfoAsync(trn ?? string.Empty, ct);
/// <summary>grains.cfc getDRVRinfo.</summary> /// <summary>grains.cfc getDRVRinfo.</summary>
[HttpGet("permit-lookups/driver-info")] [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<DriverInfoForPermitDto> DriverInfo([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverInfoAsync(nnpn ?? string.Empty, ct); public Task<DriverInfoForPermitDto> DriverInfo([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverInfoAsync(nnpn ?? string.Empty, ct);
// ------------------------------------------------------------------------------------------ MOT (register.cfc validate*) // ------------------------------------------------------------------------------------------ MOT (register.cfc validate*)

View File

@ -14,12 +14,14 @@ public static class PermissionKeys
public const string OrdersBilling = "grains.orders.billing"; public const string OrdersBilling = "grains.orders.billing";
public const string OrdersInvoices = "grains.orders.invoices"; public const string OrdersInvoices = "grains.orders.invoices";
public const string OrdersWeights = "grains.orders.weights"; public const string OrdersWeights = "grains.orders.weights";
/// <summary>طلبية التموين: distributed permits per destination type (orders menu).</summary>
public const string OrdersSupply = "grains.orders.supply";
public const string OrdersCompanyDest = "grains.orders.companyDest"; public const string OrdersCompanyDest = "grains.orders.companyDest";
public const string OrdersReportOrders = "grains.orders.reportOrders"; public const string OrdersReportOrders = "grains.orders.reportOrders";
public const string OrdersReportFinance = "grains.orders.reportFinance"; public const string OrdersReportFinance = "grains.orders.reportFinance";
public const string PermitsList = "grains.permits.list"; 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 PermitsDestinations = "grains.permits.destinations";
public const string PermitsDistribution = "grains.permits.distribution"; public const string PermitsDistribution = "grains.permits.distribution";
public const string PermitsWeighbridge = "grains.permits.weighbridge"; public const string PermitsWeighbridge = "grains.permits.weighbridge";
@ -85,14 +87,13 @@ public static class PermissionDefaults
[PermissionKeys.PermitsTruckOrder] = ["GTO"], // طلبية لسيارة [PermissionKeys.PermitsTruckOrder] = ["GTO"], // طلبية لسيارة
[PermissionKeys.RegistryBlacklist] = ["GTO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار [PermissionKeys.RegistryBlacklist] = ["GTO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار
[PermissionKeys.PermitsDistribution] = ["GTO", "GOO"], // طلبية التموين [PermissionKeys.PermitsDistribution] = ["GTO", "GOO"], // طلبية التموين
[PermissionKeys.OrdersSupply] = ["GTO", "GOO"], // طلبية التموين (orders menu)
[PermissionKeys.PermitsTruckStatus] = ["GTO", "GOO"], // استعلام عن حالة التوزيع لسيارة [PermissionKeys.PermitsTruckStatus] = ["GTO", "GOO"], // استعلام عن حالة التوزيع لسيارة
[PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية [PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية
[PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي [PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي
[PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف [PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف
[PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل [PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل
[PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ [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("owners-turn")] = ["GTO"], // تقرير دور الأفراد
[PermissionKeys.ReportTable("loading-weights")] = ["GTO"], // تقرير أوزان التحميل [PermissionKeys.ReportTable("loading-weights")] = ["GTO"], // تقرير أوزان التحميل

View File

@ -7,7 +7,8 @@ namespace NTP.Application.Access;
/// <param name="RoleCode">Caller's role code.</param> /// <param name="RoleCode">Caller's role code.</param>
/// <param name="All">True for SU: everything is allowed, <paramref name="Allowed"/> is then empty.</param> /// <param name="All">True for SU: everything is allowed, <paramref name="Allowed"/> is then empty.</param>
/// <param name="Allowed">Allowed resource keys (see <see cref="PermissionKeys"/>), e.g. grains.orders.list.</param> /// <param name="Allowed">Allowed resource keys (see <see cref="PermissionKeys"/>), e.g. grains.orders.list.</param>
public sealed record PermissionsDto(string RoleCode, bool All, IReadOnlyList<string> Allowed); /// <param name="Denied">Resources switched OFF for everybody (rows with role code DISABLED), SU included. Overrides <paramref name="All"/>.</param>
public sealed record PermissionsDto(string RoleCode, bool All, IReadOnlyList<string> Allowed, IReadOnlyList<string> Denied);
public interface IPermissionRepository public interface IPermissionRepository
{ {
@ -27,9 +28,15 @@ public interface IPermissionService
Task<bool> IsAllowedAsync(string resourceKey, CancellationToken ct = default); Task<bool> IsAllowedAsync(string resourceKey, CancellationToken ct = default);
} }
/// <summary>Role -> allowed resource keys. SU is always allowed everything; any other role is allow-listed.</summary> /// <summary>
/// Role -> allowed resource keys. SU is allowed everything; any other role is allow-listed. A resource that has a row with the
/// role code <see cref="DisabledRole"/> is switched off for EVERYBODY, SU included (a feature taken out of the system from the
/// database without a deployment).
/// </summary>
public sealed class PermissionService(IPermissionRepository repository, ICurrentUser user) : IPermissionService public sealed class PermissionService(IPermissionRepository repository, ICurrentUser user) : IPermissionService
{ {
/// <summary>Pseudo role code in GRAINS_SCREEN_PERMISSIONS: its rows are resources disabled for all users.</summary>
public const string DisabledRole = "DISABLED";
private const string SuperUser = "SU"; private const string SuperUser = "SU";
private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(60); private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(60);
private static readonly ConcurrentDictionary<string, (DateTime ExpiresUtc, HashSet<string> Keys)> Cache = new(StringComparer.OrdinalIgnoreCase); private static readonly ConcurrentDictionary<string, (DateTime ExpiresUtc, HashSet<string> Keys)> Cache = new(StringComparer.OrdinalIgnoreCase);
@ -37,19 +44,35 @@ public sealed class PermissionService(IPermissionRepository repository, ICurrent
public async Task<PermissionsDto> GetForCurrentUserAsync(CancellationToken ct = default) public async Task<PermissionsDto> GetForCurrentUserAsync(CancellationToken ct = default)
{ {
var role = user.RoleCode ?? string.Empty; 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); 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<bool> IsAllowedAsync(string resourceKey, CancellationToken ct = default) public async Task<bool> IsAllowedAsync(string resourceKey, CancellationToken ct = default)
{ {
var role = user.RoleCode ?? string.Empty; 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 (IsSuper(role)) return true;
if (!user.IsAuthenticated) return false; if (!user.IsAuthenticated) return false;
return (await KeysAsync(role, ct)).Contains(resourceKey); return (await KeysAsync(role, ct)).Contains(resourceKey);
} }
/// <summary>Resources disabled for all users. No built-in defaults: while the table is missing nothing is disabled.</summary>
private async Task<HashSet<string>> 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<string>(fromDb ?? [], StringComparer.OrdinalIgnoreCase);
Cache[DisabledRole] = (DateTime.UtcNow + CacheTtl, keys);
return keys;
}
/// <summary>For tests: forget every cached role (the cache is static, shared by all requests).</summary>
public static void ResetCache() => Cache.Clear();
private static bool IsSuper(string role) => string.Equals(role, SuperUser, StringComparison.OrdinalIgnoreCase); private static bool IsSuper(string role) => string.Equals(role, SuperUser, StringComparison.OrdinalIgnoreCase);
private async Task<HashSet<string>> KeysAsync(string role, CancellationToken ct) private async Task<HashSet<string>> KeysAsync(string role, CancellationToken ct)

View File

@ -183,6 +183,9 @@ public sealed record PermitWeightsDto(
public sealed record SaveWeightsRequest(long Pn, string EmptyWeight, string GrossWeight, string DocumentNumber); public sealed record SaveWeightsRequest(long Pn, string EmptyWeight, string GrossWeight, string DocumentNumber);
// ---------------------------------------------------------------- company destinations (compdest.cfm) // ---------------------------------------------------------------- company destinations (compdest.cfm)
/// <summary>Destinations a company can be linked to, by kind: packed (مشول), bulk (سائب) and bulk tipper (سائب قلاب).</summary>
public sealed record DestinationGroupsDto(IReadOnlyList<LookupOptionDto> Packed, IReadOnlyList<LookupOptionDto> Bulk, IReadOnlyList<LookupOptionDto> BulkGallab);
public sealed record CompanyDestinationsDto(long Scac, IReadOnlyList<long> LocationIds); public sealed record CompanyDestinationsDto(long Scac, IReadOnlyList<long> LocationIds);
public sealed record SaveCompanyDestinationsRequest(IReadOnlyList<long> LocationIds); public sealed record SaveCompanyDestinationsRequest(IReadOnlyList<long> LocationIds);

View File

@ -35,6 +35,9 @@ public interface IOrderLookupRepository
/// <summary>register.getDistination: GN exit locations of GN_TYPE 'PCKD', ordered by SORTORDER.</summary> /// <summary>register.getDistination: GN exit locations of GN_TYPE 'PCKD', ordered by SORTORDER.</summary>
Task<IReadOnlyList<LookupOptionDto>> GetPackedDestinationsAsync(CancellationToken ct = default); Task<IReadOnlyList<LookupOptionDto>> GetPackedDestinationsAsync(CancellationToken ct = default);
/// <summary>GN exit locations of one GN_TYPE ('PCKD', 'BULK', 'BULK_GALLAB'), ordered by SORTORDER.</summary>
Task<IReadOnlyList<LookupOptionDto>> GetDestinationsByGnTypeAsync(string gnType, CancellationToken ct = default);
/// <summary>NTP_TENDERS_COMPANIES with STATUSCODE='ACTIVE' (grains.cfc getCompanies).</summary> /// <summary>NTP_TENDERS_COMPANIES with STATUSCODE='ACTIVE' (grains.cfc getCompanies).</summary>
Task<IReadOnlyList<CompanyOptionDto>> GetCompaniesAsync(CancellationToken ct = default); Task<IReadOnlyList<CompanyOptionDto>> GetCompaniesAsync(CancellationToken ct = default);
} }

View File

@ -106,6 +106,7 @@ public interface IOrderLookupService
Task<IReadOnlyList<LookupOptionDto>> DestinationsAsync(CancellationToken ct); Task<IReadOnlyList<LookupOptionDto>> DestinationsAsync(CancellationToken ct);
Task<IReadOnlyList<LookupOptionDto>> BillingDestinationsAsync(CancellationToken ct); Task<IReadOnlyList<LookupOptionDto>> BillingDestinationsAsync(CancellationToken ct);
Task<IReadOnlyList<LookupOptionDto>> PackedDestinationsAsync(CancellationToken ct); Task<IReadOnlyList<LookupOptionDto>> PackedDestinationsAsync(CancellationToken ct);
Task<DestinationGroupsDto> DestinationGroupsAsync(CancellationToken ct);
Task<IReadOnlyList<CompanyOptionDto>> CompaniesAsync(CancellationToken ct); Task<IReadOnlyList<CompanyOptionDto>> CompaniesAsync(CancellationToken ct);
} }
@ -116,5 +117,9 @@ public sealed class OrderLookupService(IOrderLookupRepository repository) : IOrd
public Task<IReadOnlyList<LookupOptionDto>> DestinationsAsync(CancellationToken ct) => repository.GetLocationsAsync("EX", ct); public Task<IReadOnlyList<LookupOptionDto>> DestinationsAsync(CancellationToken ct) => repository.GetLocationsAsync("EX", ct);
public Task<IReadOnlyList<LookupOptionDto>> BillingDestinationsAsync(CancellationToken ct) => repository.GetBillingDestinationsAsync(ct); public Task<IReadOnlyList<LookupOptionDto>> BillingDestinationsAsync(CancellationToken ct) => repository.GetBillingDestinationsAsync(ct);
public Task<IReadOnlyList<LookupOptionDto>> PackedDestinationsAsync(CancellationToken ct) => repository.GetPackedDestinationsAsync(ct); public Task<IReadOnlyList<LookupOptionDto>> PackedDestinationsAsync(CancellationToken ct) => repository.GetPackedDestinationsAsync(ct);
public async Task<DestinationGroupsDto> DestinationGroupsAsync(CancellationToken ct) => new(
await repository.GetDestinationsByGnTypeAsync("PCKD", ct),
await repository.GetDestinationsByGnTypeAsync("BULK", ct),
await repository.GetDestinationsByGnTypeAsync("BULK_GALLAB", ct));
public Task<IReadOnlyList<CompanyOptionDto>> CompaniesAsync(CancellationToken ct) => repository.GetCompaniesAsync(ct); public Task<IReadOnlyList<CompanyOptionDto>> CompaniesAsync(CancellationToken ct) => repository.GetCompaniesAsync(ct);
} }

View File

@ -76,11 +76,13 @@ public sealed class CompanyDestinationService(
if (!(await lookups.GetCompaniesAsync(ct)).Any(c => c.Scac == scac)) throw OrdersErrors.CompanyNotFound(); 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<long>(); // 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(); var chosen = request.LocationIds.Distinct().ToList();
if (chosen.Any(id => !packed.Contains(id))) throw OrdersErrors.InvalidDestination(); 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 unitOfWork.ExecuteInTransactionAsync(async token =>
{ {
await repository.ReplaceAsync(scac, packed, chosen, user.UserId, token); await repository.ReplaceAsync(scac, packed, chosen, user.UserId, token);

View File

@ -228,8 +228,8 @@ public sealed class PermitService(
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
EnsureCompanyAccess(permit.CompanyCode); EnsureCompanyAccess(permit.CompanyCode);
// Deviation: legacy did not check the status; the UI only offers "edit" for REQST / PLND, so the API enforces it. // 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)) if (permit.ShipmentStatusCode is not (PermitStatus.Requested or PermitStatus.Planned or PermitStatus.Open))
throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus); throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus);
await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: false, ct); await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: false, ct);

View File

@ -73,6 +73,9 @@ public static class PermitActionRules
case PermitStatus.Planned: case PermitStatus.Planned:
a.Add(Accept); a.Add(Reject); a.Add(Edit); a.Add(Accept); a.Add(Reject); a.Add(Edit);
break; 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.Accepted:
case PermitStatus.Released: case PermitStatus.Released:
a.Add(RevokeAccepted); a.Add(Print); a.Add(RevokeAccepted); a.Add(Print);

View File

@ -43,6 +43,13 @@ internal sealed class OrderLookupRepository(IDbSession session, ILogger<OrderLoo
ORDER BY t.sortorder, t.id ORDER BY t.sortorder, t.id
""", null, ct); """, null, ct);
public Task<IReadOnlyList<LookupOptionDto>> 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<IReadOnlyList<CompanyOptionDto>> GetCompaniesAsync(CancellationToken ct = default) => public async Task<IReadOnlyList<CompanyOptionDto>> GetCompaniesAsync(CancellationToken ct = default) =>
(await QueryAsync<CompanyRow>(""" (await QueryAsync<CompanyRow>("""
SELECT t.scac AS Scac, SELECT t.scac AS Scac,

View File

@ -212,9 +212,14 @@ internal sealed class ReportsRepository(IDbSession session, ILogger<ReportsRepos
/// <summary>INFERRED from weightsReport.cfr (page grainsReports i=7: date range only): loading weights per permit.</summary> /// <summary>INFERRED from weightsReport.cfr (page grainsReports i=7: date range only): loading weights per permit.</summary>
private Task<IReadOnlyList<IDictionary<string, object?>>> LoadingWeights(ReportFilter f, ReportScope s, CancellationToken ct) private Task<IReadOnlyList<IDictionary<string, object?>>> 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 = ""; var visitor = "";
if (IsDestVisitor(s)) { visitor = " and loc.id = :LocId"; p.Add("LocId", s.LocationId ?? -1); } 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($""" return RowsAsync($"""
select p.pn as pn, p.tn as tn, getcompanynamefromscac(p.companycode, 62) as company, 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, {CargoDecode} as cargoType, loc2.name as origin, loc.name as destination,
@ -226,12 +231,15 @@ internal sealed class ReportsRepository(IDbSession session, ILogger<ReportsRepos
where p.domain = 'GN' and e.permitid = p.id and e.eventtype in ('LTW', 'LGW', 'LNW') where p.domain = 'GN' and e.permitid = p.id and e.eventtype in ('LTW', 'LGW', 'LNW')
and ct.domain = 'GN' and p.shipmentmode = ct.id and ct.domain = 'GN' and p.shipmentmode = ct.id
and loc.id = p.destinationaddressid and loc2.id = p.originaddressid and loc.id = p.destinationaddressid and loc2.id = p.originaddressid
and e.eventdate >= :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 group by p.id, p.pn, p.tn, p.companycode, ct.code, loc2.name, loc.name
order by min(e.eventdate), p.id order by min(e.eventdate), p.id
""", p, ct); """, p, ct);
} }
/// <summary>SQL DATE literal of a day (yyyy-mm-dd from a DateOnly: no user text reaches the statement).</summary>
private static string DateLiteral(DateOnly d) => $"to_date('{d:yyyy-MM-dd}', 'yyyy-mm-dd')";
/// <summary>INFERRED from GRINS_INCAPABILITY.cfr (page grainsReports i=6: order-date range): permits with their load/discharge weights.</summary> /// <summary>INFERRED from GRINS_INCAPABILITY.cfr (page grainsReports i=6: order-date range): permits with their load/discharge weights.</summary>
private Task<IReadOnlyList<IDictionary<string, object?>>> Incapability(ReportFilter f, ReportScope s, CancellationToken ct) private Task<IReadOnlyList<IDictionary<string, object?>>> Incapability(ReportFilter f, ReportScope s, CancellationToken ct)
{ {

View File

@ -64,8 +64,8 @@ public class OracleCredentialGuardTests
[Fact] [Fact]
public void Key_is_user_at_datasource_without_the_password() 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.Equal("NTP@db-host:1521/service", key);
Assert.DoesNotContain("secret123", key); Assert.DoesNotContain("123456", key);
} }
} }

View File

@ -5,6 +5,9 @@ namespace NTP.Tests;
public class PermissionTests 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 private sealed class FakeUser(string role, bool authenticated = true) : ICurrentUser
{ {
public bool IsAuthenticated => authenticated; public bool IsAuthenticated => authenticated;
@ -28,11 +31,15 @@ public class PermissionTests
public bool IsInAnyRole(params string[] roleCodes) => roleCodes.Any(IsInRole); public bool IsInAnyRole(params string[] roleCodes) => roleCodes.Any(IsInRole);
} }
private sealed class FakeRepo(Func<string, IReadOnlyList<string>?> answer) : IPermissionRepository /// <param name="answer">Rows of a role. The DISABLED pseudo role is answered by <paramref name="disabled"/> instead.</param>
private sealed class FakeRepo(Func<string, IReadOnlyList<string>?> answer, IReadOnlyList<string>? disabled = null) : IPermissionRepository
{ {
public int Calls; public int Calls; // lookups of real roles only
public readonly List<string> Asked = [];
public Task<IReadOnlyList<string>?> GetAllowedAsync(string roleCode, CancellationToken ct = default) public Task<IReadOnlyList<string>?> GetAllowedAsync(string roleCode, CancellationToken ct = default)
{ {
Asked.Add(roleCode);
if (roleCode == PermissionService.DisabledRole) return Task.FromResult(disabled);
Calls++; Calls++;
return Task.FromResult(answer(roleCode)); 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)); private static PermissionService Svc(string role, FakeRepo repo, bool authenticated = true) => new(repo, new FakeUser(role, authenticated));
[Fact] [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 repo = new FakeRepo(_ => throw new InvalidOperationException("must not be called"));
var svc = Svc("SU", repo); var svc = Svc("SU", repo);
@ -50,7 +57,8 @@ public class PermissionTests
Assert.True(dto.All); Assert.True(dto.All);
Assert.Empty(dto.Allowed); Assert.Empty(dto.Allowed);
Assert.True(await svc.IsAllowedAsync("grains.anything.at.all")); 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] [Fact]
@ -93,6 +101,46 @@ public class PermissionTests
Assert.True(await Svc("SU", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.RegistryDriversCreate)); 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<string>? 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] [Fact]
public async Task Screens_not_in_the_sheet_are_hidden_from_non_super_roles() public async Task Screens_not_in_the_sheet_are_hidden_from_non_super_roles()
{ {

View File

@ -144,6 +144,20 @@ public class PermitActionRuleTests
Assert.Contains(PermitActionRules.PhoneAccept, staff); 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] [Fact]
public void Accepted_permit_offers_convert_to_resd_only_to_su_gpo() public void Accepted_permit_offers_convert_to_resd_only_to_su_gpo()
{ {

View File

@ -53,12 +53,14 @@ export interface Permissions {
roleCode: string; roleCode: string;
all: boolean; all: boolean;
allowed: string[]; allowed: string[];
/** Resources switched off for everybody (SU included), from the database. */
denied: string[];
} }
export const authApi = { export const authApi = {
async permissions(): Promise<Permissions> { async permissions(): Promise<Permissions> {
const r = await api.get<Raw>('/auth/permissions', undefined, { silent: true }); const r = await api.get<Raw>('/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<LoginResult> { async login(username: string, password: string): Promise<LoginResult> {
const r = await api.post<Raw>('/auth/login', { userName: username, password }, { noAuthRedirect: true }); const r = await api.post<Raw>('/auth/login', { userName: username, password }, { noAuthRedirect: true });

View File

@ -77,7 +77,7 @@ registerMock('GET', /^\/auth\/me$/, () => ({
userId: 1001, name: 'demo', roleCode: 'SU', roleName: 'Super user', domain: 'NTP', locationId: 5, 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, 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('PUT', /^\/auth\/language$/, () => ({}));
registerMock('POST', /^\/auth\/change-password$/, () => ({ message: 'تم تغيير كلمة المرور' })); registerMock('POST', /^\/auth\/change-password$/, () => ({ message: 'تم تغيير كلمة المرور' }));
registerMock('POST', /^\/files\/temp$/, () => ({ id: `tmp-${Date.now()}` })); registerMock('POST', /^\/files\/temp$/, () => ({ id: `tmp-${Date.now()}` }));

View File

@ -12,6 +12,7 @@ import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined';
import { api, ApiError, type PagedResult } from '@/api/client'; import { api, ApiError, type PagedResult } from '@/api/client';
import { EmptyState } from '@/components/EmptyState'; import { EmptyState } from '@/components/EmptyState';
import { LoadingBanner } from '@/components/LoadingBanner'; import { LoadingBanner } from '@/components/LoadingBanner';
import { SectionPaper } from '@/components/SectionPaper';
import { StatusChip } from '@/components/StatusChip'; import { StatusChip } from '@/components/StatusChip';
import { formatDate, formatDateTime, formatNumber, getPath } from '@/components/meta/format'; import { formatDate, formatDateTime, formatNumber, getPath } from '@/components/meta/format';
import type { ColumnMeta, FilterMeta, GridMeta, RowAction } from '@/components/meta/types'; import type { ColumnMeta, FilterMeta, GridMeta, RowAction } from '@/components/meta/types';
@ -214,7 +215,7 @@ export function DataGrid<T>({ meta }: DataGridProps<T>) {
{updating && <LoadingBanner variant="update" />} {updating && <LoadingBanner variant="update" />}
{(blankGrid || (canLoad && !firstLoad && !q.isError)) && ( {(blankGrid || (canLoad && !firstLoad && !q.isError)) && (
<Paper variant="outlined" sx={{ opacity: updating ? 0.55 : 1, transition: 'opacity .15s' }} aria-busy={updating}> <SectionPaper sx={{ opacity: updating ? 0.55 : 1, transition: 'opacity .15s', overflow: 'hidden' }} aria-busy={updating}>
{items.length === 0 && !blankGrid && !meta.emptyAsGrid ? ( {items.length === 0 && !blankGrid && !meta.emptyAsGrid ? (
<EmptyState <EmptyState
title={t('grid.empty')} title={t('grid.empty')}
@ -249,7 +250,7 @@ export function DataGrid<T>({ meta }: DataGridProps<T>) {
key={meta.rowKey(row)} key={meta.rowKey(row)}
hover hover
onClick={meta.onRowClick ? () => meta.onRowClick!(row) : undefined} 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)} {hasActions && actionsBefore && actionsCell(row)}
{columns.map((c) => ( {columns.map((c) => (
@ -278,7 +279,7 @@ export function DataGrid<T>({ meta }: DataGridProps<T>) {
/> />
</> </>
)} )}
</Paper> </SectionPaper>
)} )}
<FilterDrawer <FilterDrawer

View File

@ -0,0 +1,65 @@
import type { ReactNode } from 'react';
import { Box, Button, Checkbox, Chip, FormControlLabel, FormGroup, Stack, Typography } from '@mui/material';
import { alpha } from '@mui/material/styles';
export interface DestinationGroup {
key: string;
title: string;
icon: ReactNode;
options: { id: number; name: string | null }[];
}
/**
* Destination check boxes grouped by kind (tinted header, `n / total` chip, select all / clear per group).
* Used by the company destinations screen; same look as the destinations panel of the trucks registry.
*/
export function DestinationGroups(props: {
groups: DestinationGroup[];
selected: ReadonlySet<number>;
onChange: (next: Set<number>) => 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 (
<Stack spacing={1.5}>
{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 (
<Box key={g.key} sx={{ border: 1, borderColor: 'divider', borderRadius: 2, overflow: 'hidden' }}>
<Stack
direction="row" spacing={1}
sx={(th) => ({ alignItems: 'center', px: 1.5, py: 0.75, bgcolor: alpha(th.palette.primary.main, 0.08), borderBottom: 1, borderColor: 'divider' })}
>
<Box sx={{ display: 'flex', color: 'primary.main' }}>{g.icon}</Box>
<Typography sx={{ fontSize: 13.5, fontWeight: 700, color: 'text.primary' }}>{g.title}</Typography>
<Chip size="small" color="primary" variant="outlined" label={<bdi dir="ltr">{`${count} / ${g.options.length}`}</bdi>} sx={{ height: 20, fontSize: 11.5 }} />
<Box sx={{ flex: 1 }} />
{!disabled && (
<>
<Button size="small" sx={{ fontSize: 12, minWidth: 0 }} onClick={() => setGroup(ids, true)}>{labels.all}</Button>
<Button size="small" color="inherit" sx={{ fontSize: 12, minWidth: 0 }} onClick={() => setGroup(ids, false)}>{labels.clear}</Button>
</>
)}
</Stack>
<FormGroup row sx={{ px: 1.5, py: 1 }}>
{g.options.map((o) => (
<FormControlLabel
key={o.id}
sx={{ minWidth: { xs: '100%', sm: '33%' }, marginInlineEnd: 0, '& .MuiFormControlLabel-label': { fontSize: 13 } }}
label={o.name ?? String(o.id)}
control={<Checkbox size="small" disabled={disabled} checked={selected.has(o.id)} onChange={(e) => toggle(o.id, e.target.checked)} />}
/>
))}
</FormGroup>
</Box>
);
})}
</Stack>
);
}

View File

@ -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 (
<SectionPaper sx={{ maxWidth, overflow: 'hidden' }}>
<Box sx={{ p: { xs: 2, sm: 2.5 }, pb: actions ? { xs: 2, sm: 2.5 } : undefined }}>
<SectionTitle icon={icon} title={title} />
{children}
</Box>
{actions && (
<Stack
direction="row" spacing={1} useFlexGap
sx={(t) => ({ 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}
</Stack>
)}
</SectionPaper>
);
}
/** Two columns of fields on wide screens, one on phones. */
export function FormGrid({ children }: { children: ReactNode }) {
return <Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, minmax(0, 1fr))' } }}>{children}</Box>;
}

View File

@ -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 (
<Typography
component="h2"
sx={{ display: 'flex', alignItems: 'center', gap: 1, m: 0, mb: 1.5, fontSize: 15, fontWeight: 700, lineHeight: 1.4, color: 'text.primary', pb: 0.75, borderBottom: 1, borderColor: 'divider' }}
>
<Icon sx={{ fontSize: 20, color: 'inherit' }} />
{title}
</Typography>
);
}

View File

@ -5,7 +5,7 @@ import { gridKey } from '@/components/DataGrid';
import type { OptionItem, OptionsLoader } from '@/components/meta/types'; import type { OptionItem, OptionsLoader } from '@/components/meta/types';
import { useLanguage } from '@/providers/LanguageProvider'; import { useLanguage } from '@/providers/LanguageProvider';
import type { import type {
BillingPermit, CompanyDestinations, CompanyOption, FinancialBillingPage, LookupOption, OrdersResult, BillingPermit, CompanyDestinations, CompanyOption, DestinationGroupsData, FinancialBillingPage, LookupOption, OrdersResult,
PermitWeights, TenderOrderReport, PermitWeights, TenderOrderReport,
} from './types'; } from './types';
@ -49,11 +49,11 @@ export function useCompanies() {
}); });
} }
export function usePackedDestinations() { export function useDestinationGroups() {
const { lang, langReady } = useLanguage(); const { lang, langReady } = useLanguage();
return useQuery({ return useQuery({
queryKey: ['grains.orders.packedDest', lang], queryKey: ['grains.orders.destGroups', lang],
queryFn: () => api.get<LookupOption[]>(`${BASE}/lookups/packed-destinations`, undefined, { silent: true }), queryFn: () => api.get<DestinationGroupsData>(`${BASE}/lookups/destination-groups`, undefined, { silent: true }),
enabled: langReady, enabled: langReady,
staleTime: 5 * 60_000, staleTime: 5 * 60_000,
}); });

View File

@ -1,15 +1,19 @@
import { useEffect, useMemo, useState, type KeyboardEvent } from 'react'; import { useEffect, useMemo, useState, type KeyboardEvent } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { 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, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography,
} from '@mui/material'; } from '@mui/material';
import AddIcon from '@mui/icons-material/Add'; import AddIcon from '@mui/icons-material/Add';
import AssessmentIcon from '@mui/icons-material/Assessment'; import AssessmentIcon from '@mui/icons-material/Assessment';
import DownloadIcon from '@mui/icons-material/Download'; import DownloadIcon from '@mui/icons-material/Download';
import 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 SearchIcon from '@mui/icons-material/Search';
import { ApiError } from '@/api/client'; import { ApiError } from '@/api/client';
import { DataGrid } from '@/components/DataGrid'; import { DataGrid } from '@/components/DataGrid';
import { DestinationGroups } from '@/components/DestinationGroups';
import { LoadingBanner } from '@/components/LoadingBanner'; import { LoadingBanner } from '@/components/LoadingBanner';
import { MetaForm } from '@/components/MetaForm'; import { MetaForm } from '@/components/MetaForm';
import { PageHeader } from '@/components/PageHeader'; import { PageHeader } from '@/components/PageHeader';
@ -20,7 +24,7 @@ import { useConfirm } from '@/providers/ConfirmProvider';
import { useToast } from '@/providers/ToastProvider'; import { useToast } from '@/providers/ToastProvider';
import { import {
downloadExport, fetchBillingPermit, fetchPermitWeights, useAddBilling, useCompanies, useCompanyDestinations, downloadExport, fetchBillingPermit, fetchPermitWeights, useAddBilling, useCompanies, useCompanyDestinations,
useCreateOrder, useDeleteOrder, usePackedDestinations, usePublishOrder, useSaveCompanyDestinations, useSaveWeights, useCreateOrder, useDeleteOrder, useDestinationGroups, usePublishOrder, useSaveCompanyDestinations, useSaveWeights,
useSetQuota, useTenderOrderReport, useSetQuota, useTenderOrderReport,
} from './api'; } from './api';
import { billingForm, billingGrid, financialGrid, invoiceGrid, weightsForm } from './meta/billing'; import { billingForm, billingGrid, financialGrid, invoiceGrid, weightsForm } from './meta/billing';
@ -397,7 +401,7 @@ export function CompanyDestinationsPage() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
const confirm = useConfirm(); const confirm = useConfirm();
const companies = useCompanies(); const companies = useCompanies();
const packed = usePackedDestinations(); const groupsData = useDestinationGroups();
const [scac, setScac] = useState<number | null>(null); const [scac, setScac] = useState<number | null>(null);
const current = useCompanyDestinations(scac); const current = useCompanyDestinations(scac);
const save = useSaveCompanyDestinations(scac); const save = useSaveCompanyDestinations(scac);
@ -407,13 +411,17 @@ export function CompanyDestinationsPage() {
setChecked(new Set(current.data?.locationIds ?? [])); setChecked(new Set(current.data?.locationIds ?? []));
}, [current.data]); }, [current.data]);
const list = packed.data ?? []; const groups = [
const toggle = (id: number) => setChecked((s) => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n; }); { key: 'packed', title: t('ord.compDest.packed'), icon: <Inventory2Icon fontSize="small" />, options: groupsData.data?.packed ?? [] },
{ key: 'bulk', title: t('ord.compDest.bulk'), icon: <GrainIcon fontSize="small" />, options: groupsData.data?.bulk ?? [] },
{ key: 'bulkGallab', title: t('ord.compDest.bulkGallab'), icon: <LocalShippingIcon fontSize="small" />, options: groupsData.data?.bulkGallab ?? [] },
];
const all = groups.flatMap((g) => g.options);
async function onSave() { async function onSave() {
if (scac === null) return; if (scac === null) return;
if (!(await confirm({ message: t('ord.compDest.saveConfirm') }))) 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 ( return (
@ -431,26 +439,13 @@ export function CompanyDestinationsPage() {
</TextField> </TextField>
{scac === null && <Alert severity="info">{t('ord.compDest.pick')}</Alert>} {scac === null && <Alert severity="info">{t('ord.compDest.pick')}</Alert>}
{scac !== null && (current.isPending || packed.isPending) && <LoadingBanner variant="first" />} {scac !== null && (current.isPending || groupsData.isPending) && <LoadingBanner variant="first" />}
{current.isError && <Alert severity="error">{errText(current.error, t('error.generic'))}</Alert>} {current.isError && <Alert severity="error">{errText(current.error, t('error.generic'))}</Alert>}
{scac !== null && current.data && ( {scac !== null && current.data && (
<> <>
<Stack direction="row" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}> {all.length === 0 && <Alert severity="info">{t('ord.compDest.empty')}</Alert>}
<Typography variant="subtitle1" sx={{ flex: 1 }}>{t('ord.compDest.packed')}</Typography> <DestinationGroups groups={groups} selected={checked} onChange={setChecked} labels={{ all: t('ord.compDest.all'), clear: t('ord.compDest.clear') }} />
<Button size="small" onClick={() => setChecked(new Set(list.map((d) => d.id)))}>{t('ord.compDest.all')}</Button>
<Button size="small" onClick={() => setChecked(new Set())}>{t('ord.compDest.none')}</Button>
</Stack>
{list.length === 0 && <Alert severity="info">{t('ord.compDest.empty')}</Alert>}
<Box sx={{ display: 'grid', gap: 0.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))', lg: 'repeat(3, minmax(0, 1fr))' } }}>
{list.map((d) => (
<FormControlLabel
key={d.id}
control={<Checkbox checked={checked.has(d.id)} onChange={() => toggle(d.id)} />}
label={<><bdi dir="ltr">{d.id}</bdi> - {d.name}</>}
/>
))}
</Box>
<Box> <Box>
<Button variant="contained" onClick={() => void onSave()} disabled={save.isPending}>{t('common.save')}</Button> <Button variant="contained" onClick={() => void onSave()} disabled={save.isPending}>{t('common.save')}</Button>
</Box> </Box>

View File

@ -1,6 +1,7 @@
import type { RouteObject } from 'react-router-dom'; 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 BusinessIcon from '@mui/icons-material/Business';
import LocalShippingIcon from '@mui/icons-material/LocalShipping';
import ListAltIcon from '@mui/icons-material/ListAlt'; import ListAltIcon from '@mui/icons-material/ListAlt';
import PercentIcon from '@mui/icons-material/Percent'; import PercentIcon from '@mui/icons-material/Percent';
import ReceiptIcon from '@mui/icons-material/Receipt'; import ReceiptIcon from '@mui/icons-material/Receipt';
@ -13,6 +14,7 @@ import {
TenderOrderCreatePage, TenderOrderReportPage, TenderOrdersPage, WeightsPage, TenderOrderCreatePage, TenderOrderReportPage, TenderOrdersPage, WeightsPage,
} from './pages'; } from './pages';
import strings from './strings'; 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. * 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, icon: ReceiptLongIcon,
children: [ 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.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.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.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.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' },
], ],
}, },
]; ];

View File

@ -3,6 +3,7 @@ import { defineStrings } from '@/i18n/useUi';
/** Feature strings of the Grains "orders" slice (tender orders, quotas, billing, invoices, reports). */ /** Feature strings of the Grains "orders" slice (tender orders, quotas, billing, invoices, reports). */
export default defineStrings({ export default defineStrings({
// ---- menu // ---- menu
'ord.menu.finance': { en: 'Finance', ar: 'المالية' },
'ord.menu.group': { en: 'Orders and billing', ar: 'الطلبيات والمطالبات' }, 'ord.menu.group': { en: 'Orders and billing', ar: 'الطلبيات والمطالبات' },
'ord.menu.orders': { en: 'Tender orders', ar: 'الطلبيات' }, 'ord.menu.orders': { en: 'Tender orders', ar: 'الطلبيات' },
'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' }, 'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' },
@ -11,7 +12,7 @@ export default defineStrings({
'ord.menu.weights': { en: 'Loading weights', ar: 'تثبيت أوزان التحميل' }, 'ord.menu.weights': { en: 'Loading weights', ar: 'تثبيت أوزان التحميل' },
'ord.menu.companyDest': { en: 'Company destinations', ar: 'وجهات الشركات' }, 'ord.menu.companyDest': { en: 'Company destinations', ar: 'وجهات الشركات' },
'ord.menu.reportOrders': { en: 'Orders report', ar: 'تقرير الطلبيات' }, 'ord.menu.reportOrders': { en: 'Orders report', ar: 'تقرير الطلبيات' },
'ord.menu.reportFinance': { en: 'Financial report', ar: 'التقرير المالي' }, 'ord.menu.reportFinance': { en: 'Tender financial reports', ar: 'تقارير عطاء التموين المالية' },
'ord.crumb.new': { en: 'New', ar: 'جديد' }, 'ord.crumb.new': { en: 'New', ar: 'جديد' },
// ---- shared // ---- shared
@ -82,13 +83,16 @@ export default defineStrings({
// ---- company destinations // ---- company destinations
'ord.compDest.title': { en: 'Company destinations', ar: 'وجهات الشركات' }, 'ord.compDest.title': { en: 'Company destinations', ar: 'وجهات الشركات' },
'ord.compDest.subtitle': { en: 'Packed-cargo destinations each company may receive', ar: 'وجهات المشوّل المسموحة لكل شركة' }, 'ord.compDest.subtitle': { en: 'Packed, bulk and bulk-tipper destinations each company may receive', ar: 'وجهات المشول والسائب والسائب (قلاب) المسموحة لكل شركة' },
'ord.compDest.packed': { en: 'Packed destinations', 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.all': { en: 'Select all', ar: 'تحديد الكل' },
'ord.compDest.none': { en: 'Clear all', ar: 'إلغاء التحديد' }, 'ord.compDest.none': { en: 'Clear all', ar: 'إلغاء التحديد' },
'ord.compDest.saveConfirm': { en: 'Save the destinations of this company?', 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.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 // ---- financial report
'ord.fin.title': { en: 'Financial billing report', ar: 'تقارير عطاء التموين المالية' }, 'ord.fin.title': { en: 'Financial billing report', ar: 'تقارير عطاء التموين المالية' },

View File

@ -92,6 +92,8 @@ export interface PermitWeights {
documentNumber: string | null; documentNumber: string | null;
} }
export interface DestinationGroupsData { packed: LookupOption[]; bulk: LookupOption[]; bulkGallab: LookupOption[] }
export interface CompanyDestinations { export interface CompanyDestinations {
scac: number; scac: number;
locationIds: number[]; locationIds: number[];

View File

@ -1,6 +1,6 @@
import type { FilterMeta, GridMeta, L10n, OptionItem, StatusMeta } from '@/components/meta/types'; import type { FilterMeta, GridMeta, L10n, OptionItem, StatusMeta } from '@/components/meta/types';
import { cargoOptions, companyFilterOptions, exitLocationOptions, tenderOrderDateOptions } from '../api'; 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). */ /** 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<string, L10n> = { const actionLabels: Record<string, L10n> = {
view: { en: 'View', ar: 'مشاهدة' }, view: { en: 'View', ar: 'مشاهدة' },
submit: { en: 'Submit order', ar: 'تقديم الطلب' }, submit: { en: 'Submit order', ar: 'تقديم الطلب' },
edit: { en: 'Edit order', ar: 'تعديل الطلب' }, edit: { en: 'Edit information', ar: 'تعديل المعلومات' },
accept: { en: 'Confirm turn', ar: 'تثبيت الدور' }, accept: { en: 'Confirm turn', ar: 'تثبيت الدور' },
reject: { en: 'Revoke confirmation', ar: 'الغاء التثبيت' }, reject: { en: 'Revoke confirmation', ar: 'الغاء التثبيت' },
revokeAccepted: { en: 'Cancel 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. */ /** Row actions are computed by the server (`actions`): only the allowed buttons are shown. */
export const permitRowActions = (h: PermitGridHandlers): NonNullable<GridMeta<PermitListItem>['rowActions']> => export const permitRowActions = (h: PermitGridHandlers): NonNullable<GridMeta<PermitListItem>['rowActions']> =>
Object.keys(actionLabels).map((a) => ({ Object.keys(actionLabels).filter((a) => a !== 'edit').map((a) => ({
key: a, key: a,
label: actionLabels[a]!, label: actionLabels[a]!,
danger: danger.has(a), danger: danger.has(a),
@ -112,19 +112,4 @@ export const permitRowActions = (h: PermitGridHandlers): NonNullable<GridMeta<Pe
onClick: (r: PermitListItem) => h.onAction(a, r), onClick: (r: PermitListItem) => h.onAction(a, r),
})); }));
export const queueGrid = (): GridMeta<QueueItem> => ({
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 }; export { cargoOptions };

View File

@ -5,17 +5,40 @@ import {
Stack, Tab, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tabs, TextField, Typography, Stack, Tab, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tabs, TextField, Typography,
} from '@mui/material'; } from '@mui/material';
import AddIcon from '@mui/icons-material/Add'; 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 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 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 { 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 // the shared framed section look (see components/SectionPaper): every Paper on the permit screens uses it
import { SectionPaper as Paper } from '@/components/SectionPaper'; import { SectionPaper as Paper } from '@/components/SectionPaper';
import { ViewItem } from '@/components/ViewItem'; import { ViewItem } from '@/components/ViewItem';
import { EmptyState } from '@/components/EmptyState'; import { EmptyState } from '@/components/EmptyState';
import { LoadingBanner } from '@/components/LoadingBanner'; import { LoadingBanner } from '@/components/LoadingBanner';
import { PageHeader } from '@/components/PageHeader'; import { PageHeader } from '@/components/PageHeader';
import { SectionTitle } from '@/components/SectionTitle';
import { StatusChip } from '@/components/StatusChip'; 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 { elementToPdfUrl, type PdfOrientation } from '@/lib/pdf';
import { useFeatureUi } from '@/i18n/useUi'; import { useFeatureUi } from '@/i18n/useUi';
import { useAuth } from '@/providers/AuthProvider'; import { useAuth } from '@/providers/AuthProvider';
@ -23,13 +46,12 @@ import { useConfirm } from '@/providers/ConfirmProvider';
import { useToast } from '@/providers/ToastProvider'; import { useToast } from '@/providers/ToastProvider';
import { import {
fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, fetchTruck, searchDestination, searchTruckDistribution, fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, fetchTruck, searchDestination, searchTruckDistribution,
useAbsenceFeature, useActivateOrders, useActivation, useAddToQueue, useAssignByPn, useClosePermit, useDistribute, useActivateOrders, useActivation, useAddToQueue, useAssignByPn, useClosePermit, useDistribute,
useDistributionPivot, useDistributionSummary, useLocationCounts, useLocationGroups, useManualInput, useOrderDates, useDistributionPivot, useDistributionSummary, useLocationGroups, useManualInput, useOrderDates,
usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination, usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination,
useRevokeAllRequested, useSingleTruck, useSubmitOrder, useToggleAbsence, useUpdateOrder, useWeighbridgeManual, useRevokeAllRequested, useSingleTruck, useSubmitOrder, useUpdateOrder, useWeighbridgeManual,
useWeighbridgeReading, useWeights,
} from './api'; } 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 strings from './strings';
import { AcceptSlip, InSlip, OutSlip } from './slips'; import { AcceptSlip, InSlip, OutSlip } from './slips';
import type { PermitListItem, TruckDistribution } from './types'; 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. // Backend-driven (GET /auth/permissions): the role code decides on the server, not here.
const { hasRole, can } = useAuth(); const { hasRole, can } = useAuth();
return { return {
canQueueAdd: can('grains.permits.queue'), canCreate: can('grains.permits.create'),
canAbsence: can('grains.permits.absence'), canAbsence: can('grains.permits.absence'),
canClose: can('grains.permits.close'), canClose: can('grains.permits.close'),
canTruckOrder: can('grains.permits.truckOrder'), canTruckOrder: can('grains.permits.truckOrder'),
@ -187,7 +209,7 @@ function usePermitActions() {
// ================================================================= permit list (GNPermits.cfm) // ================================================================= permit list (GNPermits.cfm)
export function PermitsPage() { export function PermitsPage() {
const { t } = useFeatureUi(strings); const { t, lang } = useFeatureUi(strings);
const { user } = useAuth(); const { user } = useAuth();
const { run, element } = usePermitActions(); const { run, element } = usePermitActions();
const companyUser = Number(user?.stkId) === 62; // legacy session.stkid = 62 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) }; return { ...permitGrid(h, { companyUser, showRevoked }), rowActions: permitRowActions(h) };
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [companyUser, showRevoked]); }, [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 ( return (
<> <>
<PageHeader title={t('pm.list.title')} subtitle={t('pm.list.subtitle')} /> <PageHeader
title={t('pm.list.title')} subtitle={t('pm.list.subtitle')}
actions={canCreate && <Button variant="contained" startIcon={<AddIcon />} onClick={() => setOpen(true)}>{t('pm.queue.add')}</Button>}
/>
<DataGrid meta={meta} /> <DataGrid meta={meta} />
{element} {element}
<Dialog open={open} onClose={() => setOpen(false)} fullWidth maxWidth="xs">
<DialogTitle>{t('pm.queue.add')}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ pt: 1 }}>
<NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} onEnter={() => void save()} />
<TextField select size="small" sx={FIELD_SX} label={t('pm.queue.cargo')} value={tt} onChange={(e) => setTt(e.target.value)}>
{shipmentModeOptions.map((o) => <MenuItem key={String(o.value)} value={String(o.value)}>{typeof o.label === 'string' ? o.label : o.label[lang]}</MenuItem>)}
</TextField>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={() => setOpen(false)}>{t('common.cancel')}</Button>
<Button variant="contained" disabled={!tn.trim()} onClick={() => void save()}>{t('common.save')}</Button>
</DialogActions>
</Dialog>
</> </>
); );
} }
@ -224,6 +275,7 @@ export function PermitDetailPage() {
const [v, setV] = useState<OrderValues>(emptyOrder); const [v, setV] = useState<OrderValues>(emptyOrder);
const [info, setInfo] = useState<{ truck?: string; trailer?: string }>({}); const [info, setInfo] = useState<{ truck?: string; trailer?: string }>({});
const [loaded, setLoaded] = useState(false); const [loaded, setLoaded] = useState(false);
const [editing, setEditing] = useState(false); // the edit / submit form opens from the header button
const d = detail.data; const d = detail.data;
if (d && !loaded) { if (d && !loaded) {
@ -268,45 +320,91 @@ export function PermitDetailPage() {
async function save() { async function save() {
if (!complete || !(await confirm({ message: t(canSubmit ? 'pm.confirm.submit' : 'pm.confirm.update') }))) return; 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() }; 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 } }); const done = { onSuccess: () => setEditing(false) };
else update.mutate({ id, body }); 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 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 && (
<Button variant={editing ? 'outlined' : 'contained'} startIcon={editing ? <CloseIcon /> : <EditIcon />} onClick={() => setEditing((e) => !e)}>
{editing ? t('common.cancel') : tr(actionLabel(canSubmit ? 'submit' : 'edit'))}
</Button>
)}
{others.map((a) => (
<Button key={a} variant="outlined" color={DANGER_ACTIONS.has(a) ? 'error' : 'primary'} startIcon={ACTION_ICONS[a]} onClick={() => void run(a, id, d.statusCode)}>
{tr(actionLabel(a))}
</Button>
))}
</>
);
return ( return (
<> <>
<PageHeader <PageHeader
title={t('pm.detail.title', { pn: d.pn ?? '' })} title={t('pm.detail.title', { pn: d.pn ?? '' })}
subtitle={d.companyName ?? undefined} subtitle={d.companyName ?? undefined}
status={<StatusChip value={d.statusCode} statuses={permitStatuses} size="medium" />}
actions={headerActions}
backTo="/grains/permits" backTo="/grains/permits"
/> />
<Stack spacing={2}> <Stack spacing={2}>
<Paper sx={{ p: 2 }}> <Paper sx={{ p: 2 }}>
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))', lg: 'repeat(4, minmax(0, 1fr))' } }}> <SectionTitle icon={AssignmentIcon} title={t('pm.detail.sectionPermit')} />
<Info label={t('pm.detail.status')}><StatusChip value={d.statusCode} statuses={permitStatuses} /></Info> <Box sx={cols}>
<Info label={t('pm.detail.pn')} ltr>{d.pn}</Info>
<Info label={t('pm.detail.queueNo')} ltr>{d.queueNo}</Info> <Info label={t('pm.detail.queueNo')} ltr>{d.queueNo}</Info>
<Info label={t('pm.detail.cargo')}>{d.cargoType}</Info>
<Info label={t('pm.detail.shift')}>{d.shift}</Info> <Info label={t('pm.detail.shift')}>{d.shift}</Info>
<Info label={t('pm.detail.operation')}>{d.operationType}</Info> <Info label={t('pm.detail.cargo')}>{d.cargoType}</Info>
<Info label={t('pm.detail.truck')} ltr>{[d.truck?.tn, d.truck?.chasesNumber, d.truck?.axials].filter(Boolean).join(' / ')}</Info>
<Info label={t('pm.detail.trailer')} ltr>{[d.trailer?.tn, d.trailer?.chasesNumber, d.trailer?.axials].filter(Boolean).join(' / ')}</Info>
<Info label={t('pm.detail.driver')}>{[d.driver?.name, d.driver?.dln].filter(Boolean).join(' / ')}</Info>
</Box> </Box>
{others.length > 0 && (
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap', mt: 2 }}>
{others.map((a) => (
<Button key={a} size="small" variant="outlined" color={['reject', 'cancelOrder', 'revokePermit', 'revokeAccepted'].includes(a) ? 'error' : 'primary'}
startIcon={a === 'print' ? <PrintIcon /> : undefined} onClick={() => void run(a, id, d.statusCode)}>
{tr(actionLabel(a))}
</Button>
))}
</Stack>
)}
</Paper> </Paper>
{editable && (
<Paper sx={{ p: 2 }}> <Paper sx={{ p: 2 }}>
<Typography variant="h6" sx={{ mb: 2 }}>{t(canSubmit ? 'pm.order.submitTitle' : 'pm.order.editTitle')}</Typography> <SectionTitle icon={LocalShippingIcon} title={t('pm.detail.sectionTruck')} />
<Box sx={cols}>
<Info label={t('pm.detail.truckNo')} ltr>{d.truck?.tn}</Info>
<Info label={t('pm.detail.chassis')} ltr>{d.truck?.chasesNumber}</Info>
<Info label={t('pm.detail.axles')}>{d.truck?.axials}</Info>
<Info label={t('pm.detail.licenseDate')} ltr>{fd(d.truck?.regDate)}</Info>
</Box>
</Paper>
<Paper sx={{ p: 2 }}>
<SectionTitle icon={RvHookupIcon} title={t('pm.detail.sectionTrailer')} />
<Box sx={cols}>
<Info label={t('pm.detail.trailerNo')} ltr>{d.trailer?.tn}</Info>
<Info label={t('pm.detail.chassis')} ltr>{d.trailer?.chasesNumber}</Info>
<Info label={t('pm.detail.operation')}>{d.operationType}</Info>
<Info label={t('pm.detail.axles')}>{d.trailer?.axials}</Info>
<Info label={t('pm.detail.licenseDate')} ltr>{fd(d.trailer?.regDate)}</Info>
</Box>
</Paper>
<Paper sx={{ p: 2 }}>
<SectionTitle icon={BadgeIcon} title={t('pm.detail.sectionDriver')} />
<Box sx={cols}>
<Info label={t('pm.detail.nnpn')} ltr>{d.driver?.nnpn}</Info>
<Info label={t('pm.detail.driverName')}>{d.driver?.name}</Info>
<Info label={t('pm.detail.licenseNo')} ltr>{d.driver?.dln}</Info>
<Info label={t('pm.detail.licenseExpiry')} ltr>{fd(d.driver?.dled)}</Info>
</Box>
</Paper>
{editable && editing && (
<Paper sx={{ p: 2 }}>
<SectionTitle icon={EditIcon} title={t(canSubmit ? 'pm.order.submitTitle' : 'pm.order.editTitle')} />
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))' } }}> <Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))' } }}>
<TextField size="small" sx={FIELD_SX} label={t('pm.order.tn')} value={v.tn} onChange={set('tn')} onBlur={() => void lookupTruck()} <TextField size="small" sx={FIELD_SX} label={t('pm.order.tn')} value={v.tn} onChange={set('tn')} onBlur={() => void lookupTruck()}
helperText={info.truck} slotProps={ltr} /> helperText={info.truck} slotProps={ltr} />
@ -326,20 +424,21 @@ export function PermitDetailPage() {
</Box> </Box>
<Stack direction="row" spacing={1} sx={{ mt: 2 }}> <Stack direction="row" spacing={1} sx={{ mt: 2 }}>
<Button variant="contained" disabled={!complete} onClick={() => void save()}>{t(canSubmit ? 'pm.order.submit' : 'pm.order.update')}</Button> <Button variant="contained" disabled={!complete} onClick={() => void save()}>{t(canSubmit ? 'pm.order.submit' : 'pm.order.update')}</Button>
<Button color="inherit" onClick={() => setEditing(false)}>{t('common.cancel')}</Button>
</Stack> </Stack>
</Paper> </Paper>
)} )}
<Paper sx={{ p: 2 }}> <Paper sx={{ p: 2 }}>
<Typography variant="h6" sx={{ mb: 1 }}>{t('pm.events.title')}</Typography> <SectionTitle icon={HistoryIcon} title={t('pm.events.title')} />
<TableContainer> <TableContainer>
<Table size="small"> <Table size="small">
<TableHead> <TableHead>
<TableRow> <TableRow>
<TableCell>{t('pm.events.date')}</TableCell>
<TableCell>{t('pm.events.type')}</TableCell> <TableCell>{t('pm.events.type')}</TableCell>
<TableCell sx={{ display: { xs: 'none', sm: 'table-cell' } }}>{t('pm.events.by')}</TableCell> <TableCell sx={{ display: { xs: 'none', sm: 'table-cell' } }}>{t('pm.events.by')}</TableCell>
<TableCell>{t('pm.events.status')}</TableCell> <TableCell>{t('pm.events.status')}</TableCell>
<TableCell>{t('pm.events.date')}</TableCell>
<TableCell align="right">{t('pm.events.weight')}</TableCell> <TableCell align="right">{t('pm.events.weight')}</TableCell>
<TableCell sx={{ display: { xs: 'none', md: 'table-cell' } }}>{t('pm.events.remarks')}</TableCell> <TableCell sx={{ display: { xs: 'none', md: 'table-cell' } }}>{t('pm.events.remarks')}</TableCell>
</TableRow> </TableRow>
@ -347,15 +446,15 @@ export function PermitDetailPage() {
<TableBody> <TableBody>
{d.events.map((e, i) => ( {d.events.map((e, i) => (
<TableRow key={i}> <TableRow key={i}>
<TableCell sx={{ whiteSpace: 'nowrap' }} dir="ltr">{e.eventDate ? new Date(e.eventDate).toLocaleString('en-GB') : ''}</TableCell>
<TableCell>{e.eventCaption ?? e.eventType}</TableCell> <TableCell>{e.eventCaption ?? e.eventType}</TableCell>
<TableCell sx={{ display: { xs: 'none', sm: 'table-cell' } }}>{e.doneBy}</TableCell> <TableCell sx={{ display: { xs: 'none', sm: 'table-cell' } }}>{e.doneBy}</TableCell>
<TableCell>{e.currentStatus}</TableCell> <TableCell>{e.currentStatus}</TableCell>
<TableCell sx={{ whiteSpace: 'nowrap' }} dir="ltr">{when(e.eventDate)}</TableCell>
<TableCell align="right" dir="ltr">{e.weight === null ? '' : fmt(e.weight)}</TableCell> <TableCell align="right" dir="ltr">{e.weight === null ? '' : fmt(e.weight)}</TableCell>
<TableCell sx={{ display: { xs: 'none', md: 'table-cell' } }}>{e.remarks}</TableCell> <TableCell sx={{ display: { xs: 'none', md: 'table-cell' } }}>{e.remarks}</TableCell>
</TableRow> </TableRow>
))} ))}
{d.events.length === 0 && <TableRow><TableCell colSpan={6}>{tr({ en: 'No events', ar: 'لا توجد احداث' })}</TableCell></TableRow>} {d.events.length === 0 && <TableRow><TableCell colSpan={6}>{tr({ en: 'No movements', ar: 'لا توجد حركات' })}</TableCell></TableRow>}
</TableBody> </TableBody>
</Table> </Table>
</TableContainer> </TableContainer>
@ -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<string, ReactNode> = {
print: <PrintIcon />, accept: <CheckCircleOutlinedIcon />, reject: <BlockIcon />, revokeAccepted: <UndoIcon />, convertToResd: <SwapHorizIcon />,
phoneAccept: <PhoneCallbackIcon />, phoneReject: <PhoneDisabledIcon />, cancelOrder: <CancelOutlinedIcon />, revokePermit: <CancelOutlinedIcon />,
reactivate: <RestoreIcon />,
};
const DANGER_ACTIONS = new Set(['reject', 'revokeAccepted', 'phoneReject', 'cancelOrder', 'revokePermit']);
function Info({ label, children, ltr: isLtr }: { label: string; children?: ReactNode; ltr?: boolean }) { function Info({ label, children, ltr: isLtr }: { label: string; children?: ReactNode; ltr?: boolean }) {
return ( return (
<ViewItem label={label}> <ViewItem label={label}>
@ -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 (
<>
<PageHeader
title={t('pm.queue.title')} subtitle={t('pm.queue.subtitle')}
actions={canQueueAdd && <Button variant="contained" startIcon={<AddIcon />} onClick={() => setOpen(true)}>{t('pm.queue.add')}</Button>}
/>
<DataGrid meta={meta} />
<Dialog open={open} onClose={() => setOpen(false)} fullWidth maxWidth="xs">
<DialogTitle>{t('pm.queue.add')}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ pt: 1 }}>
<NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} onEnter={() => void save()} />
<TextField select size="small" sx={FIELD_SX} label={t('pm.queue.cargo')} value={tt} onChange={(e) => setTt(e.target.value)}>
{shipmentModeOptions.map((o) => <MenuItem key={String(o.value)} value={String(o.value)}>{typeof o.label === 'string' ? o.label : o.label[lang]}</MenuItem>)}
</TextField>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={() => setOpen(false)}>{t('common.cancel')}</Button>
<Button variant="contained" disabled={!tn.trim()} onClick={() => void save()}>{t('common.save')}</Button>
</DialogActions>
</Dialog>
</>
);
}
// ================================================================= destinations (assginggdest / ManualInput / activateOrders) // ================================================================= destinations (assginggdest / ManualInput / activateOrders)
function AssignByPn() { function AssignByPn() {
const { t, lang } = useFeatureUi(strings); const { t, lang } = useFeatureUi(strings);
@ -431,16 +497,32 @@ function AssignByPn() {
assign.mutate({ pn, destId: Number(dest), shipmentMode: Number(mode) }); assign.mutate({ pn, destId: Number(dest), shipmentMode: Number(mode) });
} }
return ( return (
<Stack spacing={2} sx={{ maxWidth: 480 }}> <FormCard
<NumberField label={t('pm.order.pn')} value={pn} onChange={setPn} /> icon={AltRouteIcon} title={t('pm.form.permitData')}
<TextField select size="small" sx={FIELD_SX} label={t('pm.dest.destination')} value={dest} onChange={(e) => setDest(e.target.value)}> actions={<Button variant="contained" startIcon={<SaveIcon />} disabled={!pn || !dest || !mode} onClick={() => void save()}>{t('common.save')}</Button>}
{locations.map((l) => <MenuItem key={l.id} value={String(l.id)}>{l.name}</MenuItem>)} >
</TextField> <FormGrid>
<NumberField autoFocus label={t('pm.order.pn')} value={pn} onChange={setPn} />
<TextField select size="small" sx={FIELD_SX} label={t('pm.dest.cargo')} value={mode} onChange={(e) => setMode(e.target.value)}> <TextField select size="small" sx={FIELD_SX} label={t('pm.dest.cargo')} value={mode} onChange={(e) => setMode(e.target.value)}>
{cargo.map((c) => <MenuItem key={c.id} value={String(c.id)}>{lang === 'ar' ? c.ar : c.en}</MenuItem>)} {cargo.map((c) => <MenuItem key={c.id} value={String(c.id)}>{lang === 'ar' ? c.ar : c.en}</MenuItem>)}
</TextField> </TextField>
<Box><Button variant="contained" disabled={!pn || !dest || !mode} onClick={() => void save()}>{t('common.save')}</Button></Box> <Box sx={{ gridColumn: { md: '1 / -1' } }}>
</Stack> <TextField select size="small" sx={FIELD_SX} label={t('pm.dest.destination')} value={dest} onChange={(e) => setDest(e.target.value)}>
{locations.map((l) => <MenuItem key={l.id} value={String(l.id)}>{l.name}</MenuItem>)}
</TextField>
</Box>
</FormGrid>
</FormCard>
);
}
/** Label beside its field (legacy manual-input screen). */
function MiRow({ label, children }: { label: string; children: ReactNode }) {
return (
<Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', sm: '110px minmax(0, 1fr)' }, alignItems: 'center', gap: 1 }}>
<Typography sx={{ fontSize: 14 }}>{label}</Typography>
<Box>{children}</Box>
</Box>
); );
} }
@ -475,22 +557,33 @@ function ManualInput() {
manual.mutate({ pn, orderId: Number(orderId), orderDate: date, ltw: Number(ltw), lgw: Number(lgw) }); manual.mutate({ pn, orderId: Number(orderId), orderDate: date, ltw: Number(ltw), lgw: Number(lgw) });
} }
return ( return (
<Stack spacing={2} sx={{ maxWidth: 480 }}> <FormCard
<NumberField label={t('pm.order.pn')} value={pn} onChange={setPn} /> icon={EditNoteIcon} title={t('pm.form.manualData')} maxWidth={860}
<TextField select size="small" sx={FIELD_SX} label={t('pm.manual.orderDate')} value={date} onChange={(e) => void loadOrders(e.target.value)}> actions={(
<>
<Button variant="contained" startIcon={<SaveIcon />} disabled={!valid} onClick={() => void save()}>{t('common.save')}</Button>
<Button onClick={() => void loadAlt()} disabled={!pn || !date}>{t('pm.manual.altList')}</Button>
</>
)}
>
<Box sx={{ display: 'grid', gap: 1.75, columnGap: 4, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, minmax(0, 1fr))' } }}>
<MiRow label={t('pm.manual.orderDate')}>
<TextField select size="small" sx={FIELD_SX} value={date} onChange={(e) => void loadOrders(e.target.value)}>
{(dates.data ?? []).map((d) => <MenuItem key={d} value={d}>{d.split('-').reverse().join('/')}</MenuItem>)} {(dates.data ?? []).map((d) => <MenuItem key={d} value={d}>{d.split('-').reverse().join('/')}</MenuItem>)}
</TextField> </TextField>
<TextField select size="small" sx={FIELD_SX} label={t('pm.manual.order')} value={orderId} onChange={(e) => setOrderId(e.target.value)} </MiRow>
<Box />
<MiRow label={t('pm.order.pn')}><NumberField label="" value={pn} onChange={setPn} /></MiRow>
<MiRow label={t('pm.manual.order')}>
<TextField select size="small" sx={FIELD_SX} value={orderId} onChange={(e) => setOrderId(e.target.value)}
helperText={orders.length === 0 && date ? t('pm.manual.noOrders') : undefined}> helperText={orders.length === 0 && date ? t('pm.manual.noOrders') : undefined}>
{orders.map((o) => <MenuItem key={o.orderId} value={String(o.orderId)}>{o.name}</MenuItem>)} {orders.map((o) => <MenuItem key={o.orderId} value={String(o.orderId)}>{o.name}</MenuItem>)}
</TextField> </TextField>
<NumberField label={t('pm.manual.ltw')} value={ltw} onChange={setLtw} /> </MiRow>
<NumberField label={t('pm.manual.lgw')} value={lgw} onChange={setLgw} /> <MiRow label={t('pm.manual.ltw')}><NumberField label="" value={ltw} onChange={setLtw} /></MiRow>
<Stack direction="row" spacing={1}> <MiRow label={t('pm.manual.lgw')}><NumberField label="" value={lgw} onChange={setLgw} /></MiRow>
<Button variant="contained" disabled={!valid} onClick={() => void save()}>{t('common.save')}</Button> </Box>
<Button onClick={() => void loadAlt()} disabled={!pn || !date}>{t('pm.manual.altList')}</Button> </FormCard>
</Stack>
</Stack>
); );
} }
@ -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); }; 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) }); } async function save() { if (await confirm({ message: t('pm.activate.confirm') })) activate.mutate([...sel], { onSuccess: () => setChecked(null) }); }
return ( return (
<Stack spacing={2}> <FormCard
<TableContainer component={Paper}> icon={PlaylistAddCheckIcon} title={t('pm.activation.title')} maxWidth={920}
actions={<Button variant="contained" startIcon={<SaveIcon />} onClick={() => void save()}>{t('common.save')}</Button>}
>
<TableContainer sx={{ border: 1, borderColor: 'divider', borderRadius: 1.5 }}>
<Table size="small"> <Table size="small">
<TableHead><TableRow><TableCell /><TableCell>{t('pm.activate.loc')}</TableCell><TableCell>{t('pm.activate.cargo')}</TableCell> <TableHead sx={{ bgcolor: 'action.hover' }}>
<TableCell align="right">{t('pm.activate.total')}</TableCell><TableCell align="right">{t('pm.activate.used')}</TableCell></TableRow></TableHead> <TableRow><TableCell /><TableCell>{t('pm.activate.loc')}</TableCell><TableCell>{t('pm.activate.cargo')}</TableCell>
<TableCell align="right">{t('pm.activate.total')}</TableCell><TableCell align="right">{t('pm.activate.used')}</TableCell></TableRow>
</TableHead>
<TableBody> <TableBody>
{rows.map((r) => { {rows.map((r) => {
const k = `${r.locId}-${r.ctId}`; const k = `${r.locId}-${r.ctId}`;
return ( return (
<TableRow key={k}> <TableRow key={k} hover>
<TableCell padding="checkbox"><Checkbox checked={sel.has(k)} disabled={r.total === 0} onChange={() => toggle(k)} /></TableCell> <TableCell padding="checkbox"><Checkbox checked={sel.has(k)} disabled={r.total === 0} onChange={() => toggle(k)} /></TableCell>
<TableCell>{r.loc}</TableCell><TableCell>{r.ct}</TableCell> <TableCell>{r.loc}</TableCell><TableCell>{r.ct}</TableCell>
<TableCell align="right" dir="ltr">{fmt(r.total)}</TableCell><TableCell align="right" dir="ltr">{fmt(r.used)}</TableCell> <TableCell align="right" dir="ltr">{fmt(r.total)}</TableCell><TableCell align="right" dir="ltr">{fmt(r.used)}</TableCell>
@ -526,8 +624,7 @@ function Activation() {
</TableBody> </TableBody>
</Table> </Table>
</TableContainer> </TableContainer>
<Box><Button variant="contained" onClick={() => void save()}>{t('common.save')}</Button></Box> </FormCard>
</Stack>
); );
} }
@ -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 (
<>
<PageHeader title={t('pm.supply.title')} subtitle={t('pm.supply.subtitle')} />
<Paper variant="outlined" sx={{ p: 2 }}>
<Table size="small">
<TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="right">{t('pm.dist.silos')}</TableCell>
<TableCell align="right">{t('pm.dist.direct')}</TableCell><TableCell align="right">{t('pm.dist.packed')}</TableCell></TableRow></TableHead>
<TableBody>{(pivot.data ?? []).map((r) => (
<TableRow key={r.companyCode ?? 0}><TableCell>{r.company}</TableCell><TableCell align="right" dir="ltr">{r.silos}</TableCell>
<TableCell align="right" dir="ltr">{r.direct}</TableCell><TableCell align="right" dir="ltr">{r.packed}</TableCell></TableRow>
))}</TableBody>
</Table>
</Paper>
</>
);
}
/** اغلاق إرسالية (permits menu): close a permit manually. */
export function ClosePermitPage() {
const { t } = useFeatureUi(strings);
const closeP = useClosePermit();
const confirm = useConfirm();
const [pn, setPn] = useState('');
return (
<>
<PageHeader title={t('pm.close.title')} subtitle={t('pm.close.subtitle')} />
<FormCard
icon={LockIcon} title={t('pm.form.permitData')} maxWidth={520}
actions={(
<Button variant="contained" color="error" startIcon={<LockIcon />} disabled={!pn}
onClick={async () => { if (await confirm({ message: t('pm.wb.closeConfirm'), danger: true })) closeP.mutate(pn); }}>{t('pm.wb.close')}</Button>
)}
>
<NumberField autoFocus label={t('pm.order.pn')} value={pn} onChange={setPn} />
</FormCard>
</>
);
}
/** استعلام عن سيارة (permits menu). */
export function TruckInquiryPage() {
const { t } = useFeatureUi(strings);
return (
<>
<PageHeader title={t('pm.dist.tabSearch')} subtitle={t('pm.inquiry.subtitle')} />
<SearchTruckTab />
</>
);
}
// ================================================================= distribution // ================================================================= distribution
function DistributeTab() { function DistributeTab() {
const fmt = useFmt(); const fmt = useFmt();
@ -575,7 +727,6 @@ function DistributeTab() {
]; ];
const [cat, setCat] = useState('PCKD'); const [cat, setCat] = useState('PCKD');
const summary = useDistributionSummary(); const summary = useDistributionSummary();
const pivot = useDistributionPivot();
async function go() { if (await confirm({ message: t('pm.dist.confirm') })) distribute.mutate(cat); } async function go() { if (await confirm({ message: t('pm.dist.confirm') })) distribute.mutate(cat); }
return ( return (
<Stack spacing={3}> <Stack spacing={3}>
@ -585,7 +736,7 @@ function DistributeTab() {
</TextField> </TextField>
<Button variant="contained" onClick={() => void go()} sx={{ whiteSpace: 'nowrap' }}>{t('pm.dist.run')}</Button> <Button variant="contained" onClick={() => void go()} sx={{ whiteSpace: 'nowrap' }}>{t('pm.dist.run')}</Button>
</Stack> </Stack>
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', lg: 'repeat(2, minmax(0, 1fr))' } }}> <Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: '1fr' }}>
<Paper sx={{ p: 2 }}> <Paper sx={{ p: 2 }}>
<Typography variant="subtitle1" sx={{ mb: 1 }}>{t('pm.dist.summary')}</Typography> <Typography variant="subtitle1" sx={{ mb: 1 }}>{t('pm.dist.summary')}</Typography>
<Table size="small"> <Table size="small">
@ -593,17 +744,6 @@ function DistributeTab() {
<TableBody>{(summary.data ?? []).map((r) => <TableRow key={r.companyCode ?? 0}><TableCell>{r.comp}</TableCell><TableCell align="right" dir="ltr">{fmt(r.cnt)}</TableCell></TableRow>)}</TableBody> <TableBody>{(summary.data ?? []).map((r) => <TableRow key={r.companyCode ?? 0}><TableCell>{r.comp}</TableCell><TableCell align="right" dir="ltr">{fmt(r.cnt)}</TableCell></TableRow>)}</TableBody>
</Table> </Table>
</Paper> </Paper>
<Paper sx={{ p: 2 }}>
<Typography variant="subtitle1" sx={{ mb: 1 }}>{t('pm.dist.pivot')}</Typography>
<Table size="small">
<TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="right">{t('pm.dist.silos')}</TableCell>
<TableCell align="right">{t('pm.dist.direct')}</TableCell><TableCell align="right">{t('pm.dist.packed')}</TableCell></TableRow></TableHead>
<TableBody>{(pivot.data ?? []).map((r) => (
<TableRow key={r.companyCode ?? 0}><TableCell>{r.company}</TableCell><TableCell align="right" dir="ltr">{r.silos}</TableCell>
<TableCell align="right" dir="ltr">{r.direct}</TableCell><TableCell align="right" dir="ltr">{r.packed}</TableCell></TableRow>
))}</TableBody>
</Table>
</Paper>
</Box> </Box>
</Stack> </Stack>
); );
@ -668,13 +808,15 @@ function SearchTruckTab() {
try { setR(await searchTruckDistribution(tn)); } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } try { setR(await searchTruckDistribution(tn)); } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); }
} }
return ( return (
<Stack spacing={2} sx={{ maxWidth: 560 }}> <Stack spacing={2}>
<Stack direction="row" spacing={1}> <FormCard
icon={SearchIcon} title={t('pm.form.truckData')} maxWidth={620}
actions={<Button variant="contained" startIcon={<SearchIcon />} disabled={!tn} onClick={() => void go()}>{t('common.search')}</Button>}
>
<NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} onEnter={() => void go()} /> <NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} onEnter={() => void go()} />
<Button variant="contained" startIcon={<SearchIcon />} onClick={() => void go()}>{t('common.search')}</Button> </FormCard>
</Stack>
{r && ( {r && (
<Paper sx={{ p: 2 }}> <FormCard icon={LocalShippingIcon} title={t('pm.form.result')} maxWidth={620}>
<Stack spacing={1}> <Stack spacing={1}>
<Info label={t('pm.search.status')}>{r.status}</Info> <Info label={t('pm.search.status')}>{r.status}</Info>
<Info label={t('pm.search.locations')}>{r.companyLocations}</Info> <Info label={t('pm.search.locations')}>{r.companyLocations}</Info>
@ -682,7 +824,7 @@ function SearchTruckTab() {
<Info label={t('pm.search.quantities')} ltr>{`${r.trucksTotalQuantity} / ${r.tenderTotalQuantity}`}</Info> <Info label={t('pm.search.quantities')} ltr>{`${r.trucksTotalQuantity} / ${r.tenderTotalQuantity}`}</Info>
{r.errorMsg && <Alert severity="warning">{r.errorMsg}</Alert>} {r.errorMsg && <Alert severity="warning">{r.errorMsg}</Alert>}
</Stack> </Stack>
</Paper> </FormCard>
)} )}
</Stack> </Stack>
); );
@ -690,142 +832,97 @@ function SearchTruckTab() {
export function DistributionPage() { export function DistributionPage() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
const [tab, setTab] = useState<'distribute' | 'process' | 'search'>('distribute'); const [tab, setTab] = useState<'distribute' | 'process'>('distribute');
const absence = useAbsenceFeature(); const { canTruckOrder } = useRoles();
const toggle = useToggleAbsence();
const confirm = useConfirm();
const { canAbsence, canTruckOrder, canTruckStatus } = useRoles();
return ( return (
<> <>
<PageHeader <PageHeader
title={t('pm.dist.title')} subtitle={t('pm.dist.subtitle')} title={t('pm.dist.title')} subtitle={t('pm.dist.subtitle')}
actions={canAbsence && (
<Button variant="outlined" onClick={async () => { if (await confirm({ message: t('pm.absence.confirm') })) toggle.mutate(undefined as never); }}>
{absence.data?.enabled ? t('pm.absence.disable') : t('pm.absence.enable')}
</Button>
)}
/> />
<Tabs value={tab} onChange={(_, v: typeof tab) => setTab(v)} variant="scrollable" sx={{ mb: 2 }}> <Tabs value={tab} onChange={(_, v: typeof tab) => setTab(v)} variant="scrollable" sx={{ mb: 2 }}>
<Tab value="distribute" label={t('pm.dist.tabDistribute')} /> <Tab value="distribute" label={t('pm.dist.tabDistribute')} />
{canTruckOrder && <Tab value="process" label={t('pm.dist.tabProcess')} />} {canTruckOrder && <Tab value="process" label={t('pm.dist.tabProcess')} />}
{canTruckStatus && <Tab value="search" label={t('pm.dist.tabSearch')} />}
</Tabs> </Tabs>
{tab === 'distribute' && <DistributeTab />} {tab === 'distribute' && <DistributeTab />}
{tab === 'process' && canTruckOrder && <ProcessTab />} {tab === 'process' && canTruckOrder && <ProcessTab />}
{tab === 'search' && canTruckStatus && <SearchTruckTab />}
</> </>
); );
} }
// ================================================================= weighbridges // ================================================================= 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 (
<Stack spacing={2} sx={{ maxWidth: 420 }}>
<NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} />
<NumberField label={t('pm.wb.weight')} value={w} onChange={setW} onEnter={() => void go()} />
<Box><Button variant="contained" disabled={!tn || !w} onClick={() => void go()}>{t('common.save')}</Button></Box>
</Stack>
);
}
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 (
<Stack spacing={2} sx={{ maxWidth: 420 }}>
<NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} />
<NumberField label={t('pm.wb.tare')} value={tare} onChange={setTare} />
<NumberField label={t('pm.wb.gross')} value={gross} onChange={setGross} />
<Box><Button variant="contained" disabled={!tn || !tare || !gross}
onClick={() => save.mutate({ tn, tareWeight: Number(tare), grossWeight: Number(gross) })}>{t('common.save')}</Button></Box>
</Stack>
);
}
function ManualTab() { function ManualTab() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
const save = useWeighbridgeManual(); const save = useWeighbridgeManual();
const toast = useToast(); const toast = useToast();
const { user } = useAuth(); const { user } = useAuth();
const [tn, setTn] = useState(''); 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 [wi, setWi] = useState('');
const [wo, setWo] = 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() { async function find() {
if (!tn) return; if (!tn) return;
try { const r = await searchDestination(tn); setDest(r.destination ? `${r.destination}${r.message ? ` - ${r.message}` : ''}` : r.message ?? ''); } try { const r = await searchDestination(tn); setFound({ destination: r.destination, message: r.message }); }
catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } 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 ( return (
<Stack spacing={2} sx={{ maxWidth: 420 }}> <Stack spacing={2}>
<NumberField autoFocus label={t('pm.order.tn')} value={tn} onChange={setTn} onEnter={() => void find()} /> <FormCard icon={SearchIcon} title={t('pm.form.truckData')} maxWidth={760}>
{dest && <Alert severity="info">{dest}</Alert>} <Stack spacing={1.5}>
<NumberField label={t('pm.wb.location')} value={loc} onChange={setLoc} /> <Stack direction="row" spacing={2} sx={{ alignItems: 'center', flexWrap: 'wrap' }} useFlexGap>
<NumberField label={t('pm.wb.first')} value={wi} onChange={setWi} /> <Box sx={{ ...row, flex: 1, minWidth: 260 }}>
<NumberField label={t('pm.wb.second')} value={wo} onChange={setWo} /> <Typography sx={{ fontSize: 14 }}>{t('pm.wb.truckNo')}</Typography>
<Stack direction="row" spacing={1}> <NumberField autoFocus label="" value={tn} onChange={(v) => { setTn(v); setFound(null); }} onEnter={() => void find()} />
<Button variant="outlined" onClick={() => void find()} disabled={!tn}>{t('pm.wb.findDest')}</Button> </Box>
<Button variant="contained" disabled={!tn || !loc || !wi || !wo} <Button variant="outlined" startIcon={<SearchIcon />} onClick={() => void find()} disabled={!tn}>{t('pm.wb.search')}</Button>
onClick={() => save.mutate({ tn, locationId: Number(loc), weightIn: Number(wi), weightOut: Number(wo) })}>{t('common.save')}</Button>
</Stack> </Stack>
<Box sx={row}>
<Typography sx={{ fontSize: 14 }}>{t('pm.wb.dest')}</Typography>
<Typography sx={{ color: 'primary.main', fontWeight: 700 }}>
{found ? (found.destination ?? '-') : ''}
{found?.message && <Typography component="span" variant="caption" sx={{ color: 'text.secondary', fontWeight: 400, marginInlineStart: 1 }}>{found.message}</Typography>}
</Typography>
</Box>
</Stack> </Stack>
); </FormCard>
}
function CountsTab() { <FormCard
const fmt = useFmt(); icon={ScaleIcon} title={t('pm.wb.card')} maxWidth={760}
const { t } = useFeatureUi(strings); actions={(
const q = useLocationCounts(); <Button variant="contained" startIcon={<SaveIcon />} disabled={!tn || !location || !wi || !wo}
if (q.isLoading) return <LoadingBanner />; onClick={() => save.mutate({ tn, locationId: Number(location), weightIn: Number(wi), weightOut: Number(wo) })}>{t('common.save')}</Button>
return ( )}
<TableContainer component={Paper} sx={{ maxWidth: 520 }}> >
<Table size="small"> <Stack spacing={1.5}>
<TableHead><TableRow><TableCell>{t('pm.wb.loc')}</TableCell><TableCell align="right">{t('pm.wb.trucks')}</TableCell></TableRow></TableHead> {!loc && (
<TableBody>{(q.data ?? []).map((r, i) => <TableRow key={i}><TableCell>{r.loc}</TableCell><TableCell align="right" dir="ltr">{fmt(r.cnt)}</TableCell></TableRow>)}</TableBody> <Box sx={row}>
</Table> <Typography sx={{ fontSize: 14 }}>{t('pm.wb.location')}</Typography>
</TableContainer> <NumberField label="" value={locInput} onChange={setLocInput} />
</Box>
)}
<Box sx={row}>
<Typography sx={{ fontSize: 14 }}>{t('pm.wb.first')}</Typography>
<NumberField label="" value={wi} onChange={setWi} />
</Box>
<Box sx={row}>
<Typography sx={{ fontSize: 14 }}>{t('pm.wb.second')}</Typography>
<NumberField label="" value={wo} onChange={setWo} />
</Box>
</Stack>
</FormCard>
</Stack>
); );
} }
export function WeighbridgePage() { export function WeighbridgePage() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
const { canClose } = useRoles();
const [tab, setTab] = useState(0);
const closeP = useClosePermit();
const confirm = useConfirm();
const [pn, setPn] = useState('');
return ( return (
<> <>
<PageHeader title={t('pm.wb.title')} subtitle={t('pm.wb.subtitle')} /> <PageHeader title={t('pm.wb.title')} subtitle={t('pm.wb.subtitle')} />
<Tabs value={tab} onChange={(_, v: number) => setTab(v)} variant="scrollable" sx={{ mb: 2 }}> <ManualTab />
<Tab label={t('pm.wb.tabEnter')} /><Tab label={t('pm.wb.tabExit')} /><Tab label={t('pm.wb.tabManual')} />
<Tab label={t('pm.wb.tabLoading')} /><Tab label={t('pm.wb.tabDischarge')} /><Tab label={t('pm.wb.tabCounts')} />{canClose && <Tab label={t('pm.wb.tabClose')} />}
</Tabs>
{tab === 0 && <ReadingTab kind="enter" />}
{tab === 1 && <ReadingTab kind="exit" />}
{tab === 2 && <ManualTab />}
{tab === 3 && <WeightsTab kind="loading-weights" />}
{tab === 4 && <WeightsTab kind="discharge-weights" />}
{tab === 5 && <CountsTab />}
{tab === 6 && canClose && (
<Stack spacing={2} sx={{ maxWidth: 420 }}>
<NumberField label={t('pm.order.pn')} value={pn} onChange={setPn} />
<Box><Button variant="contained" disabled={!pn} onClick={async () => { if (await confirm({ message: t('pm.wb.closeConfirm'), danger: true })) closeP.mutate(pn); }}>{t('pm.wb.close')}</Button></Box>
</Stack>
)}
</> </>
); );
} }

View File

@ -4,24 +4,29 @@ import EditNoteIcon from '@mui/icons-material/EditNote';
import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck'; import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck';
import AssignmentIcon from '@mui/icons-material/Assignment'; import AssignmentIcon from '@mui/icons-material/Assignment';
import LocalShippingIcon from '@mui/icons-material/LocalShipping'; 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 ScaleIcon from '@mui/icons-material/Scale';
import SortIcon from '@mui/icons-material/Sort';
import TuneIcon from '@mui/icons-material/Tune'; import TuneIcon from '@mui/icons-material/Tune';
import type { MenuItem } from '@/shell/types'; import type { MenuItem } from '@/shell/types';
import { 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'; } from './pages';
import strings from './strings'; import strings from './strings';
import registryStrings from '../grains-registry/strings';
/** Grains "permits" slice: permit list / order form / queue / destinations / distribution / weighbridges / print pages. */ /** Grains "permits" slice: permit list / order form / queue / destinations / distribution / weighbridges / print pages. */
export const routes: RouteObject[] = [ export const routes: RouteObject[] = [
{ path: '/grains/permits', element: <PermitsPage /> }, { path: '/grains/permits', element: <PermitsPage /> },
{ path: '/grains/permits/queue', element: <QueuePage /> },
{ path: '/grains/permits/destinations', element: <DestinationsPage /> }, { path: '/grains/permits/destinations', element: <DestinationsPage /> },
{ path: '/grains/permits/manual-input', element: <ManualInputPage /> }, { path: '/grains/permits/manual-input', element: <ManualInputPage /> },
{ path: '/grains/permits/activation', element: <ActivationPage /> }, { path: '/grains/permits/activation', element: <ActivationPage /> },
{ path: '/grains/permits/distribution', element: <DistributionPage /> }, { path: '/grains/permits/distribution', element: <DistributionPage /> },
{ path: '/grains/permits/weighbridge', element: <WeighbridgePage /> }, { path: '/grains/permits/weighbridge', element: <WeighbridgePage /> },
{ path: '/grains/permits/close', element: <ClosePermitPage /> },
{ path: '/grains/permits/truck-inquiry', element: <TruckInquiryPage /> },
{ path: '/grains/orders/supply', element: <SupplyOrderPage /> },
{ path: '/grains/permits/:id', element: <PermitDetailPage />, handle: { crumb: strings['pm.crumb.view'] } }, { path: '/grains/permits/:id', element: <PermitDetailPage />, handle: { crumb: strings['pm.crumb.view'] } },
{ path: '/grains/permits/:id/print/accept', element: <PrintAcceptPage />, handle: { crumb: strings['pm.crumb.print'] } }, { path: '/grains/permits/:id/print/accept', element: <PrintAcceptPage />, handle: { crumb: strings['pm.crumb.print'] } },
{ path: '/grains/permits/:id/print/in', element: <PrintInPage />, handle: { crumb: strings['pm.crumb.print'] } }, { path: '/grains/permits/:id/print/in', element: <PrintInPage />, handle: { crumb: strings['pm.crumb.print'] } },
@ -35,11 +40,13 @@ export const menu: MenuItem[] = [
icon: AssignmentIcon, icon: AssignmentIcon,
children: [ children: [
{ key: 'grains.permits.list', title: strings['pm.menu.permits'], icon: LocalShippingIcon, path: '/grains/permits' }, { 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.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.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.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' }, { key: 'grains.permits.weighbridge', title: strings['pm.menu.weighbridge'], icon: ScaleIcon, path: '/grains/permits/weighbridge' },
], ],
}, },

View File

@ -37,15 +37,29 @@ export default defineStrings({
// ---- detail / order form // ---- detail / order form
'pm.detail.title': { en: 'Permit {pn}', ar: 'الارسالية {pn}' }, 'pm.detail.title': { en: 'Permit {pn}', ar: 'الارسالية {pn}' },
'pm.detail.status': { en: 'Status', ar: 'الحالة' }, '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.queueNo': { en: 'Queue no.', ar: 'رقم الدور' },
'pm.detail.cargo': { en: 'Cargo', ar: 'الحمولة' }, 'pm.detail.cargo': { en: 'Cargo type', ar: 'نوع المادة' },
'pm.detail.shift': { en: 'Shift', ar: 'الفترة' }, 'pm.detail.shift': { en: 'Shift', ar: 'الشفت' },
'pm.detail.operation': { en: 'Operation', ar: 'نوع العملية' }, 'pm.detail.operation': { en: 'Operation', ar: 'نوع العملية' },
'pm.detail.truck': { en: 'Truck', ar: 'القاطرة' }, 'pm.detail.truck': { en: 'Truck', ar: 'القاطرة' },
'pm.detail.trailer': { en: 'Trailer', ar: 'المقطورة' }, 'pm.detail.trailer': { en: 'Trailer', ar: 'المقطورة' },
'pm.detail.driver': { en: 'Driver', ar: 'السائق' }, 'pm.detail.driver': { en: 'Driver', ar: 'السائق' },
'pm.order.submitTitle': { en: 'Submit the order', 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.pn': { en: 'Permit no.', ar: 'رقم الارسالية' },
'pm.order.tn': { en: 'Truck no.', ar: 'رقم القاطرة' }, 'pm.order.tn': { en: 'Truck no.', ar: 'رقم القاطرة' },
'pm.order.trn': { en: 'Trailer 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.update': { en: 'Save changes', ar: 'حفظ التعديلات' },
'pm.order.notRegistered': { en: 'Not registered', ar: 'غير مسجلة' }, 'pm.order.notRegistered': { en: 'Not registered', ar: 'غير مسجلة' },
'pm.order.driverMissing': { en: 'The driver must be registered in the drivers screen', ar: 'السائق يجب ان يكون مسجل في شاشة السائقين' }, 'pm.order.driverMissing': { en: 'The driver must be registered in the drivers screen', ar: 'السائق يجب ان يكون مسجل في شاشة السائقين' },
'pm.events.title': { en: 'Permit events', ar: 'احداث الارسالية' }, 'pm.events.title': { en: 'Movement log', ar: 'سجل الحركات' },
'pm.events.date': { en: 'Date', ar: 'التاريخ' }, 'pm.events.date': { en: 'Movement date', ar: 'تاريخ الحركة' },
'pm.events.type': { en: 'Event', ar: 'الحدث' }, 'pm.events.type': { en: 'Movement', ar: 'الحركة' },
'pm.events.by': { en: 'Done by', ar: 'بواسطة' }, 'pm.events.by': { en: 'Done by', ar: 'بواسطة' },
'pm.events.status': { en: 'Status', ar: 'الحالة' }, 'pm.events.status': { en: 'Status', ar: 'الحالة' },
'pm.events.weight': { en: 'Weight', 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.dest.subtitle': { en: 'Assign a destination to a supply permit', ar: 'تحديد وجهة ارسالية تموين' },
'pm.menu.manualInput': { en: 'Manual input', ar: 'الادخال اليدوي' }, 'pm.menu.manualInput': { en: 'Manual input', ar: 'الادخال اليدوي' },
'pm.menu.activation': { en: 'Activate orders', 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.manual.subtitle': { en: 'Enter a truck by hand against an order date and destination', ar: 'ادخال شاحنة يدوياً على طلبية ووجهة' },
'pm.activation.title': { en: 'Activate orders', ar: 'تفعيل الطلبيات' }, 'pm.activation.title': { en: 'Activate orders', ar: 'تفعيل الطلبيات' },
'pm.activation.subtitle': { en: 'Activate or deactivate the orders of the day', 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.cargo': { en: 'Cargo', ar: 'الحمولة' },
'pm.dest.confirm': { en: 'Assign this destination to the permit?', ar: 'هل تريد تحديد هذه الوجهة للارسالية؟' }, 'pm.dest.confirm': { en: 'Assign this destination to the permit?', ar: 'هل تريد تحديد هذه الوجهة للارسالية؟' },
'pm.manual.orderDate': { en: 'Order date', 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.noOrders': { en: 'No orders available', ar: 'لا توجد طلبيات متاحة' },
'pm.manual.ltw': { en: 'First weight (tare)', ar: 'الوزن الأول' }, 'pm.manual.ltw': { en: 'Tare weight', ar: 'وزن فارغ' },
'pm.manual.lgw': { en: 'Second weight (gross)', ar: 'الوزن الثاني' }, 'pm.manual.lgw': { en: 'Gross weight', ar: 'وزن قائم' },
'pm.manual.altList': { en: 'List orders of the permit type', 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.manual.confirm': { en: 'Assign the destination manually and record the weights?', ar: 'هل تريد تحديد الوجهة يدويا وتسجيل الأوزان؟' },
'pm.activate.loc': { en: 'Loading site', ar: 'الموقع' }, 'pm.activate.loc': { en: 'Loading site', ar: 'الموقع' },
@ -133,24 +147,40 @@ export default defineStrings({
// ---- weighbridges // ---- weighbridges
'pm.wb.title': { en: 'Weighbridges', ar: 'القبّان' }, '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.tabEnter': { en: 'Entry weighing', ar: 'وزن الدخول' },
'pm.wb.tabExit': { en: 'Exit weighing', ar: 'وزن الخروج' }, 'pm.wb.tabExit': { en: 'Exit weighing', ar: 'وزن الخروج' },
'pm.wb.tabManual': { en: 'Manual weighing', ar: 'وزن يدوي' }, 'pm.wb.tabManual': { en: 'Manual weighing', ar: 'وزن يدوي' },
'pm.wb.tabLoading': { en: 'Loading weights', ar: 'أوزان التحميل' }, 'pm.wb.tabLoading': { en: 'Loading weights', ar: 'أوزان التحميل' },
'pm.wb.tabDischarge': { en: 'Discharge weights', ar: 'أوزان التفريغ' }, 'pm.wb.tabDischarge': { en: 'Discharge weights', ar: 'أوزان التفريغ' },
'pm.wb.tabCounts': { en: 'Trucks per site', 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.weight': { en: 'Weight (kg)', ar: 'الوزن (كغم)' },
'pm.wb.tare': { en: 'Tare weight', ar: 'الوزن الفارغ' }, 'pm.wb.tare': { en: 'Tare weight', ar: 'الوزن الفارغ' },
'pm.wb.gross': { en: 'Gross weight', ar: 'الوزن القائم' }, 'pm.wb.gross': { en: 'Gross weight', ar: 'الوزن القائم' },
'pm.wb.first': { en: 'First weight (tare)', ar: 'الوزن الأول' }, 'pm.wb.first': { en: 'First weight (tare)', ar: 'الوزن الأول' },
'pm.wb.second': { en: 'Second weight (gross)', ar: 'الوزن الثاني' }, 'pm.wb.second': { en: 'Second weight (gross)', ar: 'الوزن الثاني' },
'pm.wb.location': { en: 'Weighbridge location no.', 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.findDest': { en: 'Find destination', ar: 'البحث عن الوجهة' },
'pm.wb.loc': { en: 'Site', ar: 'الموقع' }, 'pm.wb.loc': { en: 'Site', ar: 'الموقع' },
'pm.wb.trucks': { en: 'Trucks', 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: 'هل تريد اغلاق التصريح يدويا؟' }, 'pm.wb.closeConfirm': { en: 'Close this permit manually?', ar: 'هل تريد اغلاق التصريح يدويا؟' },
// ---- print // ---- print

View File

@ -1,7 +1,6 @@
import type { RouteObject } from 'react-router-dom'; import type { RouteObject } from 'react-router-dom';
import BadgeIcon from '@mui/icons-material/Badge'; import BadgeIcon from '@mui/icons-material/Badge';
import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings'; import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings';
import BlockIcon from '@mui/icons-material/Block';
import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import LocalShippingIcon from '@mui/icons-material/LocalShipping';
import PinDropIcon from '@mui/icons-material/PinDrop'; import PinDropIcon from '@mui/icons-material/PinDrop';
import RvHookupIcon from '@mui/icons-material/RvHookup'; import RvHookupIcon from '@mui/icons-material/RvHookup';
@ -51,7 +50,6 @@ export const menu: MenuItem[] = [
title: strings['reg.menu.controlGroup'], title: strings['reg.menu.controlGroup'],
icon: AdminPanelSettingsIcon, icon: AdminPanelSettingsIcon,
children: [ 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' }, { key: 'grains.registry.weighbridge', title: strings['reg.menu.weighbridge'], icon: ScaleIcon, path: '/grains/registry/weighbridge-control' },
], ],
}, },

View File

@ -6,7 +6,6 @@ import {
} from '@mui/material'; } from '@mui/material';
import DownloadIcon from '@mui/icons-material/Download'; import DownloadIcon from '@mui/icons-material/Download';
import PlayArrowIcon from '@mui/icons-material/PlayArrow'; import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import PrintIcon from '@mui/icons-material/Print';
import UploadFileIcon from '@mui/icons-material/UploadFile'; import UploadFileIcon from '@mui/icons-material/UploadFile';
import { ApiError, type PagedResult } from '@/api/client'; import { ApiError, type PagedResult } from '@/api/client';
import { DataGrid } from '@/components/DataGrid'; import { DataGrid } from '@/components/DataGrid';
@ -96,10 +95,6 @@ function useRange(opts: { company?: boolean; cargo?: boolean }) {
return { bar, params, lang, t }; return { bar, params, lang, t };
} }
const PrintButton = ({ label }: { label: string }) => (
<Button variant="outlined" startIcon={<PrintIcon />} onClick={() => window.print()}>{label}</Button>
);
function ReportShell({ title, subtitle, bar, params, query, print = true, children }: { function ReportShell({ title, subtitle, bar, params, query, print = true, children }: {
title: string; subtitle?: string; bar: ReactNode; params: RangeParams | null; title: string; subtitle?: string; bar: ReactNode; params: RangeParams | null;
query: { isPending: boolean; isError: boolean; error: unknown; isFetching: boolean; data: unknown }; 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(); const { user } = useAuth();
return ( return (
<Box> <Box>
<PageHeader title={title} subtitle={subtitle} actions={params && query.data ? <PrintButton label={t('rpt.print')} /> : undefined} /> <PageHeader title={title} subtitle={subtitle} />
{bar} {bar}
{!params && <EmptyState title={t('rpt.pickRange')} />} {!params && <EmptyState title={t('rpt.pickRange')} />}
{params && query.isPending && <LoadingBanner />} {params && query.isPending && <LoadingBanner />}
@ -420,7 +415,7 @@ export function MotMultiTripsPage() {
const names = [t('rpt.mot.companies'), t('rpt.mot.individuals')]; const names = [t('rpt.mot.companies'), t('rpt.mot.individuals')];
return ( return (
<Box> <Box>
<PageHeader title={t('rpt.mot.title')} subtitle={t('rpt.mot.note')} actions={r ? <PrintButton label={t('rpt.print')} /> : undefined} /> <PageHeader title={t('rpt.mot.title')} subtitle={t('rpt.mot.note')} />
{q.isPending && <LoadingBanner />} {q.isPending && <LoadingBanner />}
{q.isError && <Alert severity="error">{t('rpt.loadError')}: {errText(q.error, '')}</Alert>} {q.isError && <Alert severity="error">{t('rpt.loadError')}: {errText(q.error, '')}</Alert>}
{r && ( {r && (
@ -511,7 +506,6 @@ function TableReportBody({ meta }: { meta: TableReportMeta }) {
actions={ actions={
<Stack direction="row" spacing={1} sx={{ '@media print': { display: 'none' } }}> <Stack direction="row" spacing={1} sx={{ '@media print': { display: 'none' } }}>
<Button variant="outlined" startIcon={<DownloadIcon />} disabled={busy || missing.length > 0} onClick={exportExcel}>{t('rpt.excel')}</Button> <Button variant="outlined" startIcon={<DownloadIcon />} disabled={busy || missing.length > 0} onClick={exportExcel}>{t('rpt.excel')}</Button>
<PrintButton label={t('rpt.print')} />
</Stack> </Stack>
} }
/> />

View File

@ -2,7 +2,6 @@ import type { RouteObject } from 'react-router-dom';
import AssessmentIcon from '@mui/icons-material/Assessment'; import AssessmentIcon from '@mui/icons-material/Assessment';
import BarChartIcon from '@mui/icons-material/BarChart'; import BarChartIcon from '@mui/icons-material/BarChart';
import DashboardIcon from '@mui/icons-material/Dashboard'; import DashboardIcon from '@mui/icons-material/Dashboard';
import LocalShippingIcon from '@mui/icons-material/LocalShipping';
import PieChartIcon from '@mui/icons-material/PieChart'; import PieChartIcon from '@mui/icons-material/PieChart';
import ScaleIcon from '@mui/icons-material/Scale'; import ScaleIcon from '@mui/icons-material/Scale';
import TableChartIcon from '@mui/icons-material/TableChart'; import TableChartIcon from '@mui/icons-material/TableChart';
@ -14,6 +13,7 @@ import {
} from './pages'; } from './pages';
import { tableReports } from './meta'; import { tableReports } from './meta';
import strings from './strings'; import strings from './strings';
import orderStrings from '../grains-orders/strings';
const B = '/grains/reports'; const B = '/grains/reports';
@ -36,12 +36,10 @@ const table = (key: string, icon: MenuItem['icon'] = TableChartIcon): MenuItem =
export const menu: 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', key: 'grains.reports',
title: strings['rpt.menu.group'], title: strings['rpt.menu.group'],
icon: AssessmentIcon, icon: AssessmentIcon,
children: [
{
key: 'grains.reports.trips', title: strings['rpt.menu.trips'], icon: BarChartIcon,
children: [ children: [
{ key: 'grains.reports.dashboard', title: strings['rpt.menu.dashboard'], icon: DashboardIcon, path: `${B}/dashboard` }, { 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.numOfTrips', title: strings['rpt.menu.numOfTrips'], icon: BarChartIcon, path: `${B}/trips/num-of-trips` },
@ -49,40 +47,17 @@ export const menu: MenuItem[] = [
{ key: 'grains.reports.frequency', title: strings['rpt.menu.frequency'], icon: BarChartIcon, path: `${B}/trips/frequency` }, { 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.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.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('weighbridge-events', ScaleIcon), table('waybridge-summary', ScaleIcon), table('waybridge-details', ScaleIcon),
table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'), 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('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'),
table('companies-turn'), table('owners-turn'), table('companies-turn'), table('owners-turn'),
], { key: 'grains.orders.reportOrders', title: orderStrings['ord.menu.reportOrders'], icon: AssessmentIcon, path: '/grains/orders/reports/tender-orders' },
}, { key: 'grains.orders.reportFinance', title: orderStrings['ord.menu.reportFinance'], icon: AssessmentIcon, path: '/grains/orders/reports/financial-billing' },
{ table('drivers'), table('trucks'),
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` }, { key: 'grains.reports.motMulti', title: strings['rpt.menu.motMulti'], icon: BarChartIcon, path: `${B}/mot/multi-trips` },
table('mot-grain-cube'), table('mot-grain-frequency'), table('mot-grain-cube'), table('mot-grain-frequency'),
],
},
{
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.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.wbFiles', title: strings['rpt.menu.wbFiles'], icon: UploadFileIcon, path: `${B}/imports/weighbridge-files`, roles: ['SU'] },
], ],
}, },
],
},
]; ];

View File

@ -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. // No permissions answer (request failed) = nothing is allowed except for the role checks above; SU gets all=true.
const can = useCallback( 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], [perms],
); );

View File

@ -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 { useLocation, useNavigate } from 'react-router-dom';
import { import {
Box, Collapse, Divider, Drawer, IconButton, List, ListItemButton, ListItemText, Menu, MenuItem, Tooltip, Typography, 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 { Logo } from '@/components/Logo';
import { useUi } from '@/i18n/useUi'; import { useUi } from '@/i18n/useUi';
import { badgeColors } from '@/theme/tokens'; import { badgeColors } from '@/theme/tokens';
import { pathMatches } from './menuUtils'; import { findOwner } from './menuUtils';
import type { MenuItem as Item } from './types'; import type { MenuItem as Item } from './types';
export const DRAWER_FULL = 272; export const DRAWER_FULL = 272;
@ -64,22 +64,17 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob
const [open, setOpen] = useState<Record<string, boolean>>({}); const [open, setOpen] = useState<Record<string, boolean>>({});
const [pop, setPop] = useState<{ anchor: HTMLElement; item: Item } | null>(null); 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(() => { useEffect(() => {
const next: Record<string, boolean> = {}; if (!ownerTrail) return;
const walk = (list: Item[]): boolean => { setOpen((o) => ({ ...o, ...Object.fromEntries(ownerTrail.split('|').map((k) => [k, true])) }));
let any = false; }, [ownerTrail, pathname]);
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]);
const go = (path: string) => { const go = (path: string) => {
navigate(path); navigate(path);
@ -87,12 +82,13 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob
setPop(null); setPop(null);
}; };
const isActive = (it: Item): boolean => const isActive = (it: Item): boolean => (it.key === 'home' ? pathname === '/' : activeKeys.has(it.key));
(it.path === '/' ? pathname === '/' : pathMatches(pathname, it.path)) || pathMatches(pathname, it.createPath) || !!it.children?.some(isActive);
const renderRow = (it: Item, depth: number) => { const renderRow = (it: Item, depth: number) => {
const isGroup = !!it.children?.length; const isGroup = !!it.children?.length;
const hasPage = isGroup && !!it.path; // an entry with its own page AND sub entries
const active = isActive(it); const active = isActive(it);
const ownActive = hasPage && owner?.item.key === it.key;
const title = tr(it.title); const title = tr(it.title);
if (mini) { if (mini) {
@ -113,8 +109,12 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob
<> <>
<Box sx={{ display: 'flex', alignItems: 'center', mx: 1, mb: 0.25 }}> <Box sx={{ display: 'flex', alignItems: 'center', mx: 1, mb: 0.25 }}>
<ListItemButton <ListItemButton
selected={active && !isGroup} selected={(active && !isGroup) || ownActive}
onClick={() => (isGroup ? setOpen((o) => ({ ...o, [it.key]: !o[it.key] })) : it.path && go(it.path))} 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 }} sx={{ borderRadius: 1.5, gap: 1.25, paddingInlineStart: 1 + depth * 2, py: 0.75, minWidth: 0, flex: 1 }}
> >
<IconBadge item={it} size={depth ? 28 : 34} /> <IconBadge item={it} size={depth ? 28 : 34} />
@ -122,8 +122,13 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob
primary={title} primary={title}
slotProps={{ primary: { noWrap: true, sx: { fontWeight: active ? 700 : 500, fontSize: depth ? 14 : 15 } } }} slotProps={{ primary: { noWrap: true, sx: { fontWeight: active ? 700 : 500, fontSize: depth ? 14 : 15 } } }}
/> />
{isGroup && (open[it.key] ? <ExpandLess fontSize="small" /> : <ExpandMore fontSize="small" />)} {isGroup && !hasPage && (open[it.key] ? <ExpandLess fontSize="small" /> : <ExpandMore fontSize="small" />)}
</ListItemButton> </ListItemButton>
{hasPage && (
<IconButton size="small" aria-label={title} onClick={() => setOpen((o) => ({ ...o, [it.key]: !o[it.key] }))} sx={{ marginInlineStart: 0.25 }}>
{open[it.key] ? <ExpandLess fontSize="small" /> : <ExpandMore fontSize="small" />}
</IconButton>
)}
{it.createPath && ( {it.createPath && (
<Tooltip title={t('nav.create')}> <Tooltip title={t('nav.create')}>
<IconButton size="small" aria-label={`${t('nav.create')}: ${title}`} onClick={() => go(it.createPath!)} sx={{ marginInlineStart: 0.5, color: colorOf(it) }}> <IconButton size="small" aria-label={`${t('nav.create')}: ${title}`} onClick={() => go(it.createPath!)} sx={{ marginInlineStart: 0.5, color: colorOf(it) }}>
@ -165,6 +170,12 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob
)} )}
<Menu anchorEl={pop?.anchor} open={!!pop} onClose={() => setPop(null)} anchorOrigin={{ vertical: 'top', horizontal: dir === 'rtl' ? 'left' : 'right' }} transformOrigin={{ vertical: 'top', horizontal: dir === 'rtl' ? 'right' : 'left' }}> <Menu anchorEl={pop?.anchor} open={!!pop} onClose={() => setPop(null)} anchorOrigin={{ vertical: 'top', horizontal: dir === 'rtl' ? 'left' : 'right' }} transformOrigin={{ vertical: 'top', horizontal: dir === 'rtl' ? 'right' : 'left' }}>
{pop && <Typography variant="overline" sx={{ px: 2, color: 'text.secondary' }}>{tr(pop.item.title)}</Typography>} {pop && <Typography variant="overline" sx={{ px: 2, color: 'text.secondary' }}>{tr(pop.item.title)}</Typography>}
{pop?.item.path && (
<MenuItem onClick={() => go(pop.item.path!)} sx={{ gap: 1.5 }}>
<IconBadge item={pop.item} size={26} />
<Box sx={{ flex: 1 }}>{tr(pop.item.title)}</Box>
</MenuItem>
)}
{pop?.item.children?.map((c) => ( {pop?.item.children?.map((c) => (
<MenuItem key={c.key} onClick={() => c.path && go(c.path)} sx={{ gap: 1.5, paddingInlineEnd: c.createPath ? 0.5 : 2 }}> <MenuItem key={c.key} onClick={() => c.path && go(c.path)} sx={{ gap: 1.5, paddingInlineEnd: c.createPath ? 0.5 : 2 }}>
<IconBadge item={c} size={26} /> <IconBadge item={c} size={26} />

View File

@ -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). * 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) { 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. */ /** Recursively keep only items the role may see; drop groups left empty. */