From 83cf3c9b036169c8a4daef081ad8f05eb44abdf7 Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Tue, 17 Nov 2026 11:28:14 +0300 Subject: [PATCH] GTO reports, voice call action, SYSTEM_ERRORS logging, report fixes, collapsed menu logo - Grant GTO the tender-order and distribution-summary reports (db/gto-reports.sql) - Companies/owners turn: translated values, centered counters; default order date today; tender-order left-to-right, no status filter - Voice call button on permits list (grains.permits.voiceCall), IVR config in production - Save unexpected server errors into SYSTEM_ERRORS - Collapsed sidebar shows the brand mark - Production attachment paths set to /mnt/NTPFiles Co-Authored-By: Claude Sonnet 5.5 --- db/grains-screen-permissions.sql | 5 ++ db/gto-reports.sql | 17 ++++++ docs/ENVIRONMENTS.md | 1 + .../V1/Grains/PermitsController.cs | 2 +- .../ErrorHandling/GlobalExceptionHandler.cs | 12 +++- src/NTP.Api/appsettings.Production.json | 8 +++ .../Abstractions/ISystemErrorLogger.cs | 7 +++ .../Access/PermissionDefaults.cs | 4 ++ .../Grains/Reports/ReportsService.cs | 6 +- src/NTP.Infrastructure/DependencyInjection.cs | 1 + .../Grains/GrainsPermitsGateways.cs | 7 ++- .../Persistence/SystemErrorLogger.cs | 60 +++++++++++++++++++ web/src/features/grains-permits/api.ts | 3 + web/src/features/grains-permits/pages.tsx | 21 ++++++- web/src/features/grains-permits/strings.ts | 2 + web/src/features/grains-reports/meta.tsx | 23 +++---- web/src/features/grains-reports/pages.tsx | 5 +- web/src/shell/Sidebar.tsx | 2 +- 18 files changed, 161 insertions(+), 25 deletions(-) create mode 100644 db/gto-reports.sql create mode 100644 src/NTP.Application/Abstractions/ISystemErrorLogger.cs create mode 100644 src/NTP.Infrastructure/Persistence/SystemErrorLogger.cs diff --git a/db/grains-screen-permissions.sql b/db/grains-screen-permissions.sql index bed04d1..bbba6c5 100644 --- a/db/grains-screen-permissions.sql +++ b/db/grains-screen-permissions.sql @@ -63,6 +63,8 @@ INSERT ALL INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.manualEntry') -- إيقاف\تفعيل الاستنكاف INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.absence') + -- الاتصال الصوتي + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.voiceCall') -- طلبية التموين (orders menu) INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.orders.supply') INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.orders.supply') @@ -80,6 +82,9 @@ INSERT ALL INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.loading-weights') -- الارساليات المكتملة INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.closed-permits') + -- ارسالية عطاء التموين / ملخص التوزيع + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.tender-order') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.distribution-summary') -- وجهات الشركات INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.orders.companyDest') -- تحديد وجهة ارسالية تموين diff --git a/db/gto-reports.sql b/db/gto-reports.sql new file mode 100644 index 0000000..406634c --- /dev/null +++ b/db/gto-reports.sql @@ -0,0 +1,17 @@ +-- Grants GTO two more reports: ارسالية عطاء التموين (tender-order) and ملخص التوزيع (distribution-summary). +-- Safe to re-run; not run by the app. Take either away by deleting its row (the API applies it within about a minute). + +INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) +SELECT v.rolecode, v.resource_key + FROM (SELECT 'GTO' AS rolecode, 'grains.reports.t.tender-order' AS resource_key FROM dual UNION ALL + SELECT 'GTO', 'grains.reports.t.distribution-summary' FROM dual) v + WHERE NOT EXISTS (SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p WHERE p.rolecode = v.rolecode AND p.resource_key = v.resource_key); + +COMMIT; + +-- الاتصال الصوتي (voice call button on ارساليات التموين; legacy action 96): GTO. +INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) +SELECT 'GTO', 'grains.permits.voiceCall' FROM dual + WHERE NOT EXISTS (SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p WHERE p.rolecode = 'GTO' AND p.resource_key = 'grains.permits.voiceCall'); + +COMMIT; diff --git a/docs/ENVIRONMENTS.md b/docs/ENVIRONMENTS.md index 060a2c4..722f9fb 100644 --- a/docs/ENVIRONMENTS.md +++ b/docs/ENVIRONMENTS.md @@ -52,6 +52,7 @@ Apply these scripts once per database (not run by the application), in this orde 3. `db/disabled-features.sql` - features switched OFF for everybody, SU included (safe to re-run) 4. `db/permits-create-permission.sql` - right to register a turn (تسجيل دور) from the permits list, granted to GOO (safe to re-run) 5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run) +5b. `db/gto-reports.sql` - GTO gets the ارسالية عطاء التموين and ملخص التوزيع reports (safe to re-run) 6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run) **Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU diff --git a/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs b/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs index 67f234d..ddda222 100644 --- a/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs +++ b/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs @@ -359,7 +359,7 @@ public sealed class PermitDistributionController(IDistributionService distributi public Task SendAutoCall(AutoCallRequest request, CancellationToken ct) => distribution.SendAutoCallFileAsync(request, ct); [HttpPost("auto-call/ivr")] - [RequirePermission(PermissionKeys.PermitsDistribution)] + [RequirePermission(PermissionKeys.PermitsVoiceCall)] public Task TriggerIvr(CancellationToken ct) => distribution.TriggerIvrAsync(ct); } diff --git a/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs b/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs index 9a0ee12..dbd1b62 100644 --- a/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs +++ b/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs @@ -1,6 +1,7 @@ using FluentValidation; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; +using NTP.Application.Abstractions; using NTP.Application.Common; using Oracle.ManagedDataAccess.Client; @@ -14,13 +15,22 @@ namespace NTP.Api.ErrorHandling; internal sealed class GlobalExceptionHandler( IProblemDetailsService problemDetails, IHostEnvironment env, + ISystemErrorLogger systemErrors, ILogger logger) : IExceptionHandler { public async ValueTask TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct) { var (status, title, detail, errors) = Map(exception); - if (status >= 500) logger.LogError(exception, "Unhandled error: {Title}", title); + if (status >= 500) + { + logger.LogError(exception, "Unhandled error: {Title}", title); + // runtime errors are kept in SYSTEM_ERRORS (like the legacy system) + var ip = http.Connection.RemoteIpAddress; + if (ip is { IsIPv4MappedToIPv6: true }) ip = ip.MapToIPv4(); + await systemErrors.LogAsync(exception, http.User.FindFirst(AppClaims.UserId)?.Value, ip?.ToString(), + http.Request.Headers.UserAgent.ToString(), $"{http.Request.Method} {http.Request.Path}{http.Request.QueryString}"); + } else logger.LogWarning("Request failed {Status}: {Title} - {Message}", status, title, exception.Message); ProblemDetails problem = errors is null diff --git a/src/NTP.Api/appsettings.Production.json b/src/NTP.Api/appsettings.Production.json index e3d212e..edbca6c 100644 --- a/src/NTP.Api/appsettings.Production.json +++ b/src/NTP.Api/appsettings.Production.json @@ -29,6 +29,14 @@ "Registry": { "UploadedFilesPath": "/mnt/NTPFiles", "TempUploadPath": "/mnt/NTPFiles/tempuploadedfiles" + }, + + // الاتصال الصوتي button (ارساليات التموين): starts the IVR calls. The ?wsdl address is turned into a call of callAPI. + "Permits": { + "AutoCall": { + "Enabled": true, + "IvrUrl": "http://aqtcs.nafith.net/IVR/callivr.cfc?wsdl" + } } } } diff --git a/src/NTP.Application/Abstractions/ISystemErrorLogger.cs b/src/NTP.Application/Abstractions/ISystemErrorLogger.cs new file mode 100644 index 0000000..917c225 --- /dev/null +++ b/src/NTP.Application/Abstractions/ISystemErrorLogger.cs @@ -0,0 +1,7 @@ +namespace NTP.Application.Abstractions; + +/// Saves runtime (unexpected) errors into the NTP-schema table SYSTEM_ERRORS (legacy logs.cfc logSysError). Never throws. +public interface ISystemErrorLogger +{ + Task LogAsync(Exception exception, string? userId, string? ipAddress, string? browser, string? requestInfo); +} diff --git a/src/NTP.Application/Access/PermissionDefaults.cs b/src/NTP.Application/Access/PermissionDefaults.cs index 5273a14..c4660d4 100644 --- a/src/NTP.Application/Access/PermissionDefaults.cs +++ b/src/NTP.Application/Access/PermissionDefaults.cs @@ -54,6 +54,7 @@ public static class PermissionKeys public const string PermitsActivation = "grains.permits.activation"; // legacy activateOrders.cfm public const string PermitsManualEntry = "grains.permits.manualEntry"; // legacy ManualInput.cfm public const string PermitsAbsence = "grains.permits.absence"; // legacy activeOrInactiveAbsenceFeature.cfm + public const string PermitsVoiceCall = "grains.permits.voiceCall"; // legacy GNPermits.cfm "نظام الاتصال الصوتي" (action 96) // Report screens outside the business sheet allow-list: SU only (no seed rows) public const string ReportsDashboard = "grains.reports.dashboard"; @@ -97,6 +98,7 @@ public static class PermissionDefaults [PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية [PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي [PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف + [PermissionKeys.PermitsVoiceCall] = ["GTO"], // الاتصال الصوتي [PermissionKeys.OrdersInvoiceCheck] = ["GNAC"], // التأكد من الفواتير [PermissionKeys.OrdersFines] = ["GNAC"], // الغرامات [PermissionKeys.OrdersWages] = ["GNAC"], // الأجور @@ -106,6 +108,8 @@ public static class PermissionDefaults [PermissionKeys.ReportTable("owners-turn")] = ["GTO"], // تقرير دور الأفراد [PermissionKeys.ReportTable("loading-weights")] = ["GTO"], // تقرير أوزان التحميل [PermissionKeys.ReportTable("closed-permits")] = ["GTO"], // الارساليات المكتملة + [PermissionKeys.ReportTable("tender-order")] = ["GTO"], // ارسالية عطاء التموين + [PermissionKeys.ReportTable("distribution-summary")] = ["GTO"], // ملخص التوزيع [PermissionKeys.OrdersCompanyDest] = ["GOO"], // وجهات الشركات [PermissionKeys.PermitsDestinations] = ["GOO"], // تحديد وجهة ارسالية تموين }; diff --git a/src/NTP.Application/Grains/Reports/ReportsService.cs b/src/NTP.Application/Grains/Reports/ReportsService.cs index c1470ae..b651cab 100644 --- a/src/NTP.Application/Grains/Reports/ReportsService.cs +++ b/src/NTP.Application/Grains/Reports/ReportsService.cs @@ -157,7 +157,11 @@ public sealed class ReportsService(IReportsRepository repo, IReportExcelService [ C("turn", "الدور", "Turn", "number"), C("scac", "رقم الشركة", "Company code"), C("company", "اسم الشركة", "Company"), C("code", "نوع المادة", "Cargo"), C("type", "نوع التوزيع", "Distribution"), C("counter", "العداد", "Counter", "number") - ]); + ], rowFix: r => + { + r["code"] = r["code"] switch { "BULK" => "سائب", "PCKD" => "مشول", "GALLAB" => "سائب - قلاب", var v => v }; + r["type"] = r["type"] switch { "COMP" => "شركات", "AHALI" => "أفراد", var v => v }; + }); case ReportKeys.OwnersTurn: return Make(key, "تقرير دور الأفراد", "Individuals turn", [$"نوع المادة: {f.ShipmentMode} الوجهة: {f.DestAddressId}"], raw, [ diff --git a/src/NTP.Infrastructure/DependencyInjection.cs b/src/NTP.Infrastructure/DependencyInjection.cs index 530c9e0..4f09b27 100644 --- a/src/NTP.Infrastructure/DependencyInjection.cs +++ b/src/NTP.Infrastructure/DependencyInjection.cs @@ -48,6 +48,7 @@ public static class DependencyInjection services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(); + services.AddSingleton(); // Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped). // Do NOT add per-table lines here. diff --git a/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs b/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs index 2bd5e3a..3668b40 100644 --- a/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs +++ b/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs @@ -175,7 +175,12 @@ internal sealed class AutoCallGatewayService(IGrainsPermitsSettingsService setti { using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds))); - using var res = await Http.GetAsync(o.IvrUrl, cts.Token); + // The legacy code called callAPI() of the web service described by "...callivr.cfc?wsdl". A GET of the ?wsdl address + // would only download the description (always 200, nothing called), so it is turned into the real call. + var url = o.IvrUrl.EndsWith("?wsdl", StringComparison.OrdinalIgnoreCase) + ? o.IvrUrl[..^"?wsdl".Length] + "?method=callAPI" + : o.IvrUrl; + using var res = await Http.GetAsync(url, cts.Token); return res.IsSuccessStatusCode; } catch (Exception ex) when (ex is not OperationCanceledException) diff --git a/src/NTP.Infrastructure/Persistence/SystemErrorLogger.cs b/src/NTP.Infrastructure/Persistence/SystemErrorLogger.cs new file mode 100644 index 0000000..8214030 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/SystemErrorLogger.cs @@ -0,0 +1,60 @@ +using System.Text; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NTP.Application.Abstractions; +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Infrastructure.Persistence; + +/// +/// Inserts into NTP.SYSTEM_ERRORS (ID from SEQ_SYSTEM_ERRORS, ERROR, ERRORDATE, IPADDRESS(15), USERID(50), BROWSER(200)). +/// Uses its own short-lived connection so it still works when the request's connection / transaction is the thing that failed, +/// and swallows every failure (logging an error must never hide the original one). +/// +internal sealed class SystemErrorLogger(IOptions options, ILogger logger) : ISystemErrorLogger +{ + public async Task LogAsync(Exception exception, string? userId, string? ipAddress, string? browser, string? requestInfo) + { + try + { + var cs = options.Value.ConnectionString; + if (string.IsNullOrWhiteSpace(cs)) return; + + await using var con = new OracleConnection(cs); + await con.OpenAsync(CancellationToken.None); + await using var cmd = con.CreateCommand(); + cmd.BindByName = true; + cmd.CommandText = """ + INSERT INTO SYSTEM_ERRORS (ID, ERROR, ERRORDATE, IPADDRESS, USERID, BROWSER) + VALUES (SEQ_SYSTEM_ERRORS.NEXTVAL, :Err, SYSDATE, :Ip, :UserId, :Browser) + """; + cmd.Parameters.Add(new OracleParameter("Err", OracleDbType.Clob) { Value = Describe(exception, requestInfo) }); + cmd.Parameters.Add(new OracleParameter("Ip", OracleDbType.Varchar2) { Value = Cut(ipAddress, 15) ?? "-" }); + cmd.Parameters.Add(new OracleParameter("UserId", OracleDbType.Varchar2) { Value = Cut(userId, 50) }); + cmd.Parameters.Add(new OracleParameter("Browser", OracleDbType.Varchar2) { Value = Cut(browser, 200) }); + await cmd.ExecuteNonQueryAsync(CancellationToken.None); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Could not save the error into SYSTEM_ERRORS"); + } + } + + private static string? Cut(string? v, int max) => string.IsNullOrEmpty(v) ? null : v.Length <= max ? v : v[..max]; + + /// Same layout as the legacy log: details, message, SQL (n/a), then where it happened. + private static string Describe(Exception ex, string? requestInfo) + { + var sb = new StringBuilder(); + if (!string.IsNullOrEmpty(requestInfo)) sb.AppendLine("Request: " + requestInfo); + for (var e = ex; e is not null; e = e.InnerException!) + { + sb.AppendLine($"MSG: {e.GetType().FullName}: {e.Message}"); + if (e is OracleException ora) sb.AppendLine($"ORA-{ora.Number:D5}"); + if (e.InnerException is null) break; + } + sb.AppendLine("Details:"); + sb.AppendLine(ex.ToString()); + return sb.ToString(); + } +} diff --git a/web/src/features/grains-permits/api.ts b/web/src/features/grains-permits/api.ts index 4f19de9..1bc59ae 100644 --- a/web/src/features/grains-permits/api.ts +++ b/web/src/features/grains-permits/api.ts @@ -158,6 +158,9 @@ export function useClosePermit() { export function useToggleAbsence() { return useOperation(() => api.post(`${PERMITS}/absence-feature/toggle`), [['grains.permits.absence']]); } +export function useVoiceCall() { + return useOperation(() => api.post(`${DIST}/auto-call/ivr`), []); +} export function useAddToQueue() { return useOperation((v: { tn: string; tt: string; checkStatuses: boolean }) => api.post(QUEUE, v), all); } diff --git a/web/src/features/grains-permits/pages.tsx b/web/src/features/grains-permits/pages.tsx index 3e7fc54..ebfd135 100644 --- a/web/src/features/grains-permits/pages.tsx +++ b/web/src/features/grains-permits/pages.tsx @@ -14,6 +14,7 @@ import EditIcon from '@mui/icons-material/Edit'; import HistoryIcon from '@mui/icons-material/History'; import LocalShippingIcon from '@mui/icons-material/LocalShipping'; import PhoneCallbackIcon from '@mui/icons-material/PhoneCallback'; +import PhoneInTalkIcon from '@mui/icons-material/PhoneInTalk'; import PhoneDisabledIcon from '@mui/icons-material/PhoneDisabled'; import PrintIcon from '@mui/icons-material/Print'; import RestoreIcon from '@mui/icons-material/Restore'; @@ -46,7 +47,7 @@ import { useConfirm } from '@/providers/ConfirmProvider'; import { useToast } from '@/providers/ToastProvider'; import { fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, searchDestination, searchTruckDistribution, - useActivateOrders, useActivation, useAddToQueue, useAssignByPn, useClosePermit, useDistribute, + useActivateOrders, useActivation, useAddToQueue, useVoiceCall, useAssignByPn, useClosePermit, useDistribute, useDistributionPivot, useDistributionSummary, useLocationGroups, useManualInput, useOrderDates, usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination, useRevokeAllRequested, useSingleTruck, useSubmitOrder, useUpdateOrder, useWeighbridgeManual, @@ -84,6 +85,7 @@ function useRoles() { canClose: can('grains.permits.close'), canTruckOrder: can('grains.permits.truckOrder'), canTruckStatus: can('grains.permits.truckStatus'), + canVoiceCall: can('grains.permits.voiceCall'), isSu: hasRole(['SU']), }; } @@ -219,8 +221,9 @@ export function PermitsPage() { return { ...permitGrid(h, { companyUser, showRevoked }), rowActions: permitRowActions(h) }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [companyUser, showRevoked]); - const { canCreate } = useRoles(); + const { canCreate, canVoiceCall } = useRoles(); const add = useAddToQueue(); + const voiceCall = useVoiceCall(); const confirm = useConfirm(); const [open, setOpen] = useState(false); const [tn, setTn] = useState(''); @@ -234,7 +237,19 @@ export function PermitsPage() { <> } onClick={() => setOpen(true)}>{t('pm.queue.add')}} + actions={( + <> + {canVoiceCall && ( + + )} + {canCreate && } + + )} /> {element} diff --git a/web/src/features/grains-permits/strings.ts b/web/src/features/grains-permits/strings.ts index 0434ce0..e040bce 100644 --- a/web/src/features/grains-permits/strings.ts +++ b/web/src/features/grains-permits/strings.ts @@ -84,6 +84,8 @@ export default defineStrings({ // ---- queue 'pm.queue.title': { en: 'Turns (queue)', ar: 'الأدوار' }, 'pm.queue.subtitle': { en: 'Permit records waiting for a turn', ar: 'الارساليات بانتظار الدور' }, + 'pm.voice.call': { en: 'Voice call', ar: 'الاتصال الصوتي' }, + 'pm.voice.confirm': { en: 'Start the automatic voice calls now?', ar: 'هل تريد بدء الاتصال الصوتي الآن؟' }, 'pm.queue.add': { en: 'Add truck to the turn', ar: 'تسجيل دور' }, 'pm.queue.cargo': { en: 'Cargo class', ar: 'نوع الحمولة' }, 'pm.queue.confirm': { en: 'Register a turn for this truck?', ar: 'هل تريد تسجيل دور لهذه القاطرة؟' }, diff --git a/web/src/features/grains-reports/meta.tsx b/web/src/features/grains-reports/meta.tsx index 50646cc..069f744 100644 --- a/web/src/features/grains-reports/meta.tsx +++ b/web/src/features/grains-reports/meta.tsx @@ -20,6 +20,8 @@ export interface TableReportMeta { /** Shows the "extra" block returned by the backend. */ extra?: 'orderDistribution' | 'incapability'; pageSize?: number; + /** Columns read left-to-right as listed in both languages (legacy cfgrid layout). */ + visualLtr?: boolean; } const L = (k: keyof typeof strings) => strings[k]; @@ -33,17 +35,6 @@ const modeOptions = ['BULK', 'PCKD', 'GALLAB'].map((v) => opt(v, `rpt.mode.${v}` const dtypeOptions = ['COMP', 'AHALI', 'all'].map((v) => opt(v, `rpt.dtype.${v}` as keyof typeof strings)); const modeBulkPckd = ['BULK', 'PCKD'].map((v) => opt(v, `rpt.mode.${v}` as keyof typeof strings)); -const permitStatuses: StatusMeta[] = [ - { value: 'REQST', label: L('rpt.st.REQST'), color: 'warning' }, - { value: 'PLND', label: L('rpt.st.PLND'), color: 'info' }, - { value: 'OPEN', label: L('rpt.st.OPEN'), color: 'default' }, - { value: 'ACCPT', label: L('rpt.st.ACCPT'), color: 'primary' }, - { value: 'RESD', label: L('rpt.st.RESD'), color: 'primary' }, - { value: 'ACTRL', label: L('rpt.st.ACTRL'), color: 'secondary' }, - { value: 'CLRPR', label: L('rpt.st.CLRPR'), color: 'secondary' }, - { value: 'CLOSE', label: L('rpt.st.CLOSE'), color: 'success' }, - { value: 'RVKD', label: L('rpt.st.RVKD'), color: 'error' }, -]; const regStatuses = ['OPEN', 'ACCPT', 'RVKD', 'REGREQST'].map((v) => opt(v, `rpt.st.${v}` as keyof typeof strings)); const fFrom: FilterMeta = { name: 'from', type: 'date', label: L('rpt.from') }; @@ -123,8 +114,8 @@ export const tableReports: Record = { ], }, 'tender-order': { - key: 'tender-order', titleKey: 'rpt.t.tender-order', required: [], pageSize: 50, - status: { param: 'shipmentStatusCode', options: permitStatuses }, + key: 'tender-order', titleKey: 'rpt.t.tender-order', required: [], pageSize: 50, visualLtr: true, + defaults: { orderDate: '@today' }, filters: [ fOrderDate, { name: 'destAddressId', type: 'autocomplete', label: L('rpt.f.destination'), options: allDestinationsLoader }, fTn, fScac, { name: 'creationDate', type: 'date', label: L('rpt.f.creationDate') }, @@ -139,7 +130,7 @@ export const tableReports: Record = { 'distribution-summary': { key: 'distribution-summary', titleKey: 'rpt.t.distribution-summary', required: ['orderDate'], filters: [fOrderDate, { name: 'shipmentMode', type: 'select', label: L('rpt.f.shipmentMode'), options: modeBulkPckd }], - defaults: { shipmentMode: 'BULK' }, + defaults: { shipmentMode: 'BULK', orderDate: '@today' }, columns: [txt('name', H('Company', 'الشركة')), num('cnt', H('Count', 'العدد')), txt('shift', H('Shift', 'الشفت')), { key: 'orderDate', header: H('Order date', 'تاريخ الطلبية'), ltr: true }], }, 'order-distribution': { @@ -168,7 +159,7 @@ export const tableReports: Record = { { name: 'shipmentMode', type: 'select', label: L('rpt.f.shipmentMode'), options: modeOptions }, { name: 'distributionType', type: 'select', label: L('rpt.f.distributionType'), options: dtypeOptions }, ], - columns: [num('turn', H('Turn', 'الدور'), { align: 'start', width: 80 }), code('scac', H('Company code', 'رقم الشركة')), txt('company', H('Company', 'اسم الشركة')), txt('code', H('Cargo', 'نوع المادة')), txt('type', H('Distribution', 'نوع التوزيع')), num('counter', H('Counter', 'العداد'))], + columns: [num('turn', H('Turn', 'الدور'), { align: 'start', width: 80 }), code('scac', H('Company code', 'رقم الشركة')), txt('company', H('Company', 'اسم الشركة')), txt('code', H('Cargo', 'نوع المادة')), txt('type', H('Distribution', 'نوع التوزيع')), num('counter', H('Counter', 'العداد'), { align: 'center' })], }, 'owners-turn': { key: 'owners-turn', titleKey: 'rpt.t.owners-turn', required: ['destAddressId'], inferred: true, @@ -177,7 +168,7 @@ export const tableReports: Record = { { name: 'shipmentMode', type: 'select', label: L('rpt.f.shipmentMode'), options: modeBulkPckd }, { name: 'destAddressId', type: 'autocomplete', label: L('rpt.f.destination'), options: destinationsLoader, dependsOn: 'shipmentMode' }, ], - columns: [num('turn', H('Turn', 'الدور'), { align: 'start', width: 80 }), code('tn', H('Truck no.', 'رقم القاطرة')), num('trips', H('Trips', 'عدد الرحلات')), { key: 'lastTrip', header: H('Last trip', 'آخر رحلة'), format: 'datetime', ltr: true }], + columns: [num('turn', H('Turn', 'الدور'), { align: 'start', width: 80 }), code('tn', H('Truck no.', 'رقم القاطرة')), num('trips', H('Trips', 'عدد الرحلات'), { align: 'center' }), { key: 'lastTrip', header: H('Last trip', 'آخر رحلة'), format: 'datetime', ltr: true }], }, drivers: { key: 'drivers', titleKey: 'rpt.t.drivers', required: [], diff --git a/web/src/features/grains-reports/pages.tsx b/web/src/features/grains-reports/pages.tsx index d685851..59bdf3b 100644 --- a/web/src/features/grains-reports/pages.tsx +++ b/web/src/features/grains-reports/pages.tsx @@ -437,7 +437,9 @@ export function MotMultiTripsPage() { function initialDefaults(m: TableReportMeta): Record | undefined { if (m.defaults === 'today') return { from: todayIso(), to: todayIso() }; if (m.defaults === 'yesterday') return { from: yesterdayIso(), to: yesterdayIso() }; - return m.defaults; + if (!m.defaults) return undefined; + // '@today' stands for the current date + return Object.fromEntries(Object.entries(m.defaults).map(([k, v]) => [k, v === '@today' ? todayIso() : v])); } export function TableReportPage({ reportKey }: { reportKey?: string }) { @@ -477,6 +479,7 @@ function TableReportBody({ meta }: { meta: TableReportMeta }) { status: meta.status, defaultFilters: defaults, pageSize: meta.pageSize ?? 50, + visualLtr: meta.visualLtr, fetcher: async ({ page, pageSize, filters }): Promise> => { // legacy pages validated the required inputs before running the query if (meta.required.some((n) => !filters[n])) { setExtra(null); return { items: [], page, pageSize, totalCount: 0 }; } diff --git a/web/src/shell/Sidebar.tsx b/web/src/shell/Sidebar.tsx index 0b2aed7..913abbb 100644 --- a/web/src/shell/Sidebar.tsx +++ b/web/src/shell/Sidebar.tsx @@ -149,7 +149,7 @@ export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMob const content = ( - {mini ? {t('app.title').charAt(0)} : } + {mini ? Nafith : }