From bf1c04b590b849ff650e06ad72bfe4daee38c44f Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Tue, 17 Nov 2026 15:55:03 +0300 Subject: [PATCH] Security hardening, time zone, voice call SOAP, registry fixes, CO role, remarks byte limit - Permits: confirming a turn (accept/reject/revoke-accepted) is staff-only; submit needs REQST; company access check no longer passes null; seed/check-trucks SU-only; duplicate company-destinations endpoint removed - Registry: attachment download scoped to the user's company; long original names and 20-char column caps; add-trailer button after revoke - Dialer callback: constant-time key, NO_ANSWER only for REQST and legacy-style reset, postpone days capped - Voice call: SOAP callAPI like legacy, single flight, started/busy results - Company turn permits: truck number editable - Blacklist remarks cut by UTF-8 bytes (500-byte column) - Distribution: BlCategory bind, OPEN guards, process-with-destination dropdowns and server check, per-category confirmation - Container TZ=Asia/Amman; production ownership code lists; IVR config - Role CO (same rights as GTO), date field padding, home page grouping, grid and report fixes Co-Authored-By: Claude Sonnet 5.5 --- db/role-co.sql | 30 +++++ deploy/prod/docker-compose.yml | 1 + deploy/qa/Dockerfile | 3 +- deploy/qa/docker-compose.yml | 1 + docs/ENVIRONMENTS.md | 1 + .../V1/Grains/PermitsController.cs | 17 ++- src/NTP.Api/appsettings.Production.json | 5 + .../Access/PermissionDefaults.cs | 50 ++++----- src/NTP.Application/Auth/AuthService.cs | 3 + .../Grains/Permits/DestinationService.cs | 13 --- .../Grains/Permits/DistributionService.cs | 71 ++++++++---- .../Grains/Permits/GrainsPermitsOptions.cs | 6 + .../Grains/Permits/IDistributionRepository.cs | 6 +- .../Grains/Permits/IPermitRepository.cs | 3 + .../Grains/Permits/PermitService.cs | 40 ++++++- .../Grains/Permits/PermitSupport.cs | 29 +++-- .../Grains/Registry/BlacklistService.cs | 2 +- .../Grains/Registry/RegistryAccessService.cs | 8 +- .../Registry/RegistryAttachmentService.cs | 27 ++++- .../Grains/Registry/RegistryRules.cs | 33 +++++- .../Grains/Registry/RegistryValidation.cs | 6 +- .../Grains/GrainsPermitsGateways.cs | 93 +++++++++++++--- .../Grains/Permits/DistributionRepository.cs | 19 ++-- .../Grains/Permits/PermitRepository.cs | 5 +- .../Grains/Permits/PhoneEventRepository.cs | 4 +- .../Grains/Registry/BlacklistRepository.cs | 6 +- tests/NTP.Tests/AttachmentNameTests.cs | 31 ++++++ tests/NTP.Tests/BlacklistRemarksTests.cs | 33 ++++++ tests/NTP.Tests/PermissionTests.cs | 8 ++ tests/NTP.Tests/PermitsRulesTests.cs | 18 +++ web/src/components/DateField.tsx | 29 +++-- web/src/components/MetaForm/MetaForm.tsx | 4 +- web/src/features/grains-permits/pages.tsx | 104 +++++++++++++----- web/src/features/grains-permits/strings.ts | 1 + web/src/features/grains-registry/pages.tsx | 6 +- web/src/features/grains-registry/strings.ts | 1 + web/src/shell/DashboardPage.tsx | 68 +++++++++--- web/src/shell/Sidebar.tsx | 2 +- 38 files changed, 606 insertions(+), 181 deletions(-) create mode 100644 db/role-co.sql create mode 100644 tests/NTP.Tests/AttachmentNameTests.cs create mode 100644 tests/NTP.Tests/BlacklistRemarksTests.cs diff --git a/db/role-co.sql b/db/role-co.sql new file mode 100644 index 0000000..c0a7f77 --- /dev/null +++ b/db/role-co.sql @@ -0,0 +1,30 @@ +-- New role CO with the same authority as GTO. Safe to re-run; not run by the app. +-- Run order: part 1 in the NTP schema, part 2 in the primary (NAFITHTCS) schema. +-- Afterwards assign role CO to the users who need it (NTPUSERS) - they sign in as before. +-- The API applies the permission rows within about a minute, the browser on the next reload / sign-in. + +-- --------------------------------------------------------------------------------------------------------------------------- +-- Part 1 (NTP schema): the role itself, copied from GTO (level, type, manager columns). Rename it in NAME if needed. +-- --------------------------------------------------------------------------------------------------------------------------- +INSERT INTO ROLES (CODE, NAME, DIRECTMANAGER, EMPLOYEES, MANAGERS, LEVELNUMBER, ROLETYPE, TENDER) +SELECT 'CO', 'CO', r.DIRECTMANAGER, r.EMPLOYEES, r.MANAGERS, r.LEVELNUMBER, r.ROLETYPE, r.TENDER + FROM ROLES r + WHERE r.CODE = 'GTO' + AND NOT EXISTS (SELECT 1 FROM ROLES x WHERE x.CODE = 'CO'); + +COMMIT; + +-- --------------------------------------------------------------------------------------------------------------------------- +-- Part 2 (primary schema): every screen / action / report right GTO has (grains-screen-permissions.sql, gto-reports.sql, +-- menu-reorganisation.sql, registry-create-permissions.sql ...) is copied to CO. Later GTO rows: run this part again. +-- --------------------------------------------------------------------------------------------------------------------------- +INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) +SELECT 'CO', g.RESOURCE_KEY + FROM GRAINS_SCREEN_PERMISSIONS g + WHERE g.ROLECODE = 'GTO' + AND NOT EXISTS (SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS c WHERE c.ROLECODE = 'CO' AND c.RESOURCE_KEY = g.RESOURCE_KEY); + +COMMIT; + +-- Take a right away from CO by deleting its row, e.g.: +-- DELETE FROM GRAINS_SCREEN_PERMISSIONS WHERE ROLECODE = 'CO' AND RESOURCE_KEY = 'grains.permits.voiceCall'; diff --git a/deploy/prod/docker-compose.yml b/deploy/prod/docker-compose.yml index e825a32..5bd3efa 100644 --- a/deploy/prod/docker-compose.yml +++ b/deploy/prod/docker-compose.yml @@ -15,6 +15,7 @@ services: env_file: .env environment: ASPNETCORE_ENVIRONMENT: Production + TZ: Asia/Amman # permit expiry, blacklist and report times follow the Oracle server clock (Amman) ports: # change the left side (or set NTP_PORT in .env) when 8081 is taken; use 127.0.0.1: when the proxy runs on this host - "127.0.0.1:${NTP_PORT:-8081}:8080" diff --git a/deploy/qa/Dockerfile b/deploy/qa/Dockerfile index 69a300f..02f2a1d 100644 --- a/deploy/qa/Dockerfile +++ b/deploy/qa/Dockerfile @@ -21,6 +21,7 @@ WORKDIR /app COPY --from=api /app ./ COPY --from=web /web/dist ./wwwroot ENV ASPNETCORE_URLS=http://+:8080 \ - ASPNETCORE_FORWARDEDHEADERS_ENABLED=true + ASPNETCORE_FORWARDEDHEADERS_ENABLED=true \ + TZ=Asia/Amman EXPOSE 8080 ENTRYPOINT ["dotnet", "NTP.Api.dll"] diff --git a/deploy/qa/docker-compose.yml b/deploy/qa/docker-compose.yml index a4e81a2..837635a 100644 --- a/deploy/qa/docker-compose.yml +++ b/deploy/qa/docker-compose.yml @@ -11,5 +11,6 @@ services: env_file: .env environment: ASPNETCORE_ENVIRONMENT: QA + TZ: Asia/Amman ports: - "0.0.0.0:8081:8080" diff --git a/docs/ENVIRONMENTS.md b/docs/ENVIRONMENTS.md index 722f9fb..bcc5536 100644 --- a/docs/ENVIRONMENTS.md +++ b/docs/ENVIRONMENTS.md @@ -53,6 +53,7 @@ Apply these scripts once per database (not run by the application), in this orde 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) 5b. `db/gto-reports.sql` - GTO gets the ارسالية عطاء التموين and ملخص التوزيع reports (safe to re-run) +5c. `db/role-co.sql` - new role CO with the same rights as GTO: role row (NTP schema) + copy of every GTO row in GRAINS_SCREEN_PERMISSIONS (safe to re-run) 6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run) **Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU diff --git a/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs b/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs index ddda222..7323bcb 100644 --- a/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs +++ b/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs @@ -160,12 +160,12 @@ public sealed class PermitQueueController(IQueueService queue) : ControllerBase /// checkTrucks. [HttpPost("check-trucks")] - [RequirePermission(PermissionKeys.PermitsCreate)] + [Authorize(Roles = "SU")] public Task CheckTrucks([FromQuery] long tn, [FromQuery] long scac, CancellationToken ct) => queue.CheckTrucksAsync(tn, scac, ct); /// parseGrainsPermits job, on demand: create OPEN permits for the given companies. [HttpPost("seed")] - [RequirePermission(PermissionKeys.PermitsCreate)] + [Authorize(Roles = "SU")] public Task Seed(SeedPermitsRequest request, CancellationToken ct) => queue.SeedPermitsAsync(request, ct); // ---- TCS permit form (createPermit.cfm) @@ -237,11 +237,6 @@ public sealed class PermitDestinationsController(IDestinationService destination [RequirePermission(PermissionKeys.PermitsDestinations)] public Task> CompanyDestinations(long scac, CancellationToken ct) => destinations.GetCompanyDestinationsAsync(scac, ct); - [HttpPut("companies/{scac:long}")] - [RequirePermission(PermissionKeys.PermitsDestinations)] - public Task SaveCompanyDestinations(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct) => - destinations.SaveCompanyDestinationsAsync(scac, request, ct); - /// savegrainsdest (assginggdest.cfm). [HttpPost("assign-by-pn")] [RequirePermission(PermissionKeys.PermitsDestinations)] @@ -301,8 +296,9 @@ public sealed class PermitDistributionController(IDistributionService distributi [RequirePermission(PermissionKeys.PermitsDistribution)] public Task Distribute(DistributeRequest request, CancellationToken ct) => distribution.DistributeAsync(request, ct); + // not used by any screen: legacy released permits only inside the distribute loop, which also moves the queue counter [HttpPost("release")] - [RequirePermission(PermissionKeys.PermitsDistribution)] + [Authorize(Roles = "SU")] public Task Release(ReleasePermitRequest request, CancellationToken ct) => distribution.ReleaseAsync(request, ct); [HttpPost("process-open")] @@ -314,8 +310,9 @@ public sealed class PermitDistributionController(IDistributionService distributi public Task ProcessOpenWithDestination(OpenPermitWithDestinationRequest request, CancellationToken ct) => distribution.ProcessOpenPermitWithDestinationAsync(request, ct); + // legacy screen "فك دور الشركات": GNSU and SU only [HttpPost("process-company-open")] - [RequirePermission(PermissionKeys.PermitsTruckOrder)] + [Authorize(Roles = "SU,GNSU")] public Task ProcessCompanyOpen(CompanyOpenPermitsRequest request, CancellationToken ct) => distribution.ProcessCompanyOpenPermitsAsync(request, ct); @@ -340,7 +337,7 @@ public sealed class PermitDistributionController(IDistributionService distributi public Task> Blacklisted([FromQuery] string tn, CancellationToken ct) => distribution.GetBlacklistedAsync(tn, ct); [HttpPost("check-trips")] - [RequirePermission(PermissionKeys.PermitsDistribution)] + [Authorize(Roles = "SU")] public Task CheckTrips(CheckTripsRequest request, CancellationToken ct) => distribution.CheckTripsAsync(request, ct); /// RevokeAllREQST.cfm: send every REQST / PLND permit of an order id below the given limit back to OPEN. diff --git a/src/NTP.Api/appsettings.Production.json b/src/NTP.Api/appsettings.Production.json index edbca6c..94ae6e0 100644 --- a/src/NTP.Api/appsettings.Production.json +++ b/src/NTP.Api/appsettings.Production.json @@ -33,6 +33,11 @@ // الاتصال الصوتي button (ارساليات التموين): starts the IVR calls. The ?wsdl address is turned into a call of callAPI. "Permits": { + // truck ownership codes (MOT_TRUCKS.OWNERSHIPCODE) that may be added to company 327 (individuals) / to every other company; + // legacy application.GN_BadyahOwnership = 3,2 and GN_OthersOwnership = 1,2. Empty list = check skipped. + "BadiyaOwnershipCodes": [ "3", "2" ], + "OtherOwnershipCodes": [ "1", "2" ], + "AutoCall": { "Enabled": true, "IvrUrl": "http://aqtcs.nafith.net/IVR/callivr.cfc?wsdl" diff --git a/src/NTP.Application/Access/PermissionDefaults.cs b/src/NTP.Application/Access/PermissionDefaults.cs index c4660d4..409bcfe 100644 --- a/src/NTP.Application/Access/PermissionDefaults.cs +++ b/src/NTP.Application/Access/PermissionDefaults.cs @@ -82,34 +82,34 @@ public static class PermissionDefaults { public static readonly IReadOnlyDictionary RolesByResource = new Dictionary(StringComparer.OrdinalIgnoreCase) { - [PermissionKeys.PermitsList] = ["GTO", "GGO", "GOO", "GPO", "DISP"], // ارسالية عطاء التموين (DISP: own company only) - [PermissionKeys.RegistryTrucks] = ["GTO", "GOO", "GPO"], // شاشة القاطرات - [PermissionKeys.RegistryTrailers] = ["GTO", "GOO", "GPO"], // شاشة المقطورات - [PermissionKeys.RegistryDrivers] = ["GTO", "GOO", "GPO"], // شاشة السائقين المسجلين - [PermissionKeys.OrdersList] = ["GTO", "GOO"], // الطلبيات - [PermissionKeys.OrdersCreate] = ["GTO"], // طلبية جديدة (GOO was removed again; add a row per role to grant it) - [PermissionKeys.PermitsWeighbridge] = ["GTO", "GGO"], // شاشة القبان - [PermissionKeys.PermitsClose] = ["GTO", "GGO", "GOO", "GPO"], // اغلاق إرسالية - [PermissionKeys.PermitsTruckOrder] = ["GTO"], // طلبية لسيارة - [PermissionKeys.RegistryBlacklist] = ["GTO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار - [PermissionKeys.PermitsDistribution] = ["GTO", "GOO"], // طلبية التموين - [PermissionKeys.OrdersSupply] = ["GTO", "GOO"], // طلبية التموين (orders menu) - [PermissionKeys.PermitsTruckStatus] = ["GTO", "GOO"], // استعلام عن حالة التوزيع لسيارة - [PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية - [PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي - [PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف - [PermissionKeys.PermitsVoiceCall] = ["GTO"], // الاتصال الصوتي + [PermissionKeys.PermitsList] = ["GTO", "CO", "GGO", "GOO", "GPO", "DISP"], // ارسالية عطاء التموين (DISP: own company only) + [PermissionKeys.RegistryTrucks] = ["GTO", "CO", "GOO", "GPO"], // شاشة القاطرات + [PermissionKeys.RegistryTrailers] = ["GTO", "CO", "GOO", "GPO"], // شاشة المقطورات + [PermissionKeys.RegistryDrivers] = ["GTO", "CO", "GOO", "GPO"], // شاشة السائقين المسجلين + [PermissionKeys.OrdersList] = ["GTO", "CO", "GOO"], // الطلبيات + [PermissionKeys.OrdersCreate] = ["GTO", "CO"], // طلبية جديدة (GOO was removed again; add a row per role to grant it) + [PermissionKeys.PermitsWeighbridge] = ["GTO", "CO", "GGO"], // شاشة القبان + [PermissionKeys.PermitsClose] = ["GTO", "CO", "GGO", "GOO", "GPO"], // اغلاق إرسالية + [PermissionKeys.PermitsTruckOrder] = ["GTO", "CO"], // طلبية لسيارة + [PermissionKeys.RegistryBlacklist] = ["GTO", "CO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار + [PermissionKeys.PermitsDistribution] = ["GTO", "CO", "GOO"], // طلبية التموين + [PermissionKeys.OrdersSupply] = ["GTO", "CO", "GOO"], // طلبية التموين (orders menu) + [PermissionKeys.PermitsTruckStatus] = ["GTO", "CO", "GOO"], // استعلام عن حالة التوزيع لسيارة + [PermissionKeys.PermitsActivation] = ["GTO", "CO"], // شاشة تفعيل الطلبية + [PermissionKeys.PermitsManualEntry] = ["GTO", "CO"], // شاشة الادخال اليدوي + [PermissionKeys.PermitsAbsence] = ["GTO", "CO"], // إيقاف\تفعيل الاستنكاف + [PermissionKeys.PermitsVoiceCall] = ["GTO", "CO"], // الاتصال الصوتي [PermissionKeys.OrdersInvoiceCheck] = ["GNAC"], // التأكد من الفواتير [PermissionKeys.OrdersFines] = ["GNAC"], // الغرامات [PermissionKeys.OrdersWages] = ["GNAC"], // الأجور - [PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل - [PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ - [PermissionKeys.ReportTable("companies-turn")] = ["GTO", "GOO"], // تقرير دور الشركات - [PermissionKeys.ReportTable("owners-turn")] = ["GTO"], // تقرير دور الأفراد - [PermissionKeys.ReportTable("loading-weights")] = ["GTO"], // تقرير أوزان التحميل - [PermissionKeys.ReportTable("closed-permits")] = ["GTO"], // الارساليات المكتملة - [PermissionKeys.ReportTable("tender-order")] = ["GTO"], // ارسالية عطاء التموين - [PermissionKeys.ReportTable("distribution-summary")] = ["GTO"], // ملخص التوزيع + [PermissionKeys.OrdersWeights] = ["GTO", "CO"], // تثبيت أوزان التحميل + [PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "CO", "GOO"], // تقارير حركات قبان التحميل والتفريغ + [PermissionKeys.ReportTable("companies-turn")] = ["GTO", "CO", "GOO"], // تقرير دور الشركات + [PermissionKeys.ReportTable("owners-turn")] = ["GTO", "CO"], // تقرير دور الأفراد + [PermissionKeys.ReportTable("loading-weights")] = ["GTO", "CO"], // تقرير أوزان التحميل + [PermissionKeys.ReportTable("closed-permits")] = ["GTO", "CO"], // الارساليات المكتملة + [PermissionKeys.ReportTable("tender-order")] = ["GTO", "CO"], // ارسالية عطاء التموين + [PermissionKeys.ReportTable("distribution-summary")] = ["GTO", "CO"], // ملخص التوزيع [PermissionKeys.OrdersCompanyDest] = ["GOO"], // وجهات الشركات [PermissionKeys.PermitsDestinations] = ["GOO"], // تحديد وجهة ارسالية تموين }; diff --git a/src/NTP.Application/Auth/AuthService.cs b/src/NTP.Application/Auth/AuthService.cs index fc931f6..73e08b9 100644 --- a/src/NTP.Application/Auth/AuthService.cs +++ b/src/NTP.Application/Auth/AuthService.cs @@ -98,6 +98,9 @@ public sealed class AuthService( Lang: "AR", IsStaff: profile.CompanyId == StaffCompanyId); + // the company-queue cursor of the distribution screen lived in the session: a new sign-in starts from 1 again + NTP.Application.Grains.Permits.DistributionCursor.Reset(user.UserId); + // Logging (addlog 1) - legacy swallows logging errors. await TryAsync(() => repository.InsertLogAsync( new AuditLogEntry(user.UserId, client.IpAddress, user.RoleCode, LogSignIn, user.Name, client.UserAgent), ct)); diff --git a/src/NTP.Application/Grains/Permits/DestinationService.cs b/src/NTP.Application/Grains/Permits/DestinationService.cs index 5c56f7d..20d7524 100644 --- a/src/NTP.Application/Grains/Permits/DestinationService.cs +++ b/src/NTP.Application/Grains/Permits/DestinationService.cs @@ -15,7 +15,6 @@ public interface IDestinationService Task GetLocationGroupsAsync(CancellationToken ct = default); Task> GetCompaniesAsync(CancellationToken ct = default); Task> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default); - Task SaveCompanyDestinationsAsync(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct = default); Task AssignByPnAsync(AssignByPnRequest request, CancellationToken ct = default); Task> GetOrderDatesAsync(CancellationToken ct = default); @@ -53,18 +52,6 @@ public sealed class DestinationService( public Task> GetCompaniesAsync(CancellationToken ct = default) => repo.GetCompaniesAsync(ct); public Task> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default) => repo.GetCompanyLocationsAsync(scac, ct); - public async Task SaveCompanyDestinationsAsync(long scac, SaveCompanyDestinationsRequest r, CancellationToken ct = default) - { - if (scac == options.BadiyaScac) - throw new BusinessException("COMPANY_NOT_ALLOWED", "لا يمكن تحديد وجهات للأفراد من هذه الشاشة"); - await uow.ExecuteInTransactionAsync(async token => - { - await repo.ReplaceCompanyLocationsAsync(scac, r.Destinations.Distinct().ToList(), user.UserId, token); - return true; - }, ct); - return PermitOperationResult.Ok(PermitOperationResult.DefaultOk); - } - public async Task AssignByPnAsync(AssignByPnRequest r, CancellationToken ct = default) { new AssignByPnValidator().ValidateAndThrow(r); diff --git a/src/NTP.Application/Grains/Permits/DistributionService.cs b/src/NTP.Application/Grains/Permits/DistributionService.cs index e119ddc..ffa7331 100644 --- a/src/NTP.Application/Grains/Permits/DistributionService.cs +++ b/src/NTP.Application/Grains/Permits/DistributionService.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.Globalization; +using System.Security.Cryptography; using System.Text; using FluentValidation; using NTP.Application.Abstractions; @@ -35,16 +36,20 @@ public interface IDistributionService } /// Per-user position in the company queue between two "distribute companies" runs (legacy session.QueueStart). -internal static class DistributionCursor +public static class DistributionCursor { private static readonly ConcurrentDictionary Positions = new(StringComparer.OrdinalIgnoreCase); public static long Get(string user) => Positions.GetValueOrDefault(user, 1); public static void Set(string user, long value) => Positions[user] = value; + + /// Legacy kept it in the session, so every new sign-in starts again from 1. + public static void Reset(string user) => Positions.TryRemove(user, out _); } public sealed class DistributionService( IDistributionRepository repo, IDestinationRepository destinations, + IDestinationService destinationLookup, IPermitRepository permits, IPhoneEventRepository phoneRepo, IPermitService permitService, @@ -59,6 +64,8 @@ public sealed class DistributionService( // ------------------------------------------------------------------------------------------------ distributePackedBulk + private static BusinessException StateChanged() => new("PERMIT_BAD_STATE", "حالة الارسالية غير صحيحة"); + private sealed record ReleaseOutcome(string ErrorMsg, long? Scac = null, string? CargoLabel = null); public async Task DistributeAsync(DistributeRequest r, CancellationToken ct = default) @@ -137,12 +144,18 @@ public sealed class DistributionService( return true; }, ct); - await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS", new Dictionary { ["NOTIFICATIONARY"] = ownerNotes }, ct); - await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_COMP", companyNotes, ct); - + // the queue position is saved first: the distribution is already committed, so nothing after this may undo it if (cat.Request is "BULK_COMP" or "BULK_GALLAB_COMP") DistributionCursor.Set(user.UserId, companyCounter == 0 ? start + queueAvailable : 1); + // notifications are fire-and-forget (legacy ran them in a thread inside try/catch): a failure never fails the run + try + { + await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS", new Dictionary { ["NOTIFICATIONARY"] = ownerNotes }, ct); + await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_COMP", companyNotes, ct); + } + catch (Exception) when (!ct.IsCancellationRequested) { /* already logged by the gateway */ } + return PermitOperationResult.Ok($"تم توزيع {companyCounter} شركات - {ownerCounter} أفراد ، من أصل{queueAvailable}", data: new Dictionary { ["companies"] = companyCounter, ["owners"] = ownerCounter, ["available"] = queueAvailable }); } @@ -176,7 +189,7 @@ public sealed class DistributionService( return new("noDist"); } - await repo.SetRequestedWithOrderAsync(permit.Id, order.Id, ct); + if (await repo.SetRequestedWithOrderAsync(permit.Id, order.Id, ct) == 0) return new("INVALID PERMITID"); // no longer OPEN (another run took it) var d = await destinations.GetOrderDetailsAsync(order.Id, ct); await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, $"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: ct); @@ -218,14 +231,14 @@ public sealed class DistributionService( } if (orderId == 0) throw new BusinessException("NO_ORDERS_AVAILABLE", "لا توجد طلبيات متاحة"); - await repo.SetRequestedWithOrderAsync(permit.Id, orderId, token); + if (await repo.SetRequestedWithOrderAsync(permit.Id, orderId, token) == 0) throw StateChanged(); var d = await destinations.GetOrderDetailsAsync(orderId, token); await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, $"تحميل: {d?.Location} / {d?.CargoType}", ct: token); } else { - await repo.SetRequestedAsync(permit.Id, token); + if (await repo.SetRequestedAsync(permit.Id, token) == 0) throw StateChanged(); await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token); } return true; @@ -240,6 +253,11 @@ public sealed class DistributionService( if (permit.ShipmentStatusCode != PermitStatus.Open) throw new BusinessException("PERMIT_BAD_STATE", "حالة الارسالية غير صحيحة"); + // legacy offered only getAllowedDestinationsByDate(pn, date) in a dropdown; the server now enforces the same list + var allowed = await destinationLookup.GetAllowedDestinationsAsync(r.Pn, r.OrderDate, ct); + if (!allowed.Any(a => a.OrderId == r.Locations)) + throw new BusinessException("ORDER_NOT_ALLOWED", "الوجهة المختارة غير مسموحة لهذه الارسالية في هذا التاريخ"); + var order = await repo.GetOrderForManualAsync(r.Locations, ct) ?? throw new NotFoundException("Order", r.Locations); var d = await destinations.GetOrderDetailsAsync(r.Locations, ct); var orderDate = PermitDates.ParseLegacy(r.OrderDate) ?? DateTime.Today; @@ -255,7 +273,7 @@ public sealed class DistributionService( if (order.Ct == GrainsCargo.BulkGallab && scac != options.BadiyaScac) await repo.IncrementCompanyQueueAsync(scac, "GALLAB", "COMP", token); - await repo.SetRequestedManualAsync(permit.Id, r.Locations, queueId, token); + if (await repo.SetRequestedManualAsync(permit.Id, r.Locations, queueId, token) == 0) throw StateChanged(); await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, $"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: token); @@ -294,14 +312,15 @@ public sealed class DistributionService( if (await repo.IsLocationAllowedForCompanyAsync(p.CompanyCode ?? 0, order.Destenation, ct)) { - await uow.ExecuteInTransactionAsync(async token => + var changed = await uow.ExecuteInTransactionAsync(async token => { - await repo.SetRequestedWithOrderAsync(p.Id, order.Id, token); + if (await repo.SetRequestedWithOrderAsync(p.Id, order.Id, token) == 0) return false; // taken meanwhile var d = await destinations.GetOrderDetailsAsync(order.Id, token); await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, $"تحميل: {d?.Location} / {d?.CargoType}", ct: token); return true; }, ct); + if (!changed) continue; done++; if (done >= r.Count) break; } @@ -320,7 +339,7 @@ public sealed class DistributionService( ?? throw new BusinessException("TN_INVALID", "TN is invalid"); await uow.ExecuteInTransactionAsync(async token => { - await repo.SetRequestedAsync(permit.Id, token); + if (await repo.SetRequestedAsync(permit.Id, token) == 0) throw StateChanged(); await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token); return true; }, ct); @@ -430,6 +449,7 @@ public sealed class DistributionService( public async Task SendAutoCallFileAsync(AutoCallRequest r, CancellationToken ct = default) { // staff choose the company, company users are limited to their own (GrainsFactoryWeb.autoCallService2) + if (user.IsCompany(options) && user.CompanyCodeNo() is null) throw new ForbiddenException("FORBIDDEN", "غير مصرح لك بهذه العملية"); var company = user.IsCompany(options) ? user.CompanyCodeNo()?.ToString(CultureInfo.InvariantCulture) : r.CompanyCode; var filter = r with { CompanyCode = company }; var tender = PermitService.ParseTenderOrder(r.TenderOrder); @@ -441,10 +461,13 @@ public sealed class DistributionService( : PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي"); } - public async Task TriggerIvrAsync(CancellationToken ct = default) => - await autoCall.TriggerIvrAsync(ct) - ? PermitOperationResult.Ok(PermitOperationResult.DefaultOk) - : PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي"); + public async Task TriggerIvrAsync(CancellationToken ct = default) => await autoCall.TriggerIvrAsync(ct) switch + { + IvrTriggerResult.Done => PermitOperationResult.Ok(PermitOperationResult.DefaultOk), + IvrTriggerResult.Started => PermitOperationResult.Ok("بدأ الاتصال الصوتي وقد تستغرق العملية عدة دقائق"), + IvrTriggerResult.Busy => PermitOperationResult.Fail("IVR_RUNNING", "الاتصال الصوتي قيد التنفيذ حاليا، يرجى الانتظار حتى ينتهي"), + _ => PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي") + }; /// writeCallingDriverFile: CSV consumed by the auto dialer. internal static byte[] BuildCallingFile(IReadOnlyList rows) @@ -465,8 +488,13 @@ public sealed class DistributionService( return new UTF8Encoding(false).GetBytes(sb.ToString()); } - public bool IsValidDialerApiKey(string? key) => - !string.IsNullOrEmpty(options.AutoCall.ApiKey) && string.Equals(key, options.AutoCall.ApiKey, StringComparison.Ordinal); + public bool IsValidDialerApiKey(string? key) + { + var expected = options.AutoCall.ApiKey; + if (string.IsNullOrEmpty(expected) || string.IsNullOrEmpty(key)) return false; + // constant time: compare fixed-length hashes + return CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(key)), SHA256.HashData(Encoding.UTF8.GetBytes(expected))); + } /// autoCallResponse.cfc autoDail: CONFIRMED -> phone accept, POSTPONED -> phone reject for N days, NO_ANSWER -> postpone one day. public async Task HandleDialerCallbackAsync(AutoCallResponse r, CancellationToken ct = default) @@ -485,12 +513,15 @@ public sealed class DistributionService( break; case "POSTPONED": { - if (!int.TryParse(r.Value, out var days) || days <= 0) return new("500", "invalid value"); + // the manual reject offers 1..30 days; anything larger is a dialer error (and AddDays would overflow) + if (!int.TryParse(r.Value, out var days) || days <= 0 || days > MaxPostponeDays) return new("500", "invalid value"); await permitService.PhoneRejectCoreAsync(permitId.Value, $" تم التأجيل {days} يوم", days, "SYSTEM", ct); break; } case "NO_ANSWER": { + // a late callback must not reopen a permit that has moved on (confirmed, closed ...) + if (permit is null || permit.ShipmentStatusCode != PermitStatus.Requested) return new("200", "IGNORED_STATUS"); if (await phoneRepo.HasPhoneEventTodayAsync(permitId.Value, ct)) return new("200", "ALREADY_HAS_PHONE_EVENT"); await NoAnswerAsync(permit!, ct); return new("200", "NO_ANSWER"); @@ -504,6 +535,8 @@ public sealed class DistributionService( } } + private const int MaxPostponeDays = 30; + private async Task NoAnswerAsync(PermitRow permit, CancellationToken ct) { var order = permit.Scrn is long o ? await destinations.GetOrderAsync(o, ct) : null; @@ -512,7 +545,7 @@ public sealed class DistributionService( { await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.NoAnswer, "تم التأجيل ليوم واحد", ct: token); - await permits.ResetToOpenAsync(permit.Id, "SYSTEM", token); + await permits.ReopenClearingOrderAsync(permit.Id, token); // legacy: status + SCRN only (trackingno and audit columns stay) await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, PermitStatus.Open, PermitEventType.Override, ct: token); await phoneRepo.InsertBlacklistAsync(new NewBlacklistEntry { diff --git a/src/NTP.Application/Grains/Permits/GrainsPermitsOptions.cs b/src/NTP.Application/Grains/Permits/GrainsPermitsOptions.cs index edf3d00..10ddea8 100644 --- a/src/NTP.Application/Grains/Permits/GrainsPermitsOptions.cs +++ b/src/NTP.Application/Grains/Permits/GrainsPermitsOptions.cs @@ -77,6 +77,12 @@ public sealed class AutoCallOptions public string ApiKey { get; set; } = string.Empty; public int TimeoutSeconds { get; set; } = 30; + + /// How long the voice-call button waits for the IVR service before it reports "started" (the service answers only when it has dialed everybody). + public int IvrWaitSeconds { get; set; } = 20; + + /// Longest time one IVR call may keep running in the background before it is abandoned. + public int IvrTimeoutMinutes { get; set; } = 15; } /// Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage). diff --git a/src/NTP.Application/Grains/Permits/IDistributionRepository.cs b/src/NTP.Application/Grains/Permits/IDistributionRepository.cs index 66acffe..44e7afd 100644 --- a/src/NTP.Application/Grains/Permits/IDistributionRepository.cs +++ b/src/NTP.Application/Grains/Permits/IDistributionRepository.cs @@ -75,7 +75,7 @@ public interface IDistributionRepository Task GetOpenPermitWithFirmsAsync(string pn, long scac, CancellationToken ct = default); Task> GetAllowedLocationsForReleaseAsync(PermitRow permit, long scac, long badiyaScac, CancellationToken ct = default); Task GetNextOrderAsync(IReadOnlyList locations, string cargoCode, string? queueType, CancellationToken ct = default); - Task SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default); + Task SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default); Task UpdateLastPermitAsync(long orderId, long badiyaScac, CancellationToken ct = default); Task SetLastPermitAsync(long orderId, long permitId, CancellationToken ct = default); Task DeletePendingDistributionAsync(long permitId, string tn, long? orderId, CancellationToken ct = default); @@ -86,10 +86,10 @@ public interface IDistributionRepository Task GetFirstOpenPermitByTnAsync(string tn, string? cargoType, CancellationToken ct = default); Task> GetNextOrdersForTruckAsync(string tn, CancellationToken ct = default); Task IsLocationAllowedForCompanyAsync(long scac, long location, CancellationToken ct = default); - Task SetRequestedAsync(long permitId, CancellationToken ct = default); + Task SetRequestedAsync(long permitId, CancellationToken ct = default); Task GetOrderForManualAsync(long orderId, CancellationToken ct = default); Task PickQueueIdAsync(long scac, string code, string? type, CancellationToken ct = default); - Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default); + Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default); Task> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default); Task GetAnyNextOrderAsync(CancellationToken ct = default); diff --git a/src/NTP.Application/Grains/Permits/IPermitRepository.cs b/src/NTP.Application/Grains/Permits/IPermitRepository.cs index 5c5c5fd..9bdca78 100644 --- a/src/NTP.Application/Grains/Permits/IPermitRepository.cs +++ b/src/NTP.Application/Grains/Permits/IPermitRepository.cs @@ -96,6 +96,9 @@ public interface IPermitRepository Task SetStatusAsync(long id, string newStatus, string userId, CancellationToken ct = default); Task ResetTruckValidationAsync(string tn, string userId, CancellationToken ct = default); Task ResetToOpenAsync(long id, string userId, CancellationToken ct = default); + + /// NO_ANSWER of the dialer (autoCallResponse.cfc): only the status goes back to OPEN and the order link (SCRN) is cleared; nothing else changes. + Task ReopenClearingOrderAsync(long id, CancellationToken ct = default); Task RevokeNextOpenPermitsAsync(long permitId, string userId, CancellationToken ct = default); Task FindOpenConflictForReactivationAsync(PermitRow permit, CancellationToken ct = default); Task FindClosablePermitAsync(string pn, CancellationToken ct = default); diff --git a/src/NTP.Application/Grains/Permits/PermitService.cs b/src/NTP.Application/Grains/Permits/PermitService.cs index 5fbfe7c..ff0340c 100644 --- a/src/NTP.Application/Grains/Permits/PermitService.cs +++ b/src/NTP.Application/Grains/Permits/PermitService.cs @@ -203,8 +203,8 @@ public sealed class PermitService( var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); - // legacy: an order already ACCPT / RESD cannot be submitted again. - if (permit.ShipmentStatusCode is PermitStatus.Released or PermitStatus.Accepted) + // only a requested turn is submitted (legacy: the button exists for REQST only); through the API any other status used to pass + if (permit.ShipmentStatusCode != PermitStatus.Requested) throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus); await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: true, ct); @@ -294,6 +294,7 @@ public sealed class PermitService( public async Task AcceptAsync(long id, CancellationToken ct = default) { + EnsureStaff(); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); if (permit.ShipmentStatusCode != PermitStatus.Planned) @@ -331,6 +332,7 @@ public sealed class PermitService( public async Task RevokeAsync(long id, CancellationToken ct = default) { + EnsureStaff(); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); if (permit.ShipmentStatusCode != PermitStatus.Planned) @@ -348,6 +350,7 @@ public sealed class PermitService( public async Task RevokeAcceptedAsync(long id, CancellationToken ct = default) { + EnsureStaff(); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); if (permit.ShipmentStatusCode is not (PermitStatus.Accepted or PermitStatus.Released)) @@ -383,6 +386,7 @@ public sealed class PermitService( public async Task CancelOrderAsync(long id, ReasonRequest r, CancellationToken ct = default) { + EnsureOperator(); new ReasonValidator().ValidateAndThrow(r); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); // Deviation: the legacy button exists for RESD only (action 106) but the CFC had no check. @@ -402,6 +406,7 @@ public sealed class PermitService( public async Task RevokePermitAsync(long id, ReasonRequest r, CancellationToken ct = default) { + EnsureOperator(); new ReasonValidator().ValidateAndThrow(r); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); // Deviation: legacy button exists for OPEN only (action 167); enforced here. @@ -419,7 +424,10 @@ public sealed class PermitService( public async Task ReactivateAsync(long id, CancellationToken ct = default) { + // legacy: only the reactivation login, and only for the Badiya company permits (the button is hidden otherwise) + if (user.IsCompany(options) || !user.IsInAnyRole("SU", "GTO", "CO")) throw NotAllowed(); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + if (permit.CompanyCode != options.BadiyaScac) throw NotAllowed(); if (permit.ShipmentStatusCode != PermitStatus.Revoked) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); @@ -439,6 +447,7 @@ public sealed class PermitService( public async Task CancelGrainsPermitAsync(long id, CancellationToken ct = default) { + EnsureOperator(); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); if (permit.ShipmentStatusCode != PermitStatus.Released) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); @@ -470,11 +479,15 @@ public sealed class PermitService( // ------------------------------------------------------------------------------------------------ phone events - public Task PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default) => - PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct); + public Task PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default) + { + EnsureOperator(); // the dialer callback uses PhoneAcceptCoreAsync directly, not this entry point + return PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct); + } public Task PhoneRejectAsync(long id, PhoneRejectRequest r, CancellationToken ct = default) { + EnsureOperator(); new PhoneRejectValidator().ValidateAndThrow(r); return PhoneRejectCoreAsync(id, r.Reason.Trim(), r.ExpiryDays, user.UserId, ct); } @@ -625,11 +638,26 @@ public sealed class PermitService( private IReadOnlyList ActionsFor(string? status, long? companyCode) => PermitActionRules.For(status, companyCode, user.IsCompany(options), user.IsInAnyRole(GrainsRoles.Operators.Split(',')), - user.IsInAnyRole(GrainsRoles.ConvertToResd.Split(',')), user.IsInAnyRole("SU", "GTO"), options.BadiyaScac); + user.IsInAnyRole(GrainsRoles.ConvertToResd.Split(',')), user.IsInAnyRole("SU", "GTO", "CO"), options.BadiyaScac); + + private static ForbiddenException NotAllowed() => new("FORBIDDEN", "غير مصرح لك بهذه العملية"); + + /// Staff-only actions (phone confirmation, cancel / revoke): back-office operators, never a company user or dispatcher. + private void EnsureOperator() + { + if (user.IsCompany(options) || !user.IsInAnyRole(GrainsRoles.Operators.Split(','))) throw NotAllowed(); + } + + /// Confirming a turn (accept / reject / cancel the confirmation) is back-office work: legacy actions 74, 85, 88 are not held by company dispatchers. + private void EnsureStaff() + { + if (user.IsCompany(options)) throw NotAllowed(); + } private void EnsureCompanyAccess(long? permitCompany) { - if (user.IsCompany(options) && permitCompany != user.CompanyCodeNo()) + // a company user without a company code owns nothing (null == null must not pass) + if (user.IsCompany(options) && (user.CompanyCodeNo() is not long mine || permitCompany != mine)) throw new ForbiddenException("PERMIT_FOREIGN_COMPANY", "لا تملك صلاحية على هذه الإرسالية"); } diff --git a/src/NTP.Application/Grains/Permits/PermitSupport.cs b/src/NTP.Application/Grains/Permits/PermitSupport.cs index 9d3f4c1..7196f00 100644 --- a/src/NTP.Application/Grains/Permits/PermitSupport.cs +++ b/src/NTP.Application/Grains/Permits/PermitSupport.cs @@ -11,16 +11,16 @@ namespace NTP.Application.Grains.Permits; public static class GrainsRoles { /// Back-office operators: distribution, phone confirmation, manual operations, queue creation. - public const string Operators = "SU,GPO,GNSU,GNCO,GTO"; + public const string Operators = "SU,GPO,GNSU,GNCO,GTO,CO"; /// Weighbridge / gate users plus operators. - public const string Weighbridge = "SU,GPO,GNSU,GNCO,GTO,GATEIN,GATEOUT,THRU"; + public const string Weighbridge = "SU,GPO,GNSU,GNCO,GTO,CO,GATEIN,GATEOUT,THRU"; /// ConvertToResd button: legacy checks role SU or GPO only. public const string ConvertToResd = "SU,GPO"; /// Supervisors: configuration of destinations, activation of orders, absence feature. - public const string Supervisors = "SU,GPO,GNSU,GTO"; + public const string Supervisors = "SU,GPO,GNSU,GTO,CO"; } /// Helpers that replace legacy session.* lookups. @@ -100,8 +100,10 @@ public static class PermitActionRules if (isCompany) { - // Company users never see the staff-only phone / cancel / revoke / reactivate buttons. - a.RemoveAll(x => x is PhoneAccept or PhoneReject or CancelOrder or RevokePermit or Reactivate or ConvertToResd); + // Company users never see the staff-only buttons. Confirming (accept / reject / cancel the confirmation) is staff work in + // legacy too: actions 74, 85 and 88 belong to the staff groups, the company dispatcher group DISP only holds submit (73). + a.RemoveAll(x => x is PhoneAccept or PhoneReject or CancelOrder or RevokePermit or Reactivate or ConvertToResd + or Accept or Reject or RevokeAccepted); } return a; } @@ -145,8 +147,21 @@ public interface IAutoCallGatewayService /// POSTs {"TYPE":"TEST","FILE":base64} to the configured dialer URL; false when not reachable / not 200. Task SendCallFileAsync(byte[] csv, CancellationToken ct = default); - /// Calls the IVR web service (callAPI). - Task TriggerIvrAsync(CancellationToken ct = default); + /// Calls the IVR web service (callAPI). That call dials every requested truck one by one and can take minutes. + Task TriggerIvrAsync(CancellationToken ct = default); +} + +/// Outcome of . +public enum IvrTriggerResult +{ + /// The IVR service answered OK. + Done, + /// The IVR service accepted the call and is still dialing (it answers when it has finished). + Started, + /// A previous call is still running: a second one would dial every truck twice. + Busy, + /// Disabled, not configured, unreachable or refused. + Failed } /// Reads new rows from the external weighbridge database (legacy datasource GrainsWeighbridge). diff --git a/src/NTP.Application/Grains/Registry/BlacklistService.cs b/src/NTP.Application/Grains/Registry/BlacklistService.cs index 8676d50..9260ab8 100644 --- a/src/NTP.Application/Grains/Registry/BlacklistService.cs +++ b/src/NTP.Application/Grains/Registry/BlacklistService.cs @@ -21,7 +21,7 @@ public sealed class BlacklistService( IUnitOfWork unitOfWork, ICurrentUser user) : IBlacklistService { - private static readonly string[] CancelRoles = ["GNSU", "GNCO", "GTO"]; + private static readonly string[] CancelRoles = ["GNSU", "GNCO", "GTO", "CO"]; public async Task> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct) { diff --git a/src/NTP.Application/Grains/Registry/RegistryAccessService.cs b/src/NTP.Application/Grains/Registry/RegistryAccessService.cs index 5d1900a..07720bd 100644 --- a/src/NTP.Application/Grains/Registry/RegistryAccessService.cs +++ b/src/NTP.Application/Grains/Registry/RegistryAccessService.cs @@ -61,7 +61,7 @@ public sealed class RegistryAccessService( public void EnsureCompanyAccess(long? recordTcscac) { - if (IsCompanyUser && recordTcscac != CompanyCodeNo) + if (IsCompanyUser && (CompanyCodeNo is null || recordTcscac != CompanyCodeNo)) throw new NotFoundException("Registry record", "-"); } @@ -87,9 +87,9 @@ public sealed class RegistryAccessService( CanAcceptTrailer = await HasActionAsync(RegistryActions.AcceptTrailer, ct), CanAcceptDriver = await HasActionAsync(RegistryActions.AcceptDriver, ct), CanManageDestinations = await HasActionAsync(RegistryActions.Destinations, ct), - CanExportTruckReport = user.IsInAnyRole("GTO", "GOO", "GNAC"), - CanExportDriverReport = user.IsInAnyRole("GTO", "GOO"), - CanCancelBlacklist = user.IsInAnyRole("GNSU", "GNCO", "GTO") + CanExportTruckReport = user.IsInAnyRole("GTO", "CO", "GOO", "GNAC"), + CanExportDriverReport = user.IsInAnyRole("GTO", "CO", "GOO"), + CanCancelBlacklist = user.IsInAnyRole("GNSU", "GNCO", "GTO", "CO") }; } } diff --git a/src/NTP.Application/Grains/Registry/RegistryAttachmentService.cs b/src/NTP.Application/Grains/Registry/RegistryAttachmentService.cs index 4b81e37..5d3385a 100644 --- a/src/NTP.Application/Grains/Registry/RegistryAttachmentService.cs +++ b/src/NTP.Application/Grains/Registry/RegistryAttachmentService.cs @@ -15,8 +15,23 @@ public interface IRegistryAttachmentService } public sealed class RegistryAttachmentService( - IRegistryRepository repository, IRegistryFileStoreService store, IRegistrySettingsService settings) : IRegistryAttachmentService + IRegistryRepository repository, IRegistryFileStoreService store, IRegistrySettingsService settings, IRegistryAccessService access) + : IRegistryAttachmentService { + /// GRAINS_FILES.ORIGINALNAME is VARCHAR2(100). + public const int OriginalNameMaxBytes = 100; + + /// Shortens a file name to the column size (UTF-8 bytes), keeping the extension. + public static string FitOriginalName(string name) + { + name = name.Trim(); + if (System.Text.Encoding.UTF8.GetByteCount(name) <= OriginalNameMaxBytes) return name; + var ext = Path.GetExtension(name); + var stem = name[..^ext.Length]; + while (stem.Length > 0 && System.Text.Encoding.UTF8.GetByteCount(stem + ext) > OriginalNameMaxBytes) stem = stem[..^1]; + return stem + ext; + } + public const string KindTruck = "truck"; public const string KindTrailer = "trailer"; public const string KindDriver = "driver"; @@ -59,7 +74,7 @@ public sealed class RegistryAttachmentService( ?? throw new BusinessException(RegistryErrors.AttachmentMissing, RegistryMessages.AttachmentsIncomplete); var ext = Path.GetExtension(original); var stored = $"{Guid.NewGuid():N}{ext.ToLowerInvariant()}"; - await repository.InsertFileAsync(type, entityId, original, stored, ct); + await repository.InsertFileAsync(type, entityId, FitOriginalName(original), stored, ct); await store.PromoteAsync(id, folder, stored, ct); } } @@ -76,6 +91,14 @@ public sealed class RegistryAttachmentService( var (type, folder) = Map(kind); // The name must be a registered file of this type (also keeps path traversal out). var row = await repository.FindFileAsync(type, fileName, ct) ?? throw new NotFoundException("Attachment", fileName); + // a company user may only read the files of its own trucks / trailers / drivers + long? owner = kind.ToLowerInvariant() switch + { + KindTruck => (await repository.GetTruckAsync(row.EntityId, ct))?.Tcscac, + KindTrailer => (await repository.GetTrailerAsync(row.EntityId, ct))?.Tcscac, + _ => (await repository.GetDriverAsync(row.EntityId, ct))?.Tcscac + }; + access.EnsureCompanyAccess(owner); var stream = await store.OpenAsync(folder, row.FileName, ct) ?? throw new NotFoundException("Attachment", fileName); return new RegistryDownload(stream, ContentTypeOf(row.FileName), string.IsNullOrWhiteSpace(row.OriginalName) ? row.FileName : row.OriginalName); } diff --git a/src/NTP.Application/Grains/Registry/RegistryRules.cs b/src/NTP.Application/Grains/Registry/RegistryRules.cs index c683939..d0c62ac 100644 --- a/src/NTP.Application/Grains/Registry/RegistryRules.cs +++ b/src/NTP.Application/Grains/Registry/RegistryRules.cs @@ -182,9 +182,36 @@ public static class RegistryRules public static DateTime BlacklistExpiry(DateTime now, int days, int shiftStartHour, int shiftEndHour) => now.AddHours(-(24 + shiftStartHour)).Date.AddDays(days).AddHours(shiftEndHour); - /// Remarks text stored with the entry (legacy appends the automatic release date, mm/dd/yyyy HH:mm). - public static string BlacklistRemarks(string? remarks, DateTime expiry) => - $"{remarks}، سيتم فك الانتظار بشكل تلقائي بتاريخ {expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)}"; + /// GRAINSBLACKLIST.REMARKS is VARCHAR2(500): the limit is in bytes, and an Arabic letter takes two. + public const int BlacklistRemarksMaxBytes = 500; + + /// Cuts a text to at most UTF-8 bytes without splitting a character. + public static string FitBytes(string? text, int maxBytes) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + if (System.Text.Encoding.UTF8.GetByteCount(text) <= maxBytes) return text; + var sb = new System.Text.StringBuilder(); + var used = 0; + foreach (var rune in text.EnumerateRunes()) + { + var n = rune.Utf8SequenceLength; + if (used + n > maxBytes) break; + sb.Append(rune.ToString()); + used += n; + } + return sb.ToString(); + } + + /// + /// Remarks text stored with the entry (legacy appends the automatic release date, mm/dd/yyyy HH:mm). The typed text is shortened, + /// never the release-date suffix, so that the whole text fits the column. + /// + public static string BlacklistRemarks(string? remarks, DateTime expiry) + { + var suffix = $"، سيتم فك الانتظار بشكل تلقائي بتاريخ {expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)}"; + var room = Math.Max(0, BlacklistRemarksMaxBytes - System.Text.Encoding.UTF8.GetByteCount(suffix)); + return FitBytes(remarks, room) + suffix; + } /// Parses the legacy "start,end" application setting; falls back to the defaults. public static (int Start, int End) ParseShiftHours(string? setting, int defaultStart = 0, int defaultEnd = 24) diff --git a/src/NTP.Application/Grains/Registry/RegistryValidation.cs b/src/NTP.Application/Grains/Registry/RegistryValidation.cs index 9b40607..2e6c837 100644 --- a/src/NTP.Application/Grains/Registry/RegistryValidation.cs +++ b/src/NTP.Application/Grains/Registry/RegistryValidation.cs @@ -92,9 +92,9 @@ public static class RegistryValidation MaxLen(f, nameof(r.ChasesNumber), r.ChasesNumber, 20); MaxLen(f, nameof(r.OwnerName), r.OwnerName, 50); MaxLen(f, nameof(r.OwnerNnpn), r.OwnerNnpn, 20); - MaxLen(f, nameof(r.Color), r.Color, 30); - MaxLen(f, nameof(r.Model), r.Model, 30); - MaxLen(f, nameof(r.HeadType), r.HeadType, 30); + MaxLen(f, nameof(r.Color), r.Color, 20); + MaxLen(f, nameof(r.Model), r.Model, 20); + MaxLen(f, nameof(r.HeadType), r.HeadType, 20); MaxLen(f, nameof(r.PhoneNumber), r.PhoneNumber, 10); Digits(f, nameof(r.PhoneNumber), r.PhoneNumber, 10); return f; diff --git a/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs b/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs index 3668b40..5caa259 100644 --- a/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs +++ b/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs @@ -46,7 +46,7 @@ internal sealed class TcsPermitGatewayService(IGrainsPermitsSettingsService sett if (kids.Count < 3) return new(null, null, "خطأ في الاتصال
استجابة غير متوقعة"); return new(kids[0].Value.Trim(), kids[2].Value.Trim(), string.Empty); // PN, status; kids[1] = error codes (CheckWSError) } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout (TaskCanceledException) { logger.LogError(ex, "TCS createPermit failed"); return new(null, null, "خطأ في الاتصال
" + ex.Message); @@ -66,7 +66,7 @@ internal sealed class TcsPermitGatewayService(IGrainsPermitsSettingsService sett string V(IReadOnlyList l, int i) => i < l.Count ? l[i].Value.Trim() : string.Empty; return new(string.Empty, V(k, 0), V(k, 1), V(k, 2), V(k, 3), V(k, 6), V(d, 0), V(d, 1), V(d, 2), V(d, 4), V(d, 5), V(d, 6)); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout (TaskCanceledException) { logger.LogError(ex, "TCS getFopDetail failed"); return Empty("خطأ في الاتصال
" + ex.Message); @@ -134,7 +134,7 @@ internal sealed class MobileNotificationGatewayService(IGrainsPermitsSettingsSer using var res = await Http.PostAsync(o.Url, new StringContent(json, Encoding.UTF8, "application/json"), cts.Token); if (!res.IsSuccessStatusCode) logger.LogWarning("Notification {Template} -> {Status}", template, (int)res.StatusCode); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout (TaskCanceledException) { // legacy notifications were fire-and-forget; a failure never rolls back the business operation logger.LogWarning(ex, "Notification {Template} failed", template); @@ -160,37 +160,96 @@ internal sealed class AutoCallGatewayService(IGrainsPermitsSettingsService setti using var res = await Http.PostAsync(o.SendUrl, new StringContent(body, Encoding.UTF8, new MediaTypeHeaderValue("application/json")), cts.Token); return res.StatusCode == System.Net.HttpStatusCode.OK; } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout (TaskCanceledException) { logger.LogWarning(ex, "Auto call dialer unreachable"); return false; } } - public async Task TriggerIvrAsync(CancellationToken ct = default) + // The IVR call is a SOAP web service call that dials every requested truck before it answers, so it runs on its own client + // without the usual timeout, only one call may run at a time, and the screen is told "started" if the answer takes long. + private static readonly HttpClient IvrHttp = new() { Timeout = Timeout.InfiniteTimeSpan }; + private static string? _ivrNamespace; // targetNamespace of the IVR service, read once from its WSDL + private static int _ivrRunning; // 1 while a callAPI request is still being served + + public async Task TriggerIvrAsync(CancellationToken ct = default) { var o = settings.Value.AutoCall; - if (!o.Enabled || string.IsNullOrWhiteSpace(o.IvrUrl)) return false; + if (!o.Enabled || string.IsNullOrWhiteSpace(o.IvrUrl)) return IvrTriggerResult.Failed; + if (Interlocked.CompareExchange(ref _ivrRunning, 1, 0) != 0) return IvrTriggerResult.Busy; + + var handedOver = false; try { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); - cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds))); - // The legacy code called callAPI() of the web service described by "...callivr.cfc?wsdl". A GET of the ?wsdl address - // would only download the description (always 200, nothing called), so it is turned into the real call. - var url = o.IvrUrl.EndsWith("?wsdl", StringComparison.OrdinalIgnoreCase) - ? o.IvrUrl[..^"?wsdl".Length] + "?method=callAPI" - : o.IvrUrl; - using var res = await Http.GetAsync(url, cts.Token); - return res.IsSuccessStatusCode; + HttpRequestMessage req; + if (o.IvrUrl.EndsWith("?wsdl", StringComparison.OrdinalIgnoreCase)) + { + // legacy: createObject("webservice", "...callivr.cfc?wsdl").callAPI() -> SOAP 1.1 request to the CFC itself + var endpoint = o.IvrUrl[..^"?wsdl".Length]; + var ns = await IvrNamespaceAsync(o, ct); + var envelope = "" + + $""; + req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new StringContent(envelope, Encoding.UTF8, "text/xml") }; + req.Headers.TryAddWithoutValidation("SOAPAction", "\"\""); + } + else + { + req = new HttpRequestMessage(HttpMethod.Get, o.IvrUrl); + } + + var cancelAfter = new CancellationTokenSource(TimeSpan.FromMinutes(Math.Max(1, o.IvrTimeoutMinutes))); + var send = IvrHttp.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cancelAfter.Token); + var first = await Task.WhenAny(send, Task.Delay(TimeSpan.FromSeconds(Math.Max(3, o.IvrWaitSeconds)), CancellationToken.None)); + if (first == send) + { + try + { + using var res = await send; + if (!res.IsSuccessStatusCode) logger.LogWarning("IVR answered {Status}", (int)res.StatusCode); + return res.IsSuccessStatusCode ? IvrTriggerResult.Done : IvrTriggerResult.Failed; + } + finally { req.Dispose(); cancelAfter.Dispose(); } + } + + // still dialing: the call finishes in the background and releases the single-flight flag when it is over + handedOver = true; + _ = send.ContinueWith(t => + { + try + { + if (t.IsCompletedSuccessfully) { logger.LogInformation("IVR call finished with {Status}", (int)t.Result.StatusCode); t.Result.Dispose(); } + else logger.LogWarning(t.Exception?.GetBaseException(), "IVR call did not finish"); + } + finally { req.Dispose(); cancelAfter.Dispose(); Interlocked.Exchange(ref _ivrRunning, 0); } + }, TaskScheduler.Default); + return IvrTriggerResult.Started; } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (!ct.IsCancellationRequested) // includes timeouts (TaskCanceledException) { logger.LogWarning(ex, "IVR unreachable"); - return false; + return IvrTriggerResult.Failed; + } + finally + { + if (!handedOver) Interlocked.Exchange(ref _ivrRunning, 0); } } + + /// The service namespace is whatever its WSDL says (ColdFusion derives it from the folder); fetched once. + private async Task IvrNamespaceAsync(AutoCallOptions o, CancellationToken ct) + { + if (_ivrNamespace is { } known) return known; + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds))); + var wsdl = await Http.GetStringAsync(o.IvrUrl, cts.Token); + var m = System.Text.RegularExpressions.Regex.Match(wsdl, "targetNamespace\\s*=\\s*\"([^\"]+)\""); + if (!m.Success) throw new InvalidOperationException("The IVR WSDL has no targetNamespace"); + return _ivrNamespace = m.Groups[1].Value; + } } + /// /// External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO). The database engine of that datasource is not known /// (the connection is defined in the ColdFusion administrator, not in the repository), so no driver is bundled: this source reports diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DistributionRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DistributionRepository.cs index 903bffa..45a1590 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DistributionRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DistributionRepository.cs @@ -155,7 +155,8 @@ internal sealed class DistributionRepository(IDbSession session, ILogger x.Scac != badiyaScac)) p.Add("BlCategory", "DELAY_" + distributionCode); var sb = new StringBuilder("SELECT sp.id AS Id, cq.qid AS Qid, sp.scac AS Scac, TO_CHAR(sp.pn) AS Pn, sp.tn AS Tn FROM ("); for (var i = 0; i < shares.Count; i++) @@ -171,11 +172,12 @@ internal sealed class DistributionRepository(IDbSession session, ILogger 0) WHERE r <= :Cnt{i} @@ -273,8 +275,8 @@ internal sealed class DistributionRepository(IDbSession session, ILogger x.ToString(CultureInfo.InvariantCulture)).ToArray(), Ct = cargoCode, Type = queueType }, ct); } - public Task SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default) => ExecuteAsync( - "UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST', p.scrn = TO_CHAR(:OrderRef) WHERE p.id = :Id", new { OrderRef = orderId, Id = permitId }, ct); + public Task SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default) => ExecuteAsync( + "UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST', p.scrn = TO_CHAR(:OrderRef) WHERE p.id = :Id AND p.shipmentstatuscode = 'OPEN'", new { OrderRef = orderId, Id = permitId }, ct); public Task UpdateLastPermitAsync(long orderId, long badiyaScac, CancellationToken ct = default) => ExecuteAsync(""" UPDATE GRAINSTENDERORDER t @@ -326,8 +328,8 @@ internal sealed class DistributionRepository(IDbSession session, ILogger("SELECT COUNT(*) FROM GRAINS_COMPANIES_LOCATION t WHERE t.scac = :Scac AND t.locationid = :Loc", new { Scac = scac, Loc = location }, ct) > 0; - public Task SetRequestedAsync(long permitId, CancellationToken ct = default) => - ExecuteAsync("UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST' WHERE p.id = :Id", new { Id = permitId }, ct); + public Task SetRequestedAsync(long permitId, CancellationToken ct = default) => + ExecuteAsync("UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST' WHERE p.id = :Id AND p.shipmentstatuscode = 'OPEN'", new { Id = permitId }, ct); public async Task GetOrderForManualAsync(long orderId, CancellationToken ct = default) { @@ -350,8 +352,9 @@ internal sealed class DistributionRepository(IDbSession session, ILogger ExecuteAsync(""" - UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST', p.scrn = TO_CHAR(:OrderRef), p.notes = 'MANUAL_DEST', p.trackingno = :Q WHERE p.id = :Id + public Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST', p.scrn = TO_CHAR(:OrderRef), p.notes = 'MANUAL_DEST', p.trackingno = :Q + WHERE p.id = :Id AND p.shipmentstatuscode = 'OPEN' """, new { OrderRef = orderId, Q = queueId, Id = permitId }, ct); public async Task> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default) => diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitRepository.cs index e12f406..11e42ff 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitRepository.cs @@ -167,7 +167,7 @@ internal sealed class PermitRepository(IDbSession session, ILogger(PermitSelect + " WHERE p.id = :Id AND p.domain = 'GN'", new { Id = id }, ct))?.ToRow(); public async Task GetByPnAsync(string pn, CancellationToken ct = default) => - (await QueryFirstAsync(PermitSelect + " WHERE TO_CHAR(p.pn) = :Pn ORDER BY p.id DESC", new { Pn = pn }, ct))?.ToRow(); + (await QueryFirstAsync(PermitSelect + " WHERE TO_CHAR(p.pn) = :Pn AND p.domain = 'GN' ORDER BY p.id DESC", new { Pn = pn }, ct))?.ToRow(); public Task GetInfoAsync(long id, CancellationToken ct = default) => QueryFirstAsync(""" SELECT TO_CHAR(p.pn) AS Pn, p.tn AS Tn, p.trn AS Trn, p.nnpn AS Nnpn, p.shipmentstatuscode AS ShipmentStatusCode, p.tt AS Tt, @@ -349,6 +349,9 @@ internal sealed class PermitRepository(IDbSession session, ILogger ExecuteAsync( + "UPDATE PERMITS SET shipmentstatuscode = 'OPEN', scrn = NULL WHERE id = :Id", new { Id = id }, ct); + public Task RevokeNextOpenPermitsAsync(long permitId, string userId, CancellationToken ct = default) => ExecuteAsync(""" UPDATE PERMITS n SET isactive = 'N', shipmentstatuscode = 'RVKD', updatedby = :UserId, lastupdatedate = SYSDATE, trackingno = NULL WHERE n.id > :Id AND n.domain = 'GN' AND n.shipmentstatuscode = 'OPEN' diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PhoneEventRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PhoneEventRepository.cs index 61d7b32..50665d9 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PhoneEventRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PhoneEventRepository.cs @@ -1,6 +1,7 @@ using Dapper; using Microsoft.Extensions.Logging; using NTP.Application.Grains.Permits; +using NTP.Application.Grains.Registry; namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; @@ -115,5 +116,6 @@ internal sealed class PhoneEventRepository(IDbSession session, ILogger 0; - private static string Trunc(string s, int max) => s.Length <= max ? s : s[..max]; + // the columns are VARCHAR2(n): n counts bytes, so the cut is made in UTF-8 bytes (Arabic letters take two) + private static string Trunc(string s, int max) => RegistryRules.FitBytes(s, max); } diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/BlacklistRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/BlacklistRepository.cs index 7923f9f..5ded570 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/BlacklistRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/BlacklistRepository.cs @@ -59,7 +59,7 @@ internal sealed class BlacklistRepository(IDbSession session, ILogger InsertAsync(string category, string entityType, string entityId, string createdBy, DateTime expiry, string remarks, CancellationToken ct = default) { - var p = new DynamicParameters(new { Category = category, EntityType = entityType, EntityId = entityId, CreatedBy = createdBy, Expiry = expiry, Remarks = remarks }); + var p = new DynamicParameters(new { Category = category, EntityType = entityType, EntityId = entityId, CreatedBy = createdBy, Expiry = expiry, Remarks = RegistryRules.FitBytes(remarks, RegistryRules.BlacklistRemarksMaxBytes) }); p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); await ExecuteAsync(""" INSERT INTO GRAINSBLACKLIST @@ -84,14 +84,14 @@ internal sealed class BlacklistRepository(IDbSession session, ILogger ExecuteAsync(""" UPDATE TRUCK_DISTRIBUTION_LOG SET STATUSCODE = 'DELETED', UPDATEDATE = SYSDATE, NOTES = :Notes WHERE TO_CHAR(BLACKLISTID) = :BlacklistId AND STATUSCODE IN ('PENDING', 'RVKD') - """, new { Notes = remarks, BlacklistId = blacklistId.ToString(System.Globalization.CultureInfo.InvariantCulture) }, ct); + """, new { Notes = RegistryRules.FitBytes(remarks, RegistryRules.BlacklistRemarksMaxBytes), BlacklistId = blacklistId.ToString(System.Globalization.CultureInfo.InvariantCulture) }, ct); public Task ExpireDueAsync(CancellationToken ct = default) => ExecuteAsync(""" diff --git a/tests/NTP.Tests/AttachmentNameTests.cs b/tests/NTP.Tests/AttachmentNameTests.cs new file mode 100644 index 0000000..456d9bd --- /dev/null +++ b/tests/NTP.Tests/AttachmentNameTests.cs @@ -0,0 +1,31 @@ +using System.Text; +using NTP.Application.Grains.Registry; + +namespace NTP.Tests; + +public class AttachmentNameTests +{ + [Fact] + public void Short_names_are_kept() + => Assert.Equal("license.pdf", RegistryAttachmentService.FitOriginalName(" license.pdf ")); + + [Theory] + [InlineData(300)] + [InlineData(101)] + public void Long_ascii_names_are_cut_to_the_column_size_and_keep_the_extension(int length) + { + var name = new string('a', length) + ".pdf"; + var fit = RegistryAttachmentService.FitOriginalName(name); + Assert.True(Encoding.UTF8.GetByteCount(fit) <= RegistryAttachmentService.OriginalNameMaxBytes); + Assert.EndsWith(".pdf", fit); + } + + [Fact] + public void Long_arabic_names_are_measured_in_bytes() + { + var name = new string('ر', 80) + ".jpg"; // 80 chars = 160 bytes + var fit = RegistryAttachmentService.FitOriginalName(name); + Assert.True(Encoding.UTF8.GetByteCount(fit) <= RegistryAttachmentService.OriginalNameMaxBytes); + Assert.EndsWith(".jpg", fit); + } +} diff --git a/tests/NTP.Tests/BlacklistRemarksTests.cs b/tests/NTP.Tests/BlacklistRemarksTests.cs new file mode 100644 index 0000000..fcff05b --- /dev/null +++ b/tests/NTP.Tests/BlacklistRemarksTests.cs @@ -0,0 +1,33 @@ +using System.Text; +using NTP.Application.Grains.Registry; + +namespace NTP.Tests; + +public class BlacklistRemarksTests +{ + private static readonly DateTime Expiry = new(2026, 11, 20, 6, 0, 0); + + [Fact] + public void Short_remarks_are_unchanged_and_keep_the_release_date() + { + var text = RegistryRules.BlacklistRemarks("ملاحظة", Expiry); + Assert.StartsWith("ملاحظة، سيتم فك الانتظار", text); + Assert.EndsWith("11/20/2026 06:00", text); + } + + [Fact] + public void Four_hundred_arabic_letters_still_fit_the_500_byte_column_and_keep_the_release_date() + { + var text = RegistryRules.BlacklistRemarks(new string('ب', 400), Expiry); // 800 bytes typed + Assert.True(Encoding.UTF8.GetByteCount(text) <= RegistryRules.BlacklistRemarksMaxBytes); + Assert.EndsWith("11/20/2026 06:00", text); + } + + [Fact] + public void FitBytes_never_splits_a_character() + { + var fit = RegistryRules.FitBytes("ابت" + "😀" + "جد", 7); // 3 letters = 6 bytes, the emoji needs 4 more + Assert.Equal("ابت", fit); + Assert.Equal(string.Empty, RegistryRules.FitBytes(null, 10)); + } +} diff --git a/tests/NTP.Tests/PermissionTests.cs b/tests/NTP.Tests/PermissionTests.cs index 613f70a..41485b6 100644 --- a/tests/NTP.Tests/PermissionTests.cs +++ b/tests/NTP.Tests/PermissionTests.cs @@ -192,4 +192,12 @@ public class PermissionTests Assert.StartsWith("grains.", key); } } + + [Fact] + public void Role_CO_has_every_default_right_of_GTO() + { + foreach (var (key, roles) in PermissionDefaults.RolesByResource) + if (roles.Contains("GTO", StringComparer.OrdinalIgnoreCase)) + Assert.True(roles.Contains("CO", StringComparer.OrdinalIgnoreCase), $"CO is missing from {key}"); + } } diff --git a/tests/NTP.Tests/PermitsRulesTests.cs b/tests/NTP.Tests/PermitsRulesTests.cs index 7cfe7af..0ee544a 100644 --- a/tests/NTP.Tests/PermitsRulesTests.cs +++ b/tests/NTP.Tests/PermitsRulesTests.cs @@ -173,6 +173,24 @@ public class PermitActionRuleTests Assert.Contains(PermitActionRules.Reactivate, PermitActionRules.For(PermitStatus.Revoked, 327, false, true, false, true, 327)); Assert.DoesNotContain(PermitActionRules.Reactivate, PermitActionRules.For(PermitStatus.Revoked, 12, false, true, false, true, 327)); } + + [Fact] + public void Confirming_a_turn_is_staff_work_company_users_only_submit() + { + var plannedCompany = PermitActionRules.For(PermitStatus.Planned, 12, isCompany: true, isOperator: false, isConvertRole: false, isReactivator: false, 327); + Assert.DoesNotContain(PermitActionRules.Accept, plannedCompany); + Assert.DoesNotContain(PermitActionRules.Reject, plannedCompany); + Assert.Contains(PermitActionRules.Edit, plannedCompany); + + var acceptedCompany = PermitActionRules.For(PermitStatus.Accepted, 12, isCompany: true, isOperator: false, isConvertRole: false, isReactivator: false, 327); + Assert.DoesNotContain(PermitActionRules.RevokeAccepted, acceptedCompany); + + var plannedStaff = PermitActionRules.For(PermitStatus.Planned, 12, isCompany: false, isOperator: true, isConvertRole: false, isReactivator: false, 327); + Assert.Contains(PermitActionRules.Accept, plannedStaff); + Assert.Contains(PermitActionRules.Reject, plannedStaff); + var acceptedStaff = PermitActionRules.For(PermitStatus.Accepted, 12, isCompany: false, isOperator: true, isConvertRole: false, isReactivator: false, 327); + Assert.Contains(PermitActionRules.RevokeAccepted, acceptedStaff); + } } public class PermitSupportTests diff --git a/web/src/components/DateField.tsx b/web/src/components/DateField.tsx index 0322135..4e20d81 100644 --- a/web/src/components/DateField.tsx +++ b/web/src/components/DateField.tsx @@ -17,12 +17,27 @@ function displayToIso(text: string): string { return dt.getFullYear() === y && dt.getMonth() === mo - 1 && dt.getDate() === d ? `${m[3]}-${m[2]}-${m[1]}` : ''; } -/** Digits typed so far -> dd, dd/mm, dd/mm/yyyy. */ -function mask(raw: string): string { - const d = raw.replace(/\D/g, '').slice(0, 8); - if (d.length <= 2) return d; - if (d.length <= 4) return `${d.slice(0, 2)}/${d.slice(2)}`; - return `${d.slice(0, 2)}/${d.slice(2, 4)}/${d.slice(4)}`; +/** + * Typed / pasted text -> dd/mm/yyyy as far as it goes. Digits only auto-insert the slashes (0101 -> 01/01); with slashes + * (or - .) a single-digit day or month is padded as soon as the next separator is typed (1/1/2026 -> 01/01/2026). + */ +function mask(raw: string, growing = true): string { + const clean = raw.replace(/[^\d/.\-]/g, '').replace(/[.\-]/g, '/'); + if (!clean.includes('/')) { + const d = clean.slice(0, 8); + if (d.length <= 2) return d; + if (d.length <= 4) return `${d.slice(0, 2)}/${d.slice(2)}`; + return `${d.slice(0, 2)}/${d.slice(2, 4)}/${d.slice(4)}`; + } + const parts = clean.split('/').slice(0, 3); + const out = parts.map((p, i) => { + const max = i === 2 ? 4 : 2; + const v = p.slice(0, max); + return i < parts.length - 1 && v.length === 1 ? `0${v}` : v; // pad once a later separator exists + }); + // two digits of the month typed: move on to the year + if (growing && out.length === 2 && out[1]!.length === 2) out.push(''); + return out.join('/'); } type Props = Omit & { @@ -46,7 +61,7 @@ export function DateField({ value, onChange, slotProps, disabled, ...rest }: Pro }, [value]); const typed = (raw: string) => { - const next = mask(raw); + const next = mask(raw, raw.length > text.length); setText(next); onChange(displayToIso(next)); }; diff --git a/web/src/components/MetaForm/MetaForm.tsx b/web/src/components/MetaForm/MetaForm.tsx index 934a221..260e0da 100644 --- a/web/src/components/MetaForm/MetaForm.tsx +++ b/web/src/components/MetaForm/MetaForm.tsx @@ -20,6 +20,8 @@ export interface MetaFormProps { onSubmit?: (payload: FormValues) => Promise | unknown; onCancel?: () => void; submitLabel?: string; + /** Text of the bottom cancel/return button (default: common.cancel). */ + cancelLabel?: string; /** Confirmation question before saving; `false` skips the dialog. Default: the standard "Do you want to save?". */ confirmMessage?: string | false; /** Field-level errors from the backend (ApiError.fieldErrors); the first one is focused. */ @@ -193,7 +195,7 @@ export function MetaForm(props: MetaFormProps) { {onCancel && ( )} {props.extraActions} diff --git a/web/src/features/grains-permits/pages.tsx b/web/src/features/grains-permits/pages.tsx index ebfd135..0d11292 100644 --- a/web/src/features/grains-permits/pages.tsx +++ b/web/src/features/grains-permits/pages.tsx @@ -29,7 +29,6 @@ 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 { DateField } from '@/components/DateField'; import { FormCard, FormGrid } from '@/components/FormCard'; // the shared framed section look (see components/SectionPaper): every Paper on the permit screens uses it import { SectionPaper as Paper } from '@/components/SectionPaper'; @@ -46,7 +45,7 @@ import { useAuth } from '@/providers/AuthProvider'; import { useConfirm } from '@/providers/ConfirmProvider'; import { useToast } from '@/providers/ToastProvider'; import { - fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, searchDestination, searchTruckDistribution, + fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, fetchTruck, searchDestination, searchTruckDistribution, useActivateOrders, useActivation, useAddToQueue, useVoiceCall, useAssignByPn, useClosePermit, useDistribute, useDistributionPivot, useDistributionSummary, useLocationGroups, useManualInput, useOrderDates, usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination, @@ -58,9 +57,9 @@ import { AcceptSlip, InSlip, OutSlip } from './slips'; import type { PermitListItem, TruckDistribution } from './types'; /** Legacy role gates (src/NTP.Application/Grains/Permits/PermitSupport.cs GrainsRoles). */ -export const OPERATORS = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO']; -export const SUPERVISORS = ['SU', 'GPO', 'GNSU', 'GTO']; -export const WEIGHBRIDGE_ROLES = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'GATEIN', 'GATEOUT', 'THRU']; +export const OPERATORS = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'CO']; +export const SUPERVISORS = ['SU', 'GPO', 'GNSU', 'GTO', 'CO']; +export const WEIGHBRIDGE_ROLES = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'CO', 'GATEIN', 'GATEOUT', 'THRU']; const PHONE_REASONS: { value: string; en: string; ar: string }[] = [ { value: 'لايمكن الاتصال به', en: 'Cannot be reached', ar: 'لايمكن الاتصال به' }, @@ -295,6 +294,8 @@ export function PermitDetailPage() { // 'pending' = the id was changed but not validated yet (validated when Enter is pressed). const [trailerLook, setTrailerLook] = useState> | null | undefined | 'pending'>(undefined); const [driverLook, setDriverLook] = useState> | null | undefined | 'pending'>(undefined); + // A company turn (permit created from the company share) has no truck yet: the truck number is typed and validated like the trailer. + const [truckLook, setTruckLook] = useState> | undefined | 'pending'>(undefined); const d = detail.data; const openEdit = () => { @@ -305,6 +306,7 @@ export function PermitDetailPage() { }); setTrailerLook(undefined); setDriverLook(undefined); + setTruckLook(undefined); setEditing(true); }; // opened straight from the list: fill the form once the permit has loaded @@ -315,6 +317,7 @@ export function PermitDetailPage() { const nnpnTyped = v.nnpn.trim(); const ownTrn = d?.trailer?.tn ?? ''; const ownNnpn = d?.driver?.nnpn ?? ''; + const ownTn = d?.truck?.tn ?? ''; if (detail.isLoading) return ; if (!d) return ; @@ -349,17 +352,28 @@ export function PermitDetailPage() { try { setDriverLook((await fetchDriver(nnpnTyped)) ?? null); } catch (e) { setDriverLook(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } } + const changeTruck = (e: { target: { value: string } }) => { + const x = e.target.value; + setV((p) => ({ ...p, tn: x })); + setTruckLook(x.trim() ? 'pending' : undefined); + }; + async function checkTruck() { + if (!v.tn.trim() || truckLook !== 'pending') return; + try { setTruckLook((await fetchTruck(v.tn.trim())) ?? null); } + catch (e) { setTruckLook(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } + } const onEnter = (run: () => Promise) => (e: { key: string; preventDefault: () => void }) => { if (e.key === 'Enter') { e.preventDefault(); void run(); } }; const fdate = (x: string | null | undefined) => (x ? formatDate(x, lang) || x : ''); - const complete = !!(trnTyped && nnpnTyped && trailerShown && driverShown?.name && driverShown.dln && (canEdit && !canSubmit ? true : v.opType)); + const truckOk = !!ownTn || (!!v.tn.trim() && !!truckLook && truckLook !== 'pending'); + const complete = !!(truckOk && trnTyped && nnpnTyped && trailerShown && driverShown?.name && driverShown.dln && (canEdit && !canSubmit ? true : v.opType)); async function save() { if (!complete || !driverShown || !(await confirm({ message: t(canSubmit ? 'pm.confirm.submit' : 'pm.confirm.update') }))) return; // the truck never changes here; the driver data is the looked-up (or the permit's own) data of the typed id const body = { - tn: (d?.truck?.tn ?? v.tn).trim(), trn: trnTyped, nnpn: nnpnTyped, dln: (driverShown.dln ?? '').trim(), + tn: (ownTn || v.tn).trim(), trn: trnTyped, nnpn: nnpnTyped, dln: (driverShown.dln ?? '').trim(), dled: driverShown.dled || null, name: (driverShown.name ?? '').trim(), }; const done = { onSuccess: () => setEditing(false) }; @@ -449,7 +463,12 @@ export function PermitDetailPage() { {/* the truck is fixed; only the trailer number and the driver id can change, the rest follows from them */} - + {ownTn ? ( + + ) : ( + + )} {canSubmit && !d.operationTypeCode ? ( {lang === 'ar' ? 'محمل' : 'Loaded'} @@ -657,7 +676,7 @@ function Activation() { {t('pm.activate.loc')}{t('pm.activate.cargo')} - {t('pm.activate.total')}{t('pm.activate.used')} + {t('pm.activate.total')}{t('pm.activate.used')} {rows.map((r) => { @@ -666,7 +685,7 @@ function Activation() { toggle(k)} /> {r.loc}{r.ct} - {fmt(r.total)}{fmt(r.used)} + {fmt(r.total)}{fmt(r.used)} ); })} @@ -718,11 +737,11 @@ export function SupplyOrderPage() {
- {t('pm.dist.company')}{t('pm.dist.silos')} - {t('pm.dist.direct')}{t('pm.dist.packed')} + {t('pm.dist.company')}{t('pm.dist.silos')} + {t('pm.dist.direct')}{t('pm.dist.packed')}{(pivot.data ?? []).map((r) => ( - {r.company}{r.silos} - {r.direct}{r.packed} + {r.company}{r.silos} + {r.direct}{r.packed} ))}
@@ -769,28 +788,35 @@ function DistributeTab() { const { t, lang } = useFeatureUi(strings); const distribute = useDistribute(); const confirm = useConfirm(); + // confirm texts are the legacy ones (GNPermits.cfm), one per category const cats = [ - { v: 'PCKD', en: 'Packed', ar: 'مشول' }, { v: 'BULK_AHALE', en: 'Bulk - individuals', ar: 'سائب - أفراد' }, - { v: 'BULK_COMP', en: 'Bulk - companies', ar: 'سائب - شركات' }, { v: 'BULK_GALLAB_AHALE', en: 'Tipper bulk - individuals', ar: 'قلاب - أفراد' }, - { v: 'BULK_GALLAB_COMP', en: 'Tipper bulk - companies', ar: 'قلاب - شركات' }, + { v: 'PCKD', en: 'Packed', ar: 'مشول', q: 'هل أنت متأكد من توزيع طلبية المشول لهذا اليوم؟' }, + { v: 'BULK_AHALE', en: 'Bulk - individuals', ar: 'سائب - أفراد', q: 'هل أنت متأكد من توزيع طلبية سائب افراد لهذا اليوم؟' }, + { v: 'BULK_COMP', en: 'Bulk - companies', ar: 'سائب - شركات', q: 'هل أنت متأكد من توزيع طلبية سائب شركات لهذا اليوم؟' }, + { v: 'BULK_GALLAB_AHALE', en: 'Tipper bulk - individuals', ar: 'قلاب - أفراد', q: 'هل أنت متأكد من توزيع طلبية قلاب أفراد لهذا اليوم؟' }, + { v: 'BULK_GALLAB_COMP', en: 'Tipper bulk - companies', ar: 'قلاب - شركات', q: 'هل أنت متأكد من توزيع طلبية قلاب شركات لهذا اليوم؟' }, ]; - const [cat, setCat] = useState('PCKD'); + const [cat, setCat] = useState(''); // nothing preselected: a distribution run cannot be undone const summary = useDistributionSummary(); - async function go() { if (await confirm({ message: t('pm.dist.confirm') })) distribute.mutate(cat); } + async function go() { + const c = cats.find((x) => x.v === cat); + if (!c) return; + if (await confirm({ message: lang === 'ar' ? c.q : `Distribute today's ${c.en} order?` })) distribute.mutate(cat); + } return ( setCat(e.target.value)}> {cats.map((c) => {lang === 'ar' ? c.ar : c.en})} - + {t('pm.dist.summary')} - {t('pm.dist.company')}{t('pm.dist.count')} - {(summary.data ?? []).map((r) => {r.comp}{fmt(r.cnt)})} + {t('pm.dist.company')}{t('pm.dist.count')} + {(summary.data ?? []).map((r) => {r.comp}{fmt(r.cnt)})}
@@ -806,11 +832,28 @@ function ProcessTab() { const revokeAll = useRevokeAllRequested(); const { isSu } = useRoles(); const confirm = useConfirm(); + const toast = useToast(); + const dates = useOrderDates(); const [tn, setTn] = useState(''); const [pn, setPn] = useState(''); const [orderId, setOrderId] = useState(''); const [date, setDate] = useState(''); + const [reserved, setReserved] = useState(false); + const [orders, setOrders] = useState<{ orderId: number; name: string | null }[]>([]); const [limit, setLimit] = useState(''); + + // legacy: the destination list is bound to the permit number and the order date (getAllowedDestinationsByDate) + useEffect(() => { + setOrderId(''); + if (!pn || !date) { setOrders([]); return; } + let live = true; + fetchAllowedDestinations(pn, date) + .then((rows) => { if (live) setOrders(rows.filter((r) => r.orderId > 0)); }) + .catch((e) => { if (live) { setOrders([]); toast.error(e instanceof Error ? e.message : t('error.generic')); } }); + return () => { live = false; }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [pn, date]); + return ( @@ -826,11 +869,20 @@ function ProcessTab() { {t('pm.proc.withDest')} + setDate(e.target.value)}> + {(dates.data ?? []).map((d) => {d.split('-').reverse().join('/')})} + - - - + setOrderId(e.target.value)} + helperText={orders.length === 0 && pn && date ? t('pm.manual.noOrders') : undefined}> + {orders.map((o) => {o.name})} + + + setReserved(e.target.checked)} /> + {t('pm.proc.reserved')} + + {isSu && ( diff --git a/web/src/features/grains-permits/strings.ts b/web/src/features/grains-permits/strings.ts index e040bce..90621d2 100644 --- a/web/src/features/grains-permits/strings.ts +++ b/web/src/features/grains-permits/strings.ts @@ -135,6 +135,7 @@ export default defineStrings({ 'pm.proc.autoOrder': { en: 'Pick an order automatically', ar: 'اختيار طلبية تلقائيا' }, 'pm.proc.single': { en: 'Move to "order distributed" only', ar: 'تحويل الحالة فقط' }, 'pm.proc.withDest': { en: 'Distribute a permit to a chosen order', ar: 'توزيع ارسالية على طلبية محددة' }, + 'pm.proc.reserved': { en: 'Reserved turn', ar: 'دور محفوظ' }, 'pm.proc.confirm': { en: 'Distribute now?', ar: 'هل تريد التوزيع؟' }, 'pm.proc.revokeAll': { en: 'Send old requested permits back to the turn', ar: 'ارجاع الارساليات القديمة الى الدور' }, 'pm.proc.limit': { en: 'Orders below number', ar: 'الطلبيات الأقل من الرقم' }, diff --git a/web/src/features/grains-registry/pages.tsx b/web/src/features/grains-registry/pages.tsx index e686549..bcaaec9 100644 --- a/web/src/features/grains-registry/pages.tsx +++ b/web/src/features/grains-registry/pages.tsx @@ -194,7 +194,7 @@ export function TruckPage() { canAccept={!!perms?.canAcceptTruck} canRevoke={!!perms?.canRevokeTruck && !perms.isBadiyaCompany} onAccept={() => action.mutate({ id: t0.id, action: 'accept' })} onRevoke={() => action.mutate({ id: t0.id, action: 'revoke' })} - extra={perms?.canAddTrailer && canEditStatus(t0.statusCode) && (trailers.data?.length ?? 0) === 0 && ( + extra={perms?.canAddTrailer && canEditStatus(t0.statusCode) && (trailers.data?.filter((x) => x.statusCode !== 'RVKD').length ?? 0) === 0 && ( @@ -217,6 +217,7 @@ export function TruckPage() { mode={canEdit ? (isNew ? 'create' : 'edit') : 'view'} initialValues={initial} serverErrors={serverErrors} + cancelLabel={t('reg.return')} onCancel={() => navigate(gridReturnUrl(`${ROOT}/trucks`))} onSubmit={submit} > @@ -384,6 +385,7 @@ export function TrailerPage() { mode={canEdit ? (isNew ? 'create' : 'edit') : 'view'} initialValues={initial} serverErrors={serverErrors} + cancelLabel={t('reg.return')} onCancel={() => navigate(truckId ? `${ROOT}/trucks/${truckId}` : gridReturnUrl(`${ROOT}/trailers`))} onSubmit={submit} > @@ -475,6 +477,7 @@ export function DriverPage() { mode={isNew ? 'create' : 'view'} initialValues={initial} serverErrors={serverErrors} + cancelLabel={t('reg.return')} onCancel={() => navigate(gridReturnUrl(`${ROOT}/drivers`))} onSubmit={submit} > @@ -547,6 +550,7 @@ export function BlacklistCreatePage() { meta={meta} mode="create" serverErrors={serverErrors} + cancelLabel={t('reg.return')} onCancel={() => navigate(gridReturnUrl(`${ROOT}/blacklist`))} onSubmit={(p) => new Promise((resolve) => { diff --git a/web/src/features/grains-registry/strings.ts b/web/src/features/grains-registry/strings.ts index d6455ff..6135c80 100644 --- a/web/src/features/grains-registry/strings.ts +++ b/web/src/features/grains-registry/strings.ts @@ -23,6 +23,7 @@ export default defineStrings({ 'reg.status.incomp': { en: 'Incomplete', ar: 'غير مكتمل' }, 'reg.status': { en: 'Status', ar: 'الحالة' }, 'reg.accept': { en: 'Activate', ar: 'تفعيل' }, + 'reg.return': { en: 'Back', ar: 'عودة' }, 'reg.revoke': { en: 'Revoke', ar: 'إلغاء' }, 'reg.acceptConfirm': { en: 'Do you want to activate this record?', ar: 'هل تريد تفعيل هذا السجل؟' }, 'reg.revokeConfirm': { en: 'Do you want to revoke this record? This cannot be undone.', ar: 'هل تريد إلغاء هذا السجل؟ لا يمكن التراجع عن ذلك.' }, diff --git a/web/src/shell/DashboardPage.tsx b/web/src/shell/DashboardPage.tsx index 36349f9..60976fe 100644 --- a/web/src/shell/DashboardPage.tsx +++ b/web/src/shell/DashboardPage.tsx @@ -1,18 +1,33 @@ import { useMemo } from 'react'; import { Link as RouterLink } from 'react-router-dom'; -import { Alert, Box, Card, CardActionArea, Chip, Stack, Typography } from '@mui/material'; +import { Alert, Box, Card, CardActionArea, Chip, Divider, Stack, Typography } from '@mui/material'; +import { alpha } from '@mui/material/styles'; import { PageHeader } from '@/components/PageHeader'; import { useUi } from '@/i18n/useUi'; import { useAuth } from '@/providers/AuthProvider'; import { featureMenu } from '@/registry'; import { filterMenu, flatten, itemAllowed } from './menuUtils'; +import { colorOf } from './Sidebar'; +import type { MenuItem } from './types'; -/** Simple landing: who you are + quick links to every page the role can open. */ +/** Pages of one top-level menu entry: its own page (if any) and every page under it, with the sub group as caption. */ +function pagesOf(group: MenuItem, tr: (l: MenuItem['title']) => string) { + const own = group.path ? [{ item: group, caption: '' }] : []; + const below = (group.children ? flatten(group.children) : []) + .filter((e) => e.item.path) + .map((e) => ({ item: e.item, caption: e.trail.map((g) => tr(g.title)).join(' / ') })); + return [...own, ...below]; +} + +/** Landing: who you are + quick links grouped exactly like the menu (one section per menu group). */ export function DashboardPage() { const { t, tr } = useUi(); const { user, hasRole, can } = useAuth(); - const links = useMemo( - () => flatten(filterMenu(featureMenu, itemAllowed(hasRole, can), can)).filter((e) => e.item.path), + const sections = useMemo( + () => filterMenu(featureMenu, itemAllowed(hasRole, can), can) + .map((group) => ({ group, pages: pagesOf(group, tr) })) + .filter((s) => s.pages.length > 0), + // eslint-disable-next-line react-hooks/exhaustive-deps [hasRole, can], ); @@ -24,26 +39,43 @@ export function DashboardPage() { {user?.locationName && } {user?.companyCode && } - {t('nav.quickLinks')} - {links.length === 0 ? ( + {sections.length === 0 ? ( {t('nav.empty')} ) : ( - - {links.map(({ item, trail }) => { - const Icon = item.icon; + + {sections.map(({ group, pages }) => { + const GroupIcon = group.icon; + const c = colorOf(group); + // a top-level entry that is a single page is shown as one card under its own heading return ( - - - - - {tr(item.title)} - {trail.length > 0 && {trail.map((g) => tr(g.title)).join(' / ')}} + + + + - - + {tr(group.title)} + + + + {pages.map(({ item, caption }) => { + const Icon = item.icon; + return ( + + + + + {tr(item.title)} + {caption && {caption}} + + + + ); + })} + + ); })} -
+ )} ); diff --git a/web/src/shell/Sidebar.tsx b/web/src/shell/Sidebar.tsx index 913abbb..c0a7c00 100644 --- a/web/src/shell/Sidebar.tsx +++ b/web/src/shell/Sidebar.tsx @@ -19,7 +19,7 @@ import type { MenuItem as Item } from './types'; export const DRAWER_FULL = 272; export const DRAWER_MINI = 76; -function colorOf(item: Item): string { +export function colorOf(item: Item): string { if (item.color) return item.color; let h = 0; for (const ch of item.key) h = (h * 31 + ch.charCodeAt(0)) >>> 0;