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 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-17 15:55:03 +03:00
parent 334b881262
commit bf1c04b590
38 changed files with 606 additions and 181 deletions

30
db/role-co.sql Normal file
View File

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

View File

@ -15,6 +15,7 @@ services:
env_file: .env env_file: .env
environment: environment:
ASPNETCORE_ENVIRONMENT: Production ASPNETCORE_ENVIRONMENT: Production
TZ: Asia/Amman # permit expiry, blacklist and report times follow the Oracle server clock (Amman)
ports: 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 # 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" - "127.0.0.1:${NTP_PORT:-8081}:8080"

View File

@ -21,6 +21,7 @@ WORKDIR /app
COPY --from=api /app ./ COPY --from=api /app ./
COPY --from=web /web/dist ./wwwroot COPY --from=web /web/dist ./wwwroot
ENV ASPNETCORE_URLS=http://+:8080 \ ENV ASPNETCORE_URLS=http://+:8080 \
ASPNETCORE_FORWARDEDHEADERS_ENABLED=true ASPNETCORE_FORWARDEDHEADERS_ENABLED=true \
TZ=Asia/Amman
EXPOSE 8080 EXPOSE 8080
ENTRYPOINT ["dotnet", "NTP.Api.dll"] ENTRYPOINT ["dotnet", "NTP.Api.dll"]

View File

@ -11,5 +11,6 @@ services:
env_file: .env env_file: .env
environment: environment:
ASPNETCORE_ENVIRONMENT: QA ASPNETCORE_ENVIRONMENT: QA
TZ: Asia/Amman
ports: ports:
- "0.0.0.0:8081:8080" - "0.0.0.0:8081:8080"

View File

@ -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) 4. `db/permits-create-permission.sql` - right to register a turn (تسجيل دور) from the permits list, granted to GOO (safe to re-run)
5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run) 5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run)
5b. `db/gto-reports.sql` - GTO gets the ارسالية عطاء التموين and ملخص التوزيع reports (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) 6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run)
**Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU **Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU

View File

@ -160,12 +160,12 @@ public sealed class PermitQueueController(IQueueService queue) : ControllerBase
/// <summary>checkTrucks.</summary> /// <summary>checkTrucks.</summary>
[HttpPost("check-trucks")] [HttpPost("check-trucks")]
[RequirePermission(PermissionKeys.PermitsCreate)] [Authorize(Roles = "SU")]
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.PermitsCreate)] [Authorize(Roles = "SU")]
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)
@ -237,11 +237,6 @@ public sealed class PermitDestinationsController(IDestinationService destination
[RequirePermission(PermissionKeys.PermitsDestinations)] [RequirePermission(PermissionKeys.PermitsDestinations)]
public Task<IReadOnlyList<long>> CompanyDestinations(long scac, CancellationToken ct) => destinations.GetCompanyDestinationsAsync(scac, ct); public Task<IReadOnlyList<long>> CompanyDestinations(long scac, CancellationToken ct) => destinations.GetCompanyDestinationsAsync(scac, ct);
[HttpPut("companies/{scac:long}")]
[RequirePermission(PermissionKeys.PermitsDestinations)]
public Task<PermitOperationResult> SaveCompanyDestinations(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct) =>
destinations.SaveCompanyDestinationsAsync(scac, request, ct);
/// <summary>savegrainsdest (assginggdest.cfm).</summary> /// <summary>savegrainsdest (assginggdest.cfm).</summary>
[HttpPost("assign-by-pn")] [HttpPost("assign-by-pn")]
[RequirePermission(PermissionKeys.PermitsDestinations)] [RequirePermission(PermissionKeys.PermitsDestinations)]
@ -301,8 +296,9 @@ public sealed class PermitDistributionController(IDistributionService distributi
[RequirePermission(PermissionKeys.PermitsDistribution)] [RequirePermission(PermissionKeys.PermitsDistribution)]
public Task<PermitOperationResult> Distribute(DistributeRequest request, CancellationToken ct) => distribution.DistributeAsync(request, ct); public Task<PermitOperationResult> 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")] [HttpPost("release")]
[RequirePermission(PermissionKeys.PermitsDistribution)] [Authorize(Roles = "SU")]
public Task<PermitOperationResult> Release(ReleasePermitRequest request, CancellationToken ct) => distribution.ReleaseAsync(request, ct); public Task<PermitOperationResult> Release(ReleasePermitRequest request, CancellationToken ct) => distribution.ReleaseAsync(request, ct);
[HttpPost("process-open")] [HttpPost("process-open")]
@ -314,8 +310,9 @@ public sealed class PermitDistributionController(IDistributionService distributi
public Task<PermitOperationResult> ProcessOpenWithDestination(OpenPermitWithDestinationRequest request, CancellationToken ct) => public Task<PermitOperationResult> ProcessOpenWithDestination(OpenPermitWithDestinationRequest request, CancellationToken ct) =>
distribution.ProcessOpenPermitWithDestinationAsync(request, ct); distribution.ProcessOpenPermitWithDestinationAsync(request, ct);
// legacy screen "فك دور الشركات": GNSU and SU only
[HttpPost("process-company-open")] [HttpPost("process-company-open")]
[RequirePermission(PermissionKeys.PermitsTruckOrder)] [Authorize(Roles = "SU,GNSU")]
public Task<PermitOperationResult> ProcessCompanyOpen(CompanyOpenPermitsRequest request, CancellationToken ct) => public Task<PermitOperationResult> ProcessCompanyOpen(CompanyOpenPermitsRequest request, CancellationToken ct) =>
distribution.ProcessCompanyOpenPermitsAsync(request, ct); distribution.ProcessCompanyOpenPermitsAsync(request, ct);
@ -340,7 +337,7 @@ public sealed class PermitDistributionController(IDistributionService distributi
public Task<IReadOnlyList<BlacklistedDistributionDto>> Blacklisted([FromQuery] string tn, CancellationToken ct) => distribution.GetBlacklistedAsync(tn, ct); public Task<IReadOnlyList<BlacklistedDistributionDto>> Blacklisted([FromQuery] string tn, CancellationToken ct) => distribution.GetBlacklistedAsync(tn, ct);
[HttpPost("check-trips")] [HttpPost("check-trips")]
[RequirePermission(PermissionKeys.PermitsDistribution)] [Authorize(Roles = "SU")]
public Task<PermitOperationResult> CheckTrips(CheckTripsRequest request, CancellationToken ct) => distribution.CheckTripsAsync(request, ct); public Task<PermitOperationResult> CheckTrips(CheckTripsRequest request, CancellationToken ct) => distribution.CheckTripsAsync(request, ct);
/// <summary>RevokeAllREQST.cfm: send every REQST / PLND permit of an order id below the given limit back to OPEN.</summary> /// <summary>RevokeAllREQST.cfm: send every REQST / PLND permit of an order id below the given limit back to OPEN.</summary>

View File

@ -33,6 +33,11 @@
// الاتصال الصوتي button (ارساليات التموين): starts the IVR calls. The ?wsdl address is turned into a call of callAPI. // الاتصال الصوتي button (ارساليات التموين): starts the IVR calls. The ?wsdl address is turned into a call of callAPI.
"Permits": { "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": { "AutoCall": {
"Enabled": true, "Enabled": true,
"IvrUrl": "http://aqtcs.nafith.net/IVR/callivr.cfc?wsdl" "IvrUrl": "http://aqtcs.nafith.net/IVR/callivr.cfc?wsdl"

View File

@ -82,34 +82,34 @@ public static class PermissionDefaults
{ {
public static readonly IReadOnlyDictionary<string, string[]> RolesByResource = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) public static readonly IReadOnlyDictionary<string, string[]> RolesByResource = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
{ {
[PermissionKeys.PermitsList] = ["GTO", "GGO", "GOO", "GPO", "DISP"], // ارسالية عطاء التموين (DISP: own company only) [PermissionKeys.PermitsList] = ["GTO", "CO", "GGO", "GOO", "GPO", "DISP"], // ارسالية عطاء التموين (DISP: own company only)
[PermissionKeys.RegistryTrucks] = ["GTO", "GOO", "GPO"], // شاشة القاطرات [PermissionKeys.RegistryTrucks] = ["GTO", "CO", "GOO", "GPO"], // شاشة القاطرات
[PermissionKeys.RegistryTrailers] = ["GTO", "GOO", "GPO"], // شاشة المقطورات [PermissionKeys.RegistryTrailers] = ["GTO", "CO", "GOO", "GPO"], // شاشة المقطورات
[PermissionKeys.RegistryDrivers] = ["GTO", "GOO", "GPO"], // شاشة السائقين المسجلين [PermissionKeys.RegistryDrivers] = ["GTO", "CO", "GOO", "GPO"], // شاشة السائقين المسجلين
[PermissionKeys.OrdersList] = ["GTO", "GOO"], // الطلبيات [PermissionKeys.OrdersList] = ["GTO", "CO", "GOO"], // الطلبيات
[PermissionKeys.OrdersCreate] = ["GTO"], // طلبية جديدة (GOO was removed again; add a row per role to grant it) [PermissionKeys.OrdersCreate] = ["GTO", "CO"], // طلبية جديدة (GOO was removed again; add a row per role to grant it)
[PermissionKeys.PermitsWeighbridge] = ["GTO", "GGO"], // شاشة القبان [PermissionKeys.PermitsWeighbridge] = ["GTO", "CO", "GGO"], // شاشة القبان
[PermissionKeys.PermitsClose] = ["GTO", "GGO", "GOO", "GPO"], // اغلاق إرسالية [PermissionKeys.PermitsClose] = ["GTO", "CO", "GGO", "GOO", "GPO"], // اغلاق إرسالية
[PermissionKeys.PermitsTruckOrder] = ["GTO"], // طلبية لسيارة [PermissionKeys.PermitsTruckOrder] = ["GTO", "CO"], // طلبية لسيارة
[PermissionKeys.RegistryBlacklist] = ["GTO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار [PermissionKeys.RegistryBlacklist] = ["GTO", "CO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار
[PermissionKeys.PermitsDistribution] = ["GTO", "GOO"], // طلبية التموين [PermissionKeys.PermitsDistribution] = ["GTO", "CO", "GOO"], // طلبية التموين
[PermissionKeys.OrdersSupply] = ["GTO", "GOO"], // طلبية التموين (orders menu) [PermissionKeys.OrdersSupply] = ["GTO", "CO", "GOO"], // طلبية التموين (orders menu)
[PermissionKeys.PermitsTruckStatus] = ["GTO", "GOO"], // استعلام عن حالة التوزيع لسيارة [PermissionKeys.PermitsTruckStatus] = ["GTO", "CO", "GOO"], // استعلام عن حالة التوزيع لسيارة
[PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية [PermissionKeys.PermitsActivation] = ["GTO", "CO"], // شاشة تفعيل الطلبية
[PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي [PermissionKeys.PermitsManualEntry] = ["GTO", "CO"], // شاشة الادخال اليدوي
[PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف [PermissionKeys.PermitsAbsence] = ["GTO", "CO"], // إيقاف\تفعيل الاستنكاف
[PermissionKeys.PermitsVoiceCall] = ["GTO"], // الاتصال الصوتي [PermissionKeys.PermitsVoiceCall] = ["GTO", "CO"], // الاتصال الصوتي
[PermissionKeys.OrdersInvoiceCheck] = ["GNAC"], // التأكد من الفواتير [PermissionKeys.OrdersInvoiceCheck] = ["GNAC"], // التأكد من الفواتير
[PermissionKeys.OrdersFines] = ["GNAC"], // الغرامات [PermissionKeys.OrdersFines] = ["GNAC"], // الغرامات
[PermissionKeys.OrdersWages] = ["GNAC"], // الأجور [PermissionKeys.OrdersWages] = ["GNAC"], // الأجور
[PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل [PermissionKeys.OrdersWeights] = ["GTO", "CO"], // تثبيت أوزان التحميل
[PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ [PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "CO", "GOO"], // تقارير حركات قبان التحميل والتفريغ
[PermissionKeys.ReportTable("companies-turn")] = ["GTO", "GOO"], // تقرير دور الشركات [PermissionKeys.ReportTable("companies-turn")] = ["GTO", "CO", "GOO"], // تقرير دور الشركات
[PermissionKeys.ReportTable("owners-turn")] = ["GTO"], // تقرير دور الأفراد [PermissionKeys.ReportTable("owners-turn")] = ["GTO", "CO"], // تقرير دور الأفراد
[PermissionKeys.ReportTable("loading-weights")] = ["GTO"], // تقرير أوزان التحميل [PermissionKeys.ReportTable("loading-weights")] = ["GTO", "CO"], // تقرير أوزان التحميل
[PermissionKeys.ReportTable("closed-permits")] = ["GTO"], // الارساليات المكتملة [PermissionKeys.ReportTable("closed-permits")] = ["GTO", "CO"], // الارساليات المكتملة
[PermissionKeys.ReportTable("tender-order")] = ["GTO"], // ارسالية عطاء التموين [PermissionKeys.ReportTable("tender-order")] = ["GTO", "CO"], // ارسالية عطاء التموين
[PermissionKeys.ReportTable("distribution-summary")] = ["GTO"], // ملخص التوزيع [PermissionKeys.ReportTable("distribution-summary")] = ["GTO", "CO"], // ملخص التوزيع
[PermissionKeys.OrdersCompanyDest] = ["GOO"], // وجهات الشركات [PermissionKeys.OrdersCompanyDest] = ["GOO"], // وجهات الشركات
[PermissionKeys.PermitsDestinations] = ["GOO"], // تحديد وجهة ارسالية تموين [PermissionKeys.PermitsDestinations] = ["GOO"], // تحديد وجهة ارسالية تموين
}; };

View File

@ -98,6 +98,9 @@ public sealed class AuthService(
Lang: "AR", Lang: "AR",
IsStaff: profile.CompanyId == StaffCompanyId); 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. // Logging (addlog 1) - legacy swallows logging errors.
await TryAsync(() => repository.InsertLogAsync( await TryAsync(() => repository.InsertLogAsync(
new AuditLogEntry(user.UserId, client.IpAddress, user.RoleCode, LogSignIn, user.Name, client.UserAgent), ct)); new AuditLogEntry(user.UserId, client.IpAddress, user.RoleCode, LogSignIn, user.Name, client.UserAgent), ct));

View File

@ -15,7 +15,6 @@ public interface IDestinationService
Task<LocationGroupsDto> GetLocationGroupsAsync(CancellationToken ct = default); Task<LocationGroupsDto> GetLocationGroupsAsync(CancellationToken ct = default);
Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default); Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default);
Task<IReadOnlyList<long>> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default); Task<IReadOnlyList<long>> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default);
Task<PermitOperationResult> SaveCompanyDestinationsAsync(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct = default);
Task<PermitOperationResult> AssignByPnAsync(AssignByPnRequest request, CancellationToken ct = default); Task<PermitOperationResult> AssignByPnAsync(AssignByPnRequest request, CancellationToken ct = default);
Task<IReadOnlyList<string>> GetOrderDatesAsync(CancellationToken ct = default); Task<IReadOnlyList<string>> GetOrderDatesAsync(CancellationToken ct = default);
@ -53,18 +52,6 @@ public sealed class DestinationService(
public Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default) => repo.GetCompaniesAsync(ct); public Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default) => repo.GetCompaniesAsync(ct);
public Task<IReadOnlyList<long>> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default) => repo.GetCompanyLocationsAsync(scac, ct); public Task<IReadOnlyList<long>> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default) => repo.GetCompanyLocationsAsync(scac, ct);
public async Task<PermitOperationResult> 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<PermitOperationResult> AssignByPnAsync(AssignByPnRequest r, CancellationToken ct = default) public async Task<PermitOperationResult> AssignByPnAsync(AssignByPnRequest r, CancellationToken ct = default)
{ {
new AssignByPnValidator().ValidateAndThrow(r); new AssignByPnValidator().ValidateAndThrow(r);

View File

@ -1,5 +1,6 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Globalization; using System.Globalization;
using System.Security.Cryptography;
using System.Text; using System.Text;
using FluentValidation; using FluentValidation;
using NTP.Application.Abstractions; using NTP.Application.Abstractions;
@ -35,16 +36,20 @@ public interface IDistributionService
} }
/// <summary>Per-user position in the company queue between two "distribute companies" runs (legacy session.QueueStart).</summary> /// <summary>Per-user position in the company queue between two "distribute companies" runs (legacy session.QueueStart).</summary>
internal static class DistributionCursor public static class DistributionCursor
{ {
private static readonly ConcurrentDictionary<string, long> Positions = new(StringComparer.OrdinalIgnoreCase); private static readonly ConcurrentDictionary<string, long> Positions = new(StringComparer.OrdinalIgnoreCase);
public static long Get(string user) => Positions.GetValueOrDefault(user, 1); public static long Get(string user) => Positions.GetValueOrDefault(user, 1);
public static void Set(string user, long value) => Positions[user] = value; public static void Set(string user, long value) => Positions[user] = value;
/// <summary>Legacy kept it in the session, so every new sign-in starts again from 1.</summary>
public static void Reset(string user) => Positions.TryRemove(user, out _);
} }
public sealed class DistributionService( public sealed class DistributionService(
IDistributionRepository repo, IDistributionRepository repo,
IDestinationRepository destinations, IDestinationRepository destinations,
IDestinationService destinationLookup,
IPermitRepository permits, IPermitRepository permits,
IPhoneEventRepository phoneRepo, IPhoneEventRepository phoneRepo,
IPermitService permitService, IPermitService permitService,
@ -59,6 +64,8 @@ public sealed class DistributionService(
// ------------------------------------------------------------------------------------------------ distributePackedBulk // ------------------------------------------------------------------------------------------------ distributePackedBulk
private static BusinessException StateChanged() => new("PERMIT_BAD_STATE", "حالة الارسالية غير صحيحة");
private sealed record ReleaseOutcome(string ErrorMsg, long? Scac = null, string? CargoLabel = null); private sealed record ReleaseOutcome(string ErrorMsg, long? Scac = null, string? CargoLabel = null);
public async Task<PermitOperationResult> DistributeAsync(DistributeRequest r, CancellationToken ct = default) public async Task<PermitOperationResult> DistributeAsync(DistributeRequest r, CancellationToken ct = default)
@ -137,12 +144,18 @@ public sealed class DistributionService(
return true; return true;
}, ct); }, ct);
await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS", new Dictionary<string, object?> { ["NOTIFICATIONARY"] = ownerNotes }, ct); // the queue position is saved first: the distribution is already committed, so nothing after this may undo it
await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_COMP", companyNotes, ct);
if (cat.Request is "BULK_COMP" or "BULK_GALLAB_COMP") if (cat.Request is "BULK_COMP" or "BULK_GALLAB_COMP")
DistributionCursor.Set(user.UserId, companyCounter == 0 ? start + queueAvailable : 1); 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<string, object?> { ["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}", return PermitOperationResult.Ok($"تم توزيع {companyCounter} شركات - {ownerCounter} أفراد ، من أصل{queueAvailable}",
data: new Dictionary<string, object?> { ["companies"] = companyCounter, ["owners"] = ownerCounter, ["available"] = queueAvailable }); data: new Dictionary<string, object?> { ["companies"] = companyCounter, ["owners"] = ownerCounter, ["available"] = queueAvailable });
} }
@ -176,7 +189,7 @@ public sealed class DistributionService(
return new("noDist"); 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); var d = await destinations.GetOrderDetailsAsync(order.Id, ct);
await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
$"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: ct); $"تحميل: {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", "لا توجد طلبيات متاحة"); 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); var d = await destinations.GetOrderDetailsAsync(orderId, token);
await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
$"تحميل: {d?.Location} / {d?.CargoType}", ct: token); $"تحميل: {d?.Location} / {d?.CargoType}", ct: token);
} }
else 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); await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token);
} }
return true; return true;
@ -240,6 +253,11 @@ public sealed class DistributionService(
if (permit.ShipmentStatusCode != PermitStatus.Open) if (permit.ShipmentStatusCode != PermitStatus.Open)
throw new BusinessException("PERMIT_BAD_STATE", "حالة الارسالية غير صحيحة"); 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 order = await repo.GetOrderForManualAsync(r.Locations, ct) ?? throw new NotFoundException("Order", r.Locations);
var d = await destinations.GetOrderDetailsAsync(r.Locations, ct); var d = await destinations.GetOrderDetailsAsync(r.Locations, ct);
var orderDate = PermitDates.ParseLegacy(r.OrderDate) ?? DateTime.Today; var orderDate = PermitDates.ParseLegacy(r.OrderDate) ?? DateTime.Today;
@ -255,7 +273,7 @@ public sealed class DistributionService(
if (order.Ct == GrainsCargo.BulkGallab && scac != options.BadiyaScac) if (order.Ct == GrainsCargo.BulkGallab && scac != options.BadiyaScac)
await repo.IncrementCompanyQueueAsync(scac, "GALLAB", "COMP", token); 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, await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
$"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: token); $"تحميل: {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)) 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); var d = await destinations.GetOrderDetailsAsync(order.Id, token);
await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
$"تحميل: {d?.Location} / {d?.CargoType}", ct: token); $"تحميل: {d?.Location} / {d?.CargoType}", ct: token);
return true; return true;
}, ct); }, ct);
if (!changed) continue;
done++; done++;
if (done >= r.Count) break; if (done >= r.Count) break;
} }
@ -320,7 +339,7 @@ public sealed class DistributionService(
?? throw new BusinessException("TN_INVALID", "TN is invalid"); ?? throw new BusinessException("TN_INVALID", "TN is invalid");
await uow.ExecuteInTransactionAsync(async token => 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); await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token);
return true; return true;
}, ct); }, ct);
@ -430,6 +449,7 @@ public sealed class DistributionService(
public async Task<PermitOperationResult> SendAutoCallFileAsync(AutoCallRequest r, CancellationToken ct = default) public async Task<PermitOperationResult> SendAutoCallFileAsync(AutoCallRequest r, CancellationToken ct = default)
{ {
// staff choose the company, company users are limited to their own (GrainsFactoryWeb.autoCallService2) // 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 company = user.IsCompany(options) ? user.CompanyCodeNo()?.ToString(CultureInfo.InvariantCulture) : r.CompanyCode;
var filter = r with { CompanyCode = company }; var filter = r with { CompanyCode = company };
var tender = PermitService.ParseTenderOrder(r.TenderOrder); var tender = PermitService.ParseTenderOrder(r.TenderOrder);
@ -441,10 +461,13 @@ public sealed class DistributionService(
: PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي"); : PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي");
} }
public async Task<PermitOperationResult> TriggerIvrAsync(CancellationToken ct = default) => public async Task<PermitOperationResult> TriggerIvrAsync(CancellationToken ct = default) => await autoCall.TriggerIvrAsync(ct) switch
await autoCall.TriggerIvrAsync(ct) {
? PermitOperationResult.Ok(PermitOperationResult.DefaultOk) IvrTriggerResult.Done => PermitOperationResult.Ok(PermitOperationResult.DefaultOk),
: PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي"); IvrTriggerResult.Started => PermitOperationResult.Ok("بدأ الاتصال الصوتي وقد تستغرق العملية عدة دقائق"),
IvrTriggerResult.Busy => PermitOperationResult.Fail("IVR_RUNNING", "الاتصال الصوتي قيد التنفيذ حاليا، يرجى الانتظار حتى ينتهي"),
_ => PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي")
};
/// <summary>writeCallingDriverFile: CSV consumed by the auto dialer.</summary> /// <summary>writeCallingDriverFile: CSV consumed by the auto dialer.</summary>
internal static byte[] BuildCallingFile(IReadOnlyList<AutoCallDriverRow> rows) internal static byte[] BuildCallingFile(IReadOnlyList<AutoCallDriverRow> rows)
@ -465,8 +488,13 @@ public sealed class DistributionService(
return new UTF8Encoding(false).GetBytes(sb.ToString()); return new UTF8Encoding(false).GetBytes(sb.ToString());
} }
public bool IsValidDialerApiKey(string? key) => public bool IsValidDialerApiKey(string? key)
!string.IsNullOrEmpty(options.AutoCall.ApiKey) && string.Equals(key, options.AutoCall.ApiKey, StringComparison.Ordinal); {
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)));
}
/// <summary>autoCallResponse.cfc autoDail: CONFIRMED -> phone accept, POSTPONED -> phone reject for N days, NO_ANSWER -> postpone one day.</summary> /// <summary>autoCallResponse.cfc autoDail: CONFIRMED -> phone accept, POSTPONED -> phone reject for N days, NO_ANSWER -> postpone one day.</summary>
public async Task<AutoCallCallbackResult> HandleDialerCallbackAsync(AutoCallResponse r, CancellationToken ct = default) public async Task<AutoCallCallbackResult> HandleDialerCallbackAsync(AutoCallResponse r, CancellationToken ct = default)
@ -485,12 +513,15 @@ public sealed class DistributionService(
break; break;
case "POSTPONED": 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); await permitService.PhoneRejectCoreAsync(permitId.Value, $" تم التأجيل {days} يوم", days, "SYSTEM", ct);
break; break;
} }
case "NO_ANSWER": 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"); if (await phoneRepo.HasPhoneEventTodayAsync(permitId.Value, ct)) return new("200", "ALREADY_HAS_PHONE_EVENT");
await NoAnswerAsync(permit!, ct); await NoAnswerAsync(permit!, ct);
return new("200", "NO_ANSWER"); 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) private async Task NoAnswerAsync(PermitRow permit, CancellationToken ct)
{ {
var order = permit.Scrn is long o ? await destinations.GetOrderAsync(o, ct) : null; 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, await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.NoAnswer,
"تم التأجيل ليوم واحد", ct: token); "تم التأجيل ليوم واحد", 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 events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, PermitStatus.Open, PermitEventType.Override, ct: token);
await phoneRepo.InsertBlacklistAsync(new NewBlacklistEntry await phoneRepo.InsertBlacklistAsync(new NewBlacklistEntry
{ {

View File

@ -77,6 +77,12 @@ public sealed class AutoCallOptions
public string ApiKey { get; set; } = string.Empty; public string ApiKey { get; set; } = string.Empty;
public int TimeoutSeconds { get; set; } = 30; public int TimeoutSeconds { get; set; } = 30;
/// <summary>How long the voice-call button waits for the IVR service before it reports "started" (the service answers only when it has dialed everybody).</summary>
public int IvrWaitSeconds { get; set; } = 20;
/// <summary>Longest time one IVR call may keep running in the background before it is abandoned.</summary>
public int IvrTimeoutMinutes { get; set; } = 15;
} }
/// <summary>Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage).</summary> /// <summary>Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage).</summary>

View File

@ -75,7 +75,7 @@ public interface IDistributionRepository
Task<PermitRow?> GetOpenPermitWithFirmsAsync(string pn, long scac, CancellationToken ct = default); Task<PermitRow?> GetOpenPermitWithFirmsAsync(string pn, long scac, CancellationToken ct = default);
Task<IReadOnlyList<long>> GetAllowedLocationsForReleaseAsync(PermitRow permit, long scac, long badiyaScac, CancellationToken ct = default); Task<IReadOnlyList<long>> GetAllowedLocationsForReleaseAsync(PermitRow permit, long scac, long badiyaScac, CancellationToken ct = default);
Task<NextOrderPick?> GetNextOrderAsync(IReadOnlyList<long> locations, string cargoCode, string? queueType, CancellationToken ct = default); Task<NextOrderPick?> GetNextOrderAsync(IReadOnlyList<long> locations, string cargoCode, string? queueType, CancellationToken ct = default);
Task SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default); Task<int> SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default);
Task UpdateLastPermitAsync(long orderId, long badiyaScac, CancellationToken ct = default); Task UpdateLastPermitAsync(long orderId, long badiyaScac, CancellationToken ct = default);
Task SetLastPermitAsync(long orderId, long permitId, CancellationToken ct = default); Task SetLastPermitAsync(long orderId, long permitId, CancellationToken ct = default);
Task DeletePendingDistributionAsync(long permitId, string tn, long? orderId, CancellationToken ct = default); Task DeletePendingDistributionAsync(long permitId, string tn, long? orderId, CancellationToken ct = default);
@ -86,10 +86,10 @@ public interface IDistributionRepository
Task<PermitRow?> GetFirstOpenPermitByTnAsync(string tn, string? cargoType, CancellationToken ct = default); Task<PermitRow?> GetFirstOpenPermitByTnAsync(string tn, string? cargoType, CancellationToken ct = default);
Task<IReadOnlyList<NextOrderPick>> GetNextOrdersForTruckAsync(string tn, CancellationToken ct = default); Task<IReadOnlyList<NextOrderPick>> GetNextOrdersForTruckAsync(string tn, CancellationToken ct = default);
Task<bool> IsLocationAllowedForCompanyAsync(long scac, long location, CancellationToken ct = default); Task<bool> IsLocationAllowedForCompanyAsync(long scac, long location, CancellationToken ct = default);
Task SetRequestedAsync(long permitId, CancellationToken ct = default); Task<int> SetRequestedAsync(long permitId, CancellationToken ct = default);
Task<OrderForPermitRow?> GetOrderForManualAsync(long orderId, CancellationToken ct = default); Task<OrderForPermitRow?> GetOrderForManualAsync(long orderId, CancellationToken ct = default);
Task<long?> PickQueueIdAsync(long scac, string code, string? type, CancellationToken ct = default); Task<long?> PickQueueIdAsync(long scac, string code, string? type, CancellationToken ct = default);
Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default); Task<int> SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default);
Task<IReadOnlyList<PermitRow>> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default); Task<IReadOnlyList<PermitRow>> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default);
Task<NextOrderPick?> GetAnyNextOrderAsync(CancellationToken ct = default); Task<NextOrderPick?> GetAnyNextOrderAsync(CancellationToken ct = default);

View File

@ -96,6 +96,9 @@ public interface IPermitRepository
Task SetStatusAsync(long id, string newStatus, string userId, CancellationToken ct = default); Task SetStatusAsync(long id, string newStatus, string userId, CancellationToken ct = default);
Task ResetTruckValidationAsync(string tn, string userId, CancellationToken ct = default); Task ResetTruckValidationAsync(string tn, string userId, CancellationToken ct = default);
Task ResetToOpenAsync(long id, string userId, CancellationToken ct = default); Task ResetToOpenAsync(long id, string userId, CancellationToken ct = default);
/// <summary>NO_ANSWER of the dialer (autoCallResponse.cfc): only the status goes back to OPEN and the order link (SCRN) is cleared; nothing else changes.</summary>
Task ReopenClearingOrderAsync(long id, CancellationToken ct = default);
Task RevokeNextOpenPermitsAsync(long permitId, string userId, CancellationToken ct = default); Task RevokeNextOpenPermitsAsync(long permitId, string userId, CancellationToken ct = default);
Task<ActiveConflictRow?> FindOpenConflictForReactivationAsync(PermitRow permit, CancellationToken ct = default); Task<ActiveConflictRow?> FindOpenConflictForReactivationAsync(PermitRow permit, CancellationToken ct = default);
Task<PermitRow?> FindClosablePermitAsync(string pn, CancellationToken ct = default); Task<PermitRow?> FindClosablePermitAsync(string pn, CancellationToken ct = default);

View File

@ -203,8 +203,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);
// legacy: an order already ACCPT / RESD cannot be submitted again. // 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 is PermitStatus.Released or PermitStatus.Accepted) if (permit.ShipmentStatusCode != PermitStatus.Requested)
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: true, ct); await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: true, ct);
@ -294,6 +294,7 @@ public sealed class PermitService(
public async Task<PermitOperationResult> AcceptAsync(long id, CancellationToken ct = default) public async Task<PermitOperationResult> AcceptAsync(long id, CancellationToken ct = default)
{ {
EnsureStaff();
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);
if (permit.ShipmentStatusCode != PermitStatus.Planned) if (permit.ShipmentStatusCode != PermitStatus.Planned)
@ -331,6 +332,7 @@ public sealed class PermitService(
public async Task<PermitOperationResult> RevokeAsync(long id, CancellationToken ct = default) public async Task<PermitOperationResult> RevokeAsync(long id, CancellationToken ct = default)
{ {
EnsureStaff();
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);
if (permit.ShipmentStatusCode != PermitStatus.Planned) if (permit.ShipmentStatusCode != PermitStatus.Planned)
@ -348,6 +350,7 @@ public sealed class PermitService(
public async Task<PermitOperationResult> RevokeAcceptedAsync(long id, CancellationToken ct = default) public async Task<PermitOperationResult> RevokeAcceptedAsync(long id, CancellationToken ct = default)
{ {
EnsureStaff();
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);
if (permit.ShipmentStatusCode is not (PermitStatus.Accepted or PermitStatus.Released)) if (permit.ShipmentStatusCode is not (PermitStatus.Accepted or PermitStatus.Released))
@ -383,6 +386,7 @@ public sealed class PermitService(
public async Task<PermitOperationResult> CancelOrderAsync(long id, ReasonRequest r, CancellationToken ct = default) public async Task<PermitOperationResult> CancelOrderAsync(long id, ReasonRequest r, CancellationToken ct = default)
{ {
EnsureOperator();
new ReasonValidator().ValidateAndThrow(r); new ReasonValidator().ValidateAndThrow(r);
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); 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. // 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<PermitOperationResult> RevokePermitAsync(long id, ReasonRequest r, CancellationToken ct = default) public async Task<PermitOperationResult> RevokePermitAsync(long id, ReasonRequest r, CancellationToken ct = default)
{ {
EnsureOperator();
new ReasonValidator().ValidateAndThrow(r); new ReasonValidator().ValidateAndThrow(r);
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
// Deviation: legacy button exists for OPEN only (action 167); enforced here. // Deviation: legacy button exists for OPEN only (action 167); enforced here.
@ -419,7 +424,10 @@ public sealed class PermitService(
public async Task<PermitOperationResult> ReactivateAsync(long id, CancellationToken ct = default) public async Task<PermitOperationResult> 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); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
if (permit.CompanyCode != options.BadiyaScac) throw NotAllowed();
if (permit.ShipmentStatusCode != PermitStatus.Revoked) if (permit.ShipmentStatusCode != PermitStatus.Revoked)
throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة");
@ -439,6 +447,7 @@ public sealed class PermitService(
public async Task<PermitOperationResult> CancelGrainsPermitAsync(long id, CancellationToken ct = default) public async Task<PermitOperationResult> CancelGrainsPermitAsync(long id, CancellationToken ct = default)
{ {
EnsureOperator();
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
if (permit.ShipmentStatusCode != PermitStatus.Released) if (permit.ShipmentStatusCode != PermitStatus.Released)
throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة");
@ -470,11 +479,15 @@ public sealed class PermitService(
// ------------------------------------------------------------------------------------------------ phone events // ------------------------------------------------------------------------------------------------ phone events
public Task<PermitOperationResult> PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default) => public Task<PermitOperationResult> PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default)
PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct); {
EnsureOperator(); // the dialer callback uses PhoneAcceptCoreAsync directly, not this entry point
return PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct);
}
public Task<PermitOperationResult> PhoneRejectAsync(long id, PhoneRejectRequest r, CancellationToken ct = default) public Task<PermitOperationResult> PhoneRejectAsync(long id, PhoneRejectRequest r, CancellationToken ct = default)
{ {
EnsureOperator();
new PhoneRejectValidator().ValidateAndThrow(r); new PhoneRejectValidator().ValidateAndThrow(r);
return PhoneRejectCoreAsync(id, r.Reason.Trim(), r.ExpiryDays, user.UserId, ct); return PhoneRejectCoreAsync(id, r.Reason.Trim(), r.ExpiryDays, user.UserId, ct);
} }
@ -625,11 +638,26 @@ public sealed class PermitService(
private IReadOnlyList<string> ActionsFor(string? status, long? companyCode) => private IReadOnlyList<string> ActionsFor(string? status, long? companyCode) =>
PermitActionRules.For(status, companyCode, user.IsCompany(options), user.IsInAnyRole(GrainsRoles.Operators.Split(',')), 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", "غير مصرح لك بهذه العملية");
/// <summary>Staff-only actions (phone confirmation, cancel / revoke): back-office operators, never a company user or dispatcher.</summary>
private void EnsureOperator()
{
if (user.IsCompany(options) || !user.IsInAnyRole(GrainsRoles.Operators.Split(','))) throw NotAllowed();
}
/// <summary>Confirming a turn (accept / reject / cancel the confirmation) is back-office work: legacy actions 74, 85, 88 are not held by company dispatchers.</summary>
private void EnsureStaff()
{
if (user.IsCompany(options)) throw NotAllowed();
}
private void EnsureCompanyAccess(long? permitCompany) 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", "لا تملك صلاحية على هذه الإرسالية"); throw new ForbiddenException("PERMIT_FOREIGN_COMPANY", "لا تملك صلاحية على هذه الإرسالية");
} }

View File

@ -11,16 +11,16 @@ namespace NTP.Application.Grains.Permits;
public static class GrainsRoles public static class GrainsRoles
{ {
/// <summary>Back-office operators: distribution, phone confirmation, manual operations, queue creation.</summary> /// <summary>Back-office operators: distribution, phone confirmation, manual operations, queue creation.</summary>
public const string Operators = "SU,GPO,GNSU,GNCO,GTO"; public const string Operators = "SU,GPO,GNSU,GNCO,GTO,CO";
/// <summary>Weighbridge / gate users plus operators.</summary> /// <summary>Weighbridge / gate users plus operators.</summary>
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";
/// <summary>ConvertToResd button: legacy checks role SU or GPO only.</summary> /// <summary>ConvertToResd button: legacy checks role SU or GPO only.</summary>
public const string ConvertToResd = "SU,GPO"; public const string ConvertToResd = "SU,GPO";
/// <summary>Supervisors: configuration of destinations, activation of orders, absence feature.</summary> /// <summary>Supervisors: configuration of destinations, activation of orders, absence feature.</summary>
public const string Supervisors = "SU,GPO,GNSU,GTO"; public const string Supervisors = "SU,GPO,GNSU,GTO,CO";
} }
/// <summary>Helpers that replace legacy session.* lookups.</summary> /// <summary>Helpers that replace legacy session.* lookups.</summary>
@ -100,8 +100,10 @@ public static class PermitActionRules
if (isCompany) if (isCompany)
{ {
// Company users never see the staff-only phone / cancel / revoke / reactivate buttons. // Company users never see the staff-only buttons. Confirming (accept / reject / cancel the confirmation) is staff work in
a.RemoveAll(x => x is PhoneAccept or PhoneReject or CancelOrder or RevokePermit or Reactivate or ConvertToResd); // 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; return a;
} }
@ -145,8 +147,21 @@ public interface IAutoCallGatewayService
/// <summary>POSTs {"TYPE":"TEST","FILE":base64} to the configured dialer URL; false when not reachable / not 200.</summary> /// <summary>POSTs {"TYPE":"TEST","FILE":base64} to the configured dialer URL; false when not reachable / not 200.</summary>
Task<bool> SendCallFileAsync(byte[] csv, CancellationToken ct = default); Task<bool> SendCallFileAsync(byte[] csv, CancellationToken ct = default);
/// <summary>Calls the IVR web service (callAPI).</summary> /// <summary>Calls the IVR web service (callAPI). That call dials every requested truck one by one and can take minutes.</summary>
Task<bool> TriggerIvrAsync(CancellationToken ct = default); Task<IvrTriggerResult> TriggerIvrAsync(CancellationToken ct = default);
}
/// <summary>Outcome of <see cref="IAutoCallGatewayService.TriggerIvrAsync"/>.</summary>
public enum IvrTriggerResult
{
/// <summary>The IVR service answered OK.</summary>
Done,
/// <summary>The IVR service accepted the call and is still dialing (it answers when it has finished).</summary>
Started,
/// <summary>A previous call is still running: a second one would dial every truck twice.</summary>
Busy,
/// <summary>Disabled, not configured, unreachable or refused.</summary>
Failed
} }
/// <summary>Reads new rows from the external weighbridge database (legacy datasource GrainsWeighbridge).</summary> /// <summary>Reads new rows from the external weighbridge database (legacy datasource GrainsWeighbridge).</summary>

View File

@ -21,7 +21,7 @@ public sealed class BlacklistService(
IUnitOfWork unitOfWork, IUnitOfWork unitOfWork,
ICurrentUser user) : IBlacklistService ICurrentUser user) : IBlacklistService
{ {
private static readonly string[] CancelRoles = ["GNSU", "GNCO", "GTO"]; private static readonly string[] CancelRoles = ["GNSU", "GNCO", "GTO", "CO"];
public async Task<PagedResult<BlacklistGridRowDto>> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct) public async Task<PagedResult<BlacklistGridRowDto>> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct)
{ {

View File

@ -61,7 +61,7 @@ public sealed class RegistryAccessService(
public void EnsureCompanyAccess(long? recordTcscac) public void EnsureCompanyAccess(long? recordTcscac)
{ {
if (IsCompanyUser && recordTcscac != CompanyCodeNo) if (IsCompanyUser && (CompanyCodeNo is null || recordTcscac != CompanyCodeNo))
throw new NotFoundException("Registry record", "-"); throw new NotFoundException("Registry record", "-");
} }
@ -87,9 +87,9 @@ public sealed class RegistryAccessService(
CanAcceptTrailer = await HasActionAsync(RegistryActions.AcceptTrailer, ct), CanAcceptTrailer = await HasActionAsync(RegistryActions.AcceptTrailer, ct),
CanAcceptDriver = await HasActionAsync(RegistryActions.AcceptDriver, ct), CanAcceptDriver = await HasActionAsync(RegistryActions.AcceptDriver, ct),
CanManageDestinations = await HasActionAsync(RegistryActions.Destinations, ct), CanManageDestinations = await HasActionAsync(RegistryActions.Destinations, ct),
CanExportTruckReport = user.IsInAnyRole("GTO", "GOO", "GNAC"), CanExportTruckReport = user.IsInAnyRole("GTO", "CO", "GOO", "GNAC"),
CanExportDriverReport = user.IsInAnyRole("GTO", "GOO"), CanExportDriverReport = user.IsInAnyRole("GTO", "CO", "GOO"),
CanCancelBlacklist = user.IsInAnyRole("GNSU", "GNCO", "GTO") CanCancelBlacklist = user.IsInAnyRole("GNSU", "GNCO", "GTO", "CO")
}; };
} }
} }

View File

@ -15,8 +15,23 @@ public interface IRegistryAttachmentService
} }
public sealed class RegistryAttachmentService( public sealed class RegistryAttachmentService(
IRegistryRepository repository, IRegistryFileStoreService store, IRegistrySettingsService settings) : IRegistryAttachmentService IRegistryRepository repository, IRegistryFileStoreService store, IRegistrySettingsService settings, IRegistryAccessService access)
: IRegistryAttachmentService
{ {
/// <summary>GRAINS_FILES.ORIGINALNAME is VARCHAR2(100).</summary>
public const int OriginalNameMaxBytes = 100;
/// <summary>Shortens a file name to the column size (UTF-8 bytes), keeping the extension.</summary>
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 KindTruck = "truck";
public const string KindTrailer = "trailer"; public const string KindTrailer = "trailer";
public const string KindDriver = "driver"; public const string KindDriver = "driver";
@ -59,7 +74,7 @@ public sealed class RegistryAttachmentService(
?? throw new BusinessException(RegistryErrors.AttachmentMissing, RegistryMessages.AttachmentsIncomplete); ?? throw new BusinessException(RegistryErrors.AttachmentMissing, RegistryMessages.AttachmentsIncomplete);
var ext = Path.GetExtension(original); var ext = Path.GetExtension(original);
var stored = $"{Guid.NewGuid():N}{ext.ToLowerInvariant()}"; 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); await store.PromoteAsync(id, folder, stored, ct);
} }
} }
@ -76,6 +91,14 @@ public sealed class RegistryAttachmentService(
var (type, folder) = Map(kind); var (type, folder) = Map(kind);
// The name must be a registered file of this type (also keeps path traversal out). // 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); 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); 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); return new RegistryDownload(stream, ContentTypeOf(row.FileName), string.IsNullOrWhiteSpace(row.OriginalName) ? row.FileName : row.OriginalName);
} }

View File

@ -182,9 +182,36 @@ public static class RegistryRules
public static DateTime BlacklistExpiry(DateTime now, int days, int shiftStartHour, int shiftEndHour) => public static DateTime BlacklistExpiry(DateTime now, int days, int shiftStartHour, int shiftEndHour) =>
now.AddHours(-(24 + shiftStartHour)).Date.AddDays(days).AddHours(shiftEndHour); now.AddHours(-(24 + shiftStartHour)).Date.AddDays(days).AddHours(shiftEndHour);
/// <summary>Remarks text stored with the entry (legacy appends the automatic release date, mm/dd/yyyy HH:mm).</summary> /// <summary>GRAINSBLACKLIST.REMARKS is VARCHAR2(500): the limit is in bytes, and an Arabic letter takes two.</summary>
public static string BlacklistRemarks(string? remarks, DateTime expiry) => public const int BlacklistRemarksMaxBytes = 500;
$"{remarks}، سيتم فك الانتظار بشكل تلقائي بتاريخ {expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)}";
/// <summary>Cuts a text to at most <paramref name="maxBytes"/> UTF-8 bytes without splitting a character.</summary>
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();
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>Parses the legacy "start,end" application setting; falls back to the defaults.</summary> /// <summary>Parses the legacy "start,end" application setting; falls back to the defaults.</summary>
public static (int Start, int End) ParseShiftHours(string? setting, int defaultStart = 0, int defaultEnd = 24) public static (int Start, int End) ParseShiftHours(string? setting, int defaultStart = 0, int defaultEnd = 24)

View File

@ -92,9 +92,9 @@ public static class RegistryValidation
MaxLen(f, nameof(r.ChasesNumber), r.ChasesNumber, 20); MaxLen(f, nameof(r.ChasesNumber), r.ChasesNumber, 20);
MaxLen(f, nameof(r.OwnerName), r.OwnerName, 50); MaxLen(f, nameof(r.OwnerName), r.OwnerName, 50);
MaxLen(f, nameof(r.OwnerNnpn), r.OwnerNnpn, 20); MaxLen(f, nameof(r.OwnerNnpn), r.OwnerNnpn, 20);
MaxLen(f, nameof(r.Color), r.Color, 30); MaxLen(f, nameof(r.Color), r.Color, 20);
MaxLen(f, nameof(r.Model), r.Model, 30); MaxLen(f, nameof(r.Model), r.Model, 20);
MaxLen(f, nameof(r.HeadType), r.HeadType, 30); MaxLen(f, nameof(r.HeadType), r.HeadType, 20);
MaxLen(f, nameof(r.PhoneNumber), r.PhoneNumber, 10); MaxLen(f, nameof(r.PhoneNumber), r.PhoneNumber, 10);
Digits(f, nameof(r.PhoneNumber), r.PhoneNumber, 10); Digits(f, nameof(r.PhoneNumber), r.PhoneNumber, 10);
return f; return f;

View File

@ -46,7 +46,7 @@ internal sealed class TcsPermitGatewayService(IGrainsPermitsSettingsService sett
if (kids.Count < 3) return new(null, null, "خطأ في الاتصال<br>استجابة غير متوقعة"); if (kids.Count < 3) return new(null, null, "خطأ في الاتصال<br>استجابة غير متوقعة");
return new(kids[0].Value.Trim(), kids[2].Value.Trim(), string.Empty); // PN, status; kids[1] = error codes (CheckWSError) 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"); logger.LogError(ex, "TCS createPermit failed");
return new(null, null, "خطأ في الاتصال<br>" + ex.Message); return new(null, null, "خطأ في الاتصال<br>" + ex.Message);
@ -66,7 +66,7 @@ internal sealed class TcsPermitGatewayService(IGrainsPermitsSettingsService sett
string V(IReadOnlyList<XElement> l, int i) => i < l.Count ? l[i].Value.Trim() : string.Empty; string V(IReadOnlyList<XElement> 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)); 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"); logger.LogError(ex, "TCS getFopDetail failed");
return Empty("خطأ في الاتصال<br>" + ex.Message); return Empty("خطأ في الاتصال<br>" + 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); 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); 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 // legacy notifications were fire-and-forget; a failure never rolls back the business operation
logger.LogWarning(ex, "Notification {Template} failed", template); logger.LogWarning(ex, "Notification {Template} failed", template);
@ -160,36 +160,95 @@ 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); 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; 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"); logger.LogWarning(ex, "Auto call dialer unreachable");
return false; return false;
} }
} }
public async Task<bool> 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<IvrTriggerResult> TriggerIvrAsync(CancellationToken ct = default)
{ {
var o = settings.Value.AutoCall; 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 try
{ {
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); HttpRequestMessage req;
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds))); if (o.IvrUrl.EndsWith("?wsdl", StringComparison.OrdinalIgnoreCase))
// 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. // legacy: createObject("webservice", "...callivr.cfc?wsdl").callAPI() -> SOAP 1.1 request to the CFC itself
var url = o.IvrUrl.EndsWith("?wsdl", StringComparison.OrdinalIgnoreCase) var endpoint = o.IvrUrl[..^"?wsdl".Length];
? o.IvrUrl[..^"?wsdl".Length] + "?method=callAPI" var ns = await IvrNamespaceAsync(o, ct);
: o.IvrUrl; var envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
using var res = await Http.GetAsync(url, cts.Token); + $"<soapenv:Body><ns:callAPI xmlns:ns=\"{System.Security.SecurityElement.Escape(ns)}\" soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"/></soapenv:Body></soapenv:Envelope>";
return res.IsSuccessStatusCode; req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new StringContent(envelope, Encoding.UTF8, "text/xml") };
req.Headers.TryAddWithoutValidation("SOAPAction", "\"\"");
} }
catch (Exception ex) when (ex is not OperationCanceledException) 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 (!ct.IsCancellationRequested) // includes timeouts (TaskCanceledException)
{ {
logger.LogWarning(ex, "IVR unreachable"); logger.LogWarning(ex, "IVR unreachable");
return false; return IvrTriggerResult.Failed;
}
finally
{
if (!handedOver) Interlocked.Exchange(ref _ivrRunning, 0);
} }
} }
/// <summary>The service namespace is whatever its WSDL says (ColdFusion derives it from the folder); fetched once.</summary>
private async Task<string> 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;
} }
}
/// <summary> /// <summary>
/// External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO). The database engine of that datasource is not known /// External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO). The database engine of that datasource is not known

View File

@ -155,7 +155,8 @@ internal sealed class DistributionRepository(IDbSession session, ILogger<Distrib
p.Add("Ct", permitCargoType); p.Add("Ct", permitCargoType);
p.Add("Badiya", badiyaScac); p.Add("Badiya", badiyaScac);
p.Add("QCode", gallabCompany ? "GALLAB" : permitCargoType); p.Add("QCode", gallabCompany ? "GALLAB" : permitCargoType);
p.Add("BlCategory", "DELAY_" + distributionCode); // :BlCategory exists in the SQL only for companies other than Badiya; an unused bind makes Oracle fail (ORA-01006)
if (shares.Any(x => 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 ("); 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++) for (var i = 0; i < shares.Count; i++)
@ -171,11 +172,12 @@ internal sealed class DistributionRepository(IDbSession session, ILogger<Distrib
sb.Append($""" sb.Append($"""
SELECT * FROM ( SELECT * FROM (
SELECT RANK() OVER (ORDER BY p.pn) r, p.id, p.pn, p.companycode AS scac, p.tn, p.firms AS alloweddestinations SELECT RANK() OVER (ORDER BY p.pn) r, p.id, p.pn, p.companycode AS scac, p.tn, p.firms AS alloweddestinations
FROM PERMITS p, FROM PERMITS p, PERMITS gc,
(SELECT MAX(id) id, tn FROM PERMITS p2 (SELECT MAX(id) id, tn FROM PERMITS p2
WHERE p2.domain = 'GN' AND p2.isactive = 'Y' AND p2.tt NOT IN (:Dist) WHERE p2.domain = 'GN' AND p2.isactive = 'Y' AND p2.tt NOT IN (:Dist)
AND p2.shipmentstatuscode NOT IN ('OPEN','CLOSE','RVKD') GROUP BY tn) pp AND p2.shipmentstatuscode NOT IN ('OPEN','CLOSE','RVKD') GROUP BY tn) pp
WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'OPEN' AND p.tn = pp.tn(+) AND pp.id IS NULL WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'OPEN' AND p.tn = pp.tn(+) AND pp.id IS NULL
AND gc.domain(+) = 'GC' AND gc.shipmentstatuscode(+) = 'REQST' AND gc.tn(+) = p.tn AND gc.id IS NULL
AND p.companycode = :Scac{i} AND p.isactive = 'Y'{tripper}{blacklist} AND p.companycode = :Scac{i} AND p.isactive = 'Y'{tripper}{blacklist}
AND p.tt = :Ct AND TO_NUMBER(p.firms) > 0) AND p.tt = :Ct AND TO_NUMBER(p.firms) > 0)
WHERE r <= :Cnt{i} WHERE r <= :Cnt{i}
@ -273,8 +275,8 @@ internal sealed class DistributionRepository(IDbSession session, ILogger<Distrib
""", new { Locs = locations.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray(), Ct = cargoCode, Type = queueType }, ct); """, new { Locs = locations.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray(), Ct = cargoCode, Type = queueType }, ct);
} }
public Task SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default) => ExecuteAsync( public Task<int> 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); "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(""" public Task UpdateLastPermitAsync(long orderId, long badiyaScac, CancellationToken ct = default) => ExecuteAsync("""
UPDATE GRAINSTENDERORDER t UPDATE GRAINSTENDERORDER t
@ -326,8 +328,8 @@ internal sealed class DistributionRepository(IDbSession session, ILogger<Distrib
await ExecuteScalarAsync<int>("SELECT COUNT(*) FROM GRAINS_COMPANIES_LOCATION t WHERE t.scac = :Scac AND t.locationid = :Loc", await ExecuteScalarAsync<int>("SELECT COUNT(*) FROM GRAINS_COMPANIES_LOCATION t WHERE t.scac = :Scac AND t.locationid = :Loc",
new { Scac = scac, Loc = location }, ct) > 0; new { Scac = scac, Loc = location }, ct) > 0;
public Task SetRequestedAsync(long permitId, CancellationToken ct = default) => public Task<int> SetRequestedAsync(long permitId, CancellationToken ct = default) =>
ExecuteAsync("UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST' WHERE p.id = :Id", new { Id = permitId }, ct); ExecuteAsync("UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST' WHERE p.id = :Id AND p.shipmentstatuscode = 'OPEN'", new { Id = permitId }, ct);
public async Task<OrderForPermitRow?> GetOrderForManualAsync(long orderId, CancellationToken ct = default) public async Task<OrderForPermitRow?> GetOrderForManualAsync(long orderId, CancellationToken ct = default)
{ {
@ -350,8 +352,9 @@ internal sealed class DistributionRepository(IDbSession session, ILogger<Distrib
""", new { Scac = scac, Code = code, Type = type }, ct); """, new { Scac = scac, Code = code, Type = type }, ct);
} }
public Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default) => ExecuteAsync(""" public Task<int> 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 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); """, new { OrderRef = orderId, Q = queueId, Id = permitId }, ct);
public async Task<IReadOnlyList<PermitRow>> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default) => public async Task<IReadOnlyList<PermitRow>> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default) =>

View File

@ -167,7 +167,7 @@ internal sealed class PermitRepository(IDbSession session, ILogger<PermitReposit
(await QueryFirstAsync<PermitDb>(PermitSelect + " WHERE p.id = :Id AND p.domain = 'GN'", new { Id = id }, ct))?.ToRow(); (await QueryFirstAsync<PermitDb>(PermitSelect + " WHERE p.id = :Id AND p.domain = 'GN'", new { Id = id }, ct))?.ToRow();
public async Task<PermitRow?> GetByPnAsync(string pn, CancellationToken ct = default) => public async Task<PermitRow?> GetByPnAsync(string pn, CancellationToken ct = default) =>
(await QueryFirstAsync<PermitDb>(PermitSelect + " WHERE TO_CHAR(p.pn) = :Pn ORDER BY p.id DESC", new { Pn = pn }, ct))?.ToRow(); (await QueryFirstAsync<PermitDb>(PermitSelect + " WHERE TO_CHAR(p.pn) = :Pn AND p.domain = 'GN' ORDER BY p.id DESC", new { Pn = pn }, ct))?.ToRow();
public Task<PermitInfoRow?> GetInfoAsync(long id, CancellationToken ct = default) => QueryFirstAsync<PermitInfoRow>(""" public Task<PermitInfoRow?> GetInfoAsync(long id, CancellationToken ct = default) => QueryFirstAsync<PermitInfoRow>("""
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, 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<PermitReposit
WHERE id = :Id WHERE id = :Id
""", new { UserId = userId, Id = id }, ct); """, new { UserId = userId, Id = id }, ct);
public Task ReopenClearingOrderAsync(long id, CancellationToken ct = default) => 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(""" 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 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' WHERE n.id > :Id AND n.domain = 'GN' AND n.shipmentstatuscode = 'OPEN'

View File

@ -1,6 +1,7 @@
using Dapper; using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NTP.Application.Grains.Permits; using NTP.Application.Grains.Permits;
using NTP.Application.Grains.Registry;
namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits;
@ -115,5 +116,6 @@ internal sealed class PhoneEventRepository(IDbSession session, ILogger<PhoneEven
WHERE eventtype IN ('PHRJCT','PHACCPT') AND permitid = :Pid AND TRUNC(eventdate) = TRUNC(SYSDATE) WHERE eventtype IN ('PHRJCT','PHACCPT') AND permitid = :Pid AND TRUNC(eventdate) = TRUNC(SYSDATE)
""", new { Pid = permitId }, ct) > 0; """, new { Pid = permitId }, ct) > 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);
} }

View File

@ -59,7 +59,7 @@ internal sealed class BlacklistRepository(IDbSession session, ILogger<BlacklistR
public async Task<long> InsertAsync(string category, string entityType, string entityId, string createdBy, DateTime expiry, string remarks, CancellationToken ct = default) public async Task<long> 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); p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output);
await ExecuteAsync(""" await ExecuteAsync("""
INSERT INTO GRAINSBLACKLIST INSERT INTO GRAINSBLACKLIST
@ -84,14 +84,14 @@ internal sealed class BlacklistRepository(IDbSession session, ILogger<BlacklistR
UPDATE GRAINSBLACKLIST UPDATE GRAINSBLACKLIST
SET STATUSCODE = 'DELETED', LASTUPDATEUSER = :UserId, LASTUPDATEDATE = SYSDATE, REMARKS = :Remarks SET STATUSCODE = 'DELETED', LASTUPDATEUSER = :UserId, LASTUPDATEDATE = SYSDATE, REMARKS = :Remarks
WHERE ID = :Id WHERE ID = :Id
""", new { UserId = user, Remarks = remarks, Id = id }, ct); """, new { UserId = user, Remarks = RegistryRules.FitBytes(remarks, RegistryRules.BlacklistRemarksMaxBytes), Id = id }, ct);
public Task DeleteDistributionLogAsync(long blacklistId, string remarks, CancellationToken ct = default) => public Task DeleteDistributionLogAsync(long blacklistId, string remarks, CancellationToken ct = default) =>
ExecuteAsync(""" ExecuteAsync("""
UPDATE TRUCK_DISTRIBUTION_LOG UPDATE TRUCK_DISTRIBUTION_LOG
SET STATUSCODE = 'DELETED', UPDATEDATE = SYSDATE, NOTES = :Notes SET STATUSCODE = 'DELETED', UPDATEDATE = SYSDATE, NOTES = :Notes
WHERE TO_CHAR(BLACKLISTID) = :BlacklistId AND STATUSCODE IN ('PENDING', 'RVKD') 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<int> ExpireDueAsync(CancellationToken ct = default) => public Task<int> ExpireDueAsync(CancellationToken ct = default) =>
ExecuteAsync(""" ExecuteAsync("""

View File

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

View File

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

View File

@ -192,4 +192,12 @@ public class PermissionTests
Assert.StartsWith("grains.", key); 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}");
}
} }

View File

@ -173,6 +173,24 @@ public class PermitActionRuleTests
Assert.Contains(PermitActionRules.Reactivate, PermitActionRules.For(PermitStatus.Revoked, 327, false, true, false, true, 327)); 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)); 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 public class PermitSupportTests

View File

@ -17,13 +17,28 @@ function displayToIso(text: string): string {
return dt.getFullYear() === y && dt.getMonth() === mo - 1 && dt.getDate() === d ? `${m[3]}-${m[2]}-${m[1]}` : ''; 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 { * Typed / pasted text -> dd/mm/yyyy as far as it goes. Digits only auto-insert the slashes (0101 -> 01/01); with slashes
const d = raw.replace(/\D/g, '').slice(0, 8); * (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 <= 2) return d;
if (d.length <= 4) return `${d.slice(0, 2)}/${d.slice(2)}`; if (d.length <= 4) return `${d.slice(0, 2)}/${d.slice(2)}`;
return `${d.slice(0, 2)}/${d.slice(2, 4)}/${d.slice(4)}`; 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<TextFieldProps, 'value' | 'onChange' | 'type'> & { type Props = Omit<TextFieldProps, 'value' | 'onChange' | 'type'> & {
/** yyyy-mm-dd (the form / API format) */ /** yyyy-mm-dd (the form / API format) */
@ -46,7 +61,7 @@ export function DateField({ value, onChange, slotProps, disabled, ...rest }: Pro
}, [value]); }, [value]);
const typed = (raw: string) => { const typed = (raw: string) => {
const next = mask(raw); const next = mask(raw, raw.length > text.length);
setText(next); setText(next);
onChange(displayToIso(next)); onChange(displayToIso(next));
}; };

View File

@ -20,6 +20,8 @@ export interface MetaFormProps {
onSubmit?: (payload: FormValues) => Promise<unknown> | unknown; onSubmit?: (payload: FormValues) => Promise<unknown> | unknown;
onCancel?: () => void; onCancel?: () => void;
submitLabel?: string; 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?". */ /** Confirmation question before saving; `false` skips the dialog. Default: the standard "Do you want to save?". */
confirmMessage?: string | false; confirmMessage?: string | false;
/** Field-level errors from the backend (ApiError.fieldErrors); the first one is focused. */ /** Field-level errors from the backend (ApiError.fieldErrors); the first one is focused. */
@ -193,7 +195,7 @@ export function MetaForm(props: MetaFormProps) {
</Button> </Button>
{onCancel && ( {onCancel && (
<Button type="button" color="inherit" onClick={onCancel}> <Button type="button" color="inherit" onClick={onCancel}>
{t('common.cancel')} {props.cancelLabel ?? t('common.cancel')}
</Button> </Button>
)} )}
{props.extraActions} {props.extraActions}

View File

@ -29,7 +29,6 @@ import LockIcon from '@mui/icons-material/Lock';
import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck'; import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck';
import ScaleIcon from '@mui/icons-material/Scale'; import ScaleIcon from '@mui/icons-material/Scale';
import { DataGrid } from '@/components/DataGrid'; import { DataGrid } from '@/components/DataGrid';
import { DateField } from '@/components/DateField';
import { FormCard, FormGrid } from '@/components/FormCard'; 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';
@ -46,7 +45,7 @@ import { useAuth } from '@/providers/AuthProvider';
import { useConfirm } from '@/providers/ConfirmProvider'; import { useConfirm } from '@/providers/ConfirmProvider';
import { useToast } from '@/providers/ToastProvider'; import { useToast } from '@/providers/ToastProvider';
import { import {
fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, searchDestination, searchTruckDistribution, fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, fetchTruck, searchDestination, searchTruckDistribution,
useActivateOrders, useActivation, useAddToQueue, useVoiceCall, useAssignByPn, useClosePermit, useDistribute, useActivateOrders, useActivation, useAddToQueue, useVoiceCall, useAssignByPn, useClosePermit, useDistribute,
useDistributionPivot, useDistributionSummary, useLocationGroups, useManualInput, useOrderDates, useDistributionPivot, useDistributionSummary, useLocationGroups, useManualInput, useOrderDates,
usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination, usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination,
@ -58,9 +57,9 @@ import { AcceptSlip, InSlip, OutSlip } from './slips';
import type { PermitListItem, TruckDistribution } from './types'; import type { PermitListItem, TruckDistribution } from './types';
/** Legacy role gates (src/NTP.Application/Grains/Permits/PermitSupport.cs GrainsRoles). */ /** Legacy role gates (src/NTP.Application/Grains/Permits/PermitSupport.cs GrainsRoles). */
export const OPERATORS = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO']; export const OPERATORS = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'CO'];
export const SUPERVISORS = ['SU', 'GPO', 'GNSU', 'GTO']; export const SUPERVISORS = ['SU', 'GPO', 'GNSU', 'GTO', 'CO'];
export const WEIGHBRIDGE_ROLES = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'GATEIN', 'GATEOUT', 'THRU']; export const WEIGHBRIDGE_ROLES = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'CO', 'GATEIN', 'GATEOUT', 'THRU'];
const PHONE_REASONS: { value: string; en: string; ar: string }[] = [ const PHONE_REASONS: { value: string; en: string; ar: string }[] = [
{ value: 'لايمكن الاتصال به', en: 'Cannot be reached', ar: 'لايمكن الاتصال به' }, { 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). // 'pending' = the id was changed but not validated yet (validated when Enter is pressed).
const [trailerLook, setTrailerLook] = useState<Awaited<ReturnType<typeof fetchTrailer>> | null | undefined | 'pending'>(undefined); const [trailerLook, setTrailerLook] = useState<Awaited<ReturnType<typeof fetchTrailer>> | null | undefined | 'pending'>(undefined);
const [driverLook, setDriverLook] = useState<Awaited<ReturnType<typeof fetchDriver>> | null | undefined | 'pending'>(undefined); const [driverLook, setDriverLook] = useState<Awaited<ReturnType<typeof fetchDriver>> | 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<Awaited<ReturnType<typeof fetchTruck>> | undefined | 'pending'>(undefined);
const d = detail.data; const d = detail.data;
const openEdit = () => { const openEdit = () => {
@ -305,6 +306,7 @@ export function PermitDetailPage() {
}); });
setTrailerLook(undefined); setTrailerLook(undefined);
setDriverLook(undefined); setDriverLook(undefined);
setTruckLook(undefined);
setEditing(true); setEditing(true);
}; };
// opened straight from the list: fill the form once the permit has loaded // 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 nnpnTyped = v.nnpn.trim();
const ownTrn = d?.trailer?.tn ?? ''; const ownTrn = d?.trailer?.tn ?? '';
const ownNnpn = d?.driver?.nnpn ?? ''; const ownNnpn = d?.driver?.nnpn ?? '';
const ownTn = d?.truck?.tn ?? '';
if (detail.isLoading) return <LoadingBanner />; if (detail.isLoading) return <LoadingBanner />;
if (!d) return <EmptyState title={t('pm.notFound')} />; if (!d) return <EmptyState title={t('pm.notFound')} />;
@ -349,17 +352,28 @@ export function PermitDetailPage() {
try { setDriverLook((await fetchDriver(nnpnTyped)) ?? null); } try { setDriverLook((await fetchDriver(nnpnTyped)) ?? null); }
catch (e) { setDriverLook(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } 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<void>) => (e: { key: string; preventDefault: () => void }) => { const onEnter = (run: () => Promise<void>) => (e: { key: string; preventDefault: () => void }) => {
if (e.key === 'Enter') { e.preventDefault(); void run(); } if (e.key === 'Enter') { e.preventDefault(); void run(); }
}; };
const fdate = (x: string | null | undefined) => (x ? formatDate(x, lang) || x : ''); 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() { async function save() {
if (!complete || !driverShown || !(await confirm({ message: t(canSubmit ? 'pm.confirm.submit' : 'pm.confirm.update') }))) return; 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 // the truck never changes here; the driver data is the looked-up (or the permit's own) data of the typed id
const body = { 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(), dled: driverShown.dled || null, name: (driverShown.name ?? '').trim(),
}; };
const done = { onSuccess: () => setEditing(false) }; const done = { onSuccess: () => setEditing(false) };
@ -449,7 +463,12 @@ export function PermitDetailPage() {
<DialogContent> <DialogContent>
<Box sx={{ display: 'grid', gap: 2, pt: 1, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))' } }}> <Box sx={{ display: 'grid', gap: 2, pt: 1, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, minmax(0, 1fr))' } }}>
{/* the truck is fixed; only the trailer number and the driver id can change, the rest follows from them */} {/* the truck is fixed; only the trailer number and the driver id can change, the rest follows from them */}
<TextField size="small" sx={FIELD_SX} label={t('pm.order.tn')} value={d.truck?.tn ?? v.tn} disabled slotProps={ltr} /> {ownTn ? (
<TextField size="small" sx={FIELD_SX} label={t('pm.order.tn')} value={ownTn} disabled slotProps={ltr} />
) : (
<TextField size="small" sx={FIELD_SX} autoFocus label={t('pm.order.tn')} value={v.tn} onChange={changeTruck} onKeyDown={onEnter(checkTruck)} slotProps={ltr}
error={!!v.tn.trim() && truckLook === null} helperText={truckLook === 'pending' ? t('pm.order.pressEnter') : truckLook === null ? t('pm.order.notRegistered') : undefined} />
)}
{canSubmit && !d.operationTypeCode ? ( {canSubmit && !d.operationTypeCode ? (
<TextField select size="small" sx={FIELD_SX} label={t('pm.order.opType')} value={v.opType} onChange={set('opType')}> <TextField select size="small" sx={FIELD_SX} label={t('pm.order.opType')} value={v.opType} onChange={set('opType')}>
<MenuItem value="IMPT">{lang === 'ar' ? 'محمل' : 'Loaded'}</MenuItem> <MenuItem value="IMPT">{lang === 'ar' ? 'محمل' : 'Loaded'}</MenuItem>
@ -657,7 +676,7 @@ function Activation() {
<Table size="small"> <Table size="small">
<TableHead sx={{ bgcolor: 'action.hover' }}> <TableHead sx={{ bgcolor: 'action.hover' }}>
<TableRow><TableCell /><TableCell>{t('pm.activate.loc')}</TableCell><TableCell>{t('pm.activate.cargo')}</TableCell> <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> <TableCell align="center">{t('pm.activate.total')}</TableCell><TableCell align="center">{t('pm.activate.used')}</TableCell></TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
{rows.map((r) => { {rows.map((r) => {
@ -666,7 +685,7 @@ function Activation() {
<TableRow key={k} hover> <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="center" dir="ltr">{fmt(r.total)}</TableCell><TableCell align="center" dir="ltr">{fmt(r.used)}</TableCell>
</TableRow> </TableRow>
); );
})} })}
@ -718,11 +737,11 @@ export function SupplyOrderPage() {
<PageHeader title={t('pm.supply.title')} subtitle={t('pm.supply.subtitle')} /> <PageHeader title={t('pm.supply.title')} subtitle={t('pm.supply.subtitle')} />
<Paper variant="outlined" sx={{ p: 2 }}> <Paper variant="outlined" sx={{ p: 2 }}>
<Table size="small"> <Table size="small">
<TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="right">{t('pm.dist.silos')}</TableCell> <TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="center">{t('pm.dist.silos')}</TableCell>
<TableCell align="right">{t('pm.dist.direct')}</TableCell><TableCell align="right">{t('pm.dist.packed')}</TableCell></TableRow></TableHead> <TableCell align="center">{t('pm.dist.direct')}</TableCell><TableCell align="center">{t('pm.dist.packed')}</TableCell></TableRow></TableHead>
<TableBody>{(pivot.data ?? []).map((r) => ( <TableBody>{(pivot.data ?? []).map((r) => (
<TableRow key={r.companyCode ?? 0}><TableCell>{r.company}</TableCell><TableCell align="right" dir="ltr">{r.silos}</TableCell> <TableRow key={r.companyCode ?? 0}><TableCell>{r.company}</TableCell><TableCell align="center" dir="ltr">{r.silos}</TableCell>
<TableCell align="right" dir="ltr">{r.direct}</TableCell><TableCell align="right" dir="ltr">{r.packed}</TableCell></TableRow> <TableCell align="center" dir="ltr">{r.direct}</TableCell><TableCell align="center" dir="ltr">{r.packed}</TableCell></TableRow>
))}</TableBody> ))}</TableBody>
</Table> </Table>
</Paper> </Paper>
@ -769,28 +788,35 @@ function DistributeTab() {
const { t, lang } = useFeatureUi(strings); const { t, lang } = useFeatureUi(strings);
const distribute = useDistribute(); const distribute = useDistribute();
const confirm = useConfirm(); const confirm = useConfirm();
// confirm texts are the legacy ones (GNPermits.cfm), one per category
const cats = [ const cats = [
{ v: 'PCKD', en: 'Packed', ar: 'مشول' }, { v: 'BULK_AHALE', en: 'Bulk - individuals', ar: 'سائب - أفراد' }, { v: 'PCKD', en: 'Packed', ar: 'مشول', q: 'هل أنت متأكد من توزيع طلبية المشول لهذا اليوم؟' },
{ v: 'BULK_COMP', en: 'Bulk - companies', ar: 'سائب - شركات' }, { v: 'BULK_GALLAB_AHALE', en: 'Tipper bulk - individuals', ar: 'قلاب - أفراد' }, { v: 'BULK_AHALE', en: 'Bulk - individuals', ar: 'سائب - أفراد', q: 'هل أنت متأكد من توزيع طلبية سائب افراد لهذا اليوم؟' },
{ v: 'BULK_GALLAB_COMP', en: 'Tipper bulk - companies', ar: 'قلاب - شركات' }, { 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(); 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 ( return (
<Stack spacing={3}> <Stack spacing={3}>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ maxWidth: 560 }}> <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ maxWidth: 560 }}>
<TextField select size="small" sx={FIELD_SX} label={t('pm.dist.category')} value={cat} onChange={(e) => setCat(e.target.value)}> <TextField select size="small" sx={FIELD_SX} label={t('pm.dist.category')} value={cat} onChange={(e) => setCat(e.target.value)}>
{cats.map((c) => <MenuItem key={c.v} value={c.v}>{lang === 'ar' ? c.ar : c.en}</MenuItem>)} {cats.map((c) => <MenuItem key={c.v} value={c.v}>{lang === 'ar' ? c.ar : c.en}</MenuItem>)}
</TextField> </TextField>
<Button variant="contained" onClick={() => void go()} sx={{ whiteSpace: 'nowrap' }}>{t('pm.dist.run')}</Button> <Button variant="contained" disabled={!cat || distribute.isPending} onClick={() => void go()} sx={{ whiteSpace: 'nowrap' }}>{t('pm.dist.run')}</Button>
</Stack> </Stack>
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: '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">
<TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="right">{t('pm.dist.count')}</TableCell></TableRow></TableHead> <TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="center">{t('pm.dist.count')}</TableCell></TableRow></TableHead>
<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="center" dir="ltr">{fmt(r.cnt)}</TableCell></TableRow>)}</TableBody>
</Table> </Table>
</Paper> </Paper>
</Box> </Box>
@ -806,11 +832,28 @@ function ProcessTab() {
const revokeAll = useRevokeAllRequested(); const revokeAll = useRevokeAllRequested();
const { isSu } = useRoles(); const { isSu } = useRoles();
const confirm = useConfirm(); const confirm = useConfirm();
const toast = useToast();
const dates = useOrderDates();
const [tn, setTn] = useState(''); const [tn, setTn] = useState('');
const [pn, setPn] = useState(''); const [pn, setPn] = useState('');
const [orderId, setOrderId] = useState(''); const [orderId, setOrderId] = useState('');
const [date, setDate] = useState(''); const [date, setDate] = useState('');
const [reserved, setReserved] = useState(false);
const [orders, setOrders] = useState<{ orderId: number; name: string | null }[]>([]);
const [limit, setLimit] = useState(''); 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 ( return (
<Stack spacing={3} sx={{ maxWidth: 520 }}> <Stack spacing={3} sx={{ maxWidth: 520 }}>
<Paper sx={{ p: 2 }}> <Paper sx={{ p: 2 }}>
@ -826,11 +869,20 @@ function ProcessTab() {
<Paper sx={{ p: 2 }}> <Paper sx={{ p: 2 }}>
<Stack spacing={2}> <Stack spacing={2}>
<Typography variant="subtitle1">{t('pm.proc.withDest')}</Typography> <Typography variant="subtitle1">{t('pm.proc.withDest')}</Typography>
<TextField select size="small" sx={FIELD_SX} label={t('pm.manual.orderDate')} value={date} onChange={(e) => setDate(e.target.value)}>
{(dates.data ?? []).map((d) => <MenuItem key={d} value={d}>{d.split('-').reverse().join('/')}</MenuItem>)}
</TextField>
<NumberField label={t('pm.order.pn')} value={pn} onChange={setPn} /> <NumberField label={t('pm.order.pn')} value={pn} onChange={setPn} />
<NumberField label={t('pm.manual.order')} value={orderId} onChange={setOrderId} /> <TextField select size="small" sx={FIELD_SX} label={t('pm.manual.order')} value={orderId} onChange={(e) => setOrderId(e.target.value)}
<DateField size="small" sx={FIELD_SX} label={t('pm.manual.orderDate')} value={date} onChange={setDate} /> helperText={orders.length === 0 && pn && date ? t('pm.manual.noOrders') : undefined}>
<Box><Button variant="contained" disabled={!pn || !orderId || !date} {orders.map((o) => <MenuItem key={o.orderId} value={String(o.orderId)}>{o.name}</MenuItem>)}
onClick={async () => { if (await confirm({ message: t('pm.proc.confirm') })) withDest.mutate({ pn, locations: Number(orderId), orderDate: date, reservedQueue: false }); }}>{t('common.save')}</Button></Box> </TextField>
<Stack direction="row" sx={{ alignItems: 'center' }}>
<Checkbox size="small" checked={reserved} onChange={(e) => setReserved(e.target.checked)} />
<Typography variant="body2">{t('pm.proc.reserved')}</Typography>
</Stack>
<Box><Button variant="contained" disabled={!pn || !orderId || !date || withDest.isPending}
onClick={async () => { if (await confirm({ message: t('pm.proc.confirm') })) withDest.mutate({ pn, locations: Number(orderId), orderDate: date, reservedQueue: reserved }); }}>{t('common.save')}</Button></Box>
</Stack> </Stack>
</Paper> </Paper>
{isSu && ( {isSu && (

View File

@ -135,6 +135,7 @@ export default defineStrings({
'pm.proc.autoOrder': { en: 'Pick an order automatically', ar: 'اختيار طلبية تلقائيا' }, 'pm.proc.autoOrder': { en: 'Pick an order automatically', ar: 'اختيار طلبية تلقائيا' },
'pm.proc.single': { en: 'Move to "order distributed" only', 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.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.confirm': { en: 'Distribute now?', ar: 'هل تريد التوزيع؟' },
'pm.proc.revokeAll': { en: 'Send old requested permits back to the turn', ar: 'ارجاع الارساليات القديمة الى الدور' }, 'pm.proc.revokeAll': { en: 'Send old requested permits back to the turn', ar: 'ارجاع الارساليات القديمة الى الدور' },
'pm.proc.limit': { en: 'Orders below number', ar: 'الطلبيات الأقل من الرقم' }, 'pm.proc.limit': { en: 'Orders below number', ar: 'الطلبيات الأقل من الرقم' },

View File

@ -194,7 +194,7 @@ export function TruckPage() {
canAccept={!!perms?.canAcceptTruck} canRevoke={!!perms?.canRevokeTruck && !perms.isBadiyaCompany} canAccept={!!perms?.canAcceptTruck} canRevoke={!!perms?.canRevokeTruck && !perms.isBadiyaCompany}
onAccept={() => action.mutate({ id: t0.id, action: 'accept' })} onAccept={() => action.mutate({ id: t0.id, action: 'accept' })}
onRevoke={() => action.mutate({ id: t0.id, action: 'revoke' })} 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 && (
<Button variant="outlined" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/trailers/new?truckId=${t0.id}`)}> <Button variant="outlined" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/trailers/new?truckId=${t0.id}`)}>
{t('reg.trucks.addTrailer')} {t('reg.trucks.addTrailer')}
</Button> </Button>
@ -217,6 +217,7 @@ export function TruckPage() {
mode={canEdit ? (isNew ? 'create' : 'edit') : 'view'} mode={canEdit ? (isNew ? 'create' : 'edit') : 'view'}
initialValues={initial} initialValues={initial}
serverErrors={serverErrors} serverErrors={serverErrors}
cancelLabel={t('reg.return')}
onCancel={() => navigate(gridReturnUrl(`${ROOT}/trucks`))} onCancel={() => navigate(gridReturnUrl(`${ROOT}/trucks`))}
onSubmit={submit} onSubmit={submit}
> >
@ -384,6 +385,7 @@ export function TrailerPage() {
mode={canEdit ? (isNew ? 'create' : 'edit') : 'view'} mode={canEdit ? (isNew ? 'create' : 'edit') : 'view'}
initialValues={initial} initialValues={initial}
serverErrors={serverErrors} serverErrors={serverErrors}
cancelLabel={t('reg.return')}
onCancel={() => navigate(truckId ? `${ROOT}/trucks/${truckId}` : gridReturnUrl(`${ROOT}/trailers`))} onCancel={() => navigate(truckId ? `${ROOT}/trucks/${truckId}` : gridReturnUrl(`${ROOT}/trailers`))}
onSubmit={submit} onSubmit={submit}
> >
@ -475,6 +477,7 @@ export function DriverPage() {
mode={isNew ? 'create' : 'view'} mode={isNew ? 'create' : 'view'}
initialValues={initial} initialValues={initial}
serverErrors={serverErrors} serverErrors={serverErrors}
cancelLabel={t('reg.return')}
onCancel={() => navigate(gridReturnUrl(`${ROOT}/drivers`))} onCancel={() => navigate(gridReturnUrl(`${ROOT}/drivers`))}
onSubmit={submit} onSubmit={submit}
> >
@ -547,6 +550,7 @@ export function BlacklistCreatePage() {
meta={meta} meta={meta}
mode="create" mode="create"
serverErrors={serverErrors} serverErrors={serverErrors}
cancelLabel={t('reg.return')}
onCancel={() => navigate(gridReturnUrl(`${ROOT}/blacklist`))} onCancel={() => navigate(gridReturnUrl(`${ROOT}/blacklist`))}
onSubmit={(p) => onSubmit={(p) =>
new Promise<void>((resolve) => { new Promise<void>((resolve) => {

View File

@ -23,6 +23,7 @@ export default defineStrings({
'reg.status.incomp': { en: 'Incomplete', ar: 'غير مكتمل' }, 'reg.status.incomp': { en: 'Incomplete', ar: 'غير مكتمل' },
'reg.status': { en: 'Status', ar: 'الحالة' }, 'reg.status': { en: 'Status', ar: 'الحالة' },
'reg.accept': { en: 'Activate', ar: 'تفعيل' }, 'reg.accept': { en: 'Activate', ar: 'تفعيل' },
'reg.return': { en: 'Back', ar: 'عودة' },
'reg.revoke': { en: 'Revoke', ar: 'إلغاء' }, 'reg.revoke': { en: 'Revoke', ar: 'إلغاء' },
'reg.acceptConfirm': { en: 'Do you want to activate this record?', 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: 'هل تريد إلغاء هذا السجل؟ لا يمكن التراجع عن ذلك.' }, 'reg.revokeConfirm': { en: 'Do you want to revoke this record? This cannot be undone.', ar: 'هل تريد إلغاء هذا السجل؟ لا يمكن التراجع عن ذلك.' },

View File

@ -1,18 +1,33 @@
import { useMemo } from 'react'; import { useMemo } from 'react';
import { Link as RouterLink } from 'react-router-dom'; 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 { PageHeader } from '@/components/PageHeader';
import { useUi } from '@/i18n/useUi'; import { useUi } from '@/i18n/useUi';
import { useAuth } from '@/providers/AuthProvider'; import { useAuth } from '@/providers/AuthProvider';
import { featureMenu } from '@/registry'; import { featureMenu } from '@/registry';
import { filterMenu, flatten, itemAllowed } from './menuUtils'; 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() { export function DashboardPage() {
const { t, tr } = useUi(); const { t, tr } = useUi();
const { user, hasRole, can } = useAuth(); const { user, hasRole, can } = useAuth();
const links = useMemo( const sections = useMemo(
() => flatten(filterMenu(featureMenu, itemAllowed(hasRole, can), can)).filter((e) => e.item.path), () => 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], [hasRole, can],
); );
@ -24,26 +39,43 @@ export function DashboardPage() {
{user?.locationName && <Chip label={`${t('dash.location')}: ${user.locationName}`} />} {user?.locationName && <Chip label={`${t('dash.location')}: ${user.locationName}`} />}
{user?.companyCode && <Chip label={`${t('dash.company')}: ${user.companyCode}`} />} {user?.companyCode && <Chip label={`${t('dash.company')}: ${user.companyCode}`} />}
</Stack> </Stack>
<Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 1.5 }}>{t('nav.quickLinks')}</Typography> {sections.length === 0 ? (
{links.length === 0 ? (
<Alert severity="info">{t('nav.empty')}</Alert> <Alert severity="info">{t('nav.empty')}</Alert>
) : ( ) : (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(4, 1fr)' } }}> <Stack spacing={3}>
{links.map(({ item, trail }) => { {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 (
<Box key={group.key} component="section">
<Stack direction="row" spacing={1.25} sx={{ alignItems: 'center', mb: 1 }}>
<Box sx={{ width: 30, height: 30, borderRadius: 1.5, display: 'grid', placeItems: 'center', bgcolor: alpha(c, 0.16), color: c }}>
<GroupIcon sx={{ fontSize: 18 }} />
</Box>
<Typography sx={{ fontWeight: 700 }}>{tr(group.title)}</Typography>
</Stack>
<Divider sx={{ mb: 1.5 }} />
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', lg: 'repeat(4, 1fr)' } }}>
{pages.map(({ item, caption }) => {
const Icon = item.icon; const Icon = item.icon;
return ( return (
<Card key={item.key} variant="outlined"> <Card key={item.key} variant="outlined">
<CardActionArea component={RouterLink} to={item.path!} sx={{ p: 2, display: 'flex', alignItems: 'center', gap: 1.5, justifyContent: 'flex-start' }}> <CardActionArea component={RouterLink} to={item.path!} sx={{ p: 1.5, display: 'flex', alignItems: 'center', gap: 1.25, justifyContent: 'flex-start' }}>
<Icon color="primary" /> <Icon sx={{ color: colorOf(item) }} />
<Box sx={{ flex: 1, minWidth: 0 }}> <Box sx={{ flex: 1, minWidth: 0 }}>
<Typography noWrap sx={{ fontWeight: 600 }}>{tr(item.title)}</Typography> <Typography noWrap sx={{ fontWeight: 600 }}>{tr(item.title)}</Typography>
{trail.length > 0 && <Typography variant="caption" color="text.secondary" noWrap>{trail.map((g) => tr(g.title)).join(' / ')}</Typography>} {caption && <Typography variant="caption" color="text.secondary" noWrap>{caption}</Typography>}
</Box> </Box>
</CardActionArea> </CardActionArea>
</Card> </Card>
); );
})} })}
</Box> </Box>
</Box>
);
})}
</Stack>
)} )}
</> </>
); );

View File

@ -19,7 +19,7 @@ import type { MenuItem as Item } from './types';
export const DRAWER_FULL = 272; export const DRAWER_FULL = 272;
export const DRAWER_MINI = 76; export const DRAWER_MINI = 76;
function colorOf(item: Item): string { export function colorOf(item: Item): string {
if (item.color) return item.color; if (item.color) return item.color;
let h = 0; let h = 0;
for (const ch of item.key) h = (h * 31 + ch.charCodeAt(0)) >>> 0; for (const ch of item.key) h = (h * 31 + ch.charCodeAt(0)) >>> 0;